repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
lukier/linux-hi3518 | drivers/isdn/sc/packet.c | 9204 | 6731 | /* $Id: packet.c,v 1.5.8.1 2001/09/23 22:24:59 kai Exp $
*
* Copyright (C) 1996 SpellCaster Telecommunications Inc.
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* For more information, please contact gpl-info@spellcast.com or write:
*
* SpellCaster Telecommunications Inc.
* 5621 Finch Avenue East, Unit #3
* Scarborough, Ontario Canada
* M1B 2T9
* +1 (416) 297-8565
* +1 (416) 297-6433 Facsimile
*/
#include "includes.h"
#include "hardware.h"
#include "message.h"
#include "card.h"
int sndpkt(int devId, int channel, int ack, struct sk_buff *data)
{
LLData ReqLnkWrite;
int status;
int card;
unsigned long len;
card = get_card_from_id(devId);
if (!IS_VALID_CARD(card)) {
pr_debug("invalid param: %d is not a valid card id\n", card);
return -ENODEV;
}
pr_debug("%s: sndpkt: frst = 0x%lx nxt = %d f = %d n = %d\n",
sc_adapter[card]->devicename,
sc_adapter[card]->channel[channel].first_sendbuf,
sc_adapter[card]->channel[channel].next_sendbuf,
sc_adapter[card]->channel[channel].free_sendbufs,
sc_adapter[card]->channel[channel].num_sendbufs);
if (!sc_adapter[card]->channel[channel].free_sendbufs) {
pr_debug("%s: out of TX buffers\n",
sc_adapter[card]->devicename);
return -EINVAL;
}
if (data->len > BUFFER_SIZE) {
pr_debug("%s: data overflows buffer size (data > buffer)\n",
sc_adapter[card]->devicename);
return -EINVAL;
}
ReqLnkWrite.buff_offset = sc_adapter[card]->channel[channel].next_sendbuf *
BUFFER_SIZE + sc_adapter[card]->channel[channel].first_sendbuf;
ReqLnkWrite.msg_len = data->len; /* sk_buff size */
pr_debug("%s: writing %d bytes to buffer offset 0x%lx\n",
sc_adapter[card]->devicename,
ReqLnkWrite.msg_len, ReqLnkWrite.buff_offset);
memcpy_toshmem(card, (char *)ReqLnkWrite.buff_offset, data->data, ReqLnkWrite.msg_len);
/*
* sendmessage
*/
pr_debug("%s: sndpkt size=%d, buf_offset=0x%lx buf_indx=%d\n",
sc_adapter[card]->devicename,
ReqLnkWrite.msg_len, ReqLnkWrite.buff_offset,
sc_adapter[card]->channel[channel].next_sendbuf);
status = sendmessage(card, CEPID, ceReqTypeLnk, ceReqClass1, ceReqLnkWrite,
channel + 1, sizeof(LLData), (unsigned int *)&ReqLnkWrite);
len = data->len;
if (status) {
pr_debug("%s: failed to send packet, status = %d\n",
sc_adapter[card]->devicename, status);
return -1;
}
else {
sc_adapter[card]->channel[channel].free_sendbufs--;
sc_adapter[card]->channel[channel].next_sendbuf =
++sc_adapter[card]->channel[channel].next_sendbuf ==
sc_adapter[card]->channel[channel].num_sendbufs ? 0 :
sc_adapter[card]->channel[channel].next_sendbuf;
pr_debug("%s: packet sent successfully\n", sc_adapter[card]->devicename);
dev_kfree_skb(data);
indicate_status(card, ISDN_STAT_BSENT, channel, (char *)&len);
}
return len;
}
void rcvpkt(int card, RspMessage *rcvmsg)
{
LLData newll;
struct sk_buff *skb;
if (!IS_VALID_CARD(card)) {
pr_debug("invalid param: %d is not a valid card id\n", card);
return;
}
switch (rcvmsg->rsp_status) {
case 0x01:
case 0x02:
case 0x70:
pr_debug("%s: error status code: 0x%x\n",
sc_adapter[card]->devicename, rcvmsg->rsp_status);
return;
case 0x00:
if (!(skb = dev_alloc_skb(rcvmsg->msg_data.response.msg_len))) {
printk(KERN_WARNING "%s: rcvpkt out of memory, dropping packet\n",
sc_adapter[card]->devicename);
return;
}
skb_put(skb, rcvmsg->msg_data.response.msg_len);
pr_debug("%s: getting data from offset: 0x%lx\n",
sc_adapter[card]->devicename,
rcvmsg->msg_data.response.buff_offset);
memcpy_fromshmem(card,
skb_put(skb, rcvmsg->msg_data.response.msg_len),
(char *)rcvmsg->msg_data.response.buff_offset,
rcvmsg->msg_data.response.msg_len);
sc_adapter[card]->card->rcvcallb_skb(sc_adapter[card]->driverId,
rcvmsg->phy_link_no - 1, skb);
case 0x03:
/*
* Recycle the buffer
*/
pr_debug("%s: buffer size : %d\n",
sc_adapter[card]->devicename, BUFFER_SIZE);
/* memset_shmem(card, rcvmsg->msg_data.response.buff_offset, 0, BUFFER_SIZE); */
newll.buff_offset = rcvmsg->msg_data.response.buff_offset;
newll.msg_len = BUFFER_SIZE;
pr_debug("%s: recycled buffer at offset 0x%lx size %d\n",
sc_adapter[card]->devicename,
newll.buff_offset, newll.msg_len);
sendmessage(card, CEPID, ceReqTypeLnk, ceReqClass1, ceReqLnkRead,
rcvmsg->phy_link_no, sizeof(LLData), (unsigned int *)&newll);
}
}
int setup_buffers(int card, int c)
{
unsigned int nBuffers, i, cBase;
unsigned int buffer_size;
LLData RcvBuffOffset;
if (!IS_VALID_CARD(card)) {
pr_debug("invalid param: %d is not a valid card id\n", card);
return -ENODEV;
}
/*
* Calculate the buffer offsets (send/recv/send/recv)
*/
pr_debug("%s: setting up channel buffer space in shared RAM\n",
sc_adapter[card]->devicename);
buffer_size = BUFFER_SIZE;
nBuffers = ((sc_adapter[card]->ramsize - BUFFER_BASE) / buffer_size) / 2;
nBuffers = nBuffers > BUFFERS_MAX ? BUFFERS_MAX : nBuffers;
pr_debug("%s: calculating buffer space: %d buffers, %d big\n",
sc_adapter[card]->devicename,
nBuffers, buffer_size);
if (nBuffers < 2) {
pr_debug("%s: not enough buffer space\n",
sc_adapter[card]->devicename);
return -1;
}
cBase = (nBuffers * buffer_size) * (c - 1);
pr_debug("%s: channel buffer offset from shared RAM: 0x%x\n",
sc_adapter[card]->devicename, cBase);
sc_adapter[card]->channel[c - 1].first_sendbuf = BUFFER_BASE + cBase;
sc_adapter[card]->channel[c - 1].num_sendbufs = nBuffers / 2;
sc_adapter[card]->channel[c - 1].free_sendbufs = nBuffers / 2;
sc_adapter[card]->channel[c - 1].next_sendbuf = 0;
pr_debug("%s: send buffer setup complete: first=0x%lx n=%d f=%d, nxt=%d\n",
sc_adapter[card]->devicename,
sc_adapter[card]->channel[c - 1].first_sendbuf,
sc_adapter[card]->channel[c - 1].num_sendbufs,
sc_adapter[card]->channel[c - 1].free_sendbufs,
sc_adapter[card]->channel[c - 1].next_sendbuf);
/*
* Prep the receive buffers
*/
pr_debug("%s: adding %d RecvBuffers:\n",
sc_adapter[card]->devicename, nBuffers / 2);
for (i = 0; i < nBuffers / 2; i++) {
RcvBuffOffset.buff_offset =
((sc_adapter[card]->channel[c - 1].first_sendbuf +
(nBuffers / 2) * buffer_size) + (buffer_size * i));
RcvBuffOffset.msg_len = buffer_size;
pr_debug("%s: adding RcvBuffer #%d offset=0x%lx sz=%d bufsz:%d\n",
sc_adapter[card]->devicename,
i + 1, RcvBuffOffset.buff_offset,
RcvBuffOffset.msg_len, buffer_size);
sendmessage(card, CEPID, ceReqTypeLnk, ceReqClass1, ceReqLnkRead,
c, sizeof(LLData), (unsigned int *)&RcvBuffOffset);
}
return 0;
}
| gpl-2.0 |
jmztaylor/android_kernel_htc_m4 | drivers/isdn/sc/message.c | 9204 | 5954 | /* $Id: message.c,v 1.5.8.2 2001/09/23 22:24:59 kai Exp $
*
* functions for sending and receiving control messages
*
* Copyright (C) 1996 SpellCaster Telecommunications Inc.
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* For more information, please contact gpl-info@spellcast.com or write:
*
* SpellCaster Telecommunications Inc.
* 5621 Finch Avenue East, Unit #3
* Scarborough, Ontario Canada
* M1B 2T9
* +1 (416) 297-8565
* +1 (416) 297-6433 Facsimile
*/
#include <linux/sched.h>
#include "includes.h"
#include "hardware.h"
#include "message.h"
#include "card.h"
/*
* receive a message from the board
*/
int receivemessage(int card, RspMessage *rspmsg)
{
DualPortMemory *dpm;
unsigned long flags;
if (!IS_VALID_CARD(card)) {
pr_debug("Invalid param: %d is not a valid card id\n", card);
return -EINVAL;
}
pr_debug("%s: Entered receivemessage\n",
sc_adapter[card]->devicename);
/*
* See if there are messages waiting
*/
if (inb(sc_adapter[card]->ioport[FIFO_STATUS]) & RF_HAS_DATA) {
/*
* Map in the DPM to the base page and copy the message
*/
spin_lock_irqsave(&sc_adapter[card]->lock, flags);
outb((sc_adapter[card]->shmem_magic >> 14) | 0x80,
sc_adapter[card]->ioport[sc_adapter[card]->shmem_pgport]);
dpm = (DualPortMemory *) sc_adapter[card]->rambase;
memcpy_fromio(rspmsg, &(dpm->rsp_queue[dpm->rsp_tail]),
MSG_LEN);
dpm->rsp_tail = (dpm->rsp_tail + 1) % MAX_MESSAGES;
inb(sc_adapter[card]->ioport[FIFO_READ]);
spin_unlock_irqrestore(&sc_adapter[card]->lock, flags);
/*
* Tell the board that the message is received
*/
pr_debug("%s: Received Message seq:%d pid:%d time:%d cmd:%d "
"cnt:%d (type,class,code):(%d,%d,%d) "
"link:%d stat:0x%x\n",
sc_adapter[card]->devicename,
rspmsg->sequence_no,
rspmsg->process_id,
rspmsg->time_stamp,
rspmsg->cmd_sequence_no,
rspmsg->msg_byte_cnt,
rspmsg->type,
rspmsg->class,
rspmsg->code,
rspmsg->phy_link_no,
rspmsg->rsp_status);
return 0;
}
return -ENOMSG;
}
/*
* send a message to the board
*/
int sendmessage(int card,
unsigned int procid,
unsigned int type,
unsigned int class,
unsigned int code,
unsigned int link,
unsigned int data_len,
unsigned int *data)
{
DualPortMemory *dpm;
ReqMessage sndmsg;
unsigned long flags;
if (!IS_VALID_CARD(card)) {
pr_debug("Invalid param: %d is not a valid card id\n", card);
return -EINVAL;
}
/*
* Make sure we only send CEPID messages when the engine is up
* and CMPID messages when it is down
*/
if (sc_adapter[card]->EngineUp && procid == CMPID) {
pr_debug("%s: Attempt to send CM message with engine up\n",
sc_adapter[card]->devicename);
return -ESRCH;
}
if (!sc_adapter[card]->EngineUp && procid == CEPID) {
pr_debug("%s: Attempt to send CE message with engine down\n",
sc_adapter[card]->devicename);
return -ESRCH;
}
memset(&sndmsg, 0, MSG_LEN);
sndmsg.msg_byte_cnt = 4;
sndmsg.type = type;
sndmsg.class = class;
sndmsg.code = code;
sndmsg.phy_link_no = link;
if (data_len > 0) {
if (data_len > MSG_DATA_LEN)
data_len = MSG_DATA_LEN;
memcpy(&(sndmsg.msg_data), data, data_len);
sndmsg.msg_byte_cnt = data_len + 8;
}
sndmsg.process_id = procid;
sndmsg.sequence_no = sc_adapter[card]->seq_no++ % 256;
/*
* wait for an empty slot in the queue
*/
while (!(inb(sc_adapter[card]->ioport[FIFO_STATUS]) & WF_NOT_FULL))
udelay(1);
/*
* Disable interrupts and map in shared memory
*/
spin_lock_irqsave(&sc_adapter[card]->lock, flags);
outb((sc_adapter[card]->shmem_magic >> 14) | 0x80,
sc_adapter[card]->ioport[sc_adapter[card]->shmem_pgport]);
dpm = (DualPortMemory *) sc_adapter[card]->rambase; /* Fix me */
memcpy_toio(&(dpm->req_queue[dpm->req_head]), &sndmsg, MSG_LEN);
dpm->req_head = (dpm->req_head + 1) % MAX_MESSAGES;
outb(sndmsg.sequence_no, sc_adapter[card]->ioport[FIFO_WRITE]);
spin_unlock_irqrestore(&sc_adapter[card]->lock, flags);
pr_debug("%s: Sent Message seq:%d pid:%d time:%d "
"cnt:%d (type,class,code):(%d,%d,%d) "
"link:%d\n ",
sc_adapter[card]->devicename,
sndmsg.sequence_no,
sndmsg.process_id,
sndmsg.time_stamp,
sndmsg.msg_byte_cnt,
sndmsg.type,
sndmsg.class,
sndmsg.code,
sndmsg.phy_link_no);
return 0;
}
int send_and_receive(int card,
unsigned int procid,
unsigned char type,
unsigned char class,
unsigned char code,
unsigned char link,
unsigned char data_len,
unsigned char *data,
RspMessage *mesgdata,
int timeout)
{
int retval;
int tries;
if (!IS_VALID_CARD(card)) {
pr_debug("Invalid param: %d is not a valid card id\n", card);
return -EINVAL;
}
sc_adapter[card]->want_async_messages = 1;
retval = sendmessage(card, procid, type, class, code, link,
data_len, (unsigned int *) data);
if (retval) {
pr_debug("%s: SendMessage failed in SAR\n",
sc_adapter[card]->devicename);
sc_adapter[card]->want_async_messages = 0;
return -EIO;
}
tries = 0;
/* wait for the response */
while (tries < timeout) {
schedule_timeout_interruptible(1);
pr_debug("SAR waiting..\n");
/*
* See if we got our message back
*/
if ((sc_adapter[card]->async_msg.type == type) &&
(sc_adapter[card]->async_msg.class == class) &&
(sc_adapter[card]->async_msg.code == code) &&
(sc_adapter[card]->async_msg.phy_link_no == link)) {
/*
* Got it!
*/
pr_debug("%s: Got ASYNC message\n",
sc_adapter[card]->devicename);
memcpy(mesgdata, &(sc_adapter[card]->async_msg),
sizeof(RspMessage));
sc_adapter[card]->want_async_messages = 0;
return 0;
}
tries++;
}
pr_debug("%s: SAR message timeout\n", sc_adapter[card]->devicename);
sc_adapter[card]->want_async_messages = 0;
return -ETIME;
}
| gpl-2.0 |
iskandar1023/Velvet-N4 | drivers/infiniband/hw/amso1100/c2_alloc.c | 13300 | 4082 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, 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/errno.h>
#include <linux/bitmap.h>
#include "c2.h"
static int c2_alloc_mqsp_chunk(struct c2_dev *c2dev, gfp_t gfp_mask,
struct sp_chunk **head)
{
int i;
struct sp_chunk *new_head;
dma_addr_t dma_addr;
new_head = dma_alloc_coherent(&c2dev->pcidev->dev, PAGE_SIZE,
&dma_addr, gfp_mask);
if (new_head == NULL)
return -ENOMEM;
new_head->dma_addr = dma_addr;
dma_unmap_addr_set(new_head, mapping, new_head->dma_addr);
new_head->next = NULL;
new_head->head = 0;
/* build list where each index is the next free slot */
for (i = 0;
i < (PAGE_SIZE - sizeof(struct sp_chunk) -
sizeof(u16)) / sizeof(u16) - 1;
i++) {
new_head->shared_ptr[i] = i + 1;
}
/* terminate list */
new_head->shared_ptr[i] = 0xFFFF;
*head = new_head;
return 0;
}
int c2_init_mqsp_pool(struct c2_dev *c2dev, gfp_t gfp_mask,
struct sp_chunk **root)
{
return c2_alloc_mqsp_chunk(c2dev, gfp_mask, root);
}
void c2_free_mqsp_pool(struct c2_dev *c2dev, struct sp_chunk *root)
{
struct sp_chunk *next;
while (root) {
next = root->next;
dma_free_coherent(&c2dev->pcidev->dev, PAGE_SIZE, root,
dma_unmap_addr(root, mapping));
root = next;
}
}
__be16 *c2_alloc_mqsp(struct c2_dev *c2dev, struct sp_chunk *head,
dma_addr_t *dma_addr, gfp_t gfp_mask)
{
u16 mqsp;
while (head) {
mqsp = head->head;
if (mqsp != 0xFFFF) {
head->head = head->shared_ptr[mqsp];
break;
} else if (head->next == NULL) {
if (c2_alloc_mqsp_chunk(c2dev, gfp_mask, &head->next) ==
0) {
head = head->next;
mqsp = head->head;
head->head = head->shared_ptr[mqsp];
break;
} else
return NULL;
} else
head = head->next;
}
if (head) {
*dma_addr = head->dma_addr +
((unsigned long) &(head->shared_ptr[mqsp]) -
(unsigned long) head);
pr_debug("%s addr %p dma_addr %llx\n", __func__,
&(head->shared_ptr[mqsp]), (unsigned long long) *dma_addr);
return (__force __be16 *) &(head->shared_ptr[mqsp]);
}
return NULL;
}
void c2_free_mqsp(__be16 *mqsp)
{
struct sp_chunk *head;
u16 idx;
/* The chunk containing this ptr begins at the page boundary */
head = (struct sp_chunk *) ((unsigned long) mqsp & PAGE_MASK);
/* Link head to new mqsp */
*mqsp = (__force __be16) head->head;
/* Compute the shared_ptr index */
idx = ((unsigned long) mqsp & ~PAGE_MASK) >> 1;
idx -= (unsigned long) &(((struct sp_chunk *) 0)->shared_ptr[0]) >> 1;
/* Point this index at the head */
head->shared_ptr[idx] = head->head;
/* Point head at this index */
head->head = idx;
}
| gpl-2.0 |
janrinze/snowballkernel | drivers/usb/otg/gpio_vbus.c | 245 | 9465 | /*
* gpio-vbus.c - simple GPIO VBUS sensing driver for B peripheral devices
*
* Copyright (c) 2008 Philipp Zabel <philipp.zabel@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/usb.h>
#include <linux/workqueue.h>
#include <linux/regulator/consumer.h>
#include <linux/usb/gadget.h>
#include <linux/usb/gpio_vbus.h>
#include <linux/usb/otg.h>
/*
* A simple GPIO VBUS sensing driver for B peripheral only devices
* with internal transceivers. It can control a D+ pullup GPIO and
* a regulator to limit the current drawn from VBUS.
*
* Needs to be loaded before the UDC driver that will use it.
*/
struct gpio_vbus_data {
struct otg_transceiver otg;
struct device *dev;
struct regulator *vbus_draw;
int vbus_draw_enabled;
unsigned mA;
struct work_struct work;
};
/*
* This driver relies on "both edges" triggering. VBUS has 100 msec to
* stabilize, so the peripheral controller driver may need to cope with
* some bouncing due to current surges (e.g. charging local capacitance)
* and contact chatter.
*
* REVISIT in desperate straits, toggling between rising and falling
* edges might be workable.
*/
#define VBUS_IRQ_FLAGS \
( IRQF_SAMPLE_RANDOM | IRQF_SHARED \
| IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING )
/* interface to regulator framework */
static void set_vbus_draw(struct gpio_vbus_data *gpio_vbus, unsigned mA)
{
struct regulator *vbus_draw = gpio_vbus->vbus_draw;
int enabled;
if (!vbus_draw)
return;
enabled = gpio_vbus->vbus_draw_enabled;
if (mA) {
regulator_set_current_limit(vbus_draw, 0, 1000 * mA);
if (!enabled) {
regulator_enable(vbus_draw);
gpio_vbus->vbus_draw_enabled = 1;
}
} else {
if (enabled) {
regulator_disable(vbus_draw);
gpio_vbus->vbus_draw_enabled = 0;
}
}
gpio_vbus->mA = mA;
}
static int is_vbus_powered(struct gpio_vbus_mach_info *pdata)
{
int vbus;
vbus = gpio_get_value(pdata->gpio_vbus);
if (pdata->gpio_vbus_inverted)
vbus = !vbus;
return vbus;
}
static void gpio_vbus_work(struct work_struct *work)
{
struct gpio_vbus_data *gpio_vbus =
container_of(work, struct gpio_vbus_data, work);
struct gpio_vbus_mach_info *pdata = gpio_vbus->dev->platform_data;
int gpio;
if (!gpio_vbus->otg.gadget)
return;
/* Peripheral controllers which manage the pullup themselves won't have
* gpio_pullup configured here. If it's configured here, we'll do what
* isp1301_omap::b_peripheral() does and enable the pullup here... although
* that may complicate usb_gadget_{,dis}connect() support.
*/
gpio = pdata->gpio_pullup;
if (is_vbus_powered(pdata)) {
gpio_vbus->otg.state = OTG_STATE_B_PERIPHERAL;
usb_gadget_vbus_connect(gpio_vbus->otg.gadget);
/* drawing a "unit load" is *always* OK, except for OTG */
set_vbus_draw(gpio_vbus, 100);
/* optionally enable D+ pullup */
if (gpio_is_valid(gpio))
gpio_set_value(gpio, !pdata->gpio_pullup_inverted);
} else {
/* optionally disable D+ pullup */
if (gpio_is_valid(gpio))
gpio_set_value(gpio, pdata->gpio_pullup_inverted);
set_vbus_draw(gpio_vbus, 0);
usb_gadget_vbus_disconnect(gpio_vbus->otg.gadget);
gpio_vbus->otg.state = OTG_STATE_B_IDLE;
}
}
/* VBUS change IRQ handler */
static irqreturn_t gpio_vbus_irq(int irq, void *data)
{
struct platform_device *pdev = data;
struct gpio_vbus_mach_info *pdata = pdev->dev.platform_data;
struct gpio_vbus_data *gpio_vbus = platform_get_drvdata(pdev);
dev_dbg(&pdev->dev, "VBUS %s (gadget: %s)\n",
is_vbus_powered(pdata) ? "supplied" : "inactive",
gpio_vbus->otg.gadget ? gpio_vbus->otg.gadget->name : "none");
if (gpio_vbus->otg.gadget)
schedule_work(&gpio_vbus->work);
return IRQ_HANDLED;
}
/* OTG transceiver interface */
/* bind/unbind the peripheral controller */
static int gpio_vbus_set_peripheral(struct otg_transceiver *otg,
struct usb_gadget *gadget)
{
struct gpio_vbus_data *gpio_vbus;
struct gpio_vbus_mach_info *pdata;
struct platform_device *pdev;
int gpio, irq;
gpio_vbus = container_of(otg, struct gpio_vbus_data, otg);
pdev = to_platform_device(gpio_vbus->dev);
pdata = gpio_vbus->dev->platform_data;
irq = gpio_to_irq(pdata->gpio_vbus);
gpio = pdata->gpio_pullup;
if (!gadget) {
dev_dbg(&pdev->dev, "unregistering gadget '%s'\n",
otg->gadget->name);
/* optionally disable D+ pullup */
if (gpio_is_valid(gpio))
gpio_set_value(gpio, pdata->gpio_pullup_inverted);
set_vbus_draw(gpio_vbus, 0);
usb_gadget_vbus_disconnect(otg->gadget);
otg->state = OTG_STATE_UNDEFINED;
otg->gadget = NULL;
return 0;
}
otg->gadget = gadget;
dev_dbg(&pdev->dev, "registered gadget '%s'\n", gadget->name);
/* initialize connection state */
gpio_vbus_irq(irq, pdev);
return 0;
}
/* effective for B devices, ignored for A-peripheral */
static int gpio_vbus_set_power(struct otg_transceiver *otg, unsigned mA)
{
struct gpio_vbus_data *gpio_vbus;
gpio_vbus = container_of(otg, struct gpio_vbus_data, otg);
if (otg->state == OTG_STATE_B_PERIPHERAL)
set_vbus_draw(gpio_vbus, mA);
return 0;
}
/* for non-OTG B devices: set/clear transceiver suspend mode */
static int gpio_vbus_set_suspend(struct otg_transceiver *otg, int suspend)
{
struct gpio_vbus_data *gpio_vbus;
gpio_vbus = container_of(otg, struct gpio_vbus_data, otg);
/* draw max 0 mA from vbus in suspend mode; or the previously
* recorded amount of current if not suspended
*
* NOTE: high powered configs (mA > 100) may draw up to 2.5 mA
* if they're wake-enabled ... we don't handle that yet.
*/
return gpio_vbus_set_power(otg, suspend ? 0 : gpio_vbus->mA);
}
/* platform driver interface */
static int __init gpio_vbus_probe(struct platform_device *pdev)
{
struct gpio_vbus_mach_info *pdata = pdev->dev.platform_data;
struct gpio_vbus_data *gpio_vbus;
struct resource *res;
int err, gpio, irq;
if (!pdata || !gpio_is_valid(pdata->gpio_vbus))
return -EINVAL;
gpio = pdata->gpio_vbus;
gpio_vbus = kzalloc(sizeof(struct gpio_vbus_data), GFP_KERNEL);
if (!gpio_vbus)
return -ENOMEM;
platform_set_drvdata(pdev, gpio_vbus);
gpio_vbus->dev = &pdev->dev;
gpio_vbus->otg.label = "gpio-vbus";
gpio_vbus->otg.state = OTG_STATE_UNDEFINED;
gpio_vbus->otg.set_peripheral = gpio_vbus_set_peripheral;
gpio_vbus->otg.set_power = gpio_vbus_set_power;
gpio_vbus->otg.set_suspend = gpio_vbus_set_suspend;
err = gpio_request(gpio, "vbus_detect");
if (err) {
dev_err(&pdev->dev, "can't request vbus gpio %d, err: %d\n",
gpio, err);
goto err_gpio;
}
gpio_direction_input(gpio);
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res) {
irq = res->start;
res->flags &= IRQF_TRIGGER_MASK;
res->flags |= IRQF_SAMPLE_RANDOM | IRQF_SHARED;
} else
irq = gpio_to_irq(gpio);
/* if data line pullup is in use, initialize it to "not pulling up" */
gpio = pdata->gpio_pullup;
if (gpio_is_valid(gpio)) {
err = gpio_request(gpio, "udc_pullup");
if (err) {
dev_err(&pdev->dev,
"can't request pullup gpio %d, err: %d\n",
gpio, err);
gpio_free(pdata->gpio_vbus);
goto err_gpio;
}
gpio_direction_output(gpio, pdata->gpio_pullup_inverted);
}
err = request_irq(irq, gpio_vbus_irq, VBUS_IRQ_FLAGS,
"vbus_detect", pdev);
if (err) {
dev_err(&pdev->dev, "can't request irq %i, err: %d\n",
irq, err);
goto err_irq;
}
INIT_WORK(&gpio_vbus->work, gpio_vbus_work);
gpio_vbus->vbus_draw = regulator_get(&pdev->dev, "vbus_draw");
if (IS_ERR(gpio_vbus->vbus_draw)) {
dev_dbg(&pdev->dev, "can't get vbus_draw regulator, err: %ld\n",
PTR_ERR(gpio_vbus->vbus_draw));
gpio_vbus->vbus_draw = NULL;
}
/* only active when a gadget is registered */
err = otg_set_transceiver(&gpio_vbus->otg);
if (err) {
dev_err(&pdev->dev, "can't register transceiver, err: %d\n",
err);
goto err_otg;
}
return 0;
err_otg:
free_irq(irq, &pdev->dev);
err_irq:
if (gpio_is_valid(pdata->gpio_pullup))
gpio_free(pdata->gpio_pullup);
gpio_free(pdata->gpio_vbus);
err_gpio:
platform_set_drvdata(pdev, NULL);
kfree(gpio_vbus);
return err;
}
static int __exit gpio_vbus_remove(struct platform_device *pdev)
{
struct gpio_vbus_data *gpio_vbus = platform_get_drvdata(pdev);
struct gpio_vbus_mach_info *pdata = pdev->dev.platform_data;
int gpio = pdata->gpio_vbus;
regulator_put(gpio_vbus->vbus_draw);
otg_set_transceiver(NULL);
free_irq(gpio_to_irq(gpio), &pdev->dev);
if (gpio_is_valid(pdata->gpio_pullup))
gpio_free(pdata->gpio_pullup);
gpio_free(gpio);
platform_set_drvdata(pdev, NULL);
kfree(gpio_vbus);
return 0;
}
/* NOTE: the gpio-vbus device may *NOT* be hotplugged */
MODULE_ALIAS("platform:gpio-vbus");
static struct platform_driver gpio_vbus_driver = {
.driver = {
.name = "gpio-vbus",
.owner = THIS_MODULE,
},
.remove = __exit_p(gpio_vbus_remove),
};
static int __init gpio_vbus_init(void)
{
return platform_driver_probe(&gpio_vbus_driver, gpio_vbus_probe);
}
module_init(gpio_vbus_init);
static void __exit gpio_vbus_exit(void)
{
platform_driver_unregister(&gpio_vbus_driver);
}
module_exit(gpio_vbus_exit);
MODULE_DESCRIPTION("simple GPIO controlled OTG transceiver driver");
MODULE_AUTHOR("Philipp Zabel");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ParanoidNote/void-kernel | sound/soc/codecs/mc1n2/mc1n2_dbg.c | 501 | 13111 | #include <sound/soc.h>
#include "mc1n2_priv.h"
#ifdef CONFIG_SND_SOC_MC1N2_DEBUG
static void mc1n2_dump_reg_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_REG_INFO *info = (MCDRV_REG_INFO *)pvPrm;
dbg_info("bRegType = 0x%02x\n", info->bRegType);
dbg_info("bAddress = 0x%02x\n", info->bAddress);
}
static void mc1n2_dump_array(const char *name,
const unsigned char *data, size_t len)
{
char str[2048], *p;
int n = (len <= 256) ? len : 256;
int i;
p = str;
for (i = 0; i < n; i++) {
p += sprintf(p, "0x%02x ", data[i]);
}
dbg_info("%s[] = {%s}\n", name, str);
}
#define DEF_PATH(p) {offsetof(MCDRV_PATH_INFO, p), #p}
static void mc1n2_dump_path_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_PATH_INFO *info = (MCDRV_PATH_INFO *)pvPrm;
int i;
struct path_table {
size_t offset;
char *name;
};
struct path_table table[] = {
DEF_PATH(asHpOut[0]), DEF_PATH(asHpOut[1]),
DEF_PATH(asSpOut[0]), DEF_PATH(asSpOut[1]),
DEF_PATH(asRcOut[0]),
DEF_PATH(asLout1[0]), DEF_PATH(asLout1[1]),
DEF_PATH(asLout2[0]), DEF_PATH(asLout2[1]),
DEF_PATH(asPeak[0]),
DEF_PATH(asDit0[0]),
DEF_PATH(asDit1[0]),
DEF_PATH(asDit2[0]),
DEF_PATH(asDac[0]), DEF_PATH(asDac[1]),
DEF_PATH(asAe[0]),
DEF_PATH(asCdsp[0]), DEF_PATH(asCdsp[1]),
DEF_PATH(asCdsp[2]), DEF_PATH(asCdsp[3]),
DEF_PATH(asAdc0[0]), DEF_PATH(asAdc0[1]),
DEF_PATH(asAdc1[0]),
DEF_PATH(asMix[0]),
DEF_PATH(asBias[0]),
};
#define N_PATH_TABLE (sizeof(table) / sizeof(struct path_table))
for (i = 0; i < N_PATH_TABLE; i++) {
MCDRV_CHANNEL *ch = (MCDRV_CHANNEL *)((void *)info + table[i].offset);
int j;
for (j = 0; j < SOURCE_BLOCK_NUM; j++) {
if (ch->abSrcOnOff[j] != 0) {
dbg_info("%s.abSrcOnOff[%d] = 0x%02x\n",
table[i].name, j, ch->abSrcOnOff[j]);
}
}
}
}
#define DEF_VOL(v) {offsetof(MCDRV_VOL_INFO, v), #v}
static void mc1n2_dump_vol_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_VOL_INFO *info = (MCDRV_VOL_INFO *)pvPrm;
int i;
struct vol_table {
size_t offset;
char *name;
};
struct vol_table table[] = {
DEF_VOL(aswD_Ad0[0]), DEF_VOL(aswD_Ad0[1]),
DEF_VOL(aswD_Ad1[0]),
DEF_VOL(aswD_Aeng6[0]), DEF_VOL(aswD_Aeng6[1]),
DEF_VOL(aswD_Pdm[0]), DEF_VOL(aswD_Pdm[1]),
DEF_VOL(aswD_Dtmfb[0]), DEF_VOL(aswD_Dtmfb[1]),
DEF_VOL(aswD_Dir0[0]), DEF_VOL(aswD_Dir0[1]),
DEF_VOL(aswD_Dir1[0]), DEF_VOL(aswD_Dir1[1]),
DEF_VOL(aswD_Dir2[0]), DEF_VOL(aswD_Dir2[1]),
DEF_VOL(aswD_Ad0Att[0]), DEF_VOL(aswD_Ad0Att[1]),
DEF_VOL(aswD_Ad1Att[0]),
DEF_VOL(aswD_Dir0Att[0]), DEF_VOL(aswD_Dir0Att[1]),
DEF_VOL(aswD_Dir1Att[0]), DEF_VOL(aswD_Dir1Att[1]),
DEF_VOL(aswD_Dir2Att[0]), DEF_VOL(aswD_Dir2Att[1]),
DEF_VOL(aswD_SideTone[0]), DEF_VOL(aswD_SideTone[1]),
DEF_VOL(aswD_DtmfAtt[0]), DEF_VOL(aswD_DtmfAtt[1]),
DEF_VOL(aswD_DacMaster[0]), DEF_VOL(aswD_DacMaster[1]),
DEF_VOL(aswD_DacVoice[0]), DEF_VOL(aswD_DacVoice[1]),
DEF_VOL(aswD_DacAtt[0]), DEF_VOL(aswD_DacAtt[1]),
DEF_VOL(aswD_Dit0[0]), DEF_VOL(aswD_Dit0[1]),
DEF_VOL(aswD_Dit1[0]), DEF_VOL(aswD_Dit1[1]),
DEF_VOL(aswD_Dit2[0]), DEF_VOL(aswD_Dit2[1]),
DEF_VOL(aswA_Ad0[0]), DEF_VOL(aswA_Ad0[1]),
DEF_VOL(aswA_Ad1[0]),
DEF_VOL(aswA_Lin1[0]), DEF_VOL(aswA_Lin1[1]),
DEF_VOL(aswA_Lin2[0]), DEF_VOL(aswA_Lin2[1]),
DEF_VOL(aswA_Mic1[0]),
DEF_VOL(aswA_Mic2[0]),
DEF_VOL(aswA_Mic3[0]),
DEF_VOL(aswA_Hp[0]), DEF_VOL(aswA_Hp[1]),
DEF_VOL(aswA_Sp[0]), DEF_VOL(aswA_Sp[1]),
DEF_VOL(aswA_Rc[0]),
DEF_VOL(aswA_Lout1[0]), DEF_VOL(aswA_Lout1[1]),
DEF_VOL(aswA_Lout2[0]), DEF_VOL(aswA_Lout2[1]),
DEF_VOL(aswA_Mic1Gain[0]),
DEF_VOL(aswA_Mic2Gain[0]),
DEF_VOL(aswA_Mic3Gain[0]),
DEF_VOL(aswA_HpGain[0]),
};
#define N_VOL_TABLE (sizeof(table) / sizeof(struct vol_table))
for (i = 0; i < N_VOL_TABLE; i++) {
SINT16 vol = *(SINT16 *)((void *)info + table[i].offset);
if (vol & 0x0001) {
dbg_info("%s = 0x%04x\n", table[i].name, (vol & 0xfffe));
}
}
}
static void mc1n2_dump_dio_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_DIO_INFO *info = (MCDRV_DIO_INFO *)pvPrm;
MCDRV_DIO_PORT *port;
UINT32 update;
int i;
for (i = 0; i < IOPORT_NUM; i++) {
dbg_info("asPortInfo[%d]:\n", i);
port = &info->asPortInfo[i];
update = dPrm >> (i*3);
if (update & MCDRV_DIO0_COM_UPDATE_FLAG) {
dbg_info("sDioCommon.bMasterSlave = 0x%02x\n",
port->sDioCommon.bMasterSlave);
dbg_info(" bAutoFs = 0x%02x\n",
port->sDioCommon.bAutoFs);
dbg_info(" bFs = 0x%02x\n",
port->sDioCommon.bFs);
dbg_info(" bBckFs = 0x%02x\n",
port->sDioCommon.bBckFs);
dbg_info(" bInterface = 0x%02x\n",
port->sDioCommon.bInterface);
dbg_info(" bBckInvert = 0x%02x\n",
port->sDioCommon.bBckInvert);
dbg_info(" bPcmHizTim = 0x%02x\n",
port->sDioCommon.bPcmHizTim);
dbg_info(" bPcmClkDown = 0x%02x\n",
port->sDioCommon.bPcmClkDown);
dbg_info(" bPcmFrame = 0x%02x\n",
port->sDioCommon.bPcmFrame);
dbg_info(" bPcmHighPeriod = 0x%02x\n",
port->sDioCommon.bPcmHighPeriod);
}
if (update & MCDRV_DIO0_DIR_UPDATE_FLAG) {
dbg_info("sDir.wSrcRate = 0x%04x\n",
port->sDir.wSrcRate);
dbg_info(" sDaFormat.bBitSel = 0x%02x\n",
port->sDir.sDaFormat.bBitSel);
dbg_info(" bMode = 0x%02x\n",
port->sDir.sDaFormat.bMode);
dbg_info(" sPcmFormat.bMono = 0x%02x\n",
port->sDir.sPcmFormat.bMono);
dbg_info(" bOrder = 0x%02x\n",
port->sDir.sPcmFormat.bOrder);
dbg_info(" bLaw = 0x%02x\n",
port->sDir.sPcmFormat.bLaw);
dbg_info(" bBitSel = 0x%02x\n",
port->sDir.sPcmFormat.bBitSel);
dbg_info(" abSlot[] = {0x%02x, 0x%02x}\n",
port->sDir.abSlot[0], port->sDir.abSlot[1]);
}
if (update & MCDRV_DIO0_DIT_UPDATE_FLAG) {
dbg_info("sDit.wSrcRate = 0x%04x\n",
port->sDit.wSrcRate);
dbg_info(" sDaFormat.bBitSel = 0x%02x\n",
port->sDit.sDaFormat.bBitSel);
dbg_info(" bMode = 0x%02x\n",
port->sDit.sDaFormat.bMode);
dbg_info(" sPcmFormat.bMono = 0x%02x\n",
port->sDit.sPcmFormat.bMono);
dbg_info(" bOrder = 0x%02x\n",
port->sDit.sPcmFormat.bOrder);
dbg_info(" bLaw = 0x%02x\n",
port->sDit.sPcmFormat.bLaw);
dbg_info(" bBitSel = 0x%02x\n",
port->sDit.sPcmFormat.bBitSel);
dbg_info(" abSlot[] = {0x%02x, 0x%02x}\n",
port->sDit.abSlot[0], port->sDit.abSlot[1]);
}
}
}
static void mc1n2_dump_dac_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_DAC_INFO *info = (MCDRV_DAC_INFO *)pvPrm;
if (dPrm & MCDRV_DAC_MSWP_UPDATE_FLAG) {
dbg_info("bMasterSwap = 0x%02x\n", info->bMasterSwap);
}
if (dPrm & MCDRV_DAC_VSWP_UPDATE_FLAG) {
dbg_info("bVoiceSwap = 0x%02x\n", info->bVoiceSwap);
}
if (dPrm & MCDRV_DAC_HPF_UPDATE_FLAG) {
dbg_info("bDcCut = 0x%02x\n", info->bDcCut);
}
}
static void mc1n2_dump_adc_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_ADC_INFO *info = (MCDRV_ADC_INFO *)pvPrm;
if (dPrm & MCDRV_ADCADJ_UPDATE_FLAG) {
dbg_info("bAgcAdjust = 0x%02x\n", info->bAgcAdjust);
}
if (dPrm & MCDRV_ADCAGC_UPDATE_FLAG) {
dbg_info("bAgcOn = 0x%02x\n", info->bAgcOn);
}
if (dPrm & MCDRV_ADCMONO_UPDATE_FLAG) {
dbg_info("bMono = 0x%02x\n", info->bMono);
}
}
static void mc1n2_dump_sp_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_SP_INFO *info = (MCDRV_SP_INFO *)pvPrm;
dbg_info("bSwap = 0x%02x\n", info->bSwap);
}
static void mc1n2_dump_dng_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_DNG_INFO *info = (MCDRV_DNG_INFO *)pvPrm;
if (dPrm & MCDRV_DNGSW_HP_UPDATE_FLAG) {
dbg_info("HP:abOnOff = 0x%02x\n", info->abOnOff[0]);
}
if (dPrm & MCDRV_DNGTHRES_HP_UPDATE_FLAG) {
dbg_info("HP:abThreshold = 0x%02x\n", info->abThreshold[0]);
}
if (dPrm & MCDRV_DNGHOLD_HP_UPDATE_FLAG) {
dbg_info("HP:abHold = 0x%02x\n", info->abHold[0]);
}
if (dPrm & MCDRV_DNGATK_HP_UPDATE_FLAG) {
dbg_info("HP:abAttack = 0x%02x\n", info->abAttack[0]);
}
if (dPrm & MCDRV_DNGREL_HP_UPDATE_FLAG) {
dbg_info("HP:abRelease = 0x%02x\n", info->abRelease[0]);
}
if (dPrm & MCDRV_DNGTARGET_HP_UPDATE_FLAG) {
dbg_info("HP:abTarget = 0x%02x\n", info->abTarget[0]);
}
if (dPrm & MCDRV_DNGSW_SP_UPDATE_FLAG) {
dbg_info("SP:abOnOff = 0x%02x\n", info->abOnOff[1]);
}
if (dPrm & MCDRV_DNGTHRES_SP_UPDATE_FLAG) {
dbg_info("SP:abThreshold = 0x%02x\n", info->abThreshold[1]);
}
if (dPrm & MCDRV_DNGHOLD_SP_UPDATE_FLAG) {
dbg_info("SP:abHold = 0x%02x\n", info->abHold[1]);
}
if (dPrm & MCDRV_DNGATK_SP_UPDATE_FLAG) {
dbg_info("SP:abAttack = 0x%02x\n", info->abAttack[1]);
}
if (dPrm & MCDRV_DNGREL_SP_UPDATE_FLAG) {
dbg_info("SP:abRelease = 0x%02x\n", info->abRelease[1]);
}
if (dPrm & MCDRV_DNGTARGET_SP_UPDATE_FLAG) {
dbg_info("SP:abTarget = 0x%02x\n", info->abTarget[1]);
}
if (dPrm & MCDRV_DNGSW_RC_UPDATE_FLAG) {
dbg_info("RC:abOnOff = 0x%02x\n", info->abOnOff[2]);
}
if (dPrm & MCDRV_DNGTHRES_RC_UPDATE_FLAG) {
dbg_info("RC:abThreshold = 0x%02x\n", info->abThreshold[2]);
}
if (dPrm & MCDRV_DNGHOLD_RC_UPDATE_FLAG) {
dbg_info("RC:abHold = 0x%02x\n", info->abHold[2]);
}
if (dPrm & MCDRV_DNGATK_RC_UPDATE_FLAG) {
dbg_info("RC:abAttack = 0x%02x\n", info->abAttack[2]);
}
if (dPrm & MCDRV_DNGREL_RC_UPDATE_FLAG) {
dbg_info("RC:abRelease = 0x%02x\n", info->abRelease[2]);
}
if (dPrm & MCDRV_DNGTARGET_RC_UPDATE_FLAG) {
dbg_info("RC:abTarget = 0x%02x\n", info->abTarget[2]);
}
}
static void mc1n2_dump_ae_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_AE_INFO *info = (MCDRV_AE_INFO *)pvPrm;
dbg_info("bOnOff = 0x%02x\n", info->bOnOff);
if (dPrm & MCDRV_AEUPDATE_FLAG_BEX) {
mc1n2_dump_array("abBex", info->abBex, BEX_PARAM_SIZE);
}
if (dPrm & MCDRV_AEUPDATE_FLAG_WIDE) {
mc1n2_dump_array("abWide", info->abWide, WIDE_PARAM_SIZE);
}
if (dPrm & MCDRV_AEUPDATE_FLAG_DRC) {
mc1n2_dump_array("abDrc", info->abDrc, DRC_PARAM_SIZE);
}
if (dPrm & MCDRV_AEUPDATE_FLAG_EQ5) {
mc1n2_dump_array("abEq5", info->abEq5, EQ5_PARAM_SIZE);
}
if (dPrm & MCDRV_AEUPDATE_FLAG_EQ3) {
mc1n2_dump_array("abEq3", info->abEq3, EQ5_PARAM_SIZE);
}
}
static void mc1n2_dump_pdm_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_PDM_INFO *info = (MCDRV_PDM_INFO *)pvPrm;
if (dPrm & MCDRV_PDMCLK_UPDATE_FLAG) {
dbg_info("bClk = 0x%02x\n", info->bClk);
}
if (dPrm & MCDRV_PDMADJ_UPDATE_FLAG) {
dbg_info("bAgcAdjust = 0x%02x\n", info->bAgcAdjust);
}
if (dPrm & MCDRV_PDMAGC_UPDATE_FLAG) {
dbg_info("bAgcOn = 0x%02x\n", info->bAgcOn);
}
if (dPrm & MCDRV_PDMEDGE_UPDATE_FLAG) {
dbg_info("bPdmEdge = 0x%02x\n", info->bPdmEdge);
}
if (dPrm & MCDRV_PDMWAIT_UPDATE_FLAG) {
dbg_info("bPdmWait = 0x%02x\n", info->bPdmWait);
}
if (dPrm & MCDRV_PDMSEL_UPDATE_FLAG) {
dbg_info("bPdmSel = 0x%02x\n", info->bPdmSel);
}
if (dPrm & MCDRV_PDMMONO_UPDATE_FLAG) {
dbg_info("bMono = 0x%02x\n", info->bMono);
}
}
static void mc1n2_dump_clksw_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_CLKSW_INFO *info = (MCDRV_CLKSW_INFO *)pvPrm;
dbg_info("bClkSrc = 0x%02x\n", info->bClkSrc);
}
static void mc1n2_dump_syseq_info(const void *pvPrm, UINT32 dPrm)
{
MCDRV_SYSEQ_INFO *info = (MCDRV_SYSEQ_INFO *)pvPrm;
int i;
if (dPrm & MCDRV_SYSEQ_ONOFF_UPDATE_FLAG) {
dbg_info("bOnOff = 0x%02x\n", info->bOnOff);
}
if (dPrm & MCDRV_SYSEQ_PARAM_UPDATE_FLAG) {
for (i = 0; i < 15; i++){
dbg_info("abParam[%d] = 0x%02x\n", i, info->abParam[i]);
}
}
}
struct mc1n2_dump_func {
char *name;
void (*func)(const void *, UINT32);
};
struct mc1n2_dump_func mc1n2_dump_func_map[] = {
{"MCDRV_INIT", NULL},
{"MCDRV_TERM", NULL},
{"MCDRV_READ_REG", mc1n2_dump_reg_info},
{"MCDRV_WRITE_REG", NULL},
{"MCDRV_GET_PATH", NULL},
{"MCDRV_SET_PATH", mc1n2_dump_path_info},
{"MCDRV_GET_VOLUME", NULL},
{"MCDRV_SET_VOLUME", mc1n2_dump_vol_info},
{"MCDRV_GET_DIGITALIO", NULL},
{"MCDRV_SET_DIGITALIO", mc1n2_dump_dio_info},
{"MCDRV_GET_DAC", NULL},
{"MCDRV_SET_DAC", mc1n2_dump_dac_info},
{"MCDRV_GET_ADC", NULL},
{"MCDRV_SET_ADC", mc1n2_dump_adc_info},
{"MCDRV_GET_SP", NULL},
{"MCDRV_SET_SP", mc1n2_dump_sp_info},
{"MCDRV_GET_DNG", NULL},
{"MCDRV_SET_DNG", mc1n2_dump_dng_info},
{"MCDRV_SET_AUDIOENGINE", mc1n2_dump_ae_info},
{"MCDRV_SET_AUDIOENGINE_EX", NULL},
{"MCDRV_SET_CDSP", NULL},
{"MCDRV_GET_CDSP_PARAM", NULL},
{"MCDRV_SET_CDSP_PARAM", NULL},
{"MCDRV_REGISTER_CDSP_CB", NULL},
{"MCDRV_GET_PDM", NULL},
{"MCDRV_SET_PDM", mc1n2_dump_pdm_info},
{"MCDRV_SET_DTMF", NULL},
{"MCDRV_CONFIG_GP", NULL},
{"MCDRV_MASK_GP", NULL},
{"MCDRV_GETSET_GP", NULL},
{"MCDRV_GET_PEAK", NULL},
{"MCDRV_IRQ", NULL},
{"MCDRV_UPDATE_CLOCK", NULL},
{"MCDRV_SWITCH_CLOCK", mc1n2_dump_clksw_info},
{"MCDRV_GET_SYSEQ", NULL},
{"MCDRV_SET_SYSEQ", mc1n2_dump_syseq_info},
};
SINT32 McDrv_Ctrl_dbg(UINT32 dCmd, void *pvPrm, UINT32 dPrm)
{
SINT32 err;
dbg_info("calling %s:\n", mc1n2_dump_func_map[dCmd].name);
if (mc1n2_dump_func_map[dCmd].func) {
mc1n2_dump_func_map[dCmd].func(pvPrm, dPrm);
}
err = McDrv_Ctrl(dCmd, pvPrm, dPrm);
dbg_info("err = %ld\n", err);
return err;
}
#endif /* CONFIG_SND_SOC_MC1N2_DEBUG */
| gpl-2.0 |
bjdooks-ct/amlogic-kernel | fs/cifs/xattr.c | 757 | 12378 | /*
* fs/cifs/xattr.c
*
* Copyright (c) International Business Machines Corp., 2003, 2007
* Author(s): Steve French (sfrench@us.ibm.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/posix_acl_xattr.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include "cifsfs.h"
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
#include "cifs_unicode.h"
#define MAX_EA_VALUE_SIZE 65535
#define CIFS_XATTR_DOS_ATTRIB "user.DosAttrib"
#define CIFS_XATTR_CIFS_ACL "system.cifs_acl"
/* BB need to add server (Samba e.g) support for security and trusted prefix */
int cifs_removexattr(struct dentry *direntry, const char *ea_name)
{
int rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path = NULL;
if (direntry == NULL)
return -EIO;
if (d_really_is_negative(direntry))
return -EIO;
sb = d_inode(direntry)->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto remove_ea_exit;
}
if (ea_name == NULL) {
cifs_dbg(FYI, "Null xattr names not supported\n");
} else if (strncmp(ea_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)
&& (strncmp(ea_name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN))) {
cifs_dbg(FYI,
"illegal xattr request %s (only user namespace supported)\n",
ea_name);
/* BB what if no namespace prefix? */
/* Should we just pass them to server, except for
system and perhaps security prefixes? */
} else {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto remove_ea_exit;
ea_name += XATTR_USER_PREFIX_LEN; /* skip past user. prefix */
if (pTcon->ses->server->ops->set_EA)
rc = pTcon->ses->server->ops->set_EA(xid, pTcon,
full_path, ea_name, NULL, (__u16)0,
cifs_sb->local_nls, cifs_remap(cifs_sb));
}
remove_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
int cifs_setxattr(struct dentry *direntry, const char *ea_name,
const void *ea_value, size_t value_size, int flags)
{
int rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path;
if (direntry == NULL)
return -EIO;
if (d_really_is_negative(direntry))
return -EIO;
sb = d_inode(direntry)->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto set_ea_exit;
}
/* return dos attributes as pseudo xattr */
/* return alt name if available as pseudo attr */
/* if proc/fs/cifs/streamstoxattr is set then
search server for EAs or streams to
returns as xattrs */
if (value_size > MAX_EA_VALUE_SIZE) {
cifs_dbg(FYI, "size of EA value too large\n");
rc = -EOPNOTSUPP;
goto set_ea_exit;
}
if (ea_name == NULL) {
cifs_dbg(FYI, "Null xattr names not supported\n");
} else if (strncmp(ea_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)
== 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto set_ea_exit;
if (strncmp(ea_name, CIFS_XATTR_DOS_ATTRIB, 14) == 0)
cifs_dbg(FYI, "attempt to set cifs inode metadata\n");
ea_name += XATTR_USER_PREFIX_LEN; /* skip past user. prefix */
if (pTcon->ses->server->ops->set_EA)
rc = pTcon->ses->server->ops->set_EA(xid, pTcon,
full_path, ea_name, ea_value, (__u16)value_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN)
== 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto set_ea_exit;
ea_name += XATTR_OS2_PREFIX_LEN; /* skip past os2. prefix */
if (pTcon->ses->server->ops->set_EA)
rc = pTcon->ses->server->ops->set_EA(xid, pTcon,
full_path, ea_name, ea_value, (__u16)value_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, CIFS_XATTR_CIFS_ACL,
strlen(CIFS_XATTR_CIFS_ACL)) == 0) {
#ifdef CONFIG_CIFS_ACL
struct cifs_ntsd *pacl;
pacl = kmalloc(value_size, GFP_KERNEL);
if (!pacl) {
rc = -ENOMEM;
} else {
memcpy(pacl, ea_value, value_size);
if (pTcon->ses->server->ops->set_acl)
rc = pTcon->ses->server->ops->set_acl(pacl,
value_size, d_inode(direntry),
full_path, CIFS_ACL_DACL);
else
rc = -EOPNOTSUPP;
if (rc == 0) /* force revalidate of the inode */
CIFS_I(d_inode(direntry))->time = 0;
kfree(pacl);
}
#else
cifs_dbg(FYI, "Set CIFS ACL not supported yet\n");
#endif /* CONFIG_CIFS_ACL */
} else {
int temp;
temp = strncmp(ea_name, POSIX_ACL_XATTR_ACCESS,
strlen(POSIX_ACL_XATTR_ACCESS));
if (temp == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBSetPosixACL(xid, pTcon, full_path,
ea_value, (const int)value_size,
ACL_TYPE_ACCESS, cifs_sb->local_nls,
cifs_remap(cifs_sb));
cifs_dbg(FYI, "set POSIX ACL rc %d\n", rc);
#else
cifs_dbg(FYI, "set POSIX ACL not supported\n");
#endif
} else if (strncmp(ea_name, POSIX_ACL_XATTR_DEFAULT,
strlen(POSIX_ACL_XATTR_DEFAULT)) == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBSetPosixACL(xid, pTcon, full_path,
ea_value, (const int)value_size,
ACL_TYPE_DEFAULT, cifs_sb->local_nls,
cifs_remap(cifs_sb));
cifs_dbg(FYI, "set POSIX default ACL rc %d\n", rc);
#else
cifs_dbg(FYI, "set default POSIX ACL not supported\n");
#endif
} else {
cifs_dbg(FYI, "illegal xattr request %s (only user namespace supported)\n",
ea_name);
/* BB what if no namespace prefix? */
/* Should we just pass them to server, except for
system and perhaps security prefixes? */
}
}
set_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
ssize_t cifs_getxattr(struct dentry *direntry, const char *ea_name,
void *ea_value, size_t buf_size)
{
ssize_t rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path;
if (direntry == NULL)
return -EIO;
if (d_really_is_negative(direntry))
return -EIO;
sb = d_inode(direntry)->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto get_ea_exit;
}
/* return dos attributes as pseudo xattr */
/* return alt name if available as pseudo attr */
if (ea_name == NULL) {
cifs_dbg(FYI, "Null xattr names not supported\n");
} else if (strncmp(ea_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)
== 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto get_ea_exit;
if (strncmp(ea_name, CIFS_XATTR_DOS_ATTRIB, 14) == 0) {
cifs_dbg(FYI, "attempt to query cifs inode metadata\n");
/* revalidate/getattr then populate from inode */
} /* BB add else when above is implemented */
ea_name += XATTR_USER_PREFIX_LEN; /* skip past user. prefix */
if (pTcon->ses->server->ops->query_all_EAs)
rc = pTcon->ses->server->ops->query_all_EAs(xid, pTcon,
full_path, ea_name, ea_value, buf_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN) == 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto get_ea_exit;
ea_name += XATTR_OS2_PREFIX_LEN; /* skip past os2. prefix */
if (pTcon->ses->server->ops->query_all_EAs)
rc = pTcon->ses->server->ops->query_all_EAs(xid, pTcon,
full_path, ea_name, ea_value, buf_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, POSIX_ACL_XATTR_ACCESS,
strlen(POSIX_ACL_XATTR_ACCESS)) == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBGetPosixACL(xid, pTcon, full_path,
ea_value, buf_size, ACL_TYPE_ACCESS,
cifs_sb->local_nls,
cifs_remap(cifs_sb));
#else
cifs_dbg(FYI, "Query POSIX ACL not supported yet\n");
#endif /* CONFIG_CIFS_POSIX */
} else if (strncmp(ea_name, POSIX_ACL_XATTR_DEFAULT,
strlen(POSIX_ACL_XATTR_DEFAULT)) == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBGetPosixACL(xid, pTcon, full_path,
ea_value, buf_size, ACL_TYPE_DEFAULT,
cifs_sb->local_nls,
cifs_remap(cifs_sb));
#else
cifs_dbg(FYI, "Query POSIX default ACL not supported yet\n");
#endif /* CONFIG_CIFS_POSIX */
} else if (strncmp(ea_name, CIFS_XATTR_CIFS_ACL,
strlen(CIFS_XATTR_CIFS_ACL)) == 0) {
#ifdef CONFIG_CIFS_ACL
u32 acllen;
struct cifs_ntsd *pacl;
if (pTcon->ses->server->ops->get_acl == NULL)
goto get_ea_exit; /* rc already EOPNOTSUPP */
pacl = pTcon->ses->server->ops->get_acl(cifs_sb,
d_inode(direntry), full_path, &acllen);
if (IS_ERR(pacl)) {
rc = PTR_ERR(pacl);
cifs_dbg(VFS, "%s: error %zd getting sec desc\n",
__func__, rc);
} else {
if (ea_value) {
if (acllen > buf_size)
acllen = -ERANGE;
else
memcpy(ea_value, pacl, acllen);
}
rc = acllen;
kfree(pacl);
}
#else
cifs_dbg(FYI, "Query CIFS ACL not supported yet\n");
#endif /* CONFIG_CIFS_ACL */
} else if (strncmp(ea_name,
XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) == 0) {
cifs_dbg(FYI, "Trusted xattr namespace not supported yet\n");
} else if (strncmp(ea_name,
XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) == 0) {
cifs_dbg(FYI, "Security xattr namespace not supported yet\n");
} else
cifs_dbg(FYI,
"illegal xattr request %s (only user namespace supported)\n",
ea_name);
/* We could add an additional check for streams ie
if proc/fs/cifs/streamstoxattr is set then
search server for EAs or streams to
returns as xattrs */
if (rc == -EINVAL)
rc = -EOPNOTSUPP;
get_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
ssize_t cifs_listxattr(struct dentry *direntry, char *data, size_t buf_size)
{
ssize_t rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path;
if (direntry == NULL)
return -EIO;
if (d_really_is_negative(direntry))
return -EIO;
sb = d_inode(direntry)->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
return -EOPNOTSUPP;
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto list_ea_exit;
}
/* return dos attributes as pseudo xattr */
/* return alt name if available as pseudo attr */
/* if proc/fs/cifs/streamstoxattr is set then
search server for EAs or streams to
returns as xattrs */
if (pTcon->ses->server->ops->query_all_EAs)
rc = pTcon->ses->server->ops->query_all_EAs(xid, pTcon,
full_path, NULL, data, buf_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
list_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
| gpl-2.0 |
BobZhome/android_kernel_gelato | drivers/net/wireless/ath/ath5k/pcu.c | 757 | 22959 | /*
* Copyright (c) 2004-2008 Reyk Floeter <reyk@openbsd.org>
* Copyright (c) 2006-2008 Nick Kossifidis <mickflemm@gmail.com>
* Copyright (c) 2007-2008 Matthew W. S. Bell <mentor@madwifi.org>
* Copyright (c) 2007-2008 Luis Rodriguez <mcgrof@winlab.rutgers.edu>
* Copyright (c) 2007-2008 Pavel Roskin <proski@gnu.org>
* Copyright (c) 2007-2008 Jiri Slaby <jirislaby@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/*********************************\
* Protocol Control Unit Functions *
\*********************************/
#include <asm/unaligned.h>
#include "ath5k.h"
#include "reg.h"
#include "debug.h"
#include "base.h"
/*******************\
* Generic functions *
\*******************/
/**
* ath5k_hw_set_opmode - Set PCU operating mode
*
* @ah: The &struct ath5k_hw
* @op_mode: &enum nl80211_iftype operating mode
*
* Initialize PCU for the various operating modes (AP/STA etc)
*/
int ath5k_hw_set_opmode(struct ath5k_hw *ah, enum nl80211_iftype op_mode)
{
struct ath_common *common = ath5k_hw_common(ah);
u32 pcu_reg, beacon_reg, low_id, high_id;
ATH5K_DBG(ah->ah_sc, ATH5K_DEBUG_MODE, "mode %d\n", op_mode);
/* Preserve rest settings */
pcu_reg = ath5k_hw_reg_read(ah, AR5K_STA_ID1) & 0xffff0000;
pcu_reg &= ~(AR5K_STA_ID1_ADHOC | AR5K_STA_ID1_AP
| AR5K_STA_ID1_KEYSRCH_MODE
| (ah->ah_version == AR5K_AR5210 ?
(AR5K_STA_ID1_PWR_SV | AR5K_STA_ID1_NO_PSPOLL) : 0));
beacon_reg = 0;
ATH5K_TRACE(ah->ah_sc);
switch (op_mode) {
case NL80211_IFTYPE_ADHOC:
pcu_reg |= AR5K_STA_ID1_ADHOC | AR5K_STA_ID1_KEYSRCH_MODE;
beacon_reg |= AR5K_BCR_ADHOC;
if (ah->ah_version == AR5K_AR5210)
pcu_reg |= AR5K_STA_ID1_NO_PSPOLL;
else
AR5K_REG_ENABLE_BITS(ah, AR5K_CFG, AR5K_CFG_IBSS);
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_MESH_POINT:
pcu_reg |= AR5K_STA_ID1_AP | AR5K_STA_ID1_KEYSRCH_MODE;
beacon_reg |= AR5K_BCR_AP;
if (ah->ah_version == AR5K_AR5210)
pcu_reg |= AR5K_STA_ID1_NO_PSPOLL;
else
AR5K_REG_DISABLE_BITS(ah, AR5K_CFG, AR5K_CFG_IBSS);
break;
case NL80211_IFTYPE_STATION:
pcu_reg |= AR5K_STA_ID1_KEYSRCH_MODE
| (ah->ah_version == AR5K_AR5210 ?
AR5K_STA_ID1_PWR_SV : 0);
case NL80211_IFTYPE_MONITOR:
pcu_reg |= AR5K_STA_ID1_KEYSRCH_MODE
| (ah->ah_version == AR5K_AR5210 ?
AR5K_STA_ID1_NO_PSPOLL : 0);
break;
default:
return -EINVAL;
}
/*
* Set PCU registers
*/
low_id = get_unaligned_le32(common->macaddr);
high_id = get_unaligned_le16(common->macaddr + 4);
ath5k_hw_reg_write(ah, low_id, AR5K_STA_ID0);
ath5k_hw_reg_write(ah, pcu_reg | high_id, AR5K_STA_ID1);
/*
* Set Beacon Control Register on 5210
*/
if (ah->ah_version == AR5K_AR5210)
ath5k_hw_reg_write(ah, beacon_reg, AR5K_BCR);
return 0;
}
/**
* ath5k_hw_update - Update MIB counters (mac layer statistics)
*
* @ah: The &struct ath5k_hw
*
* Reads MIB counters from PCU and updates sw statistics. Is called after a
* MIB interrupt, because one of these counters might have reached their maximum
* and triggered the MIB interrupt, to let us read and clear the counter.
*
* Is called in interrupt context!
*/
void ath5k_hw_update_mib_counters(struct ath5k_hw *ah)
{
struct ath5k_statistics *stats = &ah->ah_sc->stats;
/* Read-And-Clear */
stats->ack_fail += ath5k_hw_reg_read(ah, AR5K_ACK_FAIL);
stats->rts_fail += ath5k_hw_reg_read(ah, AR5K_RTS_FAIL);
stats->rts_ok += ath5k_hw_reg_read(ah, AR5K_RTS_OK);
stats->fcs_error += ath5k_hw_reg_read(ah, AR5K_FCS_FAIL);
stats->beacons += ath5k_hw_reg_read(ah, AR5K_BEACON_CNT);
}
/**
* ath5k_hw_set_ack_bitrate - set bitrate for ACKs
*
* @ah: The &struct ath5k_hw
* @high: Flag to determine if we want to use high transmition rate
* for ACKs or not
*
* If high flag is set, we tell hw to use a set of control rates based on
* the current transmition rate (check out control_rates array inside reset.c).
* If not hw just uses the lowest rate available for the current modulation
* scheme being used (1Mbit for CCK and 6Mbits for OFDM).
*/
void ath5k_hw_set_ack_bitrate_high(struct ath5k_hw *ah, bool high)
{
if (ah->ah_version != AR5K_AR5212)
return;
else {
u32 val = AR5K_STA_ID1_BASE_RATE_11B | AR5K_STA_ID1_ACKCTS_6MB;
if (high)
AR5K_REG_DISABLE_BITS(ah, AR5K_STA_ID1, val);
else
AR5K_REG_ENABLE_BITS(ah, AR5K_STA_ID1, val);
}
}
/******************\
* ACK/CTS Timeouts *
\******************/
/**
* ath5k_hw_set_ack_timeout - Set ACK timeout on PCU
*
* @ah: The &struct ath5k_hw
* @timeout: Timeout in usec
*/
static int ath5k_hw_set_ack_timeout(struct ath5k_hw *ah, unsigned int timeout)
{
ATH5K_TRACE(ah->ah_sc);
if (ath5k_hw_clocktoh(ah, AR5K_REG_MS(0xffffffff, AR5K_TIME_OUT_ACK))
<= timeout)
return -EINVAL;
AR5K_REG_WRITE_BITS(ah, AR5K_TIME_OUT, AR5K_TIME_OUT_ACK,
ath5k_hw_htoclock(ah, timeout));
return 0;
}
/**
* ath5k_hw_set_cts_timeout - Set CTS timeout on PCU
*
* @ah: The &struct ath5k_hw
* @timeout: Timeout in usec
*/
static int ath5k_hw_set_cts_timeout(struct ath5k_hw *ah, unsigned int timeout)
{
ATH5K_TRACE(ah->ah_sc);
if (ath5k_hw_clocktoh(ah, AR5K_REG_MS(0xffffffff, AR5K_TIME_OUT_CTS))
<= timeout)
return -EINVAL;
AR5K_REG_WRITE_BITS(ah, AR5K_TIME_OUT, AR5K_TIME_OUT_CTS,
ath5k_hw_htoclock(ah, timeout));
return 0;
}
/**
* ath5k_hw_htoclock - Translate usec to hw clock units
*
* @ah: The &struct ath5k_hw
* @usec: value in microseconds
*/
unsigned int ath5k_hw_htoclock(struct ath5k_hw *ah, unsigned int usec)
{
return usec * ath5k_hw_get_clockrate(ah);
}
/**
* ath5k_hw_clocktoh - Translate hw clock units to usec
* @clock: value in hw clock units
*/
unsigned int ath5k_hw_clocktoh(struct ath5k_hw *ah, unsigned int clock)
{
return clock / ath5k_hw_get_clockrate(ah);
}
/**
* ath5k_hw_get_clockrate - Get the clock rate for current mode
*
* @ah: The &struct ath5k_hw
*/
unsigned int ath5k_hw_get_clockrate(struct ath5k_hw *ah)
{
struct ieee80211_channel *channel = ah->ah_current_channel;
int clock;
if (channel->hw_value & CHANNEL_5GHZ)
clock = 40; /* 802.11a */
else if (channel->hw_value & CHANNEL_CCK)
clock = 22; /* 802.11b */
else
clock = 44; /* 802.11g */
/* Clock rate in turbo modes is twice the normal rate */
if (channel->hw_value & CHANNEL_TURBO)
clock *= 2;
return clock;
}
/**
* ath5k_hw_get_default_slottime - Get the default slot time for current mode
*
* @ah: The &struct ath5k_hw
*/
static unsigned int ath5k_hw_get_default_slottime(struct ath5k_hw *ah)
{
struct ieee80211_channel *channel = ah->ah_current_channel;
if (channel->hw_value & CHANNEL_TURBO)
return 6; /* both turbo modes */
if (channel->hw_value & CHANNEL_CCK)
return 20; /* 802.11b */
return 9; /* 802.11 a/g */
}
/**
* ath5k_hw_get_default_sifs - Get the default SIFS for current mode
*
* @ah: The &struct ath5k_hw
*/
static unsigned int ath5k_hw_get_default_sifs(struct ath5k_hw *ah)
{
struct ieee80211_channel *channel = ah->ah_current_channel;
if (channel->hw_value & CHANNEL_TURBO)
return 8; /* both turbo modes */
if (channel->hw_value & CHANNEL_5GHZ)
return 16; /* 802.11a */
return 10; /* 802.11 b/g */
}
/**
* ath5k_hw_set_lladdr - Set station id
*
* @ah: The &struct ath5k_hw
* @mac: The card's mac address
*
* Set station id on hw using the provided mac address
*/
int ath5k_hw_set_lladdr(struct ath5k_hw *ah, const u8 *mac)
{
struct ath_common *common = ath5k_hw_common(ah);
u32 low_id, high_id;
u32 pcu_reg;
ATH5K_TRACE(ah->ah_sc);
/* Set new station ID */
memcpy(common->macaddr, mac, ETH_ALEN);
pcu_reg = ath5k_hw_reg_read(ah, AR5K_STA_ID1) & 0xffff0000;
low_id = get_unaligned_le32(mac);
high_id = get_unaligned_le16(mac + 4);
ath5k_hw_reg_write(ah, low_id, AR5K_STA_ID0);
ath5k_hw_reg_write(ah, pcu_reg | high_id, AR5K_STA_ID1);
return 0;
}
/**
* ath5k_hw_set_associd - Set BSSID for association
*
* @ah: The &struct ath5k_hw
* @bssid: BSSID
* @assoc_id: Assoc id
*
* Sets the BSSID which trigers the "SME Join" operation
*/
void ath5k_hw_set_associd(struct ath5k_hw *ah)
{
struct ath_common *common = ath5k_hw_common(ah);
u16 tim_offset = 0;
/*
* Set simple BSSID mask on 5212
*/
if (ah->ah_version == AR5K_AR5212)
ath_hw_setbssidmask(common);
/*
* Set BSSID which triggers the "SME Join" operation
*/
ath5k_hw_reg_write(ah,
get_unaligned_le32(common->curbssid),
AR5K_BSS_ID0);
ath5k_hw_reg_write(ah,
get_unaligned_le16(common->curbssid + 4) |
((common->curaid & 0x3fff) << AR5K_BSS_ID1_AID_S),
AR5K_BSS_ID1);
if (common->curaid == 0) {
ath5k_hw_disable_pspoll(ah);
return;
}
AR5K_REG_WRITE_BITS(ah, AR5K_BEACON, AR5K_BEACON_TIM,
tim_offset ? tim_offset + 4 : 0);
ath5k_hw_enable_pspoll(ah, NULL, 0);
}
void ath5k_hw_set_bssid_mask(struct ath5k_hw *ah, const u8 *mask)
{
struct ath_common *common = ath5k_hw_common(ah);
ATH5K_TRACE(ah->ah_sc);
/* Cache bssid mask so that we can restore it
* on reset */
memcpy(common->bssidmask, mask, ETH_ALEN);
if (ah->ah_version == AR5K_AR5212)
ath_hw_setbssidmask(common);
}
/************\
* RX Control *
\************/
/**
* ath5k_hw_start_rx_pcu - Start RX engine
*
* @ah: The &struct ath5k_hw
*
* Starts RX engine on PCU so that hw can process RXed frames
* (ACK etc).
*
* NOTE: RX DMA should be already enabled using ath5k_hw_start_rx_dma
*/
void ath5k_hw_start_rx_pcu(struct ath5k_hw *ah)
{
ATH5K_TRACE(ah->ah_sc);
AR5K_REG_DISABLE_BITS(ah, AR5K_DIAG_SW, AR5K_DIAG_SW_DIS_RX);
}
/**
* at5k_hw_stop_rx_pcu - Stop RX engine
*
* @ah: The &struct ath5k_hw
*
* Stops RX engine on PCU
*
* TODO: Detach ANI here
*/
void ath5k_hw_stop_rx_pcu(struct ath5k_hw *ah)
{
ATH5K_TRACE(ah->ah_sc);
AR5K_REG_ENABLE_BITS(ah, AR5K_DIAG_SW, AR5K_DIAG_SW_DIS_RX);
}
/*
* Set multicast filter
*/
void ath5k_hw_set_mcast_filter(struct ath5k_hw *ah, u32 filter0, u32 filter1)
{
ATH5K_TRACE(ah->ah_sc);
/* Set the multicat filter */
ath5k_hw_reg_write(ah, filter0, AR5K_MCAST_FILTER0);
ath5k_hw_reg_write(ah, filter1, AR5K_MCAST_FILTER1);
}
/**
* ath5k_hw_get_rx_filter - Get current rx filter
*
* @ah: The &struct ath5k_hw
*
* Returns the RX filter by reading rx filter and
* phy error filter registers. RX filter is used
* to set the allowed frame types that PCU will accept
* and pass to the driver. For a list of frame types
* check out reg.h.
*/
u32 ath5k_hw_get_rx_filter(struct ath5k_hw *ah)
{
u32 data, filter = 0;
ATH5K_TRACE(ah->ah_sc);
filter = ath5k_hw_reg_read(ah, AR5K_RX_FILTER);
/*Radar detection for 5212*/
if (ah->ah_version == AR5K_AR5212) {
data = ath5k_hw_reg_read(ah, AR5K_PHY_ERR_FIL);
if (data & AR5K_PHY_ERR_FIL_RADAR)
filter |= AR5K_RX_FILTER_RADARERR;
if (data & (AR5K_PHY_ERR_FIL_OFDM | AR5K_PHY_ERR_FIL_CCK))
filter |= AR5K_RX_FILTER_PHYERR;
}
return filter;
}
/**
* ath5k_hw_set_rx_filter - Set rx filter
*
* @ah: The &struct ath5k_hw
* @filter: RX filter mask (see reg.h)
*
* Sets RX filter register and also handles PHY error filter
* register on 5212 and newer chips so that we have proper PHY
* error reporting.
*/
void ath5k_hw_set_rx_filter(struct ath5k_hw *ah, u32 filter)
{
u32 data = 0;
ATH5K_TRACE(ah->ah_sc);
/* Set PHY error filter register on 5212*/
if (ah->ah_version == AR5K_AR5212) {
if (filter & AR5K_RX_FILTER_RADARERR)
data |= AR5K_PHY_ERR_FIL_RADAR;
if (filter & AR5K_RX_FILTER_PHYERR)
data |= AR5K_PHY_ERR_FIL_OFDM | AR5K_PHY_ERR_FIL_CCK;
}
/*
* The AR5210 uses promiscous mode to detect radar activity
*/
if (ah->ah_version == AR5K_AR5210 &&
(filter & AR5K_RX_FILTER_RADARERR)) {
filter &= ~AR5K_RX_FILTER_RADARERR;
filter |= AR5K_RX_FILTER_PROM;
}
/*Zero length DMA (phy error reporting) */
if (data)
AR5K_REG_ENABLE_BITS(ah, AR5K_RXCFG, AR5K_RXCFG_ZLFDMA);
else
AR5K_REG_DISABLE_BITS(ah, AR5K_RXCFG, AR5K_RXCFG_ZLFDMA);
/*Write RX Filter register*/
ath5k_hw_reg_write(ah, filter & 0xff, AR5K_RX_FILTER);
/*Write PHY error filter register on 5212*/
if (ah->ah_version == AR5K_AR5212)
ath5k_hw_reg_write(ah, data, AR5K_PHY_ERR_FIL);
}
/****************\
* Beacon control *
\****************/
#define ATH5K_MAX_TSF_READ 10
/**
* ath5k_hw_get_tsf64 - Get the full 64bit TSF
*
* @ah: The &struct ath5k_hw
*
* Returns the current TSF
*/
u64 ath5k_hw_get_tsf64(struct ath5k_hw *ah)
{
u32 tsf_lower, tsf_upper1, tsf_upper2;
int i;
/*
* While reading TSF upper and then lower part, the clock is still
* counting (or jumping in case of IBSS merge) so we might get
* inconsistent values. To avoid this, we read the upper part again
* and check it has not been changed. We make the hypothesis that a
* maximum of 3 changes can happens in a row (we use 10 as a safe
* value).
*
* Impact on performance is pretty small, since in most cases, only
* 3 register reads are needed.
*/
tsf_upper1 = ath5k_hw_reg_read(ah, AR5K_TSF_U32);
for (i = 0; i < ATH5K_MAX_TSF_READ; i++) {
tsf_lower = ath5k_hw_reg_read(ah, AR5K_TSF_L32);
tsf_upper2 = ath5k_hw_reg_read(ah, AR5K_TSF_U32);
if (tsf_upper2 == tsf_upper1)
break;
tsf_upper1 = tsf_upper2;
}
WARN_ON( i == ATH5K_MAX_TSF_READ );
ATH5K_TRACE(ah->ah_sc);
return (((u64)tsf_upper1 << 32) | tsf_lower);
}
/**
* ath5k_hw_set_tsf64 - Set a new 64bit TSF
*
* @ah: The &struct ath5k_hw
* @tsf64: The new 64bit TSF
*
* Sets the new TSF
*/
void ath5k_hw_set_tsf64(struct ath5k_hw *ah, u64 tsf64)
{
ATH5K_TRACE(ah->ah_sc);
ath5k_hw_reg_write(ah, tsf64 & 0xffffffff, AR5K_TSF_L32);
ath5k_hw_reg_write(ah, (tsf64 >> 32) & 0xffffffff, AR5K_TSF_U32);
}
/**
* ath5k_hw_reset_tsf - Force a TSF reset
*
* @ah: The &struct ath5k_hw
*
* Forces a TSF reset on PCU
*/
void ath5k_hw_reset_tsf(struct ath5k_hw *ah)
{
u32 val;
ATH5K_TRACE(ah->ah_sc);
val = ath5k_hw_reg_read(ah, AR5K_BEACON) | AR5K_BEACON_RESET_TSF;
/*
* Each write to the RESET_TSF bit toggles a hardware internal
* signal to reset TSF, but if left high it will cause a TSF reset
* on the next chip reset as well. Thus we always write the value
* twice to clear the signal.
*/
ath5k_hw_reg_write(ah, val, AR5K_BEACON);
ath5k_hw_reg_write(ah, val, AR5K_BEACON);
}
/*
* Initialize beacon timers
*/
void ath5k_hw_init_beacon(struct ath5k_hw *ah, u32 next_beacon, u32 interval)
{
u32 timer1, timer2, timer3;
ATH5K_TRACE(ah->ah_sc);
/*
* Set the additional timers by mode
*/
switch (ah->ah_sc->opmode) {
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_STATION:
/* In STA mode timer1 is used as next wakeup
* timer and timer2 as next CFP duration start
* timer. Both in 1/8TUs. */
/* TODO: PCF handling */
if (ah->ah_version == AR5K_AR5210) {
timer1 = 0xffffffff;
timer2 = 0xffffffff;
} else {
timer1 = 0x0000ffff;
timer2 = 0x0007ffff;
}
/* Mark associated AP as PCF incapable for now */
AR5K_REG_DISABLE_BITS(ah, AR5K_STA_ID1, AR5K_STA_ID1_PCF);
break;
case NL80211_IFTYPE_ADHOC:
AR5K_REG_ENABLE_BITS(ah, AR5K_TXCFG, AR5K_TXCFG_ADHOC_BCN_ATIM);
default:
/* On non-STA modes timer1 is used as next DMA
* beacon alert (DBA) timer and timer2 as next
* software beacon alert. Both in 1/8TUs. */
timer1 = (next_beacon - AR5K_TUNE_DMA_BEACON_RESP) << 3;
timer2 = (next_beacon - AR5K_TUNE_SW_BEACON_RESP) << 3;
break;
}
/* Timer3 marks the end of our ATIM window
* a zero length window is not allowed because
* we 'll get no beacons */
timer3 = next_beacon + (ah->ah_atim_window ? ah->ah_atim_window : 1);
/*
* Set the beacon register and enable all timers.
*/
/* When in AP or Mesh Point mode zero timer0 to start TSF */
if (ah->ah_sc->opmode == NL80211_IFTYPE_AP ||
ah->ah_sc->opmode == NL80211_IFTYPE_MESH_POINT)
ath5k_hw_reg_write(ah, 0, AR5K_TIMER0);
ath5k_hw_reg_write(ah, next_beacon, AR5K_TIMER0);
ath5k_hw_reg_write(ah, timer1, AR5K_TIMER1);
ath5k_hw_reg_write(ah, timer2, AR5K_TIMER2);
ath5k_hw_reg_write(ah, timer3, AR5K_TIMER3);
/* Force a TSF reset if requested and enable beacons */
if (interval & AR5K_BEACON_RESET_TSF)
ath5k_hw_reset_tsf(ah);
ath5k_hw_reg_write(ah, interval & (AR5K_BEACON_PERIOD |
AR5K_BEACON_ENABLE),
AR5K_BEACON);
/* Flush any pending BMISS interrupts on ISR by
* performing a clear-on-write operation on PISR
* register for the BMISS bit (writing a bit on
* ISR togles a reset for that bit and leaves
* the rest bits intact) */
if (ah->ah_version == AR5K_AR5210)
ath5k_hw_reg_write(ah, AR5K_ISR_BMISS, AR5K_ISR);
else
ath5k_hw_reg_write(ah, AR5K_ISR_BMISS, AR5K_PISR);
/* TODO: Set enchanced sleep registers on AR5212
* based on vif->bss_conf params, until then
* disable power save reporting.*/
AR5K_REG_DISABLE_BITS(ah, AR5K_STA_ID1, AR5K_STA_ID1_PWR_SV);
}
/*********************\
* Key table functions *
\*********************/
/*
* Reset a key entry on the table
*/
int ath5k_hw_reset_key(struct ath5k_hw *ah, u16 entry)
{
unsigned int i, type;
u16 micentry = entry + AR5K_KEYTABLE_MIC_OFFSET;
ATH5K_TRACE(ah->ah_sc);
AR5K_ASSERT_ENTRY(entry, AR5K_KEYTABLE_SIZE);
type = ath5k_hw_reg_read(ah, AR5K_KEYTABLE_TYPE(entry));
for (i = 0; i < AR5K_KEYCACHE_SIZE; i++)
ath5k_hw_reg_write(ah, 0, AR5K_KEYTABLE_OFF(entry, i));
/* Reset associated MIC entry if TKIP
* is enabled located at offset (entry + 64) */
if (type == AR5K_KEYTABLE_TYPE_TKIP) {
AR5K_ASSERT_ENTRY(micentry, AR5K_KEYTABLE_SIZE);
for (i = 0; i < AR5K_KEYCACHE_SIZE / 2 ; i++)
ath5k_hw_reg_write(ah, 0,
AR5K_KEYTABLE_OFF(micentry, i));
}
/*
* Set NULL encryption on AR5212+
*
* Note: AR5K_KEYTABLE_TYPE -> AR5K_KEYTABLE_OFF(entry, 5)
* AR5K_KEYTABLE_TYPE_NULL -> 0x00000007
*
* Note2: Windows driver (ndiswrapper) sets this to
* 0x00000714 instead of 0x00000007
*/
if (ah->ah_version >= AR5K_AR5211) {
ath5k_hw_reg_write(ah, AR5K_KEYTABLE_TYPE_NULL,
AR5K_KEYTABLE_TYPE(entry));
if (type == AR5K_KEYTABLE_TYPE_TKIP) {
ath5k_hw_reg_write(ah, AR5K_KEYTABLE_TYPE_NULL,
AR5K_KEYTABLE_TYPE(micentry));
}
}
return 0;
}
static
int ath5k_keycache_type(const struct ieee80211_key_conf *key)
{
switch (key->alg) {
case ALG_TKIP:
return AR5K_KEYTABLE_TYPE_TKIP;
case ALG_CCMP:
return AR5K_KEYTABLE_TYPE_CCM;
case ALG_WEP:
if (key->keylen == WLAN_KEY_LEN_WEP40)
return AR5K_KEYTABLE_TYPE_40;
else if (key->keylen == WLAN_KEY_LEN_WEP104)
return AR5K_KEYTABLE_TYPE_104;
return -EINVAL;
default:
return -EINVAL;
}
return -EINVAL;
}
/*
* Set a key entry on the table
*/
int ath5k_hw_set_key(struct ath5k_hw *ah, u16 entry,
const struct ieee80211_key_conf *key, const u8 *mac)
{
unsigned int i;
int keylen;
__le32 key_v[5] = {};
__le32 key0 = 0, key1 = 0;
__le32 *rxmic, *txmic;
int keytype;
u16 micentry = entry + AR5K_KEYTABLE_MIC_OFFSET;
bool is_tkip;
const u8 *key_ptr;
ATH5K_TRACE(ah->ah_sc);
is_tkip = (key->alg == ALG_TKIP);
/*
* key->keylen comes in from mac80211 in bytes.
* TKIP is 128 bit + 128 bit mic
*/
keylen = (is_tkip) ? (128 / 8) : key->keylen;
if (entry > AR5K_KEYTABLE_SIZE ||
(is_tkip && micentry > AR5K_KEYTABLE_SIZE))
return -EOPNOTSUPP;
if (unlikely(keylen > 16))
return -EOPNOTSUPP;
keytype = ath5k_keycache_type(key);
if (keytype < 0)
return keytype;
/*
* each key block is 6 bytes wide, written as pairs of
* alternating 32 and 16 bit le values.
*/
key_ptr = key->key;
for (i = 0; keylen >= 6; keylen -= 6) {
memcpy(&key_v[i], key_ptr, 6);
i += 2;
key_ptr += 6;
}
if (keylen)
memcpy(&key_v[i], key_ptr, keylen);
/* intentionally corrupt key until mic is installed */
if (is_tkip) {
key0 = key_v[0] = ~key_v[0];
key1 = key_v[1] = ~key_v[1];
}
for (i = 0; i < ARRAY_SIZE(key_v); i++)
ath5k_hw_reg_write(ah, le32_to_cpu(key_v[i]),
AR5K_KEYTABLE_OFF(entry, i));
ath5k_hw_reg_write(ah, keytype, AR5K_KEYTABLE_TYPE(entry));
if (is_tkip) {
/* Install rx/tx MIC */
rxmic = (__le32 *) &key->key[16];
txmic = (__le32 *) &key->key[24];
if (ah->ah_combined_mic) {
key_v[0] = rxmic[0];
key_v[1] = cpu_to_le32(le32_to_cpu(txmic[0]) >> 16);
key_v[2] = rxmic[1];
key_v[3] = cpu_to_le32(le32_to_cpu(txmic[0]) & 0xffff);
key_v[4] = txmic[1];
} else {
key_v[0] = rxmic[0];
key_v[1] = 0;
key_v[2] = rxmic[1];
key_v[3] = 0;
key_v[4] = 0;
}
for (i = 0; i < ARRAY_SIZE(key_v); i++)
ath5k_hw_reg_write(ah, le32_to_cpu(key_v[i]),
AR5K_KEYTABLE_OFF(micentry, i));
ath5k_hw_reg_write(ah, AR5K_KEYTABLE_TYPE_NULL,
AR5K_KEYTABLE_TYPE(micentry));
ath5k_hw_reg_write(ah, 0, AR5K_KEYTABLE_MAC0(micentry));
ath5k_hw_reg_write(ah, 0, AR5K_KEYTABLE_MAC1(micentry));
/* restore first 2 words of key */
ath5k_hw_reg_write(ah, le32_to_cpu(~key0),
AR5K_KEYTABLE_OFF(entry, 0));
ath5k_hw_reg_write(ah, le32_to_cpu(~key1),
AR5K_KEYTABLE_OFF(entry, 1));
}
return ath5k_hw_set_key_lladdr(ah, entry, mac);
}
int ath5k_hw_set_key_lladdr(struct ath5k_hw *ah, u16 entry, const u8 *mac)
{
u32 low_id, high_id;
ATH5K_TRACE(ah->ah_sc);
/* Invalid entry (key table overflow) */
AR5K_ASSERT_ENTRY(entry, AR5K_KEYTABLE_SIZE);
/*
* MAC may be NULL if it's a broadcast key. In this case no need to
* to compute get_unaligned_le32 and get_unaligned_le16 as we
* already know it.
*/
if (!mac) {
low_id = 0xffffffff;
high_id = 0xffff | AR5K_KEYTABLE_VALID;
} else {
low_id = get_unaligned_le32(mac);
high_id = get_unaligned_le16(mac + 4) | AR5K_KEYTABLE_VALID;
}
ath5k_hw_reg_write(ah, low_id, AR5K_KEYTABLE_MAC0(entry));
ath5k_hw_reg_write(ah, high_id, AR5K_KEYTABLE_MAC1(entry));
return 0;
}
/**
* ath5k_hw_set_coverage_class - Set IEEE 802.11 coverage class
*
* @ah: The &struct ath5k_hw
* @coverage_class: IEEE 802.11 coverage class number
*
* Sets slot time, ACK timeout and CTS timeout for given coverage class.
*/
void ath5k_hw_set_coverage_class(struct ath5k_hw *ah, u8 coverage_class)
{
/* As defined by IEEE 802.11-2007 17.3.8.6 */
int slot_time = ath5k_hw_get_default_slottime(ah) + 3 * coverage_class;
int ack_timeout = ath5k_hw_get_default_sifs(ah) + slot_time;
int cts_timeout = ack_timeout;
ath5k_hw_set_slot_time(ah, slot_time);
ath5k_hw_set_ack_timeout(ah, ack_timeout);
ath5k_hw_set_cts_timeout(ah, cts_timeout);
ah->ah_coverage_class = coverage_class;
}
| gpl-2.0 |
anasanzari/Cowcopy | drivers/scsi/esas2r/esas2r_main.c | 757 | 48778 | /*
* linux/drivers/scsi/esas2r/esas2r_main.c
* For use with ATTO ExpressSAS R6xx SAS/SATA RAID controllers
*
* Copyright (c) 2001-2013 ATTO Technology, Inc.
* (mailto:linuxdrivers@attotech.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.
*
* NO WARRANTY
* THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
* LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
* solely responsible for determining the appropriateness of using and
* distributing the Program and assumes all risks associated with its
* exercise of rights under this Agreement, including but not limited to
* the risks and costs of program errors, damage to or loss of data,
* programs or equipment, and unavailability or interruption of operations.
*
* DISCLAIMER OF LIABILITY
* NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
* HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#include "esas2r.h"
MODULE_DESCRIPTION(ESAS2R_DRVR_NAME ": " ESAS2R_LONGNAME " driver");
MODULE_AUTHOR("ATTO Technology, Inc.");
MODULE_LICENSE("GPL");
MODULE_VERSION(ESAS2R_VERSION_STR);
/* global definitions */
static int found_adapters;
struct esas2r_adapter *esas2r_adapters[MAX_ADAPTERS];
#define ESAS2R_VDA_EVENT_PORT1 54414
#define ESAS2R_VDA_EVENT_PORT2 54415
#define ESAS2R_VDA_EVENT_SOCK_COUNT 2
static struct esas2r_adapter *esas2r_adapter_from_kobj(struct kobject *kobj)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct Scsi_Host *host = class_to_shost(dev);
return (struct esas2r_adapter *)host->hostdata;
}
static ssize_t read_fw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_read_fw(a, buf, off, count);
}
static ssize_t write_fw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_write_fw(a, buf, off, count);
}
static ssize_t read_fs(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_read_fs(a, buf, off, count);
}
static ssize_t write_fs(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min(sizeof(struct esas2r_ioctl_fs), count);
int result = 0;
result = esas2r_write_fs(a, buf, off, count);
if (result < 0)
result = 0;
return length;
}
static ssize_t read_vda(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_read_vda(a, buf, off, count);
}
static ssize_t write_vda(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_write_vda(a, buf, off, count);
}
static ssize_t read_live_nvram(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min_t(size_t, sizeof(struct esas2r_sas_nvram), PAGE_SIZE);
memcpy(buf, a->nvram, length);
return length;
}
static ssize_t write_live_nvram(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
struct esas2r_request *rq;
int result = -EFAULT;
rq = esas2r_alloc_request(a);
if (rq == NULL)
return -ENOMEM;
if (esas2r_write_params(a, rq, (struct esas2r_sas_nvram *)buf))
result = count;
esas2r_free_request(a, rq);
return result;
}
static ssize_t read_default_nvram(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
esas2r_nvram_get_defaults(a, (struct esas2r_sas_nvram *)buf);
return sizeof(struct esas2r_sas_nvram);
}
static ssize_t read_hw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min_t(size_t, sizeof(struct atto_ioctl), PAGE_SIZE);
if (!a->local_atto_ioctl)
return -ENOMEM;
if (handle_hba_ioctl(a, a->local_atto_ioctl) != IOCTL_SUCCESS)
return -ENOMEM;
memcpy(buf, a->local_atto_ioctl, length);
return length;
}
static ssize_t write_hw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min(sizeof(struct atto_ioctl), count);
if (!a->local_atto_ioctl) {
a->local_atto_ioctl = kzalloc(sizeof(struct atto_ioctl),
GFP_KERNEL);
if (a->local_atto_ioctl == NULL) {
esas2r_log(ESAS2R_LOG_WARN,
"write_hw kzalloc failed for %d bytes",
sizeof(struct atto_ioctl));
return -ENOMEM;
}
}
memset(a->local_atto_ioctl, 0, sizeof(struct atto_ioctl));
memcpy(a->local_atto_ioctl, buf, length);
return length;
}
#define ESAS2R_RW_BIN_ATTR(_name) \
struct bin_attribute bin_attr_ ## _name = { \
.attr = \
{ .name = __stringify(_name), .mode = S_IRUSR | S_IWUSR }, \
.size = 0, \
.read = read_ ## _name, \
.write = write_ ## _name }
ESAS2R_RW_BIN_ATTR(fw);
ESAS2R_RW_BIN_ATTR(fs);
ESAS2R_RW_BIN_ATTR(vda);
ESAS2R_RW_BIN_ATTR(hw);
ESAS2R_RW_BIN_ATTR(live_nvram);
struct bin_attribute bin_attr_default_nvram = {
.attr = { .name = "default_nvram", .mode = S_IRUGO },
.size = 0,
.read = read_default_nvram,
.write = NULL
};
static struct scsi_host_template driver_template = {
.module = THIS_MODULE,
.show_info = esas2r_show_info,
.name = ESAS2R_LONGNAME,
.release = esas2r_release,
.info = esas2r_info,
.ioctl = esas2r_ioctl,
.queuecommand = esas2r_queuecommand,
.eh_abort_handler = esas2r_eh_abort,
.eh_device_reset_handler = esas2r_device_reset,
.eh_bus_reset_handler = esas2r_bus_reset,
.eh_host_reset_handler = esas2r_host_reset,
.eh_target_reset_handler = esas2r_target_reset,
.can_queue = 128,
.this_id = -1,
.sg_tablesize = SCSI_MAX_SG_SEGMENTS,
.cmd_per_lun =
ESAS2R_DEFAULT_CMD_PER_LUN,
.present = 0,
.unchecked_isa_dma = 0,
.use_clustering = ENABLE_CLUSTERING,
.emulated = 0,
.proc_name = ESAS2R_DRVR_NAME,
.change_queue_depth = scsi_change_queue_depth,
.max_sectors = 0xFFFF,
.use_blk_tags = 1,
};
int sgl_page_size = 512;
module_param(sgl_page_size, int, 0);
MODULE_PARM_DESC(sgl_page_size,
"Scatter/gather list (SGL) page size in number of S/G "
"entries. If your application is doing a lot of very large "
"transfers, you may want to increase the SGL page size. "
"Default 512.");
int num_sg_lists = 1024;
module_param(num_sg_lists, int, 0);
MODULE_PARM_DESC(num_sg_lists,
"Number of scatter/gather lists. Default 1024.");
int sg_tablesize = SCSI_MAX_SG_SEGMENTS;
module_param(sg_tablesize, int, 0);
MODULE_PARM_DESC(sg_tablesize,
"Maximum number of entries in a scatter/gather table.");
int num_requests = 256;
module_param(num_requests, int, 0);
MODULE_PARM_DESC(num_requests,
"Number of requests. Default 256.");
int num_ae_requests = 4;
module_param(num_ae_requests, int, 0);
MODULE_PARM_DESC(num_ae_requests,
"Number of VDA asynchromous event requests. Default 4.");
int cmd_per_lun = ESAS2R_DEFAULT_CMD_PER_LUN;
module_param(cmd_per_lun, int, 0);
MODULE_PARM_DESC(cmd_per_lun,
"Maximum number of commands per LUN. Default "
DEFINED_NUM_TO_STR(ESAS2R_DEFAULT_CMD_PER_LUN) ".");
int can_queue = 128;
module_param(can_queue, int, 0);
MODULE_PARM_DESC(can_queue,
"Maximum number of commands per adapter. Default 128.");
int esas2r_max_sectors = 0xFFFF;
module_param(esas2r_max_sectors, int, 0);
MODULE_PARM_DESC(esas2r_max_sectors,
"Maximum number of disk sectors in a single data transfer. "
"Default 65535 (largest possible setting).");
int interrupt_mode = 1;
module_param(interrupt_mode, int, 0);
MODULE_PARM_DESC(interrupt_mode,
"Defines the interrupt mode to use. 0 for legacy"
", 1 for MSI. Default is MSI (1).");
static struct pci_device_id
esas2r_pci_table[] = {
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x0049,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004A,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004B,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004C,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004D,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004E,
0,
0, 0 },
{ 0, 0, 0, 0,
0,
0, 0 }
};
MODULE_DEVICE_TABLE(pci, esas2r_pci_table);
static int
esas2r_probe(struct pci_dev *pcid, const struct pci_device_id *id);
static void
esas2r_remove(struct pci_dev *pcid);
static struct pci_driver
esas2r_pci_driver = {
.name = ESAS2R_DRVR_NAME,
.id_table = esas2r_pci_table,
.probe = esas2r_probe,
.remove = esas2r_remove,
.suspend = esas2r_suspend,
.resume = esas2r_resume,
};
static int esas2r_probe(struct pci_dev *pcid,
const struct pci_device_id *id)
{
struct Scsi_Host *host = NULL;
struct esas2r_adapter *a;
int err;
size_t host_alloc_size = sizeof(struct esas2r_adapter)
+ ((num_requests) +
1) * sizeof(struct esas2r_request);
esas2r_log_dev(ESAS2R_LOG_DEBG, &(pcid->dev),
"esas2r_probe() 0x%02x 0x%02x 0x%02x 0x%02x",
pcid->vendor,
pcid->device,
pcid->subsystem_vendor,
pcid->subsystem_device);
esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
"before pci_enable_device() "
"enable_cnt: %d",
pcid->enable_cnt.counter);
err = pci_enable_device(pcid);
if (err != 0) {
esas2r_log_dev(ESAS2R_LOG_CRIT, &(pcid->dev),
"pci_enable_device() FAIL (%d)",
err);
return -ENODEV;
}
esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
"pci_enable_device() OK");
esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
"after pci_enable_device() enable_cnt: %d",
pcid->enable_cnt.counter);
host = scsi_host_alloc(&driver_template, host_alloc_size);
if (host == NULL) {
esas2r_log(ESAS2R_LOG_CRIT, "scsi_host_alloc() FAIL");
return -ENODEV;
}
memset(host->hostdata, 0, host_alloc_size);
a = (struct esas2r_adapter *)host->hostdata;
esas2r_log(ESAS2R_LOG_INFO, "scsi_host_alloc() OK host: %p", host);
/* override max LUN and max target id */
host->max_id = ESAS2R_MAX_ID + 1;
host->max_lun = 255;
/* we can handle 16-byte CDbs */
host->max_cmd_len = 16;
host->can_queue = can_queue;
host->cmd_per_lun = cmd_per_lun;
host->this_id = host->max_id + 1;
host->max_channel = 0;
host->unique_id = found_adapters;
host->sg_tablesize = sg_tablesize;
host->max_sectors = esas2r_max_sectors;
/* set to bus master for BIOses that don't do it for us */
esas2r_log(ESAS2R_LOG_INFO, "pci_set_master() called");
pci_set_master(pcid);
if (!esas2r_init_adapter(host, pcid, found_adapters)) {
esas2r_log(ESAS2R_LOG_CRIT,
"unable to initialize device at PCI bus %x:%x",
pcid->bus->number,
pcid->devfn);
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"scsi_host_put() called");
scsi_host_put(host);
return 0;
}
esas2r_log(ESAS2R_LOG_INFO, "pci_set_drvdata(%p, %p) called", pcid,
host->hostdata);
pci_set_drvdata(pcid, host);
esas2r_log(ESAS2R_LOG_INFO, "scsi_add_host() called");
err = scsi_add_host(host, &pcid->dev);
if (err) {
esas2r_log(ESAS2R_LOG_CRIT, "scsi_add_host returned %d", err);
esas2r_log_dev(ESAS2R_LOG_CRIT, &(host->shost_gendev),
"scsi_add_host() FAIL");
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"scsi_host_put() called");
scsi_host_put(host);
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"pci_set_drvdata(%p, NULL) called",
pcid);
pci_set_drvdata(pcid, NULL);
return -ENODEV;
}
esas2r_fw_event_on(a);
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"scsi_scan_host() called");
scsi_scan_host(host);
/* Add sysfs binary files */
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_fw))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: fw");
else
a->sysfs_fw_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_fs))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: fs");
else
a->sysfs_fs_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_vda))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: vda");
else
a->sysfs_vda_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_hw))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: hw");
else
a->sysfs_hw_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_live_nvram))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: live_nvram");
else
a->sysfs_live_nvram_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj,
&bin_attr_default_nvram))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: default_nvram");
else
a->sysfs_default_nvram_created = 1;
found_adapters++;
return 0;
}
static void esas2r_remove(struct pci_dev *pdev)
{
struct Scsi_Host *host;
int index;
if (pdev == NULL) {
esas2r_log(ESAS2R_LOG_WARN, "esas2r_remove pdev==NULL");
return;
}
host = pci_get_drvdata(pdev);
if (host == NULL) {
/*
* this can happen if pci_set_drvdata was already called
* to clear the host pointer. if this is the case, we
* are okay; this channel has already been cleaned up.
*/
return;
}
esas2r_log_dev(ESAS2R_LOG_INFO, &(pdev->dev),
"esas2r_remove(%p) called; "
"host:%p", pdev,
host);
index = esas2r_cleanup(host);
if (index < 0)
esas2r_log_dev(ESAS2R_LOG_WARN, &(pdev->dev),
"unknown host in %s",
__func__);
found_adapters--;
/* if this was the last adapter, clean up the rest of the driver */
if (found_adapters == 0)
esas2r_cleanup(NULL);
}
static int __init esas2r_init(void)
{
int i;
esas2r_log(ESAS2R_LOG_INFO, "%s called", __func__);
/* verify valid parameters */
if (can_queue < 1) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: can_queue must be at least 1, value "
"forced.");
can_queue = 1;
} else if (can_queue > 2048) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: can_queue must be no larger than 2048, "
"value forced.");
can_queue = 2048;
}
if (cmd_per_lun < 1) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: cmd_per_lun must be at least 1, value "
"forced.");
cmd_per_lun = 1;
} else if (cmd_per_lun > 2048) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: cmd_per_lun must be no larger than "
"2048, value forced.");
cmd_per_lun = 2048;
}
if (sg_tablesize < 32) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: sg_tablesize must be at least 32, "
"value forced.");
sg_tablesize = 32;
}
if (esas2r_max_sectors < 1) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: esas2r_max_sectors must be at least "
"1, value forced.");
esas2r_max_sectors = 1;
} else if (esas2r_max_sectors > 0xffff) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: esas2r_max_sectors must be no larger "
"than 0xffff, value forced.");
esas2r_max_sectors = 0xffff;
}
sgl_page_size &= ~(ESAS2R_SGL_ALIGN - 1);
if (sgl_page_size < SGL_PG_SZ_MIN)
sgl_page_size = SGL_PG_SZ_MIN;
else if (sgl_page_size > SGL_PG_SZ_MAX)
sgl_page_size = SGL_PG_SZ_MAX;
if (num_sg_lists < NUM_SGL_MIN)
num_sg_lists = NUM_SGL_MIN;
else if (num_sg_lists > NUM_SGL_MAX)
num_sg_lists = NUM_SGL_MAX;
if (num_requests < NUM_REQ_MIN)
num_requests = NUM_REQ_MIN;
else if (num_requests > NUM_REQ_MAX)
num_requests = NUM_REQ_MAX;
if (num_ae_requests < NUM_AE_MIN)
num_ae_requests = NUM_AE_MIN;
else if (num_ae_requests > NUM_AE_MAX)
num_ae_requests = NUM_AE_MAX;
/* set up other globals */
for (i = 0; i < MAX_ADAPTERS; i++)
esas2r_adapters[i] = NULL;
/* initialize */
driver_template.module = THIS_MODULE;
if (pci_register_driver(&esas2r_pci_driver) != 0)
esas2r_log(ESAS2R_LOG_CRIT, "pci_register_driver FAILED");
else
esas2r_log(ESAS2R_LOG_INFO, "pci_register_driver() OK");
if (!found_adapters) {
pci_unregister_driver(&esas2r_pci_driver);
esas2r_cleanup(NULL);
esas2r_log(ESAS2R_LOG_CRIT,
"driver will not be loaded because no ATTO "
"%s devices were found",
ESAS2R_DRVR_NAME);
return -1;
} else {
esas2r_log(ESAS2R_LOG_INFO, "found %d adapters",
found_adapters);
}
return 0;
}
/* Handle ioctl calls to "/proc/scsi/esas2r/ATTOnode" */
static const struct file_operations esas2r_proc_fops = {
.compat_ioctl = esas2r_proc_ioctl,
.unlocked_ioctl = esas2r_proc_ioctl,
};
static struct Scsi_Host *esas2r_proc_host;
static int esas2r_proc_major;
long esas2r_proc_ioctl(struct file *fp, unsigned int cmd, unsigned long arg)
{
return esas2r_ioctl_handler(esas2r_proc_host->hostdata,
(int)cmd, (void __user *)arg);
}
static void __exit esas2r_exit(void)
{
esas2r_log(ESAS2R_LOG_INFO, "%s called", __func__);
if (esas2r_proc_major > 0) {
esas2r_log(ESAS2R_LOG_INFO, "unregister proc");
remove_proc_entry(ATTONODE_NAME,
esas2r_proc_host->hostt->proc_dir);
unregister_chrdev(esas2r_proc_major, ESAS2R_DRVR_NAME);
esas2r_proc_major = 0;
}
esas2r_log(ESAS2R_LOG_INFO, "pci_unregister_driver() called");
pci_unregister_driver(&esas2r_pci_driver);
}
int esas2r_show_info(struct seq_file *m, struct Scsi_Host *sh)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)sh->hostdata;
struct esas2r_target *t;
int dev_count = 0;
esas2r_log(ESAS2R_LOG_DEBG, "esas2r_show_info (%p,%d)", m, sh->host_no);
seq_printf(m, ESAS2R_LONGNAME "\n"
"Driver version: "ESAS2R_VERSION_STR "\n"
"Flash version: %s\n"
"Firmware version: %s\n"
"Copyright "ESAS2R_COPYRIGHT_YEARS "\n"
"http://www.attotech.com\n"
"\n",
a->flash_rev,
a->fw_rev[0] ? a->fw_rev : "(none)");
seq_printf(m, "Adapter information:\n"
"--------------------\n"
"Model: %s\n"
"SAS address: %02X%02X%02X%02X:%02X%02X%02X%02X\n",
esas2r_get_model_name(a),
a->nvram->sas_addr[0],
a->nvram->sas_addr[1],
a->nvram->sas_addr[2],
a->nvram->sas_addr[3],
a->nvram->sas_addr[4],
a->nvram->sas_addr[5],
a->nvram->sas_addr[6],
a->nvram->sas_addr[7]);
seq_puts(m, "\n"
"Discovered devices:\n"
"\n"
" # Target ID\n"
"---------------\n");
for (t = a->targetdb; t < a->targetdb_end; t++)
if (t->buffered_target_state == TS_PRESENT) {
seq_printf(m, " %3d %3d\n",
++dev_count,
(u16)(uintptr_t)(t - a->targetdb));
}
if (dev_count == 0)
seq_puts(m, "none\n");
seq_putc(m, '\n');
return 0;
}
int esas2r_release(struct Scsi_Host *sh)
{
esas2r_log_dev(ESAS2R_LOG_INFO, &(sh->shost_gendev),
"esas2r_release() called");
esas2r_cleanup(sh);
if (sh->irq)
free_irq(sh->irq, NULL);
scsi_unregister(sh);
return 0;
}
const char *esas2r_info(struct Scsi_Host *sh)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)sh->hostdata;
static char esas2r_info_str[512];
esas2r_log_dev(ESAS2R_LOG_INFO, &(sh->shost_gendev),
"esas2r_info() called");
/*
* if we haven't done so already, register as a char driver
* and stick a node under "/proc/scsi/esas2r/ATTOnode"
*/
if (esas2r_proc_major <= 0) {
esas2r_proc_host = sh;
esas2r_proc_major = register_chrdev(0, ESAS2R_DRVR_NAME,
&esas2r_proc_fops);
esas2r_log_dev(ESAS2R_LOG_DEBG, &(sh->shost_gendev),
"register_chrdev (major %d)",
esas2r_proc_major);
if (esas2r_proc_major > 0) {
struct proc_dir_entry *pde;
pde = proc_create(ATTONODE_NAME, 0,
sh->hostt->proc_dir,
&esas2r_proc_fops);
if (!pde) {
esas2r_log_dev(ESAS2R_LOG_WARN,
&(sh->shost_gendev),
"failed to create_proc_entry");
esas2r_proc_major = -1;
}
}
}
sprintf(esas2r_info_str,
ESAS2R_LONGNAME " (bus 0x%02X, device 0x%02X, IRQ 0x%02X)"
" driver version: "ESAS2R_VERSION_STR " firmware version: "
"%s\n",
a->pcid->bus->number, a->pcid->devfn, a->pcid->irq,
a->fw_rev[0] ? a->fw_rev : "(none)");
return esas2r_info_str;
}
/* Callback for building a request scatter/gather list */
static u32 get_physaddr_from_sgc(struct esas2r_sg_context *sgc, u64 *addr)
{
u32 len;
if (likely(sgc->cur_offset == sgc->exp_offset)) {
/*
* the normal case: caller used all bytes from previous call, so
* expected offset is the same as the current offset.
*/
if (sgc->sgel_count < sgc->num_sgel) {
/* retrieve next segment, except for first time */
if (sgc->exp_offset > (u8 *)0) {
/* advance current segment */
sgc->cur_sgel = sg_next(sgc->cur_sgel);
++(sgc->sgel_count);
}
len = sg_dma_len(sgc->cur_sgel);
(*addr) = sg_dma_address(sgc->cur_sgel);
/* save the total # bytes returned to caller so far */
sgc->exp_offset += len;
} else {
len = 0;
}
} else if (sgc->cur_offset < sgc->exp_offset) {
/*
* caller did not use all bytes from previous call. need to
* compute the address based on current segment.
*/
len = sg_dma_len(sgc->cur_sgel);
(*addr) = sg_dma_address(sgc->cur_sgel);
sgc->exp_offset -= len;
/* calculate PA based on prev segment address and offsets */
*addr = *addr +
(sgc->cur_offset - sgc->exp_offset);
sgc->exp_offset += len;
/* re-calculate length based on offset */
len = lower_32_bits(
sgc->exp_offset - sgc->cur_offset);
} else { /* if ( sgc->cur_offset > sgc->exp_offset ) */
/*
* we don't expect the caller to skip ahead.
* cur_offset will never exceed the len we return
*/
len = 0;
}
return len;
}
int esas2r_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
struct esas2r_request *rq;
struct esas2r_sg_context sgc;
unsigned bufflen;
/* Assume success, if it fails we will fix the result later. */
cmd->result = DID_OK << 16;
if (unlikely(test_bit(AF_DEGRADED_MODE, &a->flags))) {
cmd->result = DID_NO_CONNECT << 16;
cmd->scsi_done(cmd);
return 0;
}
rq = esas2r_alloc_request(a);
if (unlikely(rq == NULL)) {
esas2r_debug("esas2r_alloc_request failed");
return SCSI_MLQUEUE_HOST_BUSY;
}
rq->cmd = cmd;
bufflen = scsi_bufflen(cmd);
if (likely(bufflen != 0)) {
if (cmd->sc_data_direction == DMA_TO_DEVICE)
rq->vrq->scsi.flags |= cpu_to_le32(FCP_CMND_WRD);
else if (cmd->sc_data_direction == DMA_FROM_DEVICE)
rq->vrq->scsi.flags |= cpu_to_le32(FCP_CMND_RDD);
}
memcpy(rq->vrq->scsi.cdb, cmd->cmnd, cmd->cmd_len);
rq->vrq->scsi.length = cpu_to_le32(bufflen);
rq->target_id = cmd->device->id;
rq->vrq->scsi.flags |= cpu_to_le32(cmd->device->lun);
rq->sense_buf = cmd->sense_buffer;
rq->sense_len = SCSI_SENSE_BUFFERSIZE;
esas2r_sgc_init(&sgc, a, rq, NULL);
sgc.length = bufflen;
sgc.cur_offset = NULL;
sgc.cur_sgel = scsi_sglist(cmd);
sgc.exp_offset = NULL;
sgc.num_sgel = scsi_dma_map(cmd);
sgc.sgel_count = 0;
if (unlikely(sgc.num_sgel < 0)) {
esas2r_free_request(a, rq);
return SCSI_MLQUEUE_HOST_BUSY;
}
sgc.get_phys_addr = (PGETPHYSADDR)get_physaddr_from_sgc;
if (unlikely(!esas2r_build_sg_list(a, rq, &sgc))) {
scsi_dma_unmap(cmd);
esas2r_free_request(a, rq);
return SCSI_MLQUEUE_HOST_BUSY;
}
esas2r_debug("start request %p to %d:%d\n", rq, (int)cmd->device->id,
(int)cmd->device->lun);
esas2r_start_request(a, rq);
return 0;
}
static void complete_task_management_request(struct esas2r_adapter *a,
struct esas2r_request *rq)
{
(*rq->task_management_status_ptr) = rq->req_stat;
esas2r_free_request(a, rq);
}
/**
* Searches the specified queue for the specified queue for the command
* to abort.
*
* @param [in] a
* @param [in] abort_request
* @param [in] cmd
* t
* @return 0 on failure, 1 if command was not found, 2 if command was found
*/
static int esas2r_check_active_queue(struct esas2r_adapter *a,
struct esas2r_request **abort_request,
struct scsi_cmnd *cmd,
struct list_head *queue)
{
bool found = false;
struct esas2r_request *ar = *abort_request;
struct esas2r_request *rq;
struct list_head *element, *next;
list_for_each_safe(element, next, queue) {
rq = list_entry(element, struct esas2r_request, req_list);
if (rq->cmd == cmd) {
/* Found the request. See what to do with it. */
if (queue == &a->active_list) {
/*
* We are searching the active queue, which
* means that we need to send an abort request
* to the firmware.
*/
ar = esas2r_alloc_request(a);
if (ar == NULL) {
esas2r_log_dev(ESAS2R_LOG_WARN,
&(a->host->shost_gendev),
"unable to allocate an abort request for cmd %p",
cmd);
return 0; /* Failure */
}
/*
* Task management request must be formatted
* with a lock held.
*/
ar->sense_len = 0;
ar->vrq->scsi.length = 0;
ar->target_id = rq->target_id;
ar->vrq->scsi.flags |= cpu_to_le32(
(u8)le32_to_cpu(rq->vrq->scsi.flags));
memset(ar->vrq->scsi.cdb, 0,
sizeof(ar->vrq->scsi.cdb));
ar->vrq->scsi.flags |= cpu_to_le32(
FCP_CMND_TRM);
ar->vrq->scsi.u.abort_handle =
rq->vrq->scsi.handle;
} else {
/*
* The request is pending but not active on
* the firmware. Just free it now and we'll
* report the successful abort below.
*/
list_del_init(&rq->req_list);
esas2r_free_request(a, rq);
}
found = true;
break;
}
}
if (!found)
return 1; /* Not found */
return 2; /* found */
}
int esas2r_eh_abort(struct scsi_cmnd *cmd)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
struct esas2r_request *abort_request = NULL;
unsigned long flags;
struct list_head *queue;
int result;
esas2r_log(ESAS2R_LOG_INFO, "eh_abort (%p)", cmd);
if (test_bit(AF_DEGRADED_MODE, &a->flags)) {
cmd->result = DID_ABORT << 16;
scsi_set_resid(cmd, 0);
cmd->scsi_done(cmd);
return SUCCESS;
}
spin_lock_irqsave(&a->queue_lock, flags);
/*
* Run through the defer and active queues looking for the request
* to abort.
*/
queue = &a->defer_list;
check_active_queue:
result = esas2r_check_active_queue(a, &abort_request, cmd, queue);
if (!result) {
spin_unlock_irqrestore(&a->queue_lock, flags);
return FAILED;
} else if (result == 2 && (queue == &a->defer_list)) {
queue = &a->active_list;
goto check_active_queue;
}
spin_unlock_irqrestore(&a->queue_lock, flags);
if (abort_request) {
u8 task_management_status = RS_PENDING;
/*
* the request is already active, so we need to tell
* the firmware to abort it and wait for the response.
*/
abort_request->comp_cb = complete_task_management_request;
abort_request->task_management_status_ptr =
&task_management_status;
esas2r_start_request(a, abort_request);
if (atomic_read(&a->disable_cnt) == 0)
esas2r_do_deferred_processes(a);
while (task_management_status == RS_PENDING)
msleep(10);
/*
* Once we get here, the original request will have been
* completed by the firmware and the abort request will have
* been cleaned up. we're done!
*/
return SUCCESS;
}
/*
* If we get here, either we found the inactive request and
* freed it, or we didn't find it at all. Either way, success!
*/
cmd->result = DID_ABORT << 16;
scsi_set_resid(cmd, 0);
cmd->scsi_done(cmd);
return SUCCESS;
}
static int esas2r_host_bus_reset(struct scsi_cmnd *cmd, bool host_reset)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
if (host_reset)
esas2r_reset_adapter(a);
else
esas2r_reset_bus(a);
/* above call sets the AF_OS_RESET flag. wait for it to clear. */
while (test_bit(AF_OS_RESET, &a->flags)) {
msleep(10);
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
}
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
return SUCCESS;
}
int esas2r_host_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "host_reset (%p)", cmd);
return esas2r_host_bus_reset(cmd, true);
}
int esas2r_bus_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "bus_reset (%p)", cmd);
return esas2r_host_bus_reset(cmd, false);
}
static int esas2r_dev_targ_reset(struct scsi_cmnd *cmd, bool target_reset)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
struct esas2r_request *rq;
u8 task_management_status = RS_PENDING;
bool completed;
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
retry:
rq = esas2r_alloc_request(a);
if (rq == NULL) {
if (target_reset) {
esas2r_log(ESAS2R_LOG_CRIT,
"unable to allocate a request for a "
"target reset (%d)!",
cmd->device->id);
} else {
esas2r_log(ESAS2R_LOG_CRIT,
"unable to allocate a request for a "
"device reset (%d:%d)!",
cmd->device->id,
cmd->device->lun);
}
return FAILED;
}
rq->target_id = cmd->device->id;
rq->vrq->scsi.flags |= cpu_to_le32(cmd->device->lun);
rq->req_stat = RS_PENDING;
rq->comp_cb = complete_task_management_request;
rq->task_management_status_ptr = &task_management_status;
if (target_reset) {
esas2r_debug("issuing target reset (%p) to id %d", rq,
cmd->device->id);
completed = esas2r_send_task_mgmt(a, rq, 0x20);
} else {
esas2r_debug("issuing device reset (%p) to id %d lun %d", rq,
cmd->device->id, cmd->device->lun);
completed = esas2r_send_task_mgmt(a, rq, 0x10);
}
if (completed) {
/* Task management cmd completed right away, need to free it. */
esas2r_free_request(a, rq);
} else {
/*
* Wait for firmware to complete the request. Completion
* callback will free it.
*/
while (task_management_status == RS_PENDING)
msleep(10);
}
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
if (task_management_status == RS_BUSY) {
/*
* Busy, probably because we are flashing. Wait a bit and
* try again.
*/
msleep(100);
goto retry;
}
return SUCCESS;
}
int esas2r_device_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "device_reset (%p)", cmd);
return esas2r_dev_targ_reset(cmd, false);
}
int esas2r_target_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "target_reset (%p)", cmd);
return esas2r_dev_targ_reset(cmd, true);
}
void esas2r_log_request_failure(struct esas2r_adapter *a,
struct esas2r_request *rq)
{
u8 reqstatus = rq->req_stat;
if (reqstatus == RS_SUCCESS)
return;
if (rq->vrq->scsi.function == VDA_FUNC_SCSI) {
if (reqstatus == RS_SCSI_ERROR) {
if (rq->func_rsp.scsi_rsp.sense_len >= 13) {
esas2r_log(ESAS2R_LOG_WARN,
"request failure - SCSI error %x ASC:%x ASCQ:%x CDB:%x",
rq->sense_buf[2], rq->sense_buf[12],
rq->sense_buf[13],
rq->vrq->scsi.cdb[0]);
} else {
esas2r_log(ESAS2R_LOG_WARN,
"request failure - SCSI error CDB:%x\n",
rq->vrq->scsi.cdb[0]);
}
} else if ((rq->vrq->scsi.cdb[0] != INQUIRY
&& rq->vrq->scsi.cdb[0] != REPORT_LUNS)
|| (reqstatus != RS_SEL
&& reqstatus != RS_SEL2)) {
if ((reqstatus == RS_UNDERRUN) &&
(rq->vrq->scsi.cdb[0] == INQUIRY)) {
/* Don't log inquiry underruns */
} else {
esas2r_log(ESAS2R_LOG_WARN,
"request failure - cdb:%x reqstatus:%d target:%d",
rq->vrq->scsi.cdb[0], reqstatus,
rq->target_id);
}
}
}
}
void esas2r_wait_request(struct esas2r_adapter *a, struct esas2r_request *rq)
{
u32 starttime;
u32 timeout;
starttime = jiffies_to_msecs(jiffies);
timeout = rq->timeout ? rq->timeout : 5000;
while (true) {
esas2r_polled_interrupt(a);
if (rq->req_stat != RS_STARTED)
break;
schedule_timeout_interruptible(msecs_to_jiffies(100));
if ((jiffies_to_msecs(jiffies) - starttime) > timeout) {
esas2r_hdebug("request TMO");
esas2r_bugon();
rq->req_stat = RS_TIMEOUT;
esas2r_local_reset_adapter(a);
return;
}
}
}
u32 esas2r_map_data_window(struct esas2r_adapter *a, u32 addr_lo)
{
u32 offset = addr_lo & (MW_DATA_WINDOW_SIZE - 1);
u32 base = addr_lo & -(signed int)MW_DATA_WINDOW_SIZE;
if (a->window_base != base) {
esas2r_write_register_dword(a, MVR_PCI_WIN1_REMAP,
base | MVRPW1R_ENABLE);
esas2r_flush_register_dword(a, MVR_PCI_WIN1_REMAP);
a->window_base = base;
}
return offset;
}
/* Read a block of data from chip memory */
bool esas2r_read_mem_block(struct esas2r_adapter *a,
void *to,
u32 from,
u32 size)
{
u8 *end = (u8 *)to;
while (size) {
u32 len;
u32 offset;
u32 iatvr;
iatvr = (from & -(signed int)MW_DATA_WINDOW_SIZE);
esas2r_map_data_window(a, iatvr);
offset = from & (MW_DATA_WINDOW_SIZE - 1);
len = size;
if (len > MW_DATA_WINDOW_SIZE - offset)
len = MW_DATA_WINDOW_SIZE - offset;
from += len;
size -= len;
while (len--) {
*end++ = esas2r_read_data_byte(a, offset);
offset++;
}
}
return true;
}
void esas2r_nuxi_mgt_data(u8 function, void *data)
{
struct atto_vda_grp_info *g;
struct atto_vda_devinfo *d;
struct atto_vdapart_info *p;
struct atto_vda_dh_info *h;
struct atto_vda_metrics_info *m;
struct atto_vda_schedule_info *s;
struct atto_vda_buzzer_info *b;
u8 i;
switch (function) {
case VDAMGT_BUZZER_INFO:
case VDAMGT_BUZZER_SET:
b = (struct atto_vda_buzzer_info *)data;
b->duration = le32_to_cpu(b->duration);
break;
case VDAMGT_SCHEDULE_INFO:
case VDAMGT_SCHEDULE_EVENT:
s = (struct atto_vda_schedule_info *)data;
s->id = le32_to_cpu(s->id);
break;
case VDAMGT_DEV_INFO:
case VDAMGT_DEV_CLEAN:
case VDAMGT_DEV_PT_INFO:
case VDAMGT_DEV_FEATURES:
case VDAMGT_DEV_PT_FEATURES:
case VDAMGT_DEV_OPERATION:
d = (struct atto_vda_devinfo *)data;
d->capacity = le64_to_cpu(d->capacity);
d->block_size = le32_to_cpu(d->block_size);
d->ses_dev_index = le16_to_cpu(d->ses_dev_index);
d->target_id = le16_to_cpu(d->target_id);
d->lun = le16_to_cpu(d->lun);
d->features = le16_to_cpu(d->features);
break;
case VDAMGT_GRP_INFO:
case VDAMGT_GRP_CREATE:
case VDAMGT_GRP_DELETE:
case VDAMGT_ADD_STORAGE:
case VDAMGT_MEMBER_ADD:
case VDAMGT_GRP_COMMIT:
case VDAMGT_GRP_REBUILD:
case VDAMGT_GRP_COMMIT_INIT:
case VDAMGT_QUICK_RAID:
case VDAMGT_GRP_FEATURES:
case VDAMGT_GRP_COMMIT_INIT_AUTOMAP:
case VDAMGT_QUICK_RAID_INIT_AUTOMAP:
case VDAMGT_SPARE_LIST:
case VDAMGT_SPARE_ADD:
case VDAMGT_SPARE_REMOVE:
case VDAMGT_LOCAL_SPARE_ADD:
case VDAMGT_GRP_OPERATION:
g = (struct atto_vda_grp_info *)data;
g->capacity = le64_to_cpu(g->capacity);
g->block_size = le32_to_cpu(g->block_size);
g->interleave = le32_to_cpu(g->interleave);
g->features = le16_to_cpu(g->features);
for (i = 0; i < 32; i++)
g->members[i] = le16_to_cpu(g->members[i]);
break;
case VDAMGT_PART_INFO:
case VDAMGT_PART_MAP:
case VDAMGT_PART_UNMAP:
case VDAMGT_PART_AUTOMAP:
case VDAMGT_PART_SPLIT:
case VDAMGT_PART_MERGE:
p = (struct atto_vdapart_info *)data;
p->part_size = le64_to_cpu(p->part_size);
p->start_lba = le32_to_cpu(p->start_lba);
p->block_size = le32_to_cpu(p->block_size);
p->target_id = le16_to_cpu(p->target_id);
break;
case VDAMGT_DEV_HEALTH_REQ:
h = (struct atto_vda_dh_info *)data;
h->med_defect_cnt = le32_to_cpu(h->med_defect_cnt);
h->info_exc_cnt = le32_to_cpu(h->info_exc_cnt);
break;
case VDAMGT_DEV_METRICS:
m = (struct atto_vda_metrics_info *)data;
for (i = 0; i < 32; i++)
m->dev_indexes[i] = le16_to_cpu(m->dev_indexes[i]);
break;
default:
break;
}
}
void esas2r_nuxi_cfg_data(u8 function, void *data)
{
struct atto_vda_cfg_init *ci;
switch (function) {
case VDA_CFG_INIT:
case VDA_CFG_GET_INIT:
case VDA_CFG_GET_INIT2:
ci = (struct atto_vda_cfg_init *)data;
ci->date_time.year = le16_to_cpu(ci->date_time.year);
ci->sgl_page_size = le32_to_cpu(ci->sgl_page_size);
ci->vda_version = le32_to_cpu(ci->vda_version);
ci->epoch_time = le32_to_cpu(ci->epoch_time);
ci->ioctl_tunnel = le32_to_cpu(ci->ioctl_tunnel);
ci->num_targets_backend = le32_to_cpu(ci->num_targets_backend);
break;
default:
break;
}
}
void esas2r_nuxi_ae_data(union atto_vda_ae *ae)
{
struct atto_vda_ae_raid *r = &ae->raid;
struct atto_vda_ae_lu *l = &ae->lu;
switch (ae->hdr.bytype) {
case VDAAE_HDR_TYPE_RAID:
r->dwflags = le32_to_cpu(r->dwflags);
break;
case VDAAE_HDR_TYPE_LU:
l->dwevent = le32_to_cpu(l->dwevent);
l->wphys_target_id = le16_to_cpu(l->wphys_target_id);
l->id.tgtlun.wtarget_id = le16_to_cpu(l->id.tgtlun.wtarget_id);
if (l->hdr.bylength >= offsetof(struct atto_vda_ae_lu, id)
+ sizeof(struct atto_vda_ae_lu_tgt_lun_raid)) {
l->id.tgtlun_raid.dwinterleave
= le32_to_cpu(l->id.tgtlun_raid.dwinterleave);
l->id.tgtlun_raid.dwblock_size
= le32_to_cpu(l->id.tgtlun_raid.dwblock_size);
}
break;
case VDAAE_HDR_TYPE_DISK:
default:
break;
}
}
void esas2r_free_request(struct esas2r_adapter *a, struct esas2r_request *rq)
{
unsigned long flags;
esas2r_rq_destroy_request(rq, a);
spin_lock_irqsave(&a->request_lock, flags);
list_add(&rq->comp_list, &a->avail_request);
spin_unlock_irqrestore(&a->request_lock, flags);
}
struct esas2r_request *esas2r_alloc_request(struct esas2r_adapter *a)
{
struct esas2r_request *rq;
unsigned long flags;
spin_lock_irqsave(&a->request_lock, flags);
if (unlikely(list_empty(&a->avail_request))) {
spin_unlock_irqrestore(&a->request_lock, flags);
return NULL;
}
rq = list_first_entry(&a->avail_request, struct esas2r_request,
comp_list);
list_del(&rq->comp_list);
spin_unlock_irqrestore(&a->request_lock, flags);
esas2r_rq_init_request(rq, a);
return rq;
}
void esas2r_complete_request_cb(struct esas2r_adapter *a,
struct esas2r_request *rq)
{
esas2r_debug("completing request %p\n", rq);
scsi_dma_unmap(rq->cmd);
if (unlikely(rq->req_stat != RS_SUCCESS)) {
esas2r_debug("[%x STATUS %x:%x (%x)]", rq->target_id,
rq->req_stat,
rq->func_rsp.scsi_rsp.scsi_stat,
rq->cmd);
rq->cmd->result =
((esas2r_req_status_to_error(rq->req_stat) << 16)
| (rq->func_rsp.scsi_rsp.scsi_stat & STATUS_MASK));
if (rq->req_stat == RS_UNDERRUN)
scsi_set_resid(rq->cmd,
le32_to_cpu(rq->func_rsp.scsi_rsp.
residual_length));
else
scsi_set_resid(rq->cmd, 0);
}
rq->cmd->scsi_done(rq->cmd);
esas2r_free_request(a, rq);
}
/* Run tasklet to handle stuff outside of interrupt context. */
void esas2r_adapter_tasklet(unsigned long context)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)context;
if (unlikely(test_bit(AF2_TIMER_TICK, &a->flags2))) {
clear_bit(AF2_TIMER_TICK, &a->flags2);
esas2r_timer_tick(a);
}
if (likely(test_bit(AF2_INT_PENDING, &a->flags2))) {
clear_bit(AF2_INT_PENDING, &a->flags2);
esas2r_adapter_interrupt(a);
}
if (esas2r_is_tasklet_pending(a))
esas2r_do_tasklet_tasks(a);
if (esas2r_is_tasklet_pending(a)
|| (test_bit(AF2_INT_PENDING, &a->flags2))
|| (test_bit(AF2_TIMER_TICK, &a->flags2))) {
clear_bit(AF_TASKLET_SCHEDULED, &a->flags);
esas2r_schedule_tasklet(a);
} else {
clear_bit(AF_TASKLET_SCHEDULED, &a->flags);
}
}
static void esas2r_timer_callback(unsigned long context);
void esas2r_kickoff_timer(struct esas2r_adapter *a)
{
init_timer(&a->timer);
a->timer.function = esas2r_timer_callback;
a->timer.data = (unsigned long)a;
a->timer.expires = jiffies +
msecs_to_jiffies(100);
add_timer(&a->timer);
}
static void esas2r_timer_callback(unsigned long context)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)context;
set_bit(AF2_TIMER_TICK, &a->flags2);
esas2r_schedule_tasklet(a);
esas2r_kickoff_timer(a);
}
/*
* Firmware events need to be handled outside of interrupt context
* so we schedule a delayed_work to handle them.
*/
static void
esas2r_free_fw_event(struct esas2r_fw_event_work *fw_event)
{
unsigned long flags;
struct esas2r_adapter *a = fw_event->a;
spin_lock_irqsave(&a->fw_event_lock, flags);
list_del(&fw_event->list);
kfree(fw_event);
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
void
esas2r_fw_event_off(struct esas2r_adapter *a)
{
unsigned long flags;
spin_lock_irqsave(&a->fw_event_lock, flags);
a->fw_events_off = 1;
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
void
esas2r_fw_event_on(struct esas2r_adapter *a)
{
unsigned long flags;
spin_lock_irqsave(&a->fw_event_lock, flags);
a->fw_events_off = 0;
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
static void esas2r_add_device(struct esas2r_adapter *a, u16 target_id)
{
int ret;
struct scsi_device *scsi_dev;
scsi_dev = scsi_device_lookup(a->host, 0, target_id, 0);
if (scsi_dev) {
esas2r_log_dev(
ESAS2R_LOG_WARN,
&(scsi_dev->
sdev_gendev),
"scsi device already exists at id %d", target_id);
scsi_device_put(scsi_dev);
} else {
esas2r_log_dev(
ESAS2R_LOG_INFO,
&(a->host->
shost_gendev),
"scsi_add_device() called for 0:%d:0",
target_id);
ret = scsi_add_device(a->host, 0, target_id, 0);
if (ret) {
esas2r_log_dev(
ESAS2R_LOG_CRIT,
&(a->host->
shost_gendev),
"scsi_add_device failed with %d for id %d",
ret, target_id);
}
}
}
static void esas2r_remove_device(struct esas2r_adapter *a, u16 target_id)
{
struct scsi_device *scsi_dev;
scsi_dev = scsi_device_lookup(a->host, 0, target_id, 0);
if (scsi_dev) {
scsi_device_set_state(scsi_dev, SDEV_OFFLINE);
esas2r_log_dev(
ESAS2R_LOG_INFO,
&(scsi_dev->
sdev_gendev),
"scsi_remove_device() called for 0:%d:0",
target_id);
scsi_remove_device(scsi_dev);
esas2r_log_dev(
ESAS2R_LOG_INFO,
&(scsi_dev->
sdev_gendev),
"scsi_device_put() called");
scsi_device_put(scsi_dev);
} else {
esas2r_log_dev(
ESAS2R_LOG_WARN,
&(a->host->shost_gendev),
"no target found at id %d",
target_id);
}
}
/*
* Sends a firmware asynchronous event to anyone who happens to be
* listening on the defined ATTO VDA event ports.
*/
static void esas2r_send_ae_event(struct esas2r_fw_event_work *fw_event)
{
struct esas2r_vda_ae *ae = (struct esas2r_vda_ae *)fw_event->data;
char *type;
switch (ae->vda_ae.hdr.bytype) {
case VDAAE_HDR_TYPE_RAID:
type = "RAID group state change";
break;
case VDAAE_HDR_TYPE_LU:
type = "Mapped destination LU change";
break;
case VDAAE_HDR_TYPE_DISK:
type = "Physical disk inventory change";
break;
case VDAAE_HDR_TYPE_RESET:
type = "Firmware reset";
break;
case VDAAE_HDR_TYPE_LOG_INFO:
type = "Event Log message (INFO level)";
break;
case VDAAE_HDR_TYPE_LOG_WARN:
type = "Event Log message (WARN level)";
break;
case VDAAE_HDR_TYPE_LOG_CRIT:
type = "Event Log message (CRIT level)";
break;
case VDAAE_HDR_TYPE_LOG_FAIL:
type = "Event Log message (FAIL level)";
break;
case VDAAE_HDR_TYPE_NVC:
type = "NVCache change";
break;
case VDAAE_HDR_TYPE_TLG_INFO:
type = "Time stamped log message (INFO level)";
break;
case VDAAE_HDR_TYPE_TLG_WARN:
type = "Time stamped log message (WARN level)";
break;
case VDAAE_HDR_TYPE_TLG_CRIT:
type = "Time stamped log message (CRIT level)";
break;
case VDAAE_HDR_TYPE_PWRMGT:
type = "Power management";
break;
case VDAAE_HDR_TYPE_MUTE:
type = "Mute button pressed";
break;
case VDAAE_HDR_TYPE_DEV:
type = "Device attribute change";
break;
default:
type = "Unknown";
break;
}
esas2r_log(ESAS2R_LOG_WARN,
"An async event of type \"%s\" was received from the firmware. The event contents are:",
type);
esas2r_log_hexdump(ESAS2R_LOG_WARN, &ae->vda_ae,
ae->vda_ae.hdr.bylength);
}
static void
esas2r_firmware_event_work(struct work_struct *work)
{
struct esas2r_fw_event_work *fw_event =
container_of(work, struct esas2r_fw_event_work, work.work);
struct esas2r_adapter *a = fw_event->a;
u16 target_id = *(u16 *)&fw_event->data[0];
if (a->fw_events_off)
goto done;
switch (fw_event->type) {
case fw_event_null:
break; /* do nothing */
case fw_event_lun_change:
esas2r_remove_device(a, target_id);
esas2r_add_device(a, target_id);
break;
case fw_event_present:
esas2r_add_device(a, target_id);
break;
case fw_event_not_present:
esas2r_remove_device(a, target_id);
break;
case fw_event_vda_ae:
esas2r_send_ae_event(fw_event);
break;
}
done:
esas2r_free_fw_event(fw_event);
}
void esas2r_queue_fw_event(struct esas2r_adapter *a,
enum fw_event_type type,
void *data,
int data_sz)
{
struct esas2r_fw_event_work *fw_event;
unsigned long flags;
fw_event = kzalloc(sizeof(struct esas2r_fw_event_work), GFP_ATOMIC);
if (!fw_event) {
esas2r_log(ESAS2R_LOG_WARN,
"esas2r_queue_fw_event failed to alloc");
return;
}
if (type == fw_event_vda_ae) {
struct esas2r_vda_ae *ae =
(struct esas2r_vda_ae *)fw_event->data;
ae->signature = ESAS2R_VDA_EVENT_SIG;
ae->bus_number = a->pcid->bus->number;
ae->devfn = a->pcid->devfn;
memcpy(&ae->vda_ae, data, sizeof(ae->vda_ae));
} else {
memcpy(fw_event->data, data, data_sz);
}
fw_event->type = type;
fw_event->a = a;
spin_lock_irqsave(&a->fw_event_lock, flags);
list_add_tail(&fw_event->list, &a->fw_event_list);
INIT_DELAYED_WORK(&fw_event->work, esas2r_firmware_event_work);
queue_delayed_work_on(
smp_processor_id(), a->fw_event_q, &fw_event->work,
msecs_to_jiffies(1));
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
void esas2r_target_state_changed(struct esas2r_adapter *a, u16 targ_id,
u8 state)
{
if (state == TS_LUN_CHANGE)
esas2r_queue_fw_event(a, fw_event_lun_change, &targ_id,
sizeof(targ_id));
else if (state == TS_PRESENT)
esas2r_queue_fw_event(a, fw_event_present, &targ_id,
sizeof(targ_id));
else if (state == TS_NOT_PRESENT)
esas2r_queue_fw_event(a, fw_event_not_present, &targ_id,
sizeof(targ_id));
}
/* Translate status to a Linux SCSI mid-layer error code */
int esas2r_req_status_to_error(u8 req_stat)
{
switch (req_stat) {
case RS_OVERRUN:
case RS_UNDERRUN:
case RS_SUCCESS:
/*
* NOTE: SCSI mid-layer wants a good status for a SCSI error, because
* it will check the scsi_stat value in the completion anyway.
*/
case RS_SCSI_ERROR:
return DID_OK;
case RS_SEL:
case RS_SEL2:
return DID_NO_CONNECT;
case RS_RESET:
return DID_RESET;
case RS_ABORTED:
return DID_ABORT;
case RS_BUSY:
return DID_BUS_BUSY;
}
/* everything else is just an error. */
return DID_ERROR;
}
module_init(esas2r_init);
module_exit(esas2r_exit);
| gpl-2.0 |
CyanogenMod/android_kernel_sony_msm8x60 | drivers/usb/serial/metro-usb.c | 2037 | 10965 | /*
Some of this code is credited to Linux USB open source files that are
distributed with Linux.
Copyright: 2007 Metrologic Instruments. All rights reserved.
Copyright: 2011 Azimut Ltd. <http://azimutrzn.ru/>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/moduleparam.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/uaccess.h>
#include <linux/usb/serial.h>
/* Version Information */
#define DRIVER_VERSION "v1.2.0.0"
#define DRIVER_DESC "Metrologic Instruments Inc. - USB-POS driver"
/* Product information. */
#define FOCUS_VENDOR_ID 0x0C2E
#define FOCUS_PRODUCT_ID_BI 0x0720
#define FOCUS_PRODUCT_ID_UNI 0x0700
#define METROUSB_SET_REQUEST_TYPE 0x40
#define METROUSB_SET_MODEM_CTRL_REQUEST 10
#define METROUSB_SET_BREAK_REQUEST 0x40
#define METROUSB_MCR_NONE 0x08 /* Deactivate DTR and RTS. */
#define METROUSB_MCR_RTS 0x0a /* Activate RTS. */
#define METROUSB_MCR_DTR 0x09 /* Activate DTR. */
#define WDR_TIMEOUT 5000 /* default urb timeout. */
/* Private data structure. */
struct metrousb_private {
spinlock_t lock;
int throttled;
unsigned long control_state;
};
/* Device table list. */
static struct usb_device_id id_table[] = {
{ USB_DEVICE(FOCUS_VENDOR_ID, FOCUS_PRODUCT_ID_BI) },
{ USB_DEVICE(FOCUS_VENDOR_ID, FOCUS_PRODUCT_ID_UNI) },
{ }, /* Terminating entry. */
};
MODULE_DEVICE_TABLE(usb, id_table);
/* Input parameter constants. */
static bool debug;
static void metrousb_read_int_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
struct tty_struct *tty;
unsigned char *data = urb->transfer_buffer;
int throttled = 0;
int result = 0;
unsigned long flags = 0;
dev_dbg(&port->dev, "%s\n", __func__);
switch (urb->status) {
case 0:
/* Success status, read from the port. */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* urb has been terminated. */
dev_dbg(&port->dev,
"%s - urb shutting down, error code=%d\n",
__func__, result);
return;
default:
dev_dbg(&port->dev,
"%s - non-zero urb received, error code=%d\n",
__func__, result);
goto exit;
}
/* Set the data read from the usb port into the serial port buffer. */
tty = tty_port_tty_get(&port->port);
if (!tty) {
dev_dbg(&port->dev, "%s - bad tty pointer - exiting\n",
__func__);
return;
}
if (tty && urb->actual_length) {
/* Loop through the data copying each byte to the tty layer. */
tty_insert_flip_string(tty, data, urb->actual_length);
/* Force the data to the tty layer. */
tty_flip_buffer_push(tty);
}
tty_kref_put(tty);
/* Set any port variables. */
spin_lock_irqsave(&metro_priv->lock, flags);
throttled = metro_priv->throttled;
spin_unlock_irqrestore(&metro_priv->lock, flags);
/* Continue trying to read if set. */
if (!throttled) {
usb_fill_int_urb(port->interrupt_in_urb, port->serial->dev,
usb_rcvintpipe(port->serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
metrousb_read_int_callback, port, 1);
result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
if (result)
dev_dbg(&port->dev,
"%s - failed submitting interrupt in urb, error code=%d\n",
__func__, result);
}
return;
exit:
/* Try to resubmit the urb. */
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_dbg(&port->dev,
"%s - failed submitting interrupt in urb, error code=%d\n",
__func__, result);
}
static void metrousb_cleanup(struct usb_serial_port *port)
{
dev_dbg(&port->dev, "%s\n", __func__);
if (port->serial->dev) {
/* Shutdown any interrupt in urbs. */
if (port->interrupt_in_urb) {
usb_unlink_urb(port->interrupt_in_urb);
usb_kill_urb(port->interrupt_in_urb);
}
}
}
static int metrousb_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
int result = 0;
dev_dbg(&port->dev, "%s\n", __func__);
/* Make sure the urb is initialized. */
if (!port->interrupt_in_urb) {
dev_dbg(&port->dev, "%s - interrupt urb not initialized\n",
__func__);
return -ENODEV;
}
/* Set the private data information for the port. */
spin_lock_irqsave(&metro_priv->lock, flags);
metro_priv->control_state = 0;
metro_priv->throttled = 0;
spin_unlock_irqrestore(&metro_priv->lock, flags);
/* Clear the urb pipe. */
usb_clear_halt(serial->dev, port->interrupt_in_urb->pipe);
/* Start reading from the device */
usb_fill_int_urb(port->interrupt_in_urb, serial->dev,
usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
metrousb_read_int_callback, port, 1);
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result) {
dev_dbg(&port->dev,
"%s - failed submitting interrupt in urb, error code=%d\n",
__func__, result);
goto exit;
}
dev_dbg(&port->dev, "%s - port open\n", __func__);
exit:
return result;
}
static int metrousb_set_modem_ctrl(struct usb_serial *serial, unsigned int control_state)
{
int retval = 0;
unsigned char mcr = METROUSB_MCR_NONE;
dev_dbg(&serial->dev->dev, "%s - control state = %d\n",
__func__, control_state);
/* Set the modem control value. */
if (control_state & TIOCM_DTR)
mcr |= METROUSB_MCR_DTR;
if (control_state & TIOCM_RTS)
mcr |= METROUSB_MCR_RTS;
/* Send the command to the usb port. */
retval = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
METROUSB_SET_REQUEST_TYPE, METROUSB_SET_MODEM_CTRL_REQUEST,
control_state, 0, NULL, 0, WDR_TIMEOUT);
if (retval < 0)
dev_dbg(&serial->dev->dev,
"%s - set modem ctrl=0x%x failed, error code=%d\n",
__func__, mcr, retval);
return retval;
}
static void metrousb_shutdown(struct usb_serial *serial)
{
int i = 0;
dev_dbg(&serial->dev->dev, "%s\n", __func__);
/* Stop reading and writing on all ports. */
for (i = 0; i < serial->num_ports; ++i) {
/* Close any open urbs. */
metrousb_cleanup(serial->port[i]);
/* Free memory. */
kfree(usb_get_serial_port_data(serial->port[i]));
usb_set_serial_port_data(serial->port[i], NULL);
dev_dbg(&serial->dev->dev, "%s - freed port number=%d\n",
__func__, serial->port[i]->number);
}
}
static int metrousb_startup(struct usb_serial *serial)
{
struct metrousb_private *metro_priv;
struct usb_serial_port *port;
int i = 0;
dev_dbg(&serial->dev->dev, "%s\n", __func__);
/* Loop through the serial ports setting up the private structures.
* Currently we only use one port. */
for (i = 0; i < serial->num_ports; ++i) {
port = serial->port[i];
/* Declare memory. */
metro_priv = kzalloc(sizeof(struct metrousb_private), GFP_KERNEL);
if (!metro_priv)
return -ENOMEM;
/* Initialize memory. */
spin_lock_init(&metro_priv->lock);
usb_set_serial_port_data(port, metro_priv);
dev_dbg(&serial->dev->dev, "%s - port number=%d\n ",
__func__, port->number);
}
return 0;
}
static void metrousb_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
dev_dbg(tty->dev, "%s\n", __func__);
/* Set the private information for the port to stop reading data. */
spin_lock_irqsave(&metro_priv->lock, flags);
metro_priv->throttled = 1;
spin_unlock_irqrestore(&metro_priv->lock, flags);
}
static int metrousb_tiocmget(struct tty_struct *tty)
{
unsigned long control_state = 0;
struct usb_serial_port *port = tty->driver_data;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
dev_dbg(tty->dev, "%s\n", __func__);
spin_lock_irqsave(&metro_priv->lock, flags);
control_state = metro_priv->control_state;
spin_unlock_irqrestore(&metro_priv->lock, flags);
return control_state;
}
static int metrousb_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
unsigned long control_state = 0;
dev_dbg(tty->dev, "%s - set=%d, clear=%d\n", __func__, set, clear);
spin_lock_irqsave(&metro_priv->lock, flags);
control_state = metro_priv->control_state;
/* Set the RTS and DTR values. */
if (set & TIOCM_RTS)
control_state |= TIOCM_RTS;
if (set & TIOCM_DTR)
control_state |= TIOCM_DTR;
if (clear & TIOCM_RTS)
control_state &= ~TIOCM_RTS;
if (clear & TIOCM_DTR)
control_state &= ~TIOCM_DTR;
metro_priv->control_state = control_state;
spin_unlock_irqrestore(&metro_priv->lock, flags);
return metrousb_set_modem_ctrl(serial, control_state);
}
static void metrousb_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
int result = 0;
dev_dbg(tty->dev, "%s\n", __func__);
/* Set the private information for the port to resume reading data. */
spin_lock_irqsave(&metro_priv->lock, flags);
metro_priv->throttled = 0;
spin_unlock_irqrestore(&metro_priv->lock, flags);
/* Submit the urb to read from the port. */
port->interrupt_in_urb->dev = port->serial->dev;
result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
if (result)
dev_dbg(tty->dev,
"failed submitting interrupt in urb error code=%d\n",
result);
}
static struct usb_driver metrousb_driver = {
.name = "metro-usb",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table
};
static struct usb_serial_driver metrousb_device = {
.driver = {
.owner = THIS_MODULE,
.name = "metro-usb",
},
.description = "Metrologic USB to serial converter.",
.id_table = id_table,
.num_ports = 1,
.open = metrousb_open,
.close = metrousb_cleanup,
.read_int_callback = metrousb_read_int_callback,
.attach = metrousb_startup,
.release = metrousb_shutdown,
.throttle = metrousb_throttle,
.unthrottle = metrousb_unthrottle,
.tiocmget = metrousb_tiocmget,
.tiocmset = metrousb_tiocmset,
};
static struct usb_serial_driver * const serial_drivers[] = {
&metrousb_device,
NULL,
};
module_usb_serial_driver(metrousb_driver, serial_drivers);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Philip Nicastro");
MODULE_AUTHOR("Aleksey Babahin <tamerlan311@gmail.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
/* Module input parameters */
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Print debug info (bool 1=on, 0=off)");
| gpl-2.0 |
atwilc3000/linux4sam | drivers/media/usb/dvb-usb-v2/rtl28xxu.c | 2037 | 35197 | /*
* Realtek RTL28xxU DVB USB driver
*
* Copyright (C) 2009 Antti Palosaari <crope@iki.fi>
* Copyright (C) 2011 Antti Palosaari <crope@iki.fi>
* Copyright (C) 2012 Thomas Mair <thomas.mair86@googlemail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "rtl28xxu.h"
#include "rtl2830.h"
#include "rtl2832.h"
#include "qt1010.h"
#include "mt2060.h"
#include "mxl5005s.h"
#include "fc0012.h"
#include "fc0013.h"
#include "e4000.h"
#include "fc2580.h"
#include "tua9001.h"
#include "r820t.h"
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static int rtl28xxu_ctrl_msg(struct dvb_usb_device *d, struct rtl28xxu_req *req)
{
int ret;
unsigned int pipe;
u8 requesttype;
u8 *buf;
buf = kmalloc(req->size, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto err;
}
if (req->index & CMD_WR_FLAG) {
/* write */
memcpy(buf, req->data, req->size);
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
pipe = usb_sndctrlpipe(d->udev, 0);
} else {
/* read */
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
pipe = usb_rcvctrlpipe(d->udev, 0);
}
ret = usb_control_msg(d->udev, pipe, 0, requesttype, req->value,
req->index, buf, req->size, 1000);
dvb_usb_dbg_usb_control_msg(d->udev, 0, requesttype, req->value,
req->index, buf, req->size);
if (ret > 0)
ret = 0;
/* read request, copy returned data to return buf */
if (!ret && requesttype == (USB_TYPE_VENDOR | USB_DIR_IN))
memcpy(req->data, buf, req->size);
kfree(buf);
if (ret)
goto err;
return ret;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl28xx_wr_regs(struct dvb_usb_device *d, u16 reg, u8 *val, int len)
{
struct rtl28xxu_req req;
if (reg < 0x3000)
req.index = CMD_USB_WR;
else if (reg < 0x4000)
req.index = CMD_SYS_WR;
else
req.index = CMD_IR_WR;
req.value = reg;
req.size = len;
req.data = val;
return rtl28xxu_ctrl_msg(d, &req);
}
static int rtl2831_rd_regs(struct dvb_usb_device *d, u16 reg, u8 *val, int len)
{
struct rtl28xxu_req req;
if (reg < 0x3000)
req.index = CMD_USB_RD;
else if (reg < 0x4000)
req.index = CMD_SYS_RD;
else
req.index = CMD_IR_RD;
req.value = reg;
req.size = len;
req.data = val;
return rtl28xxu_ctrl_msg(d, &req);
}
static int rtl28xx_wr_reg(struct dvb_usb_device *d, u16 reg, u8 val)
{
return rtl28xx_wr_regs(d, reg, &val, 1);
}
static int rtl28xx_rd_reg(struct dvb_usb_device *d, u16 reg, u8 *val)
{
return rtl2831_rd_regs(d, reg, val, 1);
}
static int rtl28xx_wr_reg_mask(struct dvb_usb_device *d, u16 reg, u8 val,
u8 mask)
{
int ret;
u8 tmp;
/* no need for read if whole reg is written */
if (mask != 0xff) {
ret = rtl28xx_rd_reg(d, reg, &tmp);
if (ret)
return ret;
val &= mask;
tmp &= ~mask;
val |= tmp;
}
return rtl28xx_wr_reg(d, reg, val);
}
/* I2C */
static int rtl28xxu_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
int ret;
struct dvb_usb_device *d = i2c_get_adapdata(adap);
struct rtl28xxu_priv *priv = d->priv;
struct rtl28xxu_req req;
/*
* It is not known which are real I2C bus xfer limits, but testing
* with RTL2831U + MT2060 gives max RD 24 and max WR 22 bytes.
* TODO: find out RTL2832U lens
*/
/*
* I2C adapter logic looks rather complicated due to fact it handles
* three different access methods. Those methods are;
* 1) integrated demod access
* 2) old I2C access
* 3) new I2C access
*
* Used method is selected in order 1, 2, 3. Method 3 can handle all
* requests but there is two reasons why not use it always;
* 1) It is most expensive, usually two USB messages are needed
* 2) At least RTL2831U does not support it
*
* Method 3 is needed in case of I2C write+read (typical register read)
* where write is more than one byte.
*/
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
if (num == 2 && !(msg[0].flags & I2C_M_RD) &&
(msg[1].flags & I2C_M_RD)) {
if (msg[0].len > 24 || msg[1].len > 24) {
/* TODO: check msg[0].len max */
ret = -EOPNOTSUPP;
goto err_mutex_unlock;
} else if (msg[0].addr == 0x10) {
/* method 1 - integrated demod */
req.value = (msg[0].buf[0] << 8) | (msg[0].addr << 1);
req.index = CMD_DEMOD_RD | priv->page;
req.size = msg[1].len;
req.data = &msg[1].buf[0];
ret = rtl28xxu_ctrl_msg(d, &req);
} else if (msg[0].len < 2) {
/* method 2 - old I2C */
req.value = (msg[0].buf[0] << 8) | (msg[0].addr << 1);
req.index = CMD_I2C_RD;
req.size = msg[1].len;
req.data = &msg[1].buf[0];
ret = rtl28xxu_ctrl_msg(d, &req);
} else {
/* method 3 - new I2C */
req.value = (msg[0].addr << 1);
req.index = CMD_I2C_DA_WR;
req.size = msg[0].len;
req.data = msg[0].buf;
ret = rtl28xxu_ctrl_msg(d, &req);
if (ret)
goto err_mutex_unlock;
req.value = (msg[0].addr << 1);
req.index = CMD_I2C_DA_RD;
req.size = msg[1].len;
req.data = msg[1].buf;
ret = rtl28xxu_ctrl_msg(d, &req);
}
} else if (num == 1 && !(msg[0].flags & I2C_M_RD)) {
if (msg[0].len > 22) {
/* TODO: check msg[0].len max */
ret = -EOPNOTSUPP;
goto err_mutex_unlock;
} else if (msg[0].addr == 0x10) {
/* method 1 - integrated demod */
if (msg[0].buf[0] == 0x00) {
/* save demod page for later demod access */
priv->page = msg[0].buf[1];
ret = 0;
} else {
req.value = (msg[0].buf[0] << 8) |
(msg[0].addr << 1);
req.index = CMD_DEMOD_WR | priv->page;
req.size = msg[0].len-1;
req.data = &msg[0].buf[1];
ret = rtl28xxu_ctrl_msg(d, &req);
}
} else if (msg[0].len < 23) {
/* method 2 - old I2C */
req.value = (msg[0].buf[0] << 8) | (msg[0].addr << 1);
req.index = CMD_I2C_WR;
req.size = msg[0].len-1;
req.data = &msg[0].buf[1];
ret = rtl28xxu_ctrl_msg(d, &req);
} else {
/* method 3 - new I2C */
req.value = (msg[0].addr << 1);
req.index = CMD_I2C_DA_WR;
req.size = msg[0].len;
req.data = msg[0].buf;
ret = rtl28xxu_ctrl_msg(d, &req);
}
} else {
ret = -EINVAL;
}
err_mutex_unlock:
mutex_unlock(&d->i2c_mutex);
return ret ? ret : num;
}
static u32 rtl28xxu_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm rtl28xxu_i2c_algo = {
.master_xfer = rtl28xxu_i2c_xfer,
.functionality = rtl28xxu_i2c_func,
};
static int rtl2831u_read_config(struct dvb_usb_device *d)
{
struct rtl28xxu_priv *priv = d_to_priv(d);
int ret;
u8 buf[1];
/* open RTL2831U/RTL2830 I2C gate */
struct rtl28xxu_req req_gate_open = {0x0120, 0x0011, 0x0001, "\x08"};
/* tuner probes */
struct rtl28xxu_req req_mt2060 = {0x00c0, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_qt1010 = {0x0fc4, CMD_I2C_RD, 1, buf};
dev_dbg(&d->udev->dev, "%s:\n", __func__);
/*
* RTL2831U GPIOs
* =========================================================
* GPIO0 | tuner#0 | 0 off | 1 on | MXL5005S (?)
* GPIO2 | LED | 0 off | 1 on |
* GPIO4 | tuner#1 | 0 on | 1 off | MT2060
*/
/* GPIO direction */
ret = rtl28xx_wr_reg(d, SYS_GPIO_DIR, 0x0a);
if (ret)
goto err;
/* enable as output GPIO0, GPIO2, GPIO4 */
ret = rtl28xx_wr_reg(d, SYS_GPIO_OUT_EN, 0x15);
if (ret)
goto err;
/*
* Probe used tuner. We need to know used tuner before demod attach
* since there is some demod params needed to set according to tuner.
*/
/* demod needs some time to wake up */
msleep(20);
priv->tuner_name = "NONE";
/* open demod I2C gate */
ret = rtl28xxu_ctrl_msg(d, &req_gate_open);
if (ret)
goto err;
/* check QT1010 ID(?) register; reg=0f val=2c */
ret = rtl28xxu_ctrl_msg(d, &req_qt1010);
if (ret == 0 && buf[0] == 0x2c) {
priv->tuner = TUNER_RTL2830_QT1010;
priv->tuner_name = "QT1010";
goto found;
}
/* open demod I2C gate */
ret = rtl28xxu_ctrl_msg(d, &req_gate_open);
if (ret)
goto err;
/* check MT2060 ID register; reg=00 val=63 */
ret = rtl28xxu_ctrl_msg(d, &req_mt2060);
if (ret == 0 && buf[0] == 0x63) {
priv->tuner = TUNER_RTL2830_MT2060;
priv->tuner_name = "MT2060";
goto found;
}
/* assume MXL5005S */
priv->tuner = TUNER_RTL2830_MXL5005S;
priv->tuner_name = "MXL5005S";
goto found;
found:
dev_dbg(&d->udev->dev, "%s: tuner=%s\n", __func__, priv->tuner_name);
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_read_config(struct dvb_usb_device *d)
{
struct rtl28xxu_priv *priv = d_to_priv(d);
int ret;
u8 buf[2];
/* open RTL2832U/RTL2832 I2C gate */
struct rtl28xxu_req req_gate_open = {0x0120, 0x0011, 0x0001, "\x18"};
/* close RTL2832U/RTL2832 I2C gate */
struct rtl28xxu_req req_gate_close = {0x0120, 0x0011, 0x0001, "\x10"};
/* tuner probes */
struct rtl28xxu_req req_fc0012 = {0x00c6, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_fc0013 = {0x00c6, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_mt2266 = {0x00c0, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_fc2580 = {0x01ac, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_mt2063 = {0x00c0, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_max3543 = {0x00c0, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_tua9001 = {0x7ec0, CMD_I2C_RD, 2, buf};
struct rtl28xxu_req req_mxl5007t = {0xd9c0, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_e4000 = {0x02c8, CMD_I2C_RD, 1, buf};
struct rtl28xxu_req req_tda18272 = {0x00c0, CMD_I2C_RD, 2, buf};
struct rtl28xxu_req req_r820t = {0x0034, CMD_I2C_RD, 1, buf};
dev_dbg(&d->udev->dev, "%s:\n", __func__);
/* enable GPIO3 and GPIO6 as output */
ret = rtl28xx_wr_reg_mask(d, SYS_GPIO_DIR, 0x00, 0x40);
if (ret)
goto err;
ret = rtl28xx_wr_reg_mask(d, SYS_GPIO_OUT_EN, 0x48, 0x48);
if (ret)
goto err;
/*
* Probe used tuner. We need to know used tuner before demod attach
* since there is some demod params needed to set according to tuner.
*/
/* open demod I2C gate */
ret = rtl28xxu_ctrl_msg(d, &req_gate_open);
if (ret)
goto err;
priv->tuner_name = "NONE";
/* check FC0012 ID register; reg=00 val=a1 */
ret = rtl28xxu_ctrl_msg(d, &req_fc0012);
if (ret == 0 && buf[0] == 0xa1) {
priv->tuner = TUNER_RTL2832_FC0012;
priv->tuner_name = "FC0012";
goto found;
}
/* check FC0013 ID register; reg=00 val=a3 */
ret = rtl28xxu_ctrl_msg(d, &req_fc0013);
if (ret == 0 && buf[0] == 0xa3) {
priv->tuner = TUNER_RTL2832_FC0013;
priv->tuner_name = "FC0013";
goto found;
}
/* check MT2266 ID register; reg=00 val=85 */
ret = rtl28xxu_ctrl_msg(d, &req_mt2266);
if (ret == 0 && buf[0] == 0x85) {
priv->tuner = TUNER_RTL2832_MT2266;
priv->tuner_name = "MT2266";
goto found;
}
/* check FC2580 ID register; reg=01 val=56 */
ret = rtl28xxu_ctrl_msg(d, &req_fc2580);
if (ret == 0 && buf[0] == 0x56) {
priv->tuner = TUNER_RTL2832_FC2580;
priv->tuner_name = "FC2580";
goto found;
}
/* check MT2063 ID register; reg=00 val=9e || 9c */
ret = rtl28xxu_ctrl_msg(d, &req_mt2063);
if (ret == 0 && (buf[0] == 0x9e || buf[0] == 0x9c)) {
priv->tuner = TUNER_RTL2832_MT2063;
priv->tuner_name = "MT2063";
goto found;
}
/* check MAX3543 ID register; reg=00 val=38 */
ret = rtl28xxu_ctrl_msg(d, &req_max3543);
if (ret == 0 && buf[0] == 0x38) {
priv->tuner = TUNER_RTL2832_MAX3543;
priv->tuner_name = "MAX3543";
goto found;
}
/* check TUA9001 ID register; reg=7e val=2328 */
ret = rtl28xxu_ctrl_msg(d, &req_tua9001);
if (ret == 0 && buf[0] == 0x23 && buf[1] == 0x28) {
priv->tuner = TUNER_RTL2832_TUA9001;
priv->tuner_name = "TUA9001";
goto found;
}
/* check MXL5007R ID register; reg=d9 val=14 */
ret = rtl28xxu_ctrl_msg(d, &req_mxl5007t);
if (ret == 0 && buf[0] == 0x14) {
priv->tuner = TUNER_RTL2832_MXL5007T;
priv->tuner_name = "MXL5007T";
goto found;
}
/* check E4000 ID register; reg=02 val=40 */
ret = rtl28xxu_ctrl_msg(d, &req_e4000);
if (ret == 0 && buf[0] == 0x40) {
priv->tuner = TUNER_RTL2832_E4000;
priv->tuner_name = "E4000";
goto found;
}
/* check TDA18272 ID register; reg=00 val=c760 */
ret = rtl28xxu_ctrl_msg(d, &req_tda18272);
if (ret == 0 && (buf[0] == 0xc7 || buf[1] == 0x60)) {
priv->tuner = TUNER_RTL2832_TDA18272;
priv->tuner_name = "TDA18272";
goto found;
}
/* check R820T ID register; reg=00 val=69 */
ret = rtl28xxu_ctrl_msg(d, &req_r820t);
if (ret == 0 && buf[0] == 0x69) {
priv->tuner = TUNER_RTL2832_R820T;
priv->tuner_name = "R820T";
goto found;
}
found:
dev_dbg(&d->udev->dev, "%s: tuner=%s\n", __func__, priv->tuner_name);
/* close demod I2C gate */
ret = rtl28xxu_ctrl_msg(d, &req_gate_close);
if (ret < 0)
goto err;
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static struct rtl2830_config rtl28xxu_rtl2830_mt2060_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.ts_mode = 0,
.spec_inv = 1,
.vtop = 0x20,
.krf = 0x04,
.agc_targ_val = 0x2d,
};
static struct rtl2830_config rtl28xxu_rtl2830_qt1010_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.ts_mode = 0,
.spec_inv = 1,
.vtop = 0x20,
.krf = 0x04,
.agc_targ_val = 0x2d,
};
static struct rtl2830_config rtl28xxu_rtl2830_mxl5005s_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.ts_mode = 0,
.spec_inv = 0,
.vtop = 0x3f,
.krf = 0x04,
.agc_targ_val = 0x3e,
};
static int rtl2831u_frontend_attach(struct dvb_usb_adapter *adap)
{
struct dvb_usb_device *d = adap_to_d(adap);
struct rtl28xxu_priv *priv = d_to_priv(d);
struct rtl2830_config *rtl2830_config;
int ret;
dev_dbg(&d->udev->dev, "%s:\n", __func__);
switch (priv->tuner) {
case TUNER_RTL2830_QT1010:
rtl2830_config = &rtl28xxu_rtl2830_qt1010_config;
break;
case TUNER_RTL2830_MT2060:
rtl2830_config = &rtl28xxu_rtl2830_mt2060_config;
break;
case TUNER_RTL2830_MXL5005S:
rtl2830_config = &rtl28xxu_rtl2830_mxl5005s_config;
break;
default:
dev_err(&d->udev->dev, "%s: unknown tuner=%s\n",
KBUILD_MODNAME, priv->tuner_name);
ret = -ENODEV;
goto err;
}
/* attach demodulator */
adap->fe[0] = dvb_attach(rtl2830_attach, rtl2830_config, &d->i2c_adap);
if (!adap->fe[0]) {
ret = -ENODEV;
goto err;
}
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static struct rtl2832_config rtl28xxu_rtl2832_fc0012_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.if_dvbt = 0,
.tuner = TUNER_RTL2832_FC0012
};
static struct rtl2832_config rtl28xxu_rtl2832_fc0013_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.if_dvbt = 0,
.tuner = TUNER_RTL2832_FC0013
};
static struct rtl2832_config rtl28xxu_rtl2832_tua9001_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.tuner = TUNER_RTL2832_TUA9001,
};
static struct rtl2832_config rtl28xxu_rtl2832_e4000_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.tuner = TUNER_RTL2832_E4000,
};
static struct rtl2832_config rtl28xxu_rtl2832_r820t_config = {
.i2c_addr = 0x10,
.xtal = 28800000,
.tuner = TUNER_RTL2832_R820T,
};
static int rtl2832u_fc0012_tuner_callback(struct dvb_usb_device *d,
int cmd, int arg)
{
int ret;
u8 val;
dev_dbg(&d->udev->dev, "%s: cmd=%d arg=%d\n", __func__, cmd, arg);
switch (cmd) {
case FC_FE_CALLBACK_VHF_ENABLE:
/* set output values */
ret = rtl28xx_rd_reg(d, SYS_GPIO_OUT_VAL, &val);
if (ret)
goto err;
if (arg)
val &= 0xbf; /* set GPIO6 low */
else
val |= 0x40; /* set GPIO6 high */
ret = rtl28xx_wr_reg(d, SYS_GPIO_OUT_VAL, val);
if (ret)
goto err;
break;
default:
ret = -EINVAL;
goto err;
}
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_tua9001_tuner_callback(struct dvb_usb_device *d,
int cmd, int arg)
{
int ret;
u8 val;
dev_dbg(&d->udev->dev, "%s: cmd=%d arg=%d\n", __func__, cmd, arg);
/*
* CEN always enabled by hardware wiring
* RESETN GPIO4
* RXEN GPIO1
*/
switch (cmd) {
case TUA9001_CMD_RESETN:
if (arg)
val = (1 << 4);
else
val = (0 << 4);
ret = rtl28xx_wr_reg_mask(d, SYS_GPIO_OUT_VAL, val, 0x10);
if (ret)
goto err;
break;
case TUA9001_CMD_RXEN:
if (arg)
val = (1 << 1);
else
val = (0 << 1);
ret = rtl28xx_wr_reg_mask(d, SYS_GPIO_OUT_VAL, val, 0x02);
if (ret)
goto err;
break;
}
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_tuner_callback(struct dvb_usb_device *d, int cmd, int arg)
{
struct rtl28xxu_priv *priv = d->priv;
switch (priv->tuner) {
case TUNER_RTL2832_FC0012:
return rtl2832u_fc0012_tuner_callback(d, cmd, arg);
case TUNER_RTL2832_TUA9001:
return rtl2832u_tua9001_tuner_callback(d, cmd, arg);
default:
break;
}
return 0;
}
static int rtl2832u_frontend_callback(void *adapter_priv, int component,
int cmd, int arg)
{
struct i2c_adapter *adap = adapter_priv;
struct dvb_usb_device *d = i2c_get_adapdata(adap);
dev_dbg(&d->udev->dev, "%s: component=%d cmd=%d arg=%d\n",
__func__, component, cmd, arg);
switch (component) {
case DVB_FRONTEND_COMPONENT_TUNER:
return rtl2832u_tuner_callback(d, cmd, arg);
default:
break;
}
return 0;
}
static int rtl2832u_frontend_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct dvb_usb_device *d = adap_to_d(adap);
struct rtl28xxu_priv *priv = d_to_priv(d);
struct rtl2832_config *rtl2832_config;
dev_dbg(&d->udev->dev, "%s:\n", __func__);
switch (priv->tuner) {
case TUNER_RTL2832_FC0012:
rtl2832_config = &rtl28xxu_rtl2832_fc0012_config;
break;
case TUNER_RTL2832_FC0013:
rtl2832_config = &rtl28xxu_rtl2832_fc0013_config;
break;
case TUNER_RTL2832_FC2580:
/* FIXME: do not abuse fc0012 settings */
rtl2832_config = &rtl28xxu_rtl2832_fc0012_config;
break;
case TUNER_RTL2832_TUA9001:
rtl2832_config = &rtl28xxu_rtl2832_tua9001_config;
break;
case TUNER_RTL2832_E4000:
rtl2832_config = &rtl28xxu_rtl2832_e4000_config;
break;
case TUNER_RTL2832_R820T:
rtl2832_config = &rtl28xxu_rtl2832_r820t_config;
break;
default:
dev_err(&d->udev->dev, "%s: unknown tuner=%s\n",
KBUILD_MODNAME, priv->tuner_name);
ret = -ENODEV;
goto err;
}
/* attach demodulator */
adap->fe[0] = dvb_attach(rtl2832_attach, rtl2832_config, &d->i2c_adap);
if (!adap->fe[0]) {
ret = -ENODEV;
goto err;
}
/* set fe callback */
adap->fe[0]->callback = rtl2832u_frontend_callback;
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static struct qt1010_config rtl28xxu_qt1010_config = {
.i2c_address = 0x62, /* 0xc4 */
};
static struct mt2060_config rtl28xxu_mt2060_config = {
.i2c_address = 0x60, /* 0xc0 */
.clock_out = 0,
};
static struct mxl5005s_config rtl28xxu_mxl5005s_config = {
.i2c_address = 0x63, /* 0xc6 */
.if_freq = IF_FREQ_4570000HZ,
.xtal_freq = CRYSTAL_FREQ_16000000HZ,
.agc_mode = MXL_SINGLE_AGC,
.tracking_filter = MXL_TF_C_H,
.rssi_enable = MXL_RSSI_ENABLE,
.cap_select = MXL_CAP_SEL_ENABLE,
.div_out = MXL_DIV_OUT_4,
.clock_out = MXL_CLOCK_OUT_DISABLE,
.output_load = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
.top = MXL5005S_TOP_25P2,
.mod_mode = MXL_DIGITAL_MODE,
.if_mode = MXL_ZERO_IF,
.AgcMasterByte = 0x00,
};
static int rtl2831u_tuner_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct dvb_usb_device *d = adap_to_d(adap);
struct rtl28xxu_priv *priv = d_to_priv(d);
struct i2c_adapter *rtl2830_tuner_i2c;
struct dvb_frontend *fe;
dev_dbg(&d->udev->dev, "%s:\n", __func__);
/* use rtl2830 driver I2C adapter, for more info see rtl2830 driver */
rtl2830_tuner_i2c = rtl2830_get_tuner_i2c_adapter(adap->fe[0]);
switch (priv->tuner) {
case TUNER_RTL2830_QT1010:
fe = dvb_attach(qt1010_attach, adap->fe[0],
rtl2830_tuner_i2c, &rtl28xxu_qt1010_config);
break;
case TUNER_RTL2830_MT2060:
fe = dvb_attach(mt2060_attach, adap->fe[0],
rtl2830_tuner_i2c, &rtl28xxu_mt2060_config,
1220);
break;
case TUNER_RTL2830_MXL5005S:
fe = dvb_attach(mxl5005s_attach, adap->fe[0],
rtl2830_tuner_i2c, &rtl28xxu_mxl5005s_config);
break;
default:
fe = NULL;
dev_err(&d->udev->dev, "%s: unknown tuner=%d\n", KBUILD_MODNAME,
priv->tuner);
}
if (fe == NULL) {
ret = -ENODEV;
goto err;
}
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static const struct e4000_config rtl2832u_e4000_config = {
.i2c_addr = 0x64,
.clock = 28800000,
};
static const struct fc2580_config rtl2832u_fc2580_config = {
.i2c_addr = 0x56,
.clock = 16384000,
};
static struct tua9001_config rtl2832u_tua9001_config = {
.i2c_addr = 0x60,
};
static const struct fc0012_config rtl2832u_fc0012_config = {
.i2c_address = 0x63, /* 0xc6 >> 1 */
.xtal_freq = FC_XTAL_28_8_MHZ,
};
static const struct r820t_config rtl2832u_r820t_config = {
.i2c_addr = 0x1a,
.xtal = 28800000,
.max_i2c_msg_len = 2,
.rafael_chip = CHIP_R820T,
};
static int rtl2832u_tuner_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct dvb_usb_device *d = adap_to_d(adap);
struct rtl28xxu_priv *priv = d_to_priv(d);
struct dvb_frontend *fe;
dev_dbg(&d->udev->dev, "%s:\n", __func__);
switch (priv->tuner) {
case TUNER_RTL2832_FC0012:
fe = dvb_attach(fc0012_attach, adap->fe[0],
&d->i2c_adap, &rtl2832u_fc0012_config);
/* since fc0012 includs reading the signal strength delegate
* that to the tuner driver */
adap->fe[0]->ops.read_signal_strength =
adap->fe[0]->ops.tuner_ops.get_rf_strength;
return 0;
break;
case TUNER_RTL2832_FC0013:
fe = dvb_attach(fc0013_attach, adap->fe[0],
&d->i2c_adap, 0xc6>>1, 0, FC_XTAL_28_8_MHZ);
/* fc0013 also supports signal strength reading */
adap->fe[0]->ops.read_signal_strength =
adap->fe[0]->ops.tuner_ops.get_rf_strength;
return 0;
case TUNER_RTL2832_E4000:
fe = dvb_attach(e4000_attach, adap->fe[0], &d->i2c_adap,
&rtl2832u_e4000_config);
break;
case TUNER_RTL2832_FC2580:
fe = dvb_attach(fc2580_attach, adap->fe[0], &d->i2c_adap,
&rtl2832u_fc2580_config);
break;
case TUNER_RTL2832_TUA9001:
/* enable GPIO1 and GPIO4 as output */
ret = rtl28xx_wr_reg_mask(d, SYS_GPIO_DIR, 0x00, 0x12);
if (ret)
goto err;
ret = rtl28xx_wr_reg_mask(d, SYS_GPIO_OUT_EN, 0x12, 0x12);
if (ret)
goto err;
fe = dvb_attach(tua9001_attach, adap->fe[0], &d->i2c_adap,
&rtl2832u_tua9001_config);
break;
case TUNER_RTL2832_R820T:
fe = dvb_attach(r820t_attach, adap->fe[0], &d->i2c_adap,
&rtl2832u_r820t_config);
/* Use tuner to get the signal strength */
adap->fe[0]->ops.read_signal_strength =
adap->fe[0]->ops.tuner_ops.get_rf_strength;
break;
default:
fe = NULL;
dev_err(&d->udev->dev, "%s: unknown tuner=%d\n", KBUILD_MODNAME,
priv->tuner);
}
if (fe == NULL) {
ret = -ENODEV;
goto err;
}
return 0;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl28xxu_init(struct dvb_usb_device *d)
{
int ret;
u8 val;
dev_dbg(&d->udev->dev, "%s:\n", __func__);
/* init USB endpoints */
ret = rtl28xx_rd_reg(d, USB_SYSCTL_0, &val);
if (ret)
goto err;
/* enable DMA and Full Packet Mode*/
val |= 0x09;
ret = rtl28xx_wr_reg(d, USB_SYSCTL_0, val);
if (ret)
goto err;
/* set EPA maximum packet size to 0x0200 */
ret = rtl28xx_wr_regs(d, USB_EPA_MAXPKT, "\x00\x02\x00\x00", 4);
if (ret)
goto err;
/* change EPA FIFO length */
ret = rtl28xx_wr_regs(d, USB_EPA_FIFO_CFG, "\x14\x00\x00\x00", 4);
if (ret)
goto err;
return ret;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2831u_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
u8 gpio, sys0, epa_ctl[2];
dev_dbg(&d->udev->dev, "%s: onoff=%d\n", __func__, onoff);
/* demod adc */
ret = rtl28xx_rd_reg(d, SYS_SYS0, &sys0);
if (ret)
goto err;
/* tuner power, read GPIOs */
ret = rtl28xx_rd_reg(d, SYS_GPIO_OUT_VAL, &gpio);
if (ret)
goto err;
dev_dbg(&d->udev->dev, "%s: RD SYS0=%02x GPIO_OUT_VAL=%02x\n", __func__,
sys0, gpio);
if (onoff) {
gpio |= 0x01; /* GPIO0 = 1 */
gpio &= (~0x10); /* GPIO4 = 0 */
gpio |= 0x04; /* GPIO2 = 1, LED on */
sys0 = sys0 & 0x0f;
sys0 |= 0xe0;
epa_ctl[0] = 0x00; /* clear stall */
epa_ctl[1] = 0x00; /* clear reset */
} else {
gpio &= (~0x01); /* GPIO0 = 0 */
gpio |= 0x10; /* GPIO4 = 1 */
gpio &= (~0x04); /* GPIO2 = 1, LED off */
sys0 = sys0 & (~0xc0);
epa_ctl[0] = 0x10; /* set stall */
epa_ctl[1] = 0x02; /* set reset */
}
dev_dbg(&d->udev->dev, "%s: WR SYS0=%02x GPIO_OUT_VAL=%02x\n", __func__,
sys0, gpio);
/* demod adc */
ret = rtl28xx_wr_reg(d, SYS_SYS0, sys0);
if (ret)
goto err;
/* tuner power, write GPIOs */
ret = rtl28xx_wr_reg(d, SYS_GPIO_OUT_VAL, gpio);
if (ret)
goto err;
/* streaming EP: stall & reset */
ret = rtl28xx_wr_regs(d, USB_EPA_CTL, epa_ctl, 2);
if (ret)
goto err;
if (onoff)
usb_clear_halt(d->udev, usb_rcvbulkpipe(d->udev, 0x81));
return ret;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
u8 val;
dev_dbg(&d->udev->dev, "%s: onoff=%d\n", __func__, onoff);
if (onoff) {
/* set output values */
ret = rtl28xx_rd_reg(d, SYS_GPIO_OUT_VAL, &val);
if (ret)
goto err;
val |= 0x08;
val &= 0xef;
ret = rtl28xx_wr_reg(d, SYS_GPIO_OUT_VAL, val);
if (ret)
goto err;
/* demod_ctl_1 */
ret = rtl28xx_rd_reg(d, SYS_DEMOD_CTL1, &val);
if (ret)
goto err;
val &= 0xef;
ret = rtl28xx_wr_reg(d, SYS_DEMOD_CTL1, val);
if (ret)
goto err;
/* demod control */
/* PLL enable */
ret = rtl28xx_rd_reg(d, SYS_DEMOD_CTL, &val);
if (ret)
goto err;
/* bit 7 to 1 */
val |= 0x80;
ret = rtl28xx_wr_reg(d, SYS_DEMOD_CTL, val);
if (ret)
goto err;
ret = rtl28xx_rd_reg(d, SYS_DEMOD_CTL, &val);
if (ret)
goto err;
val |= 0x20;
ret = rtl28xx_wr_reg(d, SYS_DEMOD_CTL, val);
if (ret)
goto err;
mdelay(5);
/*enable ADC_Q and ADC_I */
ret = rtl28xx_rd_reg(d, SYS_DEMOD_CTL, &val);
if (ret)
goto err;
val |= 0x48;
ret = rtl28xx_wr_reg(d, SYS_DEMOD_CTL, val);
if (ret)
goto err;
/* streaming EP: clear stall & reset */
ret = rtl28xx_wr_regs(d, USB_EPA_CTL, "\x00\x00", 2);
if (ret)
goto err;
ret = usb_clear_halt(d->udev, usb_rcvbulkpipe(d->udev, 0x81));
if (ret)
goto err;
} else {
/* demod_ctl_1 */
ret = rtl28xx_rd_reg(d, SYS_DEMOD_CTL1, &val);
if (ret)
goto err;
val |= 0x0c;
ret = rtl28xx_wr_reg(d, SYS_DEMOD_CTL1, val);
if (ret)
goto err;
/* set output values */
ret = rtl28xx_rd_reg(d, SYS_GPIO_OUT_VAL, &val);
if (ret)
goto err;
val |= 0x10;
ret = rtl28xx_wr_reg(d, SYS_GPIO_OUT_VAL, val);
if (ret)
goto err;
/* demod control */
ret = rtl28xx_rd_reg(d, SYS_DEMOD_CTL, &val);
if (ret)
goto err;
val &= 0x37;
ret = rtl28xx_wr_reg(d, SYS_DEMOD_CTL, val);
if (ret)
goto err;
/* streaming EP: set stall & reset */
ret = rtl28xx_wr_regs(d, USB_EPA_CTL, "\x10\x02", 2);
if (ret)
goto err;
}
return ret;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
#if IS_ENABLED(CONFIG_RC_CORE)
static int rtl2831u_rc_query(struct dvb_usb_device *d)
{
int ret, i;
struct rtl28xxu_priv *priv = d->priv;
u8 buf[5];
u32 rc_code;
struct rtl28xxu_reg_val rc_nec_tab[] = {
{ 0x3033, 0x80 },
{ 0x3020, 0x43 },
{ 0x3021, 0x16 },
{ 0x3022, 0x16 },
{ 0x3023, 0x5a },
{ 0x3024, 0x2d },
{ 0x3025, 0x16 },
{ 0x3026, 0x01 },
{ 0x3028, 0xb0 },
{ 0x3029, 0x04 },
{ 0x302c, 0x88 },
{ 0x302e, 0x13 },
{ 0x3030, 0xdf },
{ 0x3031, 0x05 },
};
/* init remote controller */
if (!priv->rc_active) {
for (i = 0; i < ARRAY_SIZE(rc_nec_tab); i++) {
ret = rtl28xx_wr_reg(d, rc_nec_tab[i].reg,
rc_nec_tab[i].val);
if (ret)
goto err;
}
priv->rc_active = true;
}
ret = rtl2831_rd_regs(d, SYS_IRRC_RP, buf, 5);
if (ret)
goto err;
if (buf[4] & 0x01) {
if (buf[2] == (u8) ~buf[3]) {
if (buf[0] == (u8) ~buf[1]) {
/* NEC standard (16 bit) */
rc_code = buf[0] << 8 | buf[2];
} else {
/* NEC extended (24 bit) */
rc_code = buf[0] << 16 |
buf[1] << 8 | buf[2];
}
} else {
/* NEC full (32 bit) */
rc_code = buf[0] << 24 | buf[1] << 16 |
buf[2] << 8 | buf[3];
}
rc_keydown(d->rc_dev, rc_code, 0);
ret = rtl28xx_wr_reg(d, SYS_IRRC_SR, 1);
if (ret)
goto err;
/* repeated intentionally to avoid extra keypress */
ret = rtl28xx_wr_reg(d, SYS_IRRC_SR, 1);
if (ret)
goto err;
}
return ret;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2831u_get_rc_config(struct dvb_usb_device *d,
struct dvb_usb_rc *rc)
{
rc->map_name = RC_MAP_EMPTY;
rc->allowed_protos = RC_BIT_NEC;
rc->query = rtl2831u_rc_query;
rc->interval = 400;
return 0;
}
#else
#define rtl2831u_get_rc_config NULL
#endif
#if IS_ENABLED(CONFIG_RC_CORE)
static int rtl2832u_rc_query(struct dvb_usb_device *d)
{
int ret, i;
struct rtl28xxu_priv *priv = d->priv;
u8 buf[128];
int len;
struct rtl28xxu_reg_val rc_nec_tab[] = {
{ IR_RX_CTRL, 0x20 },
{ IR_RX_BUF_CTRL, 0x80 },
{ IR_RX_IF, 0xff },
{ IR_RX_IE, 0xff },
{ IR_MAX_DURATION0, 0xd0 },
{ IR_MAX_DURATION1, 0x07 },
{ IR_IDLE_LEN0, 0xc0 },
{ IR_IDLE_LEN1, 0x00 },
{ IR_GLITCH_LEN, 0x03 },
{ IR_RX_CLK, 0x09 },
{ IR_RX_CFG, 0x1c },
{ IR_MAX_H_TOL_LEN, 0x1e },
{ IR_MAX_L_TOL_LEN, 0x1e },
{ IR_RX_CTRL, 0x80 },
};
/* init remote controller */
if (!priv->rc_active) {
for (i = 0; i < ARRAY_SIZE(rc_nec_tab); i++) {
ret = rtl28xx_wr_reg(d, rc_nec_tab[i].reg,
rc_nec_tab[i].val);
if (ret)
goto err;
}
priv->rc_active = true;
}
ret = rtl28xx_rd_reg(d, IR_RX_IF, &buf[0]);
if (ret)
goto err;
if (buf[0] != 0x83)
goto exit;
ret = rtl28xx_rd_reg(d, IR_RX_BC, &buf[0]);
if (ret)
goto err;
len = buf[0];
ret = rtl2831_rd_regs(d, IR_RX_BUF, buf, len);
/* TODO: pass raw IR to Kernel IR decoder */
ret = rtl28xx_wr_reg(d, IR_RX_IF, 0x03);
ret = rtl28xx_wr_reg(d, IR_RX_BUF_CTRL, 0x80);
ret = rtl28xx_wr_reg(d, IR_RX_CTRL, 0x80);
exit:
return ret;
err:
dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_get_rc_config(struct dvb_usb_device *d,
struct dvb_usb_rc *rc)
{
rc->map_name = RC_MAP_EMPTY;
rc->allowed_protos = RC_BIT_NEC;
rc->query = rtl2832u_rc_query;
rc->interval = 400;
return 0;
}
#else
#define rtl2832u_get_rc_config NULL
#endif
static const struct dvb_usb_device_properties rtl2831u_props = {
.driver_name = KBUILD_MODNAME,
.owner = THIS_MODULE,
.adapter_nr = adapter_nr,
.size_of_priv = sizeof(struct rtl28xxu_priv),
.power_ctrl = rtl2831u_power_ctrl,
.i2c_algo = &rtl28xxu_i2c_algo,
.read_config = rtl2831u_read_config,
.frontend_attach = rtl2831u_frontend_attach,
.tuner_attach = rtl2831u_tuner_attach,
.init = rtl28xxu_init,
.get_rc_config = rtl2831u_get_rc_config,
.num_adapters = 1,
.adapter = {
{
.stream = DVB_USB_STREAM_BULK(0x81, 6, 8 * 512),
},
},
};
static const struct dvb_usb_device_properties rtl2832u_props = {
.driver_name = KBUILD_MODNAME,
.owner = THIS_MODULE,
.adapter_nr = adapter_nr,
.size_of_priv = sizeof(struct rtl28xxu_priv),
.power_ctrl = rtl2832u_power_ctrl,
.i2c_algo = &rtl28xxu_i2c_algo,
.read_config = rtl2832u_read_config,
.frontend_attach = rtl2832u_frontend_attach,
.tuner_attach = rtl2832u_tuner_attach,
.init = rtl28xxu_init,
.get_rc_config = rtl2832u_get_rc_config,
.num_adapters = 1,
.adapter = {
{
.stream = DVB_USB_STREAM_BULK(0x81, 6, 8 * 512),
},
},
};
static const struct usb_device_id rtl28xxu_id_table[] = {
{ DVB_USB_DEVICE(USB_VID_REALTEK, USB_PID_REALTEK_RTL2831U,
&rtl2831u_props, "Realtek RTL2831U reference design", NULL) },
{ DVB_USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_FREECOM_DVBT,
&rtl2831u_props, "Freecom USB2.0 DVB-T", NULL) },
{ DVB_USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_FREECOM_DVBT_2,
&rtl2831u_props, "Freecom USB2.0 DVB-T", NULL) },
{ DVB_USB_DEVICE(USB_VID_REALTEK, 0x2832,
&rtl2832u_props, "Realtek RTL2832U reference design", NULL) },
{ DVB_USB_DEVICE(USB_VID_REALTEK, 0x2838,
&rtl2832u_props, "Realtek RTL2832U reference design", NULL) },
{ DVB_USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_T_STICK_BLACK_REV1,
&rtl2832u_props, "TerraTec Cinergy T Stick Black", NULL) },
{ DVB_USB_DEVICE(USB_VID_GTEK, USB_PID_DELOCK_USB2_DVBT,
&rtl2832u_props, "G-Tek Electronics Group Lifeview LV5TDLX DVB-T", NULL) },
{ DVB_USB_DEVICE(USB_VID_TERRATEC, USB_PID_NOXON_DAB_STICK,
&rtl2832u_props, "TerraTec NOXON DAB Stick", NULL) },
{ DVB_USB_DEVICE(USB_VID_TERRATEC, USB_PID_NOXON_DAB_STICK_REV2,
&rtl2832u_props, "TerraTec NOXON DAB Stick (rev 2)", NULL) },
{ DVB_USB_DEVICE(USB_VID_GTEK, USB_PID_TREKSTOR_TERRES_2_0,
&rtl2832u_props, "Trekstor DVB-T Stick Terres 2.0", NULL) },
{ DVB_USB_DEVICE(USB_VID_DEXATEK, 0x1101,
&rtl2832u_props, "Dexatek DK DVB-T Dongle", NULL) },
{ DVB_USB_DEVICE(USB_VID_LEADTEK, 0x6680,
&rtl2832u_props, "DigitalNow Quad DVB-T Receiver", NULL) },
{ DVB_USB_DEVICE(USB_VID_TERRATEC, 0x00d3,
&rtl2832u_props, "TerraTec Cinergy T Stick RC (Rev. 3)", NULL) },
{ DVB_USB_DEVICE(USB_VID_DEXATEK, 0x1102,
&rtl2832u_props, "Dexatek DK mini DVB-T Dongle", NULL) },
{ DVB_USB_DEVICE(USB_VID_TERRATEC, 0x00d7,
&rtl2832u_props, "TerraTec Cinergy T Stick+", NULL) },
{ DVB_USB_DEVICE(USB_VID_KWORLD_2, 0xd3a8,
&rtl2832u_props, "ASUS My Cinema-U3100Mini Plus V2", NULL) },
{ DVB_USB_DEVICE(USB_VID_KWORLD_2, 0xd393,
&rtl2832u_props, "GIGABYTE U7300", NULL) },
{ DVB_USB_DEVICE(USB_VID_DEXATEK, 0x1104,
&rtl2832u_props, "Digivox Micro Hd", NULL) },
{ DVB_USB_DEVICE(USB_VID_COMPRO, 0x0620,
&rtl2832u_props, "Compro VideoMate U620F", NULL) },
{ DVB_USB_DEVICE(USB_VID_KWORLD_2, 0xd394,
&rtl2832u_props, "MaxMedia HU394-T", NULL) },
{ }
};
MODULE_DEVICE_TABLE(usb, rtl28xxu_id_table);
static struct usb_driver rtl28xxu_usb_driver = {
.name = KBUILD_MODNAME,
.id_table = rtl28xxu_id_table,
.probe = dvb_usbv2_probe,
.disconnect = dvb_usbv2_disconnect,
.suspend = dvb_usbv2_suspend,
.resume = dvb_usbv2_resume,
.reset_resume = dvb_usbv2_reset_resume,
.no_dynamic_id = 1,
.soft_unbind = 1,
};
module_usb_driver(rtl28xxu_usb_driver);
MODULE_DESCRIPTION("Realtek RTL28xxU DVB USB driver");
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_AUTHOR("Thomas Mair <thomas.mair86@googlemail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
airidosas252/linux_sun4i_kernel | fs/xfs/xfs_rw.c | 2549 | 4655 | /*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_error.h"
#include "xfs_rw.h"
/*
* Force a shutdown of the filesystem instantly while keeping
* the filesystem consistent. We don't do an unmount here; just shutdown
* the shop, make sure that absolutely nothing persistent happens to
* this filesystem after this point.
*/
void
xfs_do_force_shutdown(
xfs_mount_t *mp,
int flags,
char *fname,
int lnnum)
{
int logerror;
logerror = flags & SHUTDOWN_LOG_IO_ERROR;
if (!(flags & SHUTDOWN_FORCE_UMOUNT)) {
xfs_notice(mp,
"%s(0x%x) called from line %d of file %s. Return address = 0x%p",
__func__, flags, lnnum, fname, __return_address);
}
/*
* No need to duplicate efforts.
*/
if (XFS_FORCED_SHUTDOWN(mp) && !logerror)
return;
/*
* This flags XFS_MOUNT_FS_SHUTDOWN, makes sure that we don't
* queue up anybody new on the log reservations, and wakes up
* everybody who's sleeping on log reservations to tell them
* the bad news.
*/
if (xfs_log_force_umount(mp, logerror))
return;
if (flags & SHUTDOWN_CORRUPT_INCORE) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_CORRUPT,
"Corruption of in-memory data detected. Shutting down filesystem");
if (XFS_ERRLEVEL_HIGH <= xfs_error_level)
xfs_stack_trace();
} else if (!(flags & SHUTDOWN_FORCE_UMOUNT)) {
if (logerror) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_LOGERROR,
"Log I/O Error Detected. Shutting down filesystem");
} else if (flags & SHUTDOWN_DEVICE_REQ) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_IOERROR,
"All device paths lost. Shutting down filesystem");
} else if (!(flags & SHUTDOWN_REMOTE_REQ)) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_IOERROR,
"I/O Error Detected. Shutting down filesystem");
}
}
if (!(flags & SHUTDOWN_FORCE_UMOUNT)) {
xfs_alert(mp,
"Please umount the filesystem and rectify the problem(s)");
}
}
/*
* Prints out an ALERT message about I/O error.
*/
void
xfs_ioerror_alert(
char *func,
struct xfs_mount *mp,
xfs_buf_t *bp,
xfs_daddr_t blkno)
{
xfs_alert(mp,
"I/O error occurred: meta-data dev %s block 0x%llx"
" (\"%s\") error %d buf count %zd",
XFS_BUFTARG_NAME(XFS_BUF_TARGET(bp)),
(__uint64_t)blkno, func,
XFS_BUF_GETERROR(bp), XFS_BUF_COUNT(bp));
}
/*
* This isn't an absolute requirement, but it is
* just a good idea to call xfs_read_buf instead of
* directly doing a read_buf call. For one, we shouldn't
* be doing this disk read if we are in SHUTDOWN state anyway,
* so this stops that from happening. Secondly, this does all
* the error checking stuff and the brelse if appropriate for
* the caller, so the code can be a little leaner.
*/
int
xfs_read_buf(
struct xfs_mount *mp,
xfs_buftarg_t *target,
xfs_daddr_t blkno,
int len,
uint flags,
xfs_buf_t **bpp)
{
xfs_buf_t *bp;
int error;
if (!flags)
flags = XBF_LOCK | XBF_MAPPED;
bp = xfs_buf_read(target, blkno, len, flags);
if (!bp)
return XFS_ERROR(EIO);
error = XFS_BUF_GETERROR(bp);
if (bp && !error && !XFS_FORCED_SHUTDOWN(mp)) {
*bpp = bp;
} else {
*bpp = NULL;
if (error) {
xfs_ioerror_alert("xfs_read_buf", mp, bp, XFS_BUF_ADDR(bp));
} else {
error = XFS_ERROR(EIO);
}
if (bp) {
XFS_BUF_UNDONE(bp);
XFS_BUF_UNDELAYWRITE(bp);
XFS_BUF_STALE(bp);
/*
* brelse clears B_ERROR and b_error
*/
xfs_buf_relse(bp);
}
}
return (error);
}
/*
* helper function to extract extent size hint from inode
*/
xfs_extlen_t
xfs_get_extsz_hint(
struct xfs_inode *ip)
{
if ((ip->i_d.di_flags & XFS_DIFLAG_EXTSIZE) && ip->i_d.di_extsize)
return ip->i_d.di_extsize;
if (XFS_IS_REALTIME_INODE(ip))
return ip->i_mount->m_sb.sb_rextsize;
return 0;
}
| gpl-2.0 |
jetonbacaj/SomeKernel_G920P_PB6 | net/bluetooth/bnep/sock.c | 3061 | 5708 | /*
BNEP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2001-2002 Inventel Systemes
Written 2001-2002 by
David Libault <david.libault@inventel.fr>
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/export.h>
#include <linux/file.h>
#include "bnep.h"
static struct bt_sock_list bnep_sk_list = {
.lock = __RW_LOCK_UNLOCKED(bnep_sk_list.lock)
};
static int bnep_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
BT_DBG("sock %p sk %p", sock, sk);
if (!sk)
return 0;
bt_sock_unlink(&bnep_sk_list, sk);
sock_orphan(sk);
sock_put(sk);
return 0;
}
static int bnep_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct bnep_connlist_req cl;
struct bnep_connadd_req ca;
struct bnep_conndel_req cd;
struct bnep_conninfo ci;
struct socket *nsock;
void __user *argp = (void __user *)arg;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
switch (cmd) {
case BNEPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
nsock = sockfd_lookup(ca.sock, &err);
if (!nsock)
return err;
if (nsock->sk->sk_state != BT_CONNECTED) {
sockfd_put(nsock);
return -EBADFD;
}
ca.device[sizeof(ca.device)-1] = 0;
err = bnep_add_connection(&ca, nsock);
if (!err) {
if (copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
} else
sockfd_put(nsock);
return err;
case BNEPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return bnep_del_connection(&cd);
case BNEPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case BNEPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = bnep_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
default:
return -EINVAL;
}
return 0;
}
#ifdef CONFIG_COMPAT
static int bnep_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
if (cmd == BNEPGETCONNLIST) {
struct bnep_connlist_req cl;
u32 uci;
int err;
if (get_user(cl.cnum, (u32 __user *) arg) ||
get_user(uci, (u32 __user *) (arg + 4)))
return -EFAULT;
cl.ci = compat_ptr(uci);
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && put_user(cl.cnum, (u32 __user *) arg))
err = -EFAULT;
return err;
}
return bnep_sock_ioctl(sock, cmd, arg);
}
#endif
static const struct proto_ops bnep_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = bnep_sock_release,
.ioctl = bnep_sock_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = bnep_sock_compat_ioctl,
#endif
.bind = sock_no_bind,
.getname = sock_no_getname,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static struct proto bnep_proto = {
.name = "BNEP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct bt_sock)
};
static int bnep_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &bnep_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &bnep_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = BT_OPEN;
bt_sock_link(&bnep_sk_list, sk);
return 0;
}
static const struct net_proto_family bnep_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = bnep_sock_create
};
int __init bnep_sock_init(void)
{
int err;
err = proto_register(&bnep_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_BNEP, &bnep_sock_family_ops);
if (err < 0) {
BT_ERR("Can't register BNEP socket");
goto error;
}
err = bt_procfs_init(&init_net, "bnep", &bnep_sk_list, NULL);
if (err < 0) {
BT_ERR("Failed to create BNEP proc file");
bt_sock_unregister(BTPROTO_BNEP);
goto error;
}
BT_INFO("BNEP socket layer initialized");
return 0;
error:
proto_unregister(&bnep_proto);
return err;
}
void __exit bnep_sock_cleanup(void)
{
bt_procfs_cleanup(&init_net, "bnep");
bt_sock_unregister(BTPROTO_BNEP);
proto_unregister(&bnep_proto);
}
| gpl-2.0 |
Jackeagle/android_kernel_lge_d838 | drivers/scsi/aacraid/commsup.c | 4853 | 55043 | /*
* Adaptec AAC series RAID controller driver
* (c) Copyright 2001 Red Hat Inc.
*
* based on the old aacraid driver that is..
* Adaptec aacraid device driver for Linux.
*
* Copyright (c) 2000-2010 Adaptec, Inc.
* 2010 PMC-Sierra, Inc. (aacraid@pmc-sierra.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Module Name:
* commsup.c
*
* Abstract: Contain all routines that are required for FSA host/adapter
* communication.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/interrupt.h>
#include <linux/semaphore.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_cmnd.h>
#include "aacraid.h"
/**
* fib_map_alloc - allocate the fib objects
* @dev: Adapter to allocate for
*
* Allocate and map the shared PCI space for the FIB blocks used to
* talk to the Adaptec firmware.
*/
static int fib_map_alloc(struct aac_dev *dev)
{
dprintk((KERN_INFO
"allocate hardware fibs pci_alloc_consistent(%p, %d * (%d + %d), %p)\n",
dev->pdev, dev->max_fib_size, dev->scsi_host_ptr->can_queue,
AAC_NUM_MGT_FIB, &dev->hw_fib_pa));
dev->hw_fib_va = pci_alloc_consistent(dev->pdev,
(dev->max_fib_size + sizeof(struct aac_fib_xporthdr))
* (dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB) + (ALIGN32 - 1),
&dev->hw_fib_pa);
if (dev->hw_fib_va == NULL)
return -ENOMEM;
return 0;
}
/**
* aac_fib_map_free - free the fib objects
* @dev: Adapter to free
*
* Free the PCI mappings and the memory allocated for FIB blocks
* on this adapter.
*/
void aac_fib_map_free(struct aac_dev *dev)
{
pci_free_consistent(dev->pdev,
dev->max_fib_size * (dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB),
dev->hw_fib_va, dev->hw_fib_pa);
dev->hw_fib_va = NULL;
dev->hw_fib_pa = 0;
}
/**
* aac_fib_setup - setup the fibs
* @dev: Adapter to set up
*
* Allocate the PCI space for the fibs, map it and then initialise the
* fib area, the unmapped fib data and also the free list
*/
int aac_fib_setup(struct aac_dev * dev)
{
struct fib *fibptr;
struct hw_fib *hw_fib;
dma_addr_t hw_fib_pa;
int i;
while (((i = fib_map_alloc(dev)) == -ENOMEM)
&& (dev->scsi_host_ptr->can_queue > (64 - AAC_NUM_MGT_FIB))) {
dev->init->MaxIoCommands = cpu_to_le32((dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB) >> 1);
dev->scsi_host_ptr->can_queue = le32_to_cpu(dev->init->MaxIoCommands) - AAC_NUM_MGT_FIB;
}
if (i<0)
return -ENOMEM;
/* 32 byte alignment for PMC */
hw_fib_pa = (dev->hw_fib_pa + (ALIGN32 - 1)) & ~(ALIGN32 - 1);
dev->hw_fib_va = (struct hw_fib *)((unsigned char *)dev->hw_fib_va +
(hw_fib_pa - dev->hw_fib_pa));
dev->hw_fib_pa = hw_fib_pa;
memset(dev->hw_fib_va, 0,
(dev->max_fib_size + sizeof(struct aac_fib_xporthdr)) *
(dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB));
/* add Xport header */
dev->hw_fib_va = (struct hw_fib *)((unsigned char *)dev->hw_fib_va +
sizeof(struct aac_fib_xporthdr));
dev->hw_fib_pa += sizeof(struct aac_fib_xporthdr);
hw_fib = dev->hw_fib_va;
hw_fib_pa = dev->hw_fib_pa;
/*
* Initialise the fibs
*/
for (i = 0, fibptr = &dev->fibs[i];
i < (dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB);
i++, fibptr++)
{
fibptr->dev = dev;
fibptr->hw_fib_va = hw_fib;
fibptr->data = (void *) fibptr->hw_fib_va->data;
fibptr->next = fibptr+1; /* Forward chain the fibs */
sema_init(&fibptr->event_wait, 0);
spin_lock_init(&fibptr->event_lock);
hw_fib->header.XferState = cpu_to_le32(0xffffffff);
hw_fib->header.SenderSize = cpu_to_le16(dev->max_fib_size);
fibptr->hw_fib_pa = hw_fib_pa;
hw_fib = (struct hw_fib *)((unsigned char *)hw_fib +
dev->max_fib_size + sizeof(struct aac_fib_xporthdr));
hw_fib_pa = hw_fib_pa +
dev->max_fib_size + sizeof(struct aac_fib_xporthdr);
}
/*
* Add the fib chain to the free list
*/
dev->fibs[dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB - 1].next = NULL;
/*
* Enable this to debug out of queue space
*/
dev->free_fib = &dev->fibs[0];
return 0;
}
/**
* aac_fib_alloc - allocate a fib
* @dev: Adapter to allocate the fib for
*
* Allocate a fib from the adapter fib pool. If the pool is empty we
* return NULL.
*/
struct fib *aac_fib_alloc(struct aac_dev *dev)
{
struct fib * fibptr;
unsigned long flags;
spin_lock_irqsave(&dev->fib_lock, flags);
fibptr = dev->free_fib;
if(!fibptr){
spin_unlock_irqrestore(&dev->fib_lock, flags);
return fibptr;
}
dev->free_fib = fibptr->next;
spin_unlock_irqrestore(&dev->fib_lock, flags);
/*
* Set the proper node type code and node byte size
*/
fibptr->type = FSAFS_NTC_FIB_CONTEXT;
fibptr->size = sizeof(struct fib);
/*
* Null out fields that depend on being zero at the start of
* each I/O
*/
fibptr->hw_fib_va->header.XferState = 0;
fibptr->flags = 0;
fibptr->callback = NULL;
fibptr->callback_data = NULL;
return fibptr;
}
/**
* aac_fib_free - free a fib
* @fibptr: fib to free up
*
* Frees up a fib and places it on the appropriate queue
*/
void aac_fib_free(struct fib *fibptr)
{
unsigned long flags, flagsv;
spin_lock_irqsave(&fibptr->event_lock, flagsv);
if (fibptr->done == 2) {
spin_unlock_irqrestore(&fibptr->event_lock, flagsv);
return;
}
spin_unlock_irqrestore(&fibptr->event_lock, flagsv);
spin_lock_irqsave(&fibptr->dev->fib_lock, flags);
if (unlikely(fibptr->flags & FIB_CONTEXT_FLAG_TIMED_OUT))
aac_config.fib_timeouts++;
if (fibptr->hw_fib_va->header.XferState != 0) {
printk(KERN_WARNING "aac_fib_free, XferState != 0, fibptr = 0x%p, XferState = 0x%x\n",
(void*)fibptr,
le32_to_cpu(fibptr->hw_fib_va->header.XferState));
}
fibptr->next = fibptr->dev->free_fib;
fibptr->dev->free_fib = fibptr;
spin_unlock_irqrestore(&fibptr->dev->fib_lock, flags);
}
/**
* aac_fib_init - initialise a fib
* @fibptr: The fib to initialize
*
* Set up the generic fib fields ready for use
*/
void aac_fib_init(struct fib *fibptr)
{
struct hw_fib *hw_fib = fibptr->hw_fib_va;
hw_fib->header.StructType = FIB_MAGIC;
hw_fib->header.Size = cpu_to_le16(fibptr->dev->max_fib_size);
hw_fib->header.XferState = cpu_to_le32(HostOwned | FibInitialized | FibEmpty | FastResponseCapable);
hw_fib->header.SenderFibAddress = 0; /* Filled in later if needed */
hw_fib->header.ReceiverFibAddress = cpu_to_le32(fibptr->hw_fib_pa);
hw_fib->header.SenderSize = cpu_to_le16(fibptr->dev->max_fib_size);
}
/**
* fib_deallocate - deallocate a fib
* @fibptr: fib to deallocate
*
* Will deallocate and return to the free pool the FIB pointed to by the
* caller.
*/
static void fib_dealloc(struct fib * fibptr)
{
struct hw_fib *hw_fib = fibptr->hw_fib_va;
BUG_ON(hw_fib->header.StructType != FIB_MAGIC);
hw_fib->header.XferState = 0;
}
/*
* Commuication primitives define and support the queuing method we use to
* support host to adapter commuication. All queue accesses happen through
* these routines and are the only routines which have a knowledge of the
* how these queues are implemented.
*/
/**
* aac_get_entry - get a queue entry
* @dev: Adapter
* @qid: Queue Number
* @entry: Entry return
* @index: Index return
* @nonotify: notification control
*
* With a priority the routine returns a queue entry if the queue has free entries. If the queue
* is full(no free entries) than no entry is returned and the function returns 0 otherwise 1 is
* returned.
*/
static int aac_get_entry (struct aac_dev * dev, u32 qid, struct aac_entry **entry, u32 * index, unsigned long *nonotify)
{
struct aac_queue * q;
unsigned long idx;
/*
* All of the queues wrap when they reach the end, so we check
* to see if they have reached the end and if they have we just
* set the index back to zero. This is a wrap. You could or off
* the high bits in all updates but this is a bit faster I think.
*/
q = &dev->queues->queue[qid];
idx = *index = le32_to_cpu(*(q->headers.producer));
/* Interrupt Moderation, only interrupt for first two entries */
if (idx != le32_to_cpu(*(q->headers.consumer))) {
if (--idx == 0) {
if (qid == AdapNormCmdQueue)
idx = ADAP_NORM_CMD_ENTRIES;
else
idx = ADAP_NORM_RESP_ENTRIES;
}
if (idx != le32_to_cpu(*(q->headers.consumer)))
*nonotify = 1;
}
if (qid == AdapNormCmdQueue) {
if (*index >= ADAP_NORM_CMD_ENTRIES)
*index = 0; /* Wrap to front of the Producer Queue. */
} else {
if (*index >= ADAP_NORM_RESP_ENTRIES)
*index = 0; /* Wrap to front of the Producer Queue. */
}
/* Queue is full */
if ((*index + 1) == le32_to_cpu(*(q->headers.consumer))) {
printk(KERN_WARNING "Queue %d full, %u outstanding.\n",
qid, q->numpending);
return 0;
} else {
*entry = q->base + *index;
return 1;
}
}
/**
* aac_queue_get - get the next free QE
* @dev: Adapter
* @index: Returned index
* @priority: Priority of fib
* @fib: Fib to associate with the queue entry
* @wait: Wait if queue full
* @fibptr: Driver fib object to go with fib
* @nonotify: Don't notify the adapter
*
* Gets the next free QE off the requested priorty adapter command
* queue and associates the Fib with the QE. The QE represented by
* index is ready to insert on the queue when this routine returns
* success.
*/
int aac_queue_get(struct aac_dev * dev, u32 * index, u32 qid, struct hw_fib * hw_fib, int wait, struct fib * fibptr, unsigned long *nonotify)
{
struct aac_entry * entry = NULL;
int map = 0;
if (qid == AdapNormCmdQueue) {
/* if no entries wait for some if caller wants to */
while (!aac_get_entry(dev, qid, &entry, index, nonotify)) {
printk(KERN_ERR "GetEntries failed\n");
}
/*
* Setup queue entry with a command, status and fib mapped
*/
entry->size = cpu_to_le32(le16_to_cpu(hw_fib->header.Size));
map = 1;
} else {
while (!aac_get_entry(dev, qid, &entry, index, nonotify)) {
/* if no entries wait for some if caller wants to */
}
/*
* Setup queue entry with command, status and fib mapped
*/
entry->size = cpu_to_le32(le16_to_cpu(hw_fib->header.Size));
entry->addr = hw_fib->header.SenderFibAddress;
/* Restore adapters pointer to the FIB */
hw_fib->header.ReceiverFibAddress = hw_fib->header.SenderFibAddress; /* Let the adapter now where to find its data */
map = 0;
}
/*
* If MapFib is true than we need to map the Fib and put pointers
* in the queue entry.
*/
if (map)
entry->addr = cpu_to_le32(fibptr->hw_fib_pa);
return 0;
}
/*
* Define the highest level of host to adapter communication routines.
* These routines will support host to adapter FS commuication. These
* routines have no knowledge of the commuication method used. This level
* sends and receives FIBs. This level has no knowledge of how these FIBs
* get passed back and forth.
*/
/**
* aac_fib_send - send a fib to the adapter
* @command: Command to send
* @fibptr: The fib
* @size: Size of fib data area
* @priority: Priority of Fib
* @wait: Async/sync select
* @reply: True if a reply is wanted
* @callback: Called with reply
* @callback_data: Passed to callback
*
* Sends the requested FIB to the adapter and optionally will wait for a
* response FIB. If the caller does not wish to wait for a response than
* an event to wait on must be supplied. This event will be set when a
* response FIB is received from the adapter.
*/
int aac_fib_send(u16 command, struct fib *fibptr, unsigned long size,
int priority, int wait, int reply, fib_callback callback,
void *callback_data)
{
struct aac_dev * dev = fibptr->dev;
struct hw_fib * hw_fib = fibptr->hw_fib_va;
unsigned long flags = 0;
unsigned long qflags;
unsigned long mflags = 0;
unsigned long sflags = 0;
if (!(hw_fib->header.XferState & cpu_to_le32(HostOwned)))
return -EBUSY;
/*
* There are 5 cases with the wait and response requested flags.
* The only invalid cases are if the caller requests to wait and
* does not request a response and if the caller does not want a
* response and the Fib is not allocated from pool. If a response
* is not requesed the Fib will just be deallocaed by the DPC
* routine when the response comes back from the adapter. No
* further processing will be done besides deleting the Fib. We
* will have a debug mode where the adapter can notify the host
* it had a problem and the host can log that fact.
*/
fibptr->flags = 0;
if (wait && !reply) {
return -EINVAL;
} else if (!wait && reply) {
hw_fib->header.XferState |= cpu_to_le32(Async | ResponseExpected);
FIB_COUNTER_INCREMENT(aac_config.AsyncSent);
} else if (!wait && !reply) {
hw_fib->header.XferState |= cpu_to_le32(NoResponseExpected);
FIB_COUNTER_INCREMENT(aac_config.NoResponseSent);
} else if (wait && reply) {
hw_fib->header.XferState |= cpu_to_le32(ResponseExpected);
FIB_COUNTER_INCREMENT(aac_config.NormalSent);
}
/*
* Map the fib into 32bits by using the fib number
*/
hw_fib->header.SenderFibAddress = cpu_to_le32(((u32)(fibptr - dev->fibs)) << 2);
hw_fib->header.SenderData = (u32)(fibptr - dev->fibs);
/*
* Set FIB state to indicate where it came from and if we want a
* response from the adapter. Also load the command from the
* caller.
*
* Map the hw fib pointer as a 32bit value
*/
hw_fib->header.Command = cpu_to_le16(command);
hw_fib->header.XferState |= cpu_to_le32(SentFromHost);
fibptr->hw_fib_va->header.Flags = 0; /* 0 the flags field - internal only*/
/*
* Set the size of the Fib we want to send to the adapter
*/
hw_fib->header.Size = cpu_to_le16(sizeof(struct aac_fibhdr) + size);
if (le16_to_cpu(hw_fib->header.Size) > le16_to_cpu(hw_fib->header.SenderSize)) {
return -EMSGSIZE;
}
/*
* Get a queue entry connect the FIB to it and send an notify
* the adapter a command is ready.
*/
hw_fib->header.XferState |= cpu_to_le32(NormalPriority);
/*
* Fill in the Callback and CallbackContext if we are not
* going to wait.
*/
if (!wait) {
fibptr->callback = callback;
fibptr->callback_data = callback_data;
fibptr->flags = FIB_CONTEXT_FLAG;
}
fibptr->done = 0;
FIB_COUNTER_INCREMENT(aac_config.FibsSent);
dprintk((KERN_DEBUG "Fib contents:.\n"));
dprintk((KERN_DEBUG " Command = %d.\n", le32_to_cpu(hw_fib->header.Command)));
dprintk((KERN_DEBUG " SubCommand = %d.\n", le32_to_cpu(((struct aac_query_mount *)fib_data(fibptr))->command)));
dprintk((KERN_DEBUG " XferState = %x.\n", le32_to_cpu(hw_fib->header.XferState)));
dprintk((KERN_DEBUG " hw_fib va being sent=%p\n",fibptr->hw_fib_va));
dprintk((KERN_DEBUG " hw_fib pa being sent=%lx\n",(ulong)fibptr->hw_fib_pa));
dprintk((KERN_DEBUG " fib being sent=%p\n",fibptr));
if (!dev->queues)
return -EBUSY;
if (wait) {
spin_lock_irqsave(&dev->manage_lock, mflags);
if (dev->management_fib_count >= AAC_NUM_MGT_FIB) {
printk(KERN_INFO "No management Fibs Available:%d\n",
dev->management_fib_count);
spin_unlock_irqrestore(&dev->manage_lock, mflags);
return -EBUSY;
}
dev->management_fib_count++;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
spin_lock_irqsave(&fibptr->event_lock, flags);
}
if (dev->sync_mode) {
if (wait)
spin_unlock_irqrestore(&fibptr->event_lock, flags);
spin_lock_irqsave(&dev->sync_lock, sflags);
if (dev->sync_fib) {
list_add_tail(&fibptr->fiblink, &dev->sync_fib_list);
spin_unlock_irqrestore(&dev->sync_lock, sflags);
} else {
dev->sync_fib = fibptr;
spin_unlock_irqrestore(&dev->sync_lock, sflags);
aac_adapter_sync_cmd(dev, SEND_SYNCHRONOUS_FIB,
(u32)fibptr->hw_fib_pa, 0, 0, 0, 0, 0,
NULL, NULL, NULL, NULL, NULL);
}
if (wait) {
fibptr->flags |= FIB_CONTEXT_FLAG_WAIT;
if (down_interruptible(&fibptr->event_wait)) {
fibptr->flags &= ~FIB_CONTEXT_FLAG_WAIT;
return -EFAULT;
}
return 0;
}
return -EINPROGRESS;
}
if (aac_adapter_deliver(fibptr) != 0) {
printk(KERN_ERR "aac_fib_send: returned -EBUSY\n");
if (wait) {
spin_unlock_irqrestore(&fibptr->event_lock, flags);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
}
return -EBUSY;
}
/*
* If the caller wanted us to wait for response wait now.
*/
if (wait) {
spin_unlock_irqrestore(&fibptr->event_lock, flags);
/* Only set for first known interruptable command */
if (wait < 0) {
/*
* *VERY* Dangerous to time out a command, the
* assumption is made that we have no hope of
* functioning because an interrupt routing or other
* hardware failure has occurred.
*/
unsigned long count = 36000000L; /* 3 minutes */
while (down_trylock(&fibptr->event_wait)) {
int blink;
if (--count == 0) {
struct aac_queue * q = &dev->queues->queue[AdapNormCmdQueue];
spin_lock_irqsave(q->lock, qflags);
q->numpending--;
spin_unlock_irqrestore(q->lock, qflags);
if (wait == -1) {
printk(KERN_ERR "aacraid: aac_fib_send: first asynchronous command timed out.\n"
"Usually a result of a PCI interrupt routing problem;\n"
"update mother board BIOS or consider utilizing one of\n"
"the SAFE mode kernel options (acpi, apic etc)\n");
}
return -ETIMEDOUT;
}
if ((blink = aac_adapter_check_health(dev)) > 0) {
if (wait == -1) {
printk(KERN_ERR "aacraid: aac_fib_send: adapter blinkLED 0x%x.\n"
"Usually a result of a serious unrecoverable hardware problem\n",
blink);
}
return -EFAULT;
}
udelay(5);
}
} else if (down_interruptible(&fibptr->event_wait)) {
/* Do nothing ... satisfy
* down_interruptible must_check */
}
spin_lock_irqsave(&fibptr->event_lock, flags);
if (fibptr->done == 0) {
fibptr->done = 2; /* Tell interrupt we aborted */
spin_unlock_irqrestore(&fibptr->event_lock, flags);
return -ERESTARTSYS;
}
spin_unlock_irqrestore(&fibptr->event_lock, flags);
BUG_ON(fibptr->done == 0);
if(unlikely(fibptr->flags & FIB_CONTEXT_FLAG_TIMED_OUT))
return -ETIMEDOUT;
return 0;
}
/*
* If the user does not want a response than return success otherwise
* return pending
*/
if (reply)
return -EINPROGRESS;
else
return 0;
}
/**
* aac_consumer_get - get the top of the queue
* @dev: Adapter
* @q: Queue
* @entry: Return entry
*
* Will return a pointer to the entry on the top of the queue requested that
* we are a consumer of, and return the address of the queue entry. It does
* not change the state of the queue.
*/
int aac_consumer_get(struct aac_dev * dev, struct aac_queue * q, struct aac_entry **entry)
{
u32 index;
int status;
if (le32_to_cpu(*q->headers.producer) == le32_to_cpu(*q->headers.consumer)) {
status = 0;
} else {
/*
* The consumer index must be wrapped if we have reached
* the end of the queue, else we just use the entry
* pointed to by the header index
*/
if (le32_to_cpu(*q->headers.consumer) >= q->entries)
index = 0;
else
index = le32_to_cpu(*q->headers.consumer);
*entry = q->base + index;
status = 1;
}
return(status);
}
/**
* aac_consumer_free - free consumer entry
* @dev: Adapter
* @q: Queue
* @qid: Queue ident
*
* Frees up the current top of the queue we are a consumer of. If the
* queue was full notify the producer that the queue is no longer full.
*/
void aac_consumer_free(struct aac_dev * dev, struct aac_queue *q, u32 qid)
{
int wasfull = 0;
u32 notify;
if ((le32_to_cpu(*q->headers.producer)+1) == le32_to_cpu(*q->headers.consumer))
wasfull = 1;
if (le32_to_cpu(*q->headers.consumer) >= q->entries)
*q->headers.consumer = cpu_to_le32(1);
else
le32_add_cpu(q->headers.consumer, 1);
if (wasfull) {
switch (qid) {
case HostNormCmdQueue:
notify = HostNormCmdNotFull;
break;
case HostNormRespQueue:
notify = HostNormRespNotFull;
break;
default:
BUG();
return;
}
aac_adapter_notify(dev, notify);
}
}
/**
* aac_fib_adapter_complete - complete adapter issued fib
* @fibptr: fib to complete
* @size: size of fib
*
* Will do all necessary work to complete a FIB that was sent from
* the adapter.
*/
int aac_fib_adapter_complete(struct fib *fibptr, unsigned short size)
{
struct hw_fib * hw_fib = fibptr->hw_fib_va;
struct aac_dev * dev = fibptr->dev;
struct aac_queue * q;
unsigned long nointr = 0;
unsigned long qflags;
if (dev->comm_interface == AAC_COMM_MESSAGE_TYPE1) {
kfree(hw_fib);
return 0;
}
if (hw_fib->header.XferState == 0) {
if (dev->comm_interface == AAC_COMM_MESSAGE)
kfree(hw_fib);
return 0;
}
/*
* If we plan to do anything check the structure type first.
*/
if (hw_fib->header.StructType != FIB_MAGIC) {
if (dev->comm_interface == AAC_COMM_MESSAGE)
kfree(hw_fib);
return -EINVAL;
}
/*
* This block handles the case where the adapter had sent us a
* command and we have finished processing the command. We
* call completeFib when we are done processing the command
* and want to send a response back to the adapter. This will
* send the completed cdb to the adapter.
*/
if (hw_fib->header.XferState & cpu_to_le32(SentFromAdapter)) {
if (dev->comm_interface == AAC_COMM_MESSAGE) {
kfree (hw_fib);
} else {
u32 index;
hw_fib->header.XferState |= cpu_to_le32(HostProcessed);
if (size) {
size += sizeof(struct aac_fibhdr);
if (size > le16_to_cpu(hw_fib->header.SenderSize))
return -EMSGSIZE;
hw_fib->header.Size = cpu_to_le16(size);
}
q = &dev->queues->queue[AdapNormRespQueue];
spin_lock_irqsave(q->lock, qflags);
aac_queue_get(dev, &index, AdapNormRespQueue, hw_fib, 1, NULL, &nointr);
*(q->headers.producer) = cpu_to_le32(index + 1);
spin_unlock_irqrestore(q->lock, qflags);
if (!(nointr & (int)aac_config.irq_mod))
aac_adapter_notify(dev, AdapNormRespQueue);
}
} else {
printk(KERN_WARNING "aac_fib_adapter_complete: "
"Unknown xferstate detected.\n");
BUG();
}
return 0;
}
/**
* aac_fib_complete - fib completion handler
* @fib: FIB to complete
*
* Will do all necessary work to complete a FIB.
*/
int aac_fib_complete(struct fib *fibptr)
{
unsigned long flags;
struct hw_fib * hw_fib = fibptr->hw_fib_va;
/*
* Check for a fib which has already been completed
*/
if (hw_fib->header.XferState == 0)
return 0;
/*
* If we plan to do anything check the structure type first.
*/
if (hw_fib->header.StructType != FIB_MAGIC)
return -EINVAL;
/*
* This block completes a cdb which orginated on the host and we
* just need to deallocate the cdb or reinit it. At this point the
* command is complete that we had sent to the adapter and this
* cdb could be reused.
*/
spin_lock_irqsave(&fibptr->event_lock, flags);
if (fibptr->done == 2) {
spin_unlock_irqrestore(&fibptr->event_lock, flags);
return 0;
}
spin_unlock_irqrestore(&fibptr->event_lock, flags);
if((hw_fib->header.XferState & cpu_to_le32(SentFromHost)) &&
(hw_fib->header.XferState & cpu_to_le32(AdapterProcessed)))
{
fib_dealloc(fibptr);
}
else if(hw_fib->header.XferState & cpu_to_le32(SentFromHost))
{
/*
* This handles the case when the host has aborted the I/O
* to the adapter because the adapter is not responding
*/
fib_dealloc(fibptr);
} else if(hw_fib->header.XferState & cpu_to_le32(HostOwned)) {
fib_dealloc(fibptr);
} else {
BUG();
}
return 0;
}
/**
* aac_printf - handle printf from firmware
* @dev: Adapter
* @val: Message info
*
* Print a message passed to us by the controller firmware on the
* Adaptec board
*/
void aac_printf(struct aac_dev *dev, u32 val)
{
char *cp = dev->printfbuf;
if (dev->printf_enabled)
{
int length = val & 0xffff;
int level = (val >> 16) & 0xffff;
/*
* The size of the printfbuf is set in port.c
* There is no variable or define for it
*/
if (length > 255)
length = 255;
if (cp[length] != 0)
cp[length] = 0;
if (level == LOG_AAC_HIGH_ERROR)
printk(KERN_WARNING "%s:%s", dev->name, cp);
else
printk(KERN_INFO "%s:%s", dev->name, cp);
}
memset(cp, 0, 256);
}
/**
* aac_handle_aif - Handle a message from the firmware
* @dev: Which adapter this fib is from
* @fibptr: Pointer to fibptr from adapter
*
* This routine handles a driver notify fib from the adapter and
* dispatches it to the appropriate routine for handling.
*/
#define AIF_SNIFF_TIMEOUT (30*HZ)
static void aac_handle_aif(struct aac_dev * dev, struct fib * fibptr)
{
struct hw_fib * hw_fib = fibptr->hw_fib_va;
struct aac_aifcmd * aifcmd = (struct aac_aifcmd *)hw_fib->data;
u32 channel, id, lun, container;
struct scsi_device *device;
enum {
NOTHING,
DELETE,
ADD,
CHANGE
} device_config_needed = NOTHING;
/* Sniff for container changes */
if (!dev || !dev->fsa_dev)
return;
container = channel = id = lun = (u32)-1;
/*
* We have set this up to try and minimize the number of
* re-configures that take place. As a result of this when
* certain AIF's come in we will set a flag waiting for another
* type of AIF before setting the re-config flag.
*/
switch (le32_to_cpu(aifcmd->command)) {
case AifCmdDriverNotify:
switch (le32_to_cpu(((__le32 *)aifcmd->data)[0])) {
/*
* Morph or Expand complete
*/
case AifDenMorphComplete:
case AifDenVolumeExtendComplete:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
/*
* Find the scsi_device associated with the SCSI
* address. Make sure we have the right array, and if
* so set the flag to initiate a new re-config once we
* see an AifEnConfigChange AIF come through.
*/
if ((dev != NULL) && (dev->scsi_host_ptr != NULL)) {
device = scsi_device_lookup(dev->scsi_host_ptr,
CONTAINER_TO_CHANNEL(container),
CONTAINER_TO_ID(container),
CONTAINER_TO_LUN(container));
if (device) {
dev->fsa_dev[container].config_needed = CHANGE;
dev->fsa_dev[container].config_waiting_on = AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
scsi_device_put(device);
}
}
}
/*
* If we are waiting on something and this happens to be
* that thing then set the re-configure flag.
*/
if (container != (u32)-1) {
if (container >= dev->maximum_num_containers)
break;
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
} else for (container = 0;
container < dev->maximum_num_containers; ++container) {
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
}
break;
case AifCmdEventNotify:
switch (le32_to_cpu(((__le32 *)aifcmd->data)[0])) {
case AifEnBatteryEvent:
dev->cache_protected =
(((__le32 *)aifcmd->data)[1] == cpu_to_le32(3));
break;
/*
* Add an Array.
*/
case AifEnAddContainer:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
dev->fsa_dev[container].config_needed = ADD;
dev->fsa_dev[container].config_waiting_on =
AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
break;
/*
* Delete an Array.
*/
case AifEnDeleteContainer:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
dev->fsa_dev[container].config_needed = DELETE;
dev->fsa_dev[container].config_waiting_on =
AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
break;
/*
* Container change detected. If we currently are not
* waiting on something else, setup to wait on a Config Change.
*/
case AifEnContainerChange:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
if (dev->fsa_dev[container].config_waiting_on &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
break;
dev->fsa_dev[container].config_needed = CHANGE;
dev->fsa_dev[container].config_waiting_on =
AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
break;
case AifEnConfigChange:
break;
case AifEnAddJBOD:
case AifEnDeleteJBOD:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if ((container >> 28)) {
container = (u32)-1;
break;
}
channel = (container >> 24) & 0xF;
if (channel >= dev->maximum_num_channels) {
container = (u32)-1;
break;
}
id = container & 0xFFFF;
if (id >= dev->maximum_num_physicals) {
container = (u32)-1;
break;
}
lun = (container >> 16) & 0xFF;
container = (u32)-1;
channel = aac_phys_to_logical(channel);
device_config_needed =
(((__le32 *)aifcmd->data)[0] ==
cpu_to_le32(AifEnAddJBOD)) ? ADD : DELETE;
if (device_config_needed == ADD) {
device = scsi_device_lookup(dev->scsi_host_ptr,
channel,
id,
lun);
if (device) {
scsi_remove_device(device);
scsi_device_put(device);
}
}
break;
case AifEnEnclosureManagement:
/*
* If in JBOD mode, automatic exposure of new
* physical target to be suppressed until configured.
*/
if (dev->jbod)
break;
switch (le32_to_cpu(((__le32 *)aifcmd->data)[3])) {
case EM_DRIVE_INSERTION:
case EM_DRIVE_REMOVAL:
container = le32_to_cpu(
((__le32 *)aifcmd->data)[2]);
if ((container >> 28)) {
container = (u32)-1;
break;
}
channel = (container >> 24) & 0xF;
if (channel >= dev->maximum_num_channels) {
container = (u32)-1;
break;
}
id = container & 0xFFFF;
lun = (container >> 16) & 0xFF;
container = (u32)-1;
if (id >= dev->maximum_num_physicals) {
/* legacy dev_t ? */
if ((0x2000 <= id) || lun || channel ||
((channel = (id >> 7) & 0x3F) >=
dev->maximum_num_channels))
break;
lun = (id >> 4) & 7;
id &= 0xF;
}
channel = aac_phys_to_logical(channel);
device_config_needed =
(((__le32 *)aifcmd->data)[3]
== cpu_to_le32(EM_DRIVE_INSERTION)) ?
ADD : DELETE;
break;
}
break;
}
/*
* If we are waiting on something and this happens to be
* that thing then set the re-configure flag.
*/
if (container != (u32)-1) {
if (container >= dev->maximum_num_containers)
break;
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
} else for (container = 0;
container < dev->maximum_num_containers; ++container) {
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
}
break;
case AifCmdJobProgress:
/*
* These are job progress AIF's. When a Clear is being
* done on a container it is initially created then hidden from
* the OS. When the clear completes we don't get a config
* change so we monitor the job status complete on a clear then
* wait for a container change.
*/
if (((__le32 *)aifcmd->data)[1] == cpu_to_le32(AifJobCtrZero) &&
(((__le32 *)aifcmd->data)[6] == ((__le32 *)aifcmd->data)[5] ||
((__le32 *)aifcmd->data)[4] == cpu_to_le32(AifJobStsSuccess))) {
for (container = 0;
container < dev->maximum_num_containers;
++container) {
/*
* Stomp on all config sequencing for all
* containers?
*/
dev->fsa_dev[container].config_waiting_on =
AifEnContainerChange;
dev->fsa_dev[container].config_needed = ADD;
dev->fsa_dev[container].config_waiting_stamp =
jiffies;
}
}
if (((__le32 *)aifcmd->data)[1] == cpu_to_le32(AifJobCtrZero) &&
((__le32 *)aifcmd->data)[6] == 0 &&
((__le32 *)aifcmd->data)[4] == cpu_to_le32(AifJobStsRunning)) {
for (container = 0;
container < dev->maximum_num_containers;
++container) {
/*
* Stomp on all config sequencing for all
* containers?
*/
dev->fsa_dev[container].config_waiting_on =
AifEnContainerChange;
dev->fsa_dev[container].config_needed = DELETE;
dev->fsa_dev[container].config_waiting_stamp =
jiffies;
}
}
break;
}
container = 0;
retry_next:
if (device_config_needed == NOTHING)
for (; container < dev->maximum_num_containers; ++container) {
if ((dev->fsa_dev[container].config_waiting_on == 0) &&
(dev->fsa_dev[container].config_needed != NOTHING) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT)) {
device_config_needed =
dev->fsa_dev[container].config_needed;
dev->fsa_dev[container].config_needed = NOTHING;
channel = CONTAINER_TO_CHANNEL(container);
id = CONTAINER_TO_ID(container);
lun = CONTAINER_TO_LUN(container);
break;
}
}
if (device_config_needed == NOTHING)
return;
/*
* If we decided that a re-configuration needs to be done,
* schedule it here on the way out the door, please close the door
* behind you.
*/
/*
* Find the scsi_device associated with the SCSI address,
* and mark it as changed, invalidating the cache. This deals
* with changes to existing device IDs.
*/
if (!dev || !dev->scsi_host_ptr)
return;
/*
* force reload of disk info via aac_probe_container
*/
if ((channel == CONTAINER_CHANNEL) &&
(device_config_needed != NOTHING)) {
if (dev->fsa_dev[container].valid == 1)
dev->fsa_dev[container].valid = 2;
aac_probe_container(dev, container);
}
device = scsi_device_lookup(dev->scsi_host_ptr, channel, id, lun);
if (device) {
switch (device_config_needed) {
case DELETE:
#if (defined(AAC_DEBUG_INSTRUMENT_AIF_DELETE))
scsi_remove_device(device);
#else
if (scsi_device_online(device)) {
scsi_device_set_state(device, SDEV_OFFLINE);
sdev_printk(KERN_INFO, device,
"Device offlined - %s\n",
(channel == CONTAINER_CHANNEL) ?
"array deleted" :
"enclosure services event");
}
#endif
break;
case ADD:
if (!scsi_device_online(device)) {
sdev_printk(KERN_INFO, device,
"Device online - %s\n",
(channel == CONTAINER_CHANNEL) ?
"array created" :
"enclosure services event");
scsi_device_set_state(device, SDEV_RUNNING);
}
/* FALLTHRU */
case CHANGE:
if ((channel == CONTAINER_CHANNEL)
&& (!dev->fsa_dev[container].valid)) {
#if (defined(AAC_DEBUG_INSTRUMENT_AIF_DELETE))
scsi_remove_device(device);
#else
if (!scsi_device_online(device))
break;
scsi_device_set_state(device, SDEV_OFFLINE);
sdev_printk(KERN_INFO, device,
"Device offlined - %s\n",
"array failed");
#endif
break;
}
scsi_rescan_device(&device->sdev_gendev);
default:
break;
}
scsi_device_put(device);
device_config_needed = NOTHING;
}
if (device_config_needed == ADD)
scsi_add_device(dev->scsi_host_ptr, channel, id, lun);
if (channel == CONTAINER_CHANNEL) {
container++;
device_config_needed = NOTHING;
goto retry_next;
}
}
static int _aac_reset_adapter(struct aac_dev *aac, int forced)
{
int index, quirks;
int retval;
struct Scsi_Host *host;
struct scsi_device *dev;
struct scsi_cmnd *command;
struct scsi_cmnd *command_list;
int jafo = 0;
/*
* Assumptions:
* - host is locked, unless called by the aacraid thread.
* (a matter of convenience, due to legacy issues surrounding
* eh_host_adapter_reset).
* - in_reset is asserted, so no new i/o is getting to the
* card.
* - The card is dead, or will be very shortly ;-/ so no new
* commands are completing in the interrupt service.
*/
host = aac->scsi_host_ptr;
scsi_block_requests(host);
aac_adapter_disable_int(aac);
if (aac->thread->pid != current->pid) {
spin_unlock_irq(host->host_lock);
kthread_stop(aac->thread);
jafo = 1;
}
/*
* If a positive health, means in a known DEAD PANIC
* state and the adapter could be reset to `try again'.
*/
retval = aac_adapter_restart(aac, forced ? 0 : aac_adapter_check_health(aac));
if (retval)
goto out;
/*
* Loop through the fibs, close the synchronous FIBS
*/
for (retval = 1, index = 0; index < (aac->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB); index++) {
struct fib *fib = &aac->fibs[index];
if (!(fib->hw_fib_va->header.XferState & cpu_to_le32(NoResponseExpected | Async)) &&
(fib->hw_fib_va->header.XferState & cpu_to_le32(ResponseExpected))) {
unsigned long flagv;
spin_lock_irqsave(&fib->event_lock, flagv);
up(&fib->event_wait);
spin_unlock_irqrestore(&fib->event_lock, flagv);
schedule();
retval = 0;
}
}
/* Give some extra time for ioctls to complete. */
if (retval == 0)
ssleep(2);
index = aac->cardtype;
/*
* Re-initialize the adapter, first free resources, then carefully
* apply the initialization sequence to come back again. Only risk
* is a change in Firmware dropping cache, it is assumed the caller
* will ensure that i/o is queisced and the card is flushed in that
* case.
*/
aac_fib_map_free(aac);
pci_free_consistent(aac->pdev, aac->comm_size, aac->comm_addr, aac->comm_phys);
aac->comm_addr = NULL;
aac->comm_phys = 0;
kfree(aac->queues);
aac->queues = NULL;
free_irq(aac->pdev->irq, aac);
if (aac->msi)
pci_disable_msi(aac->pdev);
kfree(aac->fsa_dev);
aac->fsa_dev = NULL;
quirks = aac_get_driver_ident(index)->quirks;
if (quirks & AAC_QUIRK_31BIT) {
if (((retval = pci_set_dma_mask(aac->pdev, DMA_BIT_MASK(31)))) ||
((retval = pci_set_consistent_dma_mask(aac->pdev, DMA_BIT_MASK(31)))))
goto out;
} else {
if (((retval = pci_set_dma_mask(aac->pdev, DMA_BIT_MASK(32)))) ||
((retval = pci_set_consistent_dma_mask(aac->pdev, DMA_BIT_MASK(32)))))
goto out;
}
if ((retval = (*(aac_get_driver_ident(index)->init))(aac)))
goto out;
if (quirks & AAC_QUIRK_31BIT)
if ((retval = pci_set_dma_mask(aac->pdev, DMA_BIT_MASK(32))))
goto out;
if (jafo) {
aac->thread = kthread_run(aac_command_thread, aac, aac->name);
if (IS_ERR(aac->thread)) {
retval = PTR_ERR(aac->thread);
goto out;
}
}
(void)aac_get_adapter_info(aac);
if ((quirks & AAC_QUIRK_34SG) && (host->sg_tablesize > 34)) {
host->sg_tablesize = 34;
host->max_sectors = (host->sg_tablesize * 8) + 112;
}
if ((quirks & AAC_QUIRK_17SG) && (host->sg_tablesize > 17)) {
host->sg_tablesize = 17;
host->max_sectors = (host->sg_tablesize * 8) + 112;
}
aac_get_config_status(aac, 1);
aac_get_containers(aac);
/*
* This is where the assumption that the Adapter is quiesced
* is important.
*/
command_list = NULL;
__shost_for_each_device(dev, host) {
unsigned long flags;
spin_lock_irqsave(&dev->list_lock, flags);
list_for_each_entry(command, &dev->cmd_list, list)
if (command->SCp.phase == AAC_OWNER_FIRMWARE) {
command->SCp.buffer = (struct scatterlist *)command_list;
command_list = command;
}
spin_unlock_irqrestore(&dev->list_lock, flags);
}
while ((command = command_list)) {
command_list = (struct scsi_cmnd *)command->SCp.buffer;
command->SCp.buffer = NULL;
command->result = DID_OK << 16
| COMMAND_COMPLETE << 8
| SAM_STAT_TASK_SET_FULL;
command->SCp.phase = AAC_OWNER_ERROR_HANDLER;
command->scsi_done(command);
}
retval = 0;
out:
aac->in_reset = 0;
scsi_unblock_requests(host);
if (jafo) {
spin_lock_irq(host->host_lock);
}
return retval;
}
int aac_reset_adapter(struct aac_dev * aac, int forced)
{
unsigned long flagv = 0;
int retval;
struct Scsi_Host * host;
if (spin_trylock_irqsave(&aac->fib_lock, flagv) == 0)
return -EBUSY;
if (aac->in_reset) {
spin_unlock_irqrestore(&aac->fib_lock, flagv);
return -EBUSY;
}
aac->in_reset = 1;
spin_unlock_irqrestore(&aac->fib_lock, flagv);
/*
* Wait for all commands to complete to this specific
* target (block maximum 60 seconds). Although not necessary,
* it does make us a good storage citizen.
*/
host = aac->scsi_host_ptr;
scsi_block_requests(host);
if (forced < 2) for (retval = 60; retval; --retval) {
struct scsi_device * dev;
struct scsi_cmnd * command;
int active = 0;
__shost_for_each_device(dev, host) {
spin_lock_irqsave(&dev->list_lock, flagv);
list_for_each_entry(command, &dev->cmd_list, list) {
if (command->SCp.phase == AAC_OWNER_FIRMWARE) {
active++;
break;
}
}
spin_unlock_irqrestore(&dev->list_lock, flagv);
if (active)
break;
}
/*
* We can exit If all the commands are complete
*/
if (active == 0)
break;
ssleep(1);
}
/* Quiesce build, flush cache, write through mode */
if (forced < 2)
aac_send_shutdown(aac);
spin_lock_irqsave(host->host_lock, flagv);
retval = _aac_reset_adapter(aac, forced ? forced : ((aac_check_reset != 0) && (aac_check_reset != 1)));
spin_unlock_irqrestore(host->host_lock, flagv);
if ((forced < 2) && (retval == -ENODEV)) {
/* Unwind aac_send_shutdown() IOP_RESET unsupported/disabled */
struct fib * fibctx = aac_fib_alloc(aac);
if (fibctx) {
struct aac_pause *cmd;
int status;
aac_fib_init(fibctx);
cmd = (struct aac_pause *) fib_data(fibctx);
cmd->command = cpu_to_le32(VM_ContainerConfig);
cmd->type = cpu_to_le32(CT_PAUSE_IO);
cmd->timeout = cpu_to_le32(1);
cmd->min = cpu_to_le32(1);
cmd->noRescan = cpu_to_le32(1);
cmd->count = cpu_to_le32(0);
status = aac_fib_send(ContainerCommand,
fibctx,
sizeof(struct aac_pause),
FsaNormal,
-2 /* Timeout silently */, 1,
NULL, NULL);
if (status >= 0)
aac_fib_complete(fibctx);
/* FIB should be freed only after getting
* the response from the F/W */
if (status != -ERESTARTSYS)
aac_fib_free(fibctx);
}
}
return retval;
}
int aac_check_health(struct aac_dev * aac)
{
int BlinkLED;
unsigned long time_now, flagv = 0;
struct list_head * entry;
struct Scsi_Host * host;
/* Extending the scope of fib_lock slightly to protect aac->in_reset */
if (spin_trylock_irqsave(&aac->fib_lock, flagv) == 0)
return 0;
if (aac->in_reset || !(BlinkLED = aac_adapter_check_health(aac))) {
spin_unlock_irqrestore(&aac->fib_lock, flagv);
return 0; /* OK */
}
aac->in_reset = 1;
/* Fake up an AIF:
* aac_aifcmd.command = AifCmdEventNotify = 1
* aac_aifcmd.seqnum = 0xFFFFFFFF
* aac_aifcmd.data[0] = AifEnExpEvent = 23
* aac_aifcmd.data[1] = AifExeFirmwarePanic = 3
* aac.aifcmd.data[2] = AifHighPriority = 3
* aac.aifcmd.data[3] = BlinkLED
*/
time_now = jiffies/HZ;
entry = aac->fib_list.next;
/*
* For each Context that is on the
* fibctxList, make a copy of the
* fib, and then set the event to wake up the
* thread that is waiting for it.
*/
while (entry != &aac->fib_list) {
/*
* Extract the fibctx
*/
struct aac_fib_context *fibctx = list_entry(entry, struct aac_fib_context, next);
struct hw_fib * hw_fib;
struct fib * fib;
/*
* Check if the queue is getting
* backlogged
*/
if (fibctx->count > 20) {
/*
* It's *not* jiffies folks,
* but jiffies / HZ, so do not
* panic ...
*/
u32 time_last = fibctx->jiffies;
/*
* Has it been > 2 minutes
* since the last read off
* the queue?
*/
if ((time_now - time_last) > aif_timeout) {
entry = entry->next;
aac_close_fib_context(aac, fibctx);
continue;
}
}
/*
* Warning: no sleep allowed while
* holding spinlock
*/
hw_fib = kzalloc(sizeof(struct hw_fib), GFP_ATOMIC);
fib = kzalloc(sizeof(struct fib), GFP_ATOMIC);
if (fib && hw_fib) {
struct aac_aifcmd * aif;
fib->hw_fib_va = hw_fib;
fib->dev = aac;
aac_fib_init(fib);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof (struct fib);
fib->data = hw_fib->data;
aif = (struct aac_aifcmd *)hw_fib->data;
aif->command = cpu_to_le32(AifCmdEventNotify);
aif->seqnum = cpu_to_le32(0xFFFFFFFF);
((__le32 *)aif->data)[0] = cpu_to_le32(AifEnExpEvent);
((__le32 *)aif->data)[1] = cpu_to_le32(AifExeFirmwarePanic);
((__le32 *)aif->data)[2] = cpu_to_le32(AifHighPriority);
((__le32 *)aif->data)[3] = cpu_to_le32(BlinkLED);
/*
* Put the FIB onto the
* fibctx's fibs
*/
list_add_tail(&fib->fiblink, &fibctx->fib_list);
fibctx->count++;
/*
* Set the event to wake up the
* thread that will waiting.
*/
up(&fibctx->wait_sem);
} else {
printk(KERN_WARNING "aifd: didn't allocate NewFib.\n");
kfree(fib);
kfree(hw_fib);
}
entry = entry->next;
}
spin_unlock_irqrestore(&aac->fib_lock, flagv);
if (BlinkLED < 0) {
printk(KERN_ERR "%s: Host adapter dead %d\n", aac->name, BlinkLED);
goto out;
}
printk(KERN_ERR "%s: Host adapter BLINK LED 0x%x\n", aac->name, BlinkLED);
if (!aac_check_reset || ((aac_check_reset == 1) &&
(aac->supplement_adapter_info.SupportedOptions2 &
AAC_OPTION_IGNORE_RESET)))
goto out;
host = aac->scsi_host_ptr;
if (aac->thread->pid != current->pid)
spin_lock_irqsave(host->host_lock, flagv);
BlinkLED = _aac_reset_adapter(aac, aac_check_reset != 1);
if (aac->thread->pid != current->pid)
spin_unlock_irqrestore(host->host_lock, flagv);
return BlinkLED;
out:
aac->in_reset = 0;
return BlinkLED;
}
/**
* aac_command_thread - command processing thread
* @dev: Adapter to monitor
*
* Waits on the commandready event in it's queue. When the event gets set
* it will pull FIBs off it's queue. It will continue to pull FIBs off
* until the queue is empty. When the queue is empty it will wait for
* more FIBs.
*/
int aac_command_thread(void *data)
{
struct aac_dev *dev = data;
struct hw_fib *hw_fib, *hw_newfib;
struct fib *fib, *newfib;
struct aac_fib_context *fibctx;
unsigned long flags;
DECLARE_WAITQUEUE(wait, current);
unsigned long next_jiffies = jiffies + HZ;
unsigned long next_check_jiffies = next_jiffies;
long difference = HZ;
/*
* We can only have one thread per adapter for AIF's.
*/
if (dev->aif_thread)
return -EINVAL;
/*
* Let the DPC know it has a place to send the AIF's to.
*/
dev->aif_thread = 1;
add_wait_queue(&dev->queues->queue[HostNormCmdQueue].cmdready, &wait);
set_current_state(TASK_INTERRUPTIBLE);
dprintk ((KERN_INFO "aac_command_thread start\n"));
while (1) {
spin_lock_irqsave(dev->queues->queue[HostNormCmdQueue].lock, flags);
while(!list_empty(&(dev->queues->queue[HostNormCmdQueue].cmdq))) {
struct list_head *entry;
struct aac_aifcmd * aifcmd;
set_current_state(TASK_RUNNING);
entry = dev->queues->queue[HostNormCmdQueue].cmdq.next;
list_del(entry);
spin_unlock_irqrestore(dev->queues->queue[HostNormCmdQueue].lock, flags);
fib = list_entry(entry, struct fib, fiblink);
/*
* We will process the FIB here or pass it to a
* worker thread that is TBD. We Really can't
* do anything at this point since we don't have
* anything defined for this thread to do.
*/
hw_fib = fib->hw_fib_va;
memset(fib, 0, sizeof(struct fib));
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
/*
* We only handle AifRequest fibs from the adapter.
*/
aifcmd = (struct aac_aifcmd *) hw_fib->data;
if (aifcmd->command == cpu_to_le32(AifCmdDriverNotify)) {
/* Handle Driver Notify Events */
aac_handle_aif(dev, fib);
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, (u16)sizeof(u32));
} else {
/* The u32 here is important and intended. We are using
32bit wrapping time to fit the adapter field */
u32 time_now, time_last;
unsigned long flagv;
unsigned num;
struct hw_fib ** hw_fib_pool, ** hw_fib_p;
struct fib ** fib_pool, ** fib_p;
/* Sniff events */
if ((aifcmd->command ==
cpu_to_le32(AifCmdEventNotify)) ||
(aifcmd->command ==
cpu_to_le32(AifCmdJobProgress))) {
aac_handle_aif(dev, fib);
}
time_now = jiffies/HZ;
/*
* Warning: no sleep allowed while
* holding spinlock. We take the estimate
* and pre-allocate a set of fibs outside the
* lock.
*/
num = le32_to_cpu(dev->init->AdapterFibsSize)
/ sizeof(struct hw_fib); /* some extra */
spin_lock_irqsave(&dev->fib_lock, flagv);
entry = dev->fib_list.next;
while (entry != &dev->fib_list) {
entry = entry->next;
++num;
}
spin_unlock_irqrestore(&dev->fib_lock, flagv);
hw_fib_pool = NULL;
fib_pool = NULL;
if (num
&& ((hw_fib_pool = kmalloc(sizeof(struct hw_fib *) * num, GFP_KERNEL)))
&& ((fib_pool = kmalloc(sizeof(struct fib *) * num, GFP_KERNEL)))) {
hw_fib_p = hw_fib_pool;
fib_p = fib_pool;
while (hw_fib_p < &hw_fib_pool[num]) {
if (!(*(hw_fib_p++) = kmalloc(sizeof(struct hw_fib), GFP_KERNEL))) {
--hw_fib_p;
break;
}
if (!(*(fib_p++) = kmalloc(sizeof(struct fib), GFP_KERNEL))) {
kfree(*(--hw_fib_p));
break;
}
}
if ((num = hw_fib_p - hw_fib_pool) == 0) {
kfree(fib_pool);
fib_pool = NULL;
kfree(hw_fib_pool);
hw_fib_pool = NULL;
}
} else {
kfree(hw_fib_pool);
hw_fib_pool = NULL;
}
spin_lock_irqsave(&dev->fib_lock, flagv);
entry = dev->fib_list.next;
/*
* For each Context that is on the
* fibctxList, make a copy of the
* fib, and then set the event to wake up the
* thread that is waiting for it.
*/
hw_fib_p = hw_fib_pool;
fib_p = fib_pool;
while (entry != &dev->fib_list) {
/*
* Extract the fibctx
*/
fibctx = list_entry(entry, struct aac_fib_context, next);
/*
* Check if the queue is getting
* backlogged
*/
if (fibctx->count > 20)
{
/*
* It's *not* jiffies folks,
* but jiffies / HZ so do not
* panic ...
*/
time_last = fibctx->jiffies;
/*
* Has it been > 2 minutes
* since the last read off
* the queue?
*/
if ((time_now - time_last) > aif_timeout) {
entry = entry->next;
aac_close_fib_context(dev, fibctx);
continue;
}
}
/*
* Warning: no sleep allowed while
* holding spinlock
*/
if (hw_fib_p < &hw_fib_pool[num]) {
hw_newfib = *hw_fib_p;
*(hw_fib_p++) = NULL;
newfib = *fib_p;
*(fib_p++) = NULL;
/*
* Make the copy of the FIB
*/
memcpy(hw_newfib, hw_fib, sizeof(struct hw_fib));
memcpy(newfib, fib, sizeof(struct fib));
newfib->hw_fib_va = hw_newfib;
/*
* Put the FIB onto the
* fibctx's fibs
*/
list_add_tail(&newfib->fiblink, &fibctx->fib_list);
fibctx->count++;
/*
* Set the event to wake up the
* thread that is waiting.
*/
up(&fibctx->wait_sem);
} else {
printk(KERN_WARNING "aifd: didn't allocate NewFib.\n");
}
entry = entry->next;
}
/*
* Set the status of this FIB
*/
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, sizeof(u32));
spin_unlock_irqrestore(&dev->fib_lock, flagv);
/* Free up the remaining resources */
hw_fib_p = hw_fib_pool;
fib_p = fib_pool;
while (hw_fib_p < &hw_fib_pool[num]) {
kfree(*hw_fib_p);
kfree(*fib_p);
++fib_p;
++hw_fib_p;
}
kfree(hw_fib_pool);
kfree(fib_pool);
}
kfree(fib);
spin_lock_irqsave(dev->queues->queue[HostNormCmdQueue].lock, flags);
}
/*
* There are no more AIF's
*/
spin_unlock_irqrestore(dev->queues->queue[HostNormCmdQueue].lock, flags);
/*
* Background activity
*/
if ((time_before(next_check_jiffies,next_jiffies))
&& ((difference = next_check_jiffies - jiffies) <= 0)) {
next_check_jiffies = next_jiffies;
if (aac_check_health(dev) == 0) {
difference = ((long)(unsigned)check_interval)
* HZ;
next_check_jiffies = jiffies + difference;
} else if (!dev->queues)
break;
}
if (!time_before(next_check_jiffies,next_jiffies)
&& ((difference = next_jiffies - jiffies) <= 0)) {
struct timeval now;
int ret;
/* Don't even try to talk to adapter if its sick */
ret = aac_check_health(dev);
if (!ret && !dev->queues)
break;
next_check_jiffies = jiffies
+ ((long)(unsigned)check_interval)
* HZ;
do_gettimeofday(&now);
/* Synchronize our watches */
if (((1000000 - (1000000 / HZ)) > now.tv_usec)
&& (now.tv_usec > (1000000 / HZ)))
difference = (((1000000 - now.tv_usec) * HZ)
+ 500000) / 1000000;
else if (ret == 0) {
struct fib *fibptr;
if ((fibptr = aac_fib_alloc(dev))) {
int status;
__le32 *info;
aac_fib_init(fibptr);
info = (__le32 *) fib_data(fibptr);
if (now.tv_usec > 500000)
++now.tv_sec;
*info = cpu_to_le32(now.tv_sec);
status = aac_fib_send(SendHostTime,
fibptr,
sizeof(*info),
FsaNormal,
1, 1,
NULL,
NULL);
/* Do not set XferState to zero unless
* receives a response from F/W */
if (status >= 0)
aac_fib_complete(fibptr);
/* FIB should be freed only after
* getting the response from the F/W */
if (status != -ERESTARTSYS)
aac_fib_free(fibptr);
}
difference = (long)(unsigned)update_interval*HZ;
} else {
/* retry shortly */
difference = 10 * HZ;
}
next_jiffies = jiffies + difference;
if (time_before(next_check_jiffies,next_jiffies))
difference = next_check_jiffies - jiffies;
}
if (difference <= 0)
difference = 1;
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(difference);
if (kthread_should_stop())
break;
}
if (dev->queues)
remove_wait_queue(&dev->queues->queue[HostNormCmdQueue].cmdready, &wait);
dev->aif_thread = 0;
return 0;
}
| gpl-2.0 |
SlimSaber/kernel_sony_msm8974 | drivers/staging/vt6656/bssdb.c | 4853 | 53049 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: bssdb.c
*
* Purpose: Handles the Basic Service Set & Node Database functions
*
* Functions:
* BSSpSearchBSSList - Search known BSS list for Desire SSID or BSSID
* BSSvClearBSSList - Clear BSS List
* BSSbInsertToBSSList - Insert a BSS set into known BSS list
* BSSbUpdateToBSSList - Update BSS set in known BSS list
* BSSbIsSTAInNodeDB - Search Node DB table to find the index of matched DstAddr
* BSSvCreateOneNode - Allocate an Node for Node DB
* BSSvUpdateAPNode - Update AP Node content in Index 0 of KnownNodeDB
* BSSvSecondCallBack - One second timer callback function to update Node DB info & AP link status
* BSSvUpdateNodeTxCounter - Update Tx attemps, Tx failure counter in Node DB for auto-fall back rate control
*
* Revision History:
*
* Author: Lyndon Chen
*
* Date: July 17, 2002
*
*/
#include "ttype.h"
#include "tmacro.h"
#include "tether.h"
#include "device.h"
#include "80211hdr.h"
#include "bssdb.h"
#include "wmgr.h"
#include "datarate.h"
#include "desc.h"
#include "wcmd.h"
#include "wpa.h"
#include "baseband.h"
#include "rf.h"
#include "card.h"
#include "mac.h"
#include "wpa2.h"
#include "control.h"
#include "rndis.h"
#include "iowpa.h"
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
static int msglevel =MSG_LEVEL_INFO;
//static int msglevel =MSG_LEVEL_DEBUG;
const WORD awHWRetry0[5][5] = {
{RATE_18M, RATE_18M, RATE_12M, RATE_12M, RATE_12M},
{RATE_24M, RATE_24M, RATE_18M, RATE_12M, RATE_12M},
{RATE_36M, RATE_36M, RATE_24M, RATE_18M, RATE_18M},
{RATE_48M, RATE_48M, RATE_36M, RATE_24M, RATE_24M},
{RATE_54M, RATE_54M, RATE_48M, RATE_36M, RATE_36M}
};
const WORD awHWRetry1[5][5] = {
{RATE_18M, RATE_18M, RATE_12M, RATE_6M, RATE_6M},
{RATE_24M, RATE_24M, RATE_18M, RATE_6M, RATE_6M},
{RATE_36M, RATE_36M, RATE_24M, RATE_12M, RATE_12M},
{RATE_48M, RATE_48M, RATE_24M, RATE_12M, RATE_12M},
{RATE_54M, RATE_54M, RATE_36M, RATE_18M, RATE_18M}
};
/*--------------------- Static Functions --------------------------*/
void s_vCheckSensitivity(void *hDeviceContext);
void s_vCheckPreEDThreshold(void *hDeviceContext);
void s_uCalculateLinkQual(void *hDeviceContext);
/*--------------------- Export Variables --------------------------*/
/*--------------------- Export Functions --------------------------*/
/*+
*
* Routine Description:
* Search known BSS list for Desire SSID or BSSID.
*
* Return Value:
* PTR to KnownBSS or NULL
*
-*/
PKnownBSS BSSpSearchBSSList(void *hDeviceContext,
PBYTE pbyDesireBSSID,
PBYTE pbyDesireSSID,
CARD_PHY_TYPE ePhyType)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
PBYTE pbyBSSID = NULL;
PWLAN_IE_SSID pSSID = NULL;
PKnownBSS pCurrBSS = NULL;
PKnownBSS pSelect = NULL;
BYTE ZeroBSSID[WLAN_BSSID_LEN]={0x00,0x00,0x00,0x00,0x00,0x00};
unsigned int ii = 0;
unsigned int jj = 0;
if (pbyDesireBSSID != NULL) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSSpSearchBSSList BSSID[%02X %02X %02X-%02X %02X %02X]\n",
*pbyDesireBSSID,*(pbyDesireBSSID+1),*(pbyDesireBSSID+2),
*(pbyDesireBSSID+3),*(pbyDesireBSSID+4),*(pbyDesireBSSID+5));
if ((!is_broadcast_ether_addr(pbyDesireBSSID)) &&
(memcmp(pbyDesireBSSID, ZeroBSSID, 6)!= 0)){
pbyBSSID = pbyDesireBSSID;
}
}
if (pbyDesireSSID != NULL) {
if (((PWLAN_IE_SSID)pbyDesireSSID)->len != 0) {
pSSID = (PWLAN_IE_SSID) pbyDesireSSID;
}
}
if ((pbyBSSID != NULL)&&(pDevice->bRoaming == FALSE)) {
// match BSSID first
for (ii = 0; ii <MAX_BSS_NUM; ii++) {
pCurrBSS = &(pMgmt->sBSSList[ii]);
pCurrBSS->bSelected = FALSE;
if ((pCurrBSS->bActive) &&
(pCurrBSS->bSelected == FALSE)) {
if (!compare_ether_addr(pCurrBSS->abyBSSID, pbyBSSID)) {
if (pSSID != NULL) {
// compare ssid
if ( !memcmp(pSSID->abySSID,
((PWLAN_IE_SSID)pCurrBSS->abySSID)->abySSID,
pSSID->len)) {
if ((pMgmt->eConfigMode == WMAC_CONFIG_AUTO) ||
((pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) && WLAN_GET_CAP_INFO_IBSS(pCurrBSS->wCapInfo)) ||
((pMgmt->eConfigMode == WMAC_CONFIG_ESS_STA) && WLAN_GET_CAP_INFO_ESS(pCurrBSS->wCapInfo))
) {
pCurrBSS->bSelected = TRUE;
return(pCurrBSS);
}
}
} else {
if ((pMgmt->eConfigMode == WMAC_CONFIG_AUTO) ||
((pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) && WLAN_GET_CAP_INFO_IBSS(pCurrBSS->wCapInfo)) ||
((pMgmt->eConfigMode == WMAC_CONFIG_ESS_STA) && WLAN_GET_CAP_INFO_ESS(pCurrBSS->wCapInfo))
) {
pCurrBSS->bSelected = TRUE;
return(pCurrBSS);
}
}
}
}
}
} else {
// ignore BSSID
for (ii = 0; ii <MAX_BSS_NUM; ii++) {
pCurrBSS = &(pMgmt->sBSSList[ii]);
//2007-0721-01<Mark>by MikeLiu
// if ((pCurrBSS->bActive) &&
// (pCurrBSS->bSelected == FALSE)) {
pCurrBSS->bSelected = FALSE;
if (pCurrBSS->bActive) {
if (pSSID != NULL) {
// matched SSID
if (memcmp(pSSID->abySSID,
((PWLAN_IE_SSID)pCurrBSS->abySSID)->abySSID,
pSSID->len) ||
(pSSID->len != ((PWLAN_IE_SSID)pCurrBSS->abySSID)->len)) {
// SSID not match skip this BSS
continue;
}
}
if (((pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) && WLAN_GET_CAP_INFO_ESS(pCurrBSS->wCapInfo)) ||
((pMgmt->eConfigMode == WMAC_CONFIG_ESS_STA) && WLAN_GET_CAP_INFO_IBSS(pCurrBSS->wCapInfo))
){
// Type not match skip this BSS
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSS type mismatch.... Config[%d] BSS[0x%04x]\n", pMgmt->eConfigMode, pCurrBSS->wCapInfo);
continue;
}
if (ePhyType != PHY_TYPE_AUTO) {
if (((ePhyType == PHY_TYPE_11A) && (PHY_TYPE_11A != pCurrBSS->eNetworkTypeInUse)) ||
((ePhyType != PHY_TYPE_11A) && (PHY_TYPE_11A == pCurrBSS->eNetworkTypeInUse))) {
// PhyType not match skip this BSS
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Physical type mismatch.... ePhyType[%d] BSS[%d]\n", ePhyType, pCurrBSS->eNetworkTypeInUse);
continue;
}
}
pMgmt->pSameBSS[jj].uChannel = pCurrBSS->uChannel;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSSpSearchBSSList pSelect1[%02X %02X %02X-%02X %02X %02X]\n",*pCurrBSS->abyBSSID,*(pCurrBSS->abyBSSID+1),*(pCurrBSS->abyBSSID+2),*(pCurrBSS->abyBSSID+3),*(pCurrBSS->abyBSSID+4),*(pCurrBSS->abyBSSID+5));
jj++;
if (pSelect == NULL) {
pSelect = pCurrBSS;
} else {
// compare RSSI, select signal strong one
if (pCurrBSS->uRSSI < pSelect->uRSSI) {
pSelect = pCurrBSS;
}
}
}
}
pDevice->bSameBSSMaxNum = jj;
if (pSelect != NULL) {
pSelect->bSelected = TRUE;
if (pDevice->bRoaming == FALSE) {
// Einsn Add @20070907
memset(pbyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
memcpy(pbyDesireSSID,pCurrBSS->abySSID,WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1) ;
}
return(pSelect);
}
}
return(NULL);
}
/*+
*
* Routine Description:
* Clear BSS List
*
* Return Value:
* None.
*
-*/
void BSSvClearBSSList(void *hDeviceContext, BOOL bKeepCurrBSSID)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int ii;
for (ii = 0; ii < MAX_BSS_NUM; ii++) {
if (bKeepCurrBSSID) {
if (pMgmt->sBSSList[ii].bActive &&
!compare_ether_addr(pMgmt->sBSSList[ii].abyBSSID,
pMgmt->abyCurrBSSID)) {
//mike mark: there are two same BSSID in list if that AP is in hidden ssid mode,one 's SSID is null,
// but other's is obvious, so if it acssociate with your STA exactly,you must keep two
// of them!!!!!!!!!
// bKeepCurrBSSID = FALSE;
continue;
}
}
pMgmt->sBSSList[ii].bActive = FALSE;
memset(&pMgmt->sBSSList[ii], 0, sizeof(KnownBSS));
}
BSSvClearAnyBSSJoinRecord(pDevice);
}
/*+
*
* Routine Description:
* search BSS list by BSSID & SSID if matched
*
* Return Value:
* TRUE if found.
*
-*/
PKnownBSS BSSpAddrIsInBSSList(void *hDeviceContext,
PBYTE abyBSSID,
PWLAN_IE_SSID pSSID)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
PKnownBSS pBSSList = NULL;
unsigned int ii;
for (ii = 0; ii < MAX_BSS_NUM; ii++) {
pBSSList = &(pMgmt->sBSSList[ii]);
if (pBSSList->bActive) {
if (!compare_ether_addr(pBSSList->abyBSSID, abyBSSID)) {
if (pSSID->len == ((PWLAN_IE_SSID)pBSSList->abySSID)->len){
if (memcmp(pSSID->abySSID,
((PWLAN_IE_SSID)pBSSList->abySSID)->abySSID,
pSSID->len) == 0)
return pBSSList;
}
}
}
}
return NULL;
};
/*+
*
* Routine Description:
* Insert a BSS set into known BSS list
*
* Return Value:
* TRUE if success.
*
-*/
BOOL BSSbInsertToBSSList(void *hDeviceContext,
PBYTE abyBSSIDAddr,
QWORD qwTimestamp,
WORD wBeaconInterval,
WORD wCapInfo,
BYTE byCurrChannel,
PWLAN_IE_SSID pSSID,
PWLAN_IE_SUPP_RATES pSuppRates,
PWLAN_IE_SUPP_RATES pExtSuppRates,
PERPObject psERP,
PWLAN_IE_RSN pRSN,
PWLAN_IE_RSN_EXT pRSNWPA,
PWLAN_IE_COUNTRY pIE_Country,
PWLAN_IE_QUIET pIE_Quiet,
unsigned int uIELength,
PBYTE pbyIEs,
void *pRxPacketContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
PSRxMgmtPacket pRxPacket = (PSRxMgmtPacket)pRxPacketContext;
PKnownBSS pBSSList = NULL;
unsigned int ii;
BOOL bParsingQuiet = FALSE;
pBSSList = (PKnownBSS)&(pMgmt->sBSSList[0]);
for (ii = 0; ii < MAX_BSS_NUM; ii++) {
pBSSList = (PKnownBSS)&(pMgmt->sBSSList[ii]);
if (!pBSSList->bActive)
break;
}
if (ii == MAX_BSS_NUM){
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Get free KnowBSS node failed.\n");
return FALSE;
}
// save the BSS info
pBSSList->bActive = TRUE;
memcpy( pBSSList->abyBSSID, abyBSSIDAddr, WLAN_BSSID_LEN);
HIDWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(HIDWORD(qwTimestamp));
LODWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(LODWORD(qwTimestamp));
pBSSList->wBeaconInterval = cpu_to_le16(wBeaconInterval);
pBSSList->wCapInfo = cpu_to_le16(wCapInfo);
pBSSList->uClearCount = 0;
if (pSSID->len > WLAN_SSID_MAXLEN)
pSSID->len = WLAN_SSID_MAXLEN;
memcpy( pBSSList->abySSID, pSSID, pSSID->len + WLAN_IEHDR_LEN);
pBSSList->uChannel = byCurrChannel;
if (pSuppRates->len > WLAN_RATES_MAXLEN)
pSuppRates->len = WLAN_RATES_MAXLEN;
memcpy( pBSSList->abySuppRates, pSuppRates, pSuppRates->len + WLAN_IEHDR_LEN);
if (pExtSuppRates != NULL) {
if (pExtSuppRates->len > WLAN_RATES_MAXLEN)
pExtSuppRates->len = WLAN_RATES_MAXLEN;
memcpy(pBSSList->abyExtSuppRates, pExtSuppRates, pExtSuppRates->len + WLAN_IEHDR_LEN);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSSbInsertToBSSList: pExtSuppRates->len = %d\n", pExtSuppRates->len);
} else {
memset(pBSSList->abyExtSuppRates, 0, WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
}
pBSSList->sERP.byERP = psERP->byERP;
pBSSList->sERP.bERPExist = psERP->bERPExist;
// Check if BSS is 802.11a/b/g
if (pBSSList->uChannel > CB_MAX_CHANNEL_24G) {
pBSSList->eNetworkTypeInUse = PHY_TYPE_11A;
} else {
if (pBSSList->sERP.bERPExist == TRUE) {
pBSSList->eNetworkTypeInUse = PHY_TYPE_11G;
} else {
pBSSList->eNetworkTypeInUse = PHY_TYPE_11B;
}
}
pBSSList->byRxRate = pRxPacket->byRxRate;
pBSSList->qwLocalTSF = pRxPacket->qwLocalTSF;
pBSSList->uRSSI = pRxPacket->uRSSI;
pBSSList->bySQ = pRxPacket->bySQ;
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
(pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
// assoc with BSS
if (pBSSList == pMgmt->pCurrBSS) {
bParsingQuiet = TRUE;
}
}
WPA_ClearRSN(pBSSList);
if (pRSNWPA != NULL) {
unsigned int uLen = pRSNWPA->len + 2;
if (uLen <= (uIELength -
(unsigned int) (ULONG_PTR) ((PBYTE) pRSNWPA - pbyIEs))) {
pBSSList->wWPALen = uLen;
memcpy(pBSSList->byWPAIE, pRSNWPA, uLen);
WPA_ParseRSN(pBSSList, pRSNWPA);
}
}
WPA2_ClearRSN(pBSSList);
if (pRSN != NULL) {
unsigned int uLen = pRSN->len + 2;
if (uLen <= (uIELength -
(unsigned int) (ULONG_PTR) ((PBYTE) pRSN - pbyIEs))) {
pBSSList->wRSNLen = uLen;
memcpy(pBSSList->byRSNIE, pRSN, uLen);
WPA2vParseRSN(pBSSList, pRSN);
}
}
if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) || (pBSSList->bWPA2Valid == TRUE)) {
PSKeyItem pTransmitKey = NULL;
BOOL bIs802_1x = FALSE;
for (ii = 0; ii < pBSSList->wAKMSSAuthCount; ii ++) {
if (pBSSList->abyAKMSSAuthType[ii] == WLAN_11i_AKMSS_802_1X) {
bIs802_1x = TRUE;
break;
}
}
if ((bIs802_1x == TRUE) && (pSSID->len == ((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->len) &&
( !memcmp(pSSID->abySSID, ((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->abySSID, pSSID->len))) {
bAdd_PMKID_Candidate((void *) pDevice,
pBSSList->abyBSSID,
&pBSSList->sRSNCapObj);
if ((pDevice->bLinkPass == TRUE) && (pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
if ((KeybGetTransmitKey(&(pDevice->sKey), pDevice->abyBSSID, PAIRWISE_KEY, &pTransmitKey) == TRUE) ||
(KeybGetTransmitKey(&(pDevice->sKey), pDevice->abyBSSID, GROUP_KEY, &pTransmitKey) == TRUE)) {
pDevice->gsPMKIDCandidate.StatusType = Ndis802_11StatusType_PMKID_CandidateList;
pDevice->gsPMKIDCandidate.Version = 1;
}
}
}
}
if (pDevice->bUpdateBBVGA) {
// Moniter if RSSI is too strong.
pBSSList->byRSSIStatCnt = 0;
RFvRSSITodBm(pDevice, (BYTE)(pRxPacket->uRSSI), &pBSSList->ldBmMAX);
pBSSList->ldBmAverage[0] = pBSSList->ldBmMAX;
pBSSList->ldBmAverRange = pBSSList->ldBmMAX;
for (ii = 1; ii < RSSI_STAT_COUNT; ii++)
pBSSList->ldBmAverage[ii] = 0;
}
pBSSList->uIELength = uIELength;
if (pBSSList->uIELength > WLAN_BEACON_FR_MAXLEN)
pBSSList->uIELength = WLAN_BEACON_FR_MAXLEN;
memcpy(pBSSList->abyIEs, pbyIEs, pBSSList->uIELength);
return TRUE;
}
/*+
*
* Routine Description:
* Update BSS set in known BSS list
*
* Return Value:
* TRUE if success.
*
-*/
// TODO: input structure modify
BOOL BSSbUpdateToBSSList(void *hDeviceContext,
QWORD qwTimestamp,
WORD wBeaconInterval,
WORD wCapInfo,
BYTE byCurrChannel,
BOOL bChannelHit,
PWLAN_IE_SSID pSSID,
PWLAN_IE_SUPP_RATES pSuppRates,
PWLAN_IE_SUPP_RATES pExtSuppRates,
PERPObject psERP,
PWLAN_IE_RSN pRSN,
PWLAN_IE_RSN_EXT pRSNWPA,
PWLAN_IE_COUNTRY pIE_Country,
PWLAN_IE_QUIET pIE_Quiet,
PKnownBSS pBSSList,
unsigned int uIELength,
PBYTE pbyIEs,
void *pRxPacketContext)
{
int ii, jj;
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
PSRxMgmtPacket pRxPacket = (PSRxMgmtPacket)pRxPacketContext;
signed long ldBm, ldBmSum;
BOOL bParsingQuiet = FALSE;
if (pBSSList == NULL)
return FALSE;
HIDWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(HIDWORD(qwTimestamp));
LODWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(LODWORD(qwTimestamp));
pBSSList->wBeaconInterval = cpu_to_le16(wBeaconInterval);
pBSSList->wCapInfo = cpu_to_le16(wCapInfo);
pBSSList->uClearCount = 0;
pBSSList->uChannel = byCurrChannel;
if (pSSID->len > WLAN_SSID_MAXLEN)
pSSID->len = WLAN_SSID_MAXLEN;
if ((pSSID->len != 0) && (pSSID->abySSID[0] != 0))
memcpy(pBSSList->abySSID, pSSID, pSSID->len + WLAN_IEHDR_LEN);
memcpy(pBSSList->abySuppRates, pSuppRates,pSuppRates->len + WLAN_IEHDR_LEN);
if (pExtSuppRates != NULL) {
memcpy(pBSSList->abyExtSuppRates, pExtSuppRates,pExtSuppRates->len + WLAN_IEHDR_LEN);
} else {
memset(pBSSList->abyExtSuppRates, 0, WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
}
pBSSList->sERP.byERP = psERP->byERP;
pBSSList->sERP.bERPExist = psERP->bERPExist;
// Check if BSS is 802.11a/b/g
if (pBSSList->uChannel > CB_MAX_CHANNEL_24G) {
pBSSList->eNetworkTypeInUse = PHY_TYPE_11A;
} else {
if (pBSSList->sERP.bERPExist == TRUE) {
pBSSList->eNetworkTypeInUse = PHY_TYPE_11G;
} else {
pBSSList->eNetworkTypeInUse = PHY_TYPE_11B;
}
}
pBSSList->byRxRate = pRxPacket->byRxRate;
pBSSList->qwLocalTSF = pRxPacket->qwLocalTSF;
if(bChannelHit)
pBSSList->uRSSI = pRxPacket->uRSSI;
pBSSList->bySQ = pRxPacket->bySQ;
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
(pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
// assoc with BSS
if (pBSSList == pMgmt->pCurrBSS) {
bParsingQuiet = TRUE;
}
}
WPA_ClearRSN(pBSSList); //mike update
if (pRSNWPA != NULL) {
unsigned int uLen = pRSNWPA->len + 2;
if (uLen <= (uIELength -
(unsigned int) (ULONG_PTR) ((PBYTE) pRSNWPA - pbyIEs))) {
pBSSList->wWPALen = uLen;
memcpy(pBSSList->byWPAIE, pRSNWPA, uLen);
WPA_ParseRSN(pBSSList, pRSNWPA);
}
}
WPA2_ClearRSN(pBSSList); //mike update
if (pRSN != NULL) {
unsigned int uLen = pRSN->len + 2;
if (uLen <= (uIELength -
(unsigned int) (ULONG_PTR) ((PBYTE) pRSN - pbyIEs))) {
pBSSList->wRSNLen = uLen;
memcpy(pBSSList->byRSNIE, pRSN, uLen);
WPA2vParseRSN(pBSSList, pRSN);
}
}
if (pRxPacket->uRSSI != 0) {
RFvRSSITodBm(pDevice, (BYTE)(pRxPacket->uRSSI), &ldBm);
// Moniter if RSSI is too strong.
pBSSList->byRSSIStatCnt++;
pBSSList->byRSSIStatCnt %= RSSI_STAT_COUNT;
pBSSList->ldBmAverage[pBSSList->byRSSIStatCnt] = ldBm;
ldBmSum = 0;
for (ii = 0, jj = 0; ii < RSSI_STAT_COUNT; ii++) {
if (pBSSList->ldBmAverage[ii] != 0) {
pBSSList->ldBmMAX =
max(pBSSList->ldBmAverage[ii], ldBm);
ldBmSum +=
pBSSList->ldBmAverage[ii];
jj++;
}
}
pBSSList->ldBmAverRange = ldBmSum /jj;
}
pBSSList->uIELength = uIELength;
if (pBSSList->uIELength > WLAN_BEACON_FR_MAXLEN)
pBSSList->uIELength = WLAN_BEACON_FR_MAXLEN;
memcpy(pBSSList->abyIEs, pbyIEs, pBSSList->uIELength);
return TRUE;
}
/*+
*
* Routine Description:
* Search Node DB table to find the index of matched DstAddr
*
* Return Value:
* None
*
-*/
BOOL BSSbIsSTAInNodeDB(void *hDeviceContext,
PBYTE abyDstAddr,
unsigned int *puNodeIndex)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int ii;
// Index = 0 reserved for AP Node
for (ii = 1; ii < (MAX_NODE_NUM + 1); ii++) {
if (pMgmt->sNodeDBTable[ii].bActive) {
if (!compare_ether_addr(abyDstAddr,
pMgmt->sNodeDBTable[ii].abyMACAddr)) {
*puNodeIndex = ii;
return TRUE;
}
}
}
return FALSE;
};
/*+
*
* Routine Description:
* Find an empty node and allocated; if no empty found,
* instand used of most inactive one.
*
* Return Value:
* None
*
-*/
void BSSvCreateOneNode(void *hDeviceContext, unsigned int *puNodeIndex)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int ii;
unsigned int BigestCount = 0;
unsigned int SelectIndex;
struct sk_buff *skb;
// Index = 0 reserved for AP Node (In STA mode)
// Index = 0 reserved for Broadcast/MultiCast (In AP mode)
SelectIndex = 1;
for (ii = 1; ii < (MAX_NODE_NUM + 1); ii++) {
if (pMgmt->sNodeDBTable[ii].bActive) {
if (pMgmt->sNodeDBTable[ii].uInActiveCount > BigestCount) {
BigestCount = pMgmt->sNodeDBTable[ii].uInActiveCount;
SelectIndex = ii;
}
}
else {
break;
}
}
// if not found replace uInActiveCount is largest one.
if ( ii == (MAX_NODE_NUM + 1)) {
*puNodeIndex = SelectIndex;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Replace inactive node = %d\n", SelectIndex);
// clear ps buffer
if (pMgmt->sNodeDBTable[*puNodeIndex].sTxPSQueue.next != NULL) {
while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[*puNodeIndex].sTxPSQueue)) != NULL)
dev_kfree_skb(skb);
}
}
else {
*puNodeIndex = ii;
}
memset(&pMgmt->sNodeDBTable[*puNodeIndex], 0, sizeof(KnownNodeDB));
pMgmt->sNodeDBTable[*puNodeIndex].bActive = TRUE;
pMgmt->sNodeDBTable[*puNodeIndex].uRatePollTimeout = FALLBACK_POLL_SECOND;
// for AP mode PS queue
skb_queue_head_init(&pMgmt->sNodeDBTable[*puNodeIndex].sTxPSQueue);
pMgmt->sNodeDBTable[*puNodeIndex].byAuthSequence = 0;
pMgmt->sNodeDBTable[*puNodeIndex].wEnQueueCnt = 0;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Create node index = %d\n", ii);
};
/*+
*
* Routine Description:
* Remove Node by NodeIndex
*
*
* Return Value:
* None
*
-*/
void BSSvRemoveOneNode(void *hDeviceContext, unsigned int uNodeIndex)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
BYTE byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
struct sk_buff *skb;
while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue)) != NULL)
dev_kfree_skb(skb);
// clear context
memset(&pMgmt->sNodeDBTable[uNodeIndex], 0, sizeof(KnownNodeDB));
// clear tx bit map
pMgmt->abyPSTxMap[pMgmt->sNodeDBTable[uNodeIndex].wAID >> 3] &= ~byMask[pMgmt->sNodeDBTable[uNodeIndex].wAID & 7];
};
/*+
*
* Routine Description:
* Update AP Node content in Index 0 of KnownNodeDB
*
*
* Return Value:
* None
*
-*/
void BSSvUpdateAPNode(void *hDeviceContext,
PWORD pwCapInfo,
PWLAN_IE_SUPP_RATES pSuppRates,
PWLAN_IE_SUPP_RATES pExtSuppRates)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int uRateLen = WLAN_RATES_MAXLEN;
memset(&pMgmt->sNodeDBTable[0], 0, sizeof(KnownNodeDB));
pMgmt->sNodeDBTable[0].bActive = TRUE;
if (pDevice->byBBType == BB_TYPE_11B) {
uRateLen = WLAN_RATES_MAXLEN_11B;
}
pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pSuppRates,
(PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
uRateLen);
pMgmt->abyCurrExtSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pExtSuppRates,
(PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
uRateLen);
RATEvParseMaxRate((void *) pDevice,
(PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
(PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
TRUE,
&(pMgmt->sNodeDBTable[0].wMaxBasicRate),
&(pMgmt->sNodeDBTable[0].wMaxSuppRate),
&(pMgmt->sNodeDBTable[0].wSuppRate),
&(pMgmt->sNodeDBTable[0].byTopCCKBasicRate),
&(pMgmt->sNodeDBTable[0].byTopOFDMBasicRate)
);
memcpy(pMgmt->sNodeDBTable[0].abyMACAddr, pMgmt->abyCurrBSSID, WLAN_ADDR_LEN);
pMgmt->sNodeDBTable[0].wTxDataRate = pMgmt->sNodeDBTable[0].wMaxSuppRate;
pMgmt->sNodeDBTable[0].bShortPreamble = WLAN_GET_CAP_INFO_SHORTPREAMBLE(*pwCapInfo);
pMgmt->sNodeDBTable[0].uRatePollTimeout = FALLBACK_POLL_SECOND;
// Auto rate fallback function initiation.
// RATEbInit(pDevice);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pMgmt->sNodeDBTable[0].wTxDataRate = %d \n", pMgmt->sNodeDBTable[0].wTxDataRate);
};
/*+
*
* Routine Description:
* Add Multicast Node content in Index 0 of KnownNodeDB
*
*
* Return Value:
* None
*
-*/
void BSSvAddMulticastNode(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
if (!pDevice->bEnableHostWEP)
memset(&pMgmt->sNodeDBTable[0], 0, sizeof(KnownNodeDB));
memset(pMgmt->sNodeDBTable[0].abyMACAddr, 0xff, WLAN_ADDR_LEN);
pMgmt->sNodeDBTable[0].bActive = TRUE;
pMgmt->sNodeDBTable[0].bPSEnable = FALSE;
skb_queue_head_init(&pMgmt->sNodeDBTable[0].sTxPSQueue);
RATEvParseMaxRate((void *) pDevice,
(PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
(PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
TRUE,
&(pMgmt->sNodeDBTable[0].wMaxBasicRate),
&(pMgmt->sNodeDBTable[0].wMaxSuppRate),
&(pMgmt->sNodeDBTable[0].wSuppRate),
&(pMgmt->sNodeDBTable[0].byTopCCKBasicRate),
&(pMgmt->sNodeDBTable[0].byTopOFDMBasicRate)
);
pMgmt->sNodeDBTable[0].wTxDataRate = pMgmt->sNodeDBTable[0].wMaxBasicRate;
pMgmt->sNodeDBTable[0].uRatePollTimeout = FALLBACK_POLL_SECOND;
};
/*+
*
* Routine Description:
*
*
* Second call back function to update Node DB info & AP link status
*
*
* Return Value:
* none.
*
-*/
void BSSvSecondCallBack(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int ii;
PWLAN_IE_SSID pItemSSID, pCurrSSID;
unsigned int uSleepySTACnt = 0;
unsigned int uNonShortSlotSTACnt = 0;
unsigned int uLongPreambleSTACnt = 0;
viawget_wpa_header *wpahdr;
spin_lock_irq(&pDevice->lock);
pDevice->uAssocCount = 0;
//Power Saving Mode Tx Burst
if ( pDevice->bEnablePSMode == TRUE ) {
pDevice->ulPSModeWaitTx++;
if ( pDevice->ulPSModeWaitTx >= 2 ) {
pDevice->ulPSModeWaitTx = 0;
pDevice->bPSModeTxBurst = FALSE;
}
}
pDevice->byERPFlag &=
~(WLAN_SET_ERP_BARKER_MODE(1) | WLAN_SET_ERP_NONERP_PRESENT(1));
if (pDevice->wUseProtectCntDown > 0) {
pDevice->wUseProtectCntDown --;
}
else {
// disable protect mode
pDevice->byERPFlag &= ~(WLAN_SET_ERP_USE_PROTECTION(1));
}
if(pDevice->byReAssocCount > 0) {
pDevice->byReAssocCount++;
if((pDevice->byReAssocCount > 10) && (pDevice->bLinkPass != TRUE)) { //10 sec timeout
printk("Re-association timeout!!!\n");
pDevice->byReAssocCount = 0;
#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
// if(pDevice->bWPASuppWextEnabled == TRUE)
{
union iwreq_data wrqu;
memset(&wrqu, 0, sizeof (wrqu));
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
PRINT_K("wireless_send_event--->SIOCGIWAP(disassociated)\n");
wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
}
#endif
}
else if(pDevice->bLinkPass == TRUE)
pDevice->byReAssocCount = 0;
}
if((pMgmt->eCurrState!=WMAC_STATE_ASSOC) &&
(pMgmt->eLastState==WMAC_STATE_ASSOC))
{
union iwreq_data wrqu;
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.flags = RT_DISCONNECTED_EVENT_FLAG;
wireless_send_event(pDevice->dev, IWEVCUSTOM, &wrqu, NULL);
}
pMgmt->eLastState = pMgmt->eCurrState ;
s_uCalculateLinkQual((void *)pDevice);
for (ii = 0; ii < (MAX_NODE_NUM + 1); ii++) {
if (pMgmt->sNodeDBTable[ii].bActive) {
// Increase in-activity counter
pMgmt->sNodeDBTable[ii].uInActiveCount++;
if (ii > 0) {
if (pMgmt->sNodeDBTable[ii].uInActiveCount > MAX_INACTIVE_COUNT) {
BSSvRemoveOneNode(pDevice, ii);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO
"Inactive timeout [%d] sec, STA index = [%d] remove\n", MAX_INACTIVE_COUNT, ii);
continue;
}
if (pMgmt->sNodeDBTable[ii].eNodeState >= NODE_ASSOC) {
pDevice->uAssocCount++;
// check if Non ERP exist
if (pMgmt->sNodeDBTable[ii].uInActiveCount < ERP_RECOVER_COUNT) {
if (!pMgmt->sNodeDBTable[ii].bShortPreamble) {
pDevice->byERPFlag |= WLAN_SET_ERP_BARKER_MODE(1);
uLongPreambleSTACnt ++;
}
if (!pMgmt->sNodeDBTable[ii].bERPExist) {
pDevice->byERPFlag |= WLAN_SET_ERP_NONERP_PRESENT(1);
pDevice->byERPFlag |= WLAN_SET_ERP_USE_PROTECTION(1);
}
if (!pMgmt->sNodeDBTable[ii].bShortSlotTime)
uNonShortSlotSTACnt++;
}
}
// check if any STA in PS mode
if (pMgmt->sNodeDBTable[ii].bPSEnable)
uSleepySTACnt++;
}
// Rate fallback check
if (!pDevice->bFixRate) {
if (ii > 0) {
// ii = 0 for multicast node (AP & Adhoc)
RATEvTxRateFallBack((void *)pDevice,
&(pMgmt->sNodeDBTable[ii]));
}
else {
// ii = 0 reserved for unicast AP node (Infra STA)
if (pMgmt->eCurrMode == WMAC_MODE_ESS_STA)
RATEvTxRateFallBack((void *)pDevice,
&(pMgmt->sNodeDBTable[ii]));
}
}
// check if pending PS queue
if (pMgmt->sNodeDBTable[ii].wEnQueueCnt != 0) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Index= %d, Queue = %d pending \n",
ii, pMgmt->sNodeDBTable[ii].wEnQueueCnt);
if ((ii >0) && (pMgmt->sNodeDBTable[ii].wEnQueueCnt > 15)) {
BSSvRemoveOneNode(pDevice, ii);
DBG_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Pending many queues PS STA Index = %d remove \n", ii);
continue;
}
}
}
}
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) && (pDevice->byBBType == BB_TYPE_11G)) {
// on/off protect mode
if (WLAN_GET_ERP_USE_PROTECTION(pDevice->byERPFlag)) {
if (!pDevice->bProtectMode) {
MACvEnableProtectMD(pDevice);
pDevice->bProtectMode = TRUE;
}
}
else {
if (pDevice->bProtectMode) {
MACvDisableProtectMD(pDevice);
pDevice->bProtectMode = FALSE;
}
}
// on/off short slot time
if (uNonShortSlotSTACnt > 0) {
if (pDevice->bShortSlotTime) {
pDevice->bShortSlotTime = FALSE;
BBvSetShortSlotTime(pDevice);
vUpdateIFS((void *)pDevice);
}
}
else {
if (!pDevice->bShortSlotTime) {
pDevice->bShortSlotTime = TRUE;
BBvSetShortSlotTime(pDevice);
vUpdateIFS((void *)pDevice);
}
}
// on/off barker long preamble mode
if (uLongPreambleSTACnt > 0) {
if (!pDevice->bBarkerPreambleMd) {
MACvEnableBarkerPreambleMd(pDevice);
pDevice->bBarkerPreambleMd = TRUE;
}
}
else {
if (pDevice->bBarkerPreambleMd) {
MACvDisableBarkerPreambleMd(pDevice);
pDevice->bBarkerPreambleMd = FALSE;
}
}
}
// Check if any STA in PS mode, enable DTIM multicast deliver
if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
if (uSleepySTACnt > 0)
pMgmt->sNodeDBTable[0].bPSEnable = TRUE;
else
pMgmt->sNodeDBTable[0].bPSEnable = FALSE;
}
pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
pCurrSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
if ((pMgmt->eCurrMode == WMAC_MODE_STANDBY) ||
(pMgmt->eCurrMode == WMAC_MODE_ESS_STA)) {
if (pMgmt->sNodeDBTable[0].bActive) { // Assoc with BSS
if (pDevice->bUpdateBBVGA) {
/* s_vCheckSensitivity((void *) pDevice); */
s_vCheckPreEDThreshold((void *) pDevice);
}
if ((pMgmt->sNodeDBTable[0].uInActiveCount >= (LOST_BEACON_COUNT/2)) &&
(pDevice->byBBVGACurrent != pDevice->abyBBVGA[0]) ) {
pDevice->byBBVGANew = pDevice->abyBBVGA[0];
bScheduleCommand((void *) pDevice,
WLAN_CMD_CHANGE_BBSENSITIVITY,
NULL);
}
if (pMgmt->sNodeDBTable[0].uInActiveCount >= LOST_BEACON_COUNT) {
pMgmt->sNodeDBTable[0].bActive = FALSE;
pMgmt->eCurrMode = WMAC_MODE_STANDBY;
pMgmt->eCurrState = WMAC_STATE_IDLE;
netif_stop_queue(pDevice->dev);
pDevice->bLinkPass = FALSE;
ControlvMaskByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_PAPEDELAY,LEDSTS_STS,LEDSTS_SLOW);
pDevice->bRoaming = TRUE;
pDevice->bIsRoaming = FALSE;
DBG_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Lost AP beacon [%d] sec, disconnected !\n", pMgmt->sNodeDBTable[0].uInActiveCount);
/* let wpa supplicant know AP may disconnect */
if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
wpahdr = (viawget_wpa_header *)pDevice->skb->data;
wpahdr->type = VIAWGET_DISASSOC_MSG;
wpahdr->resp_ie_len = 0;
wpahdr->req_ie_len = 0;
skb_put(pDevice->skb, sizeof(viawget_wpa_header));
pDevice->skb->dev = pDevice->wpadev;
skb_reset_mac_header(pDevice->skb);
pDevice->skb->pkt_type = PACKET_HOST;
pDevice->skb->protocol = htons(ETH_P_802_2);
memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
netif_rx(pDevice->skb);
pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
}
#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
{
union iwreq_data wrqu;
memset(&wrqu, 0, sizeof (wrqu));
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
PRINT_K("wireless_send_event--->SIOCGIWAP(disassociated)\n");
wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
}
#endif
}
}
else if (pItemSSID->len != 0) {
//Davidwang
if ((pDevice->bEnableRoaming == TRUE)&&(!(pMgmt->Cisco_cckm))) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "bRoaming %d, !\n", pDevice->bRoaming );
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "bIsRoaming %d, !\n", pDevice->bIsRoaming );
if ((pDevice->bRoaming == TRUE)&&(pDevice->bIsRoaming == TRUE)){
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Fast Roaming ...\n");
BSSvClearBSSList((void *) pDevice, pDevice->bLinkPass);
bScheduleCommand((void *) pDevice,
WLAN_CMD_BSSID_SCAN,
pMgmt->abyDesireSSID);
bScheduleCommand((void *) pDevice,
WLAN_CMD_SSID,
pMgmt->abyDesireSSID);
pDevice->uAutoReConnectTime = 0;
pDevice->uIsroamingTime = 0;
pDevice->bRoaming = FALSE;
wpahdr = (viawget_wpa_header *)pDevice->skb->data;
wpahdr->type = VIAWGET_CCKM_ROAM_MSG;
wpahdr->resp_ie_len = 0;
wpahdr->req_ie_len = 0;
skb_put(pDevice->skb, sizeof(viawget_wpa_header));
pDevice->skb->dev = pDevice->wpadev;
skb_reset_mac_header(pDevice->skb);
pDevice->skb->pkt_type = PACKET_HOST;
pDevice->skb->protocol = htons(ETH_P_802_2);
memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
netif_rx(pDevice->skb);
pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
}
else if ((pDevice->bRoaming == FALSE)&&(pDevice->bIsRoaming == TRUE)) {
pDevice->uIsroamingTime++;
if (pDevice->uIsroamingTime >= 20)
pDevice->bIsRoaming = FALSE;
}
}
else {
if (pDevice->uAutoReConnectTime < 10) {
pDevice->uAutoReConnectTime++;
#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
//network manager support need not do Roaming scan???
if(pDevice->bWPASuppWextEnabled ==TRUE)
pDevice->uAutoReConnectTime = 0;
#endif
}
else {
//mike use old encryption status for wpa reauthen
if(pDevice->bWPADEVUp)
pDevice->eEncryptionStatus = pDevice->eOldEncryptionStatus;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Roaming ...\n");
BSSvClearBSSList((void *) pDevice, pDevice->bLinkPass);
pMgmt->eScanType = WMAC_SCAN_ACTIVE;
bScheduleCommand((void *) pDevice,
WLAN_CMD_BSSID_SCAN,
pMgmt->abyDesireSSID);
bScheduleCommand((void *) pDevice,
WLAN_CMD_SSID,
pMgmt->abyDesireSSID);
pDevice->uAutoReConnectTime = 0;
}
}
}
}
if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
// if adhoc started which essid is NULL string, rescanning.
if ((pMgmt->eCurrState == WMAC_STATE_STARTED) && (pCurrSSID->len == 0)) {
if (pDevice->uAutoReConnectTime < 10) {
pDevice->uAutoReConnectTime++;
}
else {
DBG_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Adhoc re-scanning ...\n");
pMgmt->eScanType = WMAC_SCAN_ACTIVE;
bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
bScheduleCommand((void *) pDevice, WLAN_CMD_SSID, NULL);
pDevice->uAutoReConnectTime = 0;
};
}
if (pMgmt->eCurrState == WMAC_STATE_JOINTED) {
if (pDevice->bUpdateBBVGA) {
/* s_vCheckSensitivity((void *) pDevice); */
s_vCheckPreEDThreshold((void *) pDevice);
}
if (pMgmt->sNodeDBTable[0].uInActiveCount >=ADHOC_LOST_BEACON_COUNT) {
DBG_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Lost other STA beacon [%d] sec, started !\n", pMgmt->sNodeDBTable[0].uInActiveCount);
pMgmt->sNodeDBTable[0].uInActiveCount = 0;
pMgmt->eCurrState = WMAC_STATE_STARTED;
netif_stop_queue(pDevice->dev);
pDevice->bLinkPass = FALSE;
ControlvMaskByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_PAPEDELAY,LEDSTS_STS,LEDSTS_SLOW);
}
}
}
if (pDevice->bLinkPass == TRUE) {
if (netif_queue_stopped(pDevice->dev))
netif_wake_queue(pDevice->dev);
}
spin_unlock_irq(&pDevice->lock);
pMgmt->sTimerSecondCallback.expires = RUN_AT(HZ);
add_timer(&pMgmt->sTimerSecondCallback);
}
/*+
*
* Routine Description:
*
*
* Update Tx attemps, Tx failure counter in Node DB
*
*
* Return Value:
* none.
*
-*/
void BSSvUpdateNodeTxCounter(void *hDeviceContext,
PSStatCounter pStatistic,
BYTE byTSR,
BYTE byPktNO)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int uNodeIndex = 0;
BYTE byTxRetry;
WORD wRate;
WORD wFallBackRate = RATE_1M;
BYTE byFallBack;
unsigned int ii;
PBYTE pbyDestAddr;
BYTE byPktNum;
WORD wFIFOCtl;
byPktNum = (byPktNO & 0x0F) >> 4;
byTxRetry = (byTSR & 0xF0) >> 4;
wRate = (WORD) (byPktNO & 0xF0) >> 4;
wFIFOCtl = pStatistic->abyTxPktInfo[byPktNum].wFIFOCtl;
pbyDestAddr = (PBYTE) &( pStatistic->abyTxPktInfo[byPktNum].abyDestAddr[0]);
if (wFIFOCtl & FIFOCTL_AUTO_FB_0) {
byFallBack = AUTO_FB_0;
} else if (wFIFOCtl & FIFOCTL_AUTO_FB_1) {
byFallBack = AUTO_FB_1;
} else {
byFallBack = AUTO_FB_NONE;
}
// Only Unicast using support rates
if (wFIFOCtl & FIFOCTL_NEEDACK) {
if (pMgmt->eCurrMode == WMAC_MODE_ESS_STA) {
pMgmt->sNodeDBTable[0].uTxAttempts += 1;
if ( !(byTSR & (TSR_TMO | TSR_RETRYTMO))) {
// transmit success, TxAttempts at least plus one
pMgmt->sNodeDBTable[0].uTxOk[MAX_RATE]++;
if ( (byFallBack == AUTO_FB_NONE) ||
(wRate < RATE_18M) ) {
wFallBackRate = wRate;
} else if (byFallBack == AUTO_FB_0) {
if (byTxRetry < 5)
wFallBackRate = awHWRetry0[wRate-RATE_18M][byTxRetry];
else
wFallBackRate = awHWRetry0[wRate-RATE_18M][4];
} else if (byFallBack == AUTO_FB_1) {
if (byTxRetry < 5)
wFallBackRate = awHWRetry1[wRate-RATE_18M][byTxRetry];
else
wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
}
pMgmt->sNodeDBTable[0].uTxOk[wFallBackRate]++;
} else {
pMgmt->sNodeDBTable[0].uTxFailures ++;
}
pMgmt->sNodeDBTable[0].uTxRetry += byTxRetry;
if (byTxRetry != 0) {
pMgmt->sNodeDBTable[0].uTxFail[MAX_RATE]+=byTxRetry;
if ( (byFallBack == AUTO_FB_NONE) ||
(wRate < RATE_18M) ) {
pMgmt->sNodeDBTable[0].uTxFail[wRate]+=byTxRetry;
} else if (byFallBack == AUTO_FB_0) {
for (ii = 0; ii < byTxRetry; ii++) {
if (ii < 5)
wFallBackRate =
awHWRetry0[wRate-RATE_18M][ii];
else
wFallBackRate =
awHWRetry0[wRate-RATE_18M][4];
pMgmt->sNodeDBTable[0].uTxFail[wFallBackRate]++;
}
} else if (byFallBack == AUTO_FB_1) {
for (ii = 0; ii < byTxRetry; ii++) {
if (ii < 5)
wFallBackRate =
awHWRetry1[wRate-RATE_18M][ii];
else
wFallBackRate =
awHWRetry1[wRate-RATE_18M][4];
pMgmt->sNodeDBTable[0].uTxFail[wFallBackRate]++;
}
}
}
}
if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ||
(pMgmt->eCurrMode == WMAC_MODE_ESS_AP)) {
if (BSSbIsSTAInNodeDB((void *) pDevice,
pbyDestAddr,
&uNodeIndex)) {
pMgmt->sNodeDBTable[uNodeIndex].uTxAttempts += 1;
if ( !(byTSR & (TSR_TMO | TSR_RETRYTMO))) {
// transmit success, TxAttempts at least plus one
pMgmt->sNodeDBTable[uNodeIndex].uTxOk[MAX_RATE]++;
if ( (byFallBack == AUTO_FB_NONE) ||
(wRate < RATE_18M) ) {
wFallBackRate = wRate;
} else if (byFallBack == AUTO_FB_0) {
if (byTxRetry < 5)
wFallBackRate = awHWRetry0[wRate-RATE_18M][byTxRetry];
else
wFallBackRate = awHWRetry0[wRate-RATE_18M][4];
} else if (byFallBack == AUTO_FB_1) {
if (byTxRetry < 5)
wFallBackRate = awHWRetry1[wRate-RATE_18M][byTxRetry];
else
wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
}
pMgmt->sNodeDBTable[uNodeIndex].uTxOk[wFallBackRate]++;
} else {
pMgmt->sNodeDBTable[uNodeIndex].uTxFailures ++;
}
pMgmt->sNodeDBTable[uNodeIndex].uTxRetry += byTxRetry;
if (byTxRetry != 0) {
pMgmt->sNodeDBTable[uNodeIndex].uTxFail[MAX_RATE]+=byTxRetry;
if ( (byFallBack == AUTO_FB_NONE) ||
(wRate < RATE_18M) ) {
pMgmt->sNodeDBTable[uNodeIndex].uTxFail[wRate]+=byTxRetry;
} else if (byFallBack == AUTO_FB_0) {
for (ii = 0; ii < byTxRetry; ii++) {
if (ii < 5)
wFallBackRate =
awHWRetry0[wRate-RATE_18M][ii];
else
wFallBackRate =
awHWRetry0[wRate-RATE_18M][4];
pMgmt->sNodeDBTable[uNodeIndex].uTxFail[wFallBackRate]++;
}
} else if (byFallBack == AUTO_FB_1) {
for (ii = 0; ii < byTxRetry; ii++) {
if (ii < 5)
wFallBackRate = awHWRetry1[wRate-RATE_18M][ii];
else
wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
pMgmt->sNodeDBTable[uNodeIndex].uTxFail[wFallBackRate]++;
}
}
}
}
}
}
}
/*+
*
* Routine Description:
* Clear Nodes & skb in DB Table
*
*
* Parameters:
* In:
* hDeviceContext - The adapter context.
* uStartIndex - starting index
* Out:
* none
*
* Return Value:
* None.
*
-*/
void BSSvClearNodeDBTable(void *hDeviceContext,
unsigned int uStartIndex)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
struct sk_buff *skb;
unsigned int ii;
for (ii = uStartIndex; ii < (MAX_NODE_NUM + 1); ii++) {
if (pMgmt->sNodeDBTable[ii].bActive) {
// check if sTxPSQueue has been initial
if (pMgmt->sNodeDBTable[ii].sTxPSQueue.next != NULL) {
while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) != NULL){
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "PS skb != NULL %d\n", ii);
dev_kfree_skb(skb);
}
}
memset(&pMgmt->sNodeDBTable[ii], 0, sizeof(KnownNodeDB));
}
}
};
void s_vCheckSensitivity(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PKnownBSS pBSSList = NULL;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
int ii;
if ((pMgmt->eCurrState == WMAC_STATE_ASSOC) ||
((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && (pMgmt->eCurrState == WMAC_STATE_JOINTED))) {
pBSSList = BSSpAddrIsInBSSList(pDevice, pMgmt->abyCurrBSSID, (PWLAN_IE_SSID)pMgmt->abyCurrSSID);
if (pBSSList != NULL) {
/* Update BB register if RSSI is too strong */
signed long LocalldBmAverage = 0;
signed long uNumofdBm = 0;
for (ii = 0; ii < RSSI_STAT_COUNT; ii++) {
if (pBSSList->ldBmAverage[ii] != 0) {
uNumofdBm ++;
LocalldBmAverage += pBSSList->ldBmAverage[ii];
}
}
if (uNumofdBm > 0) {
LocalldBmAverage = LocalldBmAverage/uNumofdBm;
for (ii=0;ii<BB_VGA_LEVEL;ii++) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"LocalldBmAverage:%ld, %ld %02x\n", LocalldBmAverage, pDevice->ldBmThreshold[ii], pDevice->abyBBVGA[ii]);
if (LocalldBmAverage < pDevice->ldBmThreshold[ii]) {
pDevice->byBBVGANew = pDevice->abyBBVGA[ii];
break;
}
}
if (pDevice->byBBVGANew != pDevice->byBBVGACurrent) {
pDevice->uBBVGADiffCount++;
if (pDevice->uBBVGADiffCount >= BB_VGA_CHANGE_THRESHOLD)
bScheduleCommand((void *) pDevice,
WLAN_CMD_CHANGE_BBSENSITIVITY,
NULL);
} else {
pDevice->uBBVGADiffCount = 0;
}
}
}
}
}
void s_uCalculateLinkQual(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
unsigned long TxOkRatio, TxCnt;
unsigned long RxOkRatio, RxCnt;
unsigned long RssiRatio;
long ldBm;
TxCnt = pDevice->scStatistic.TxNoRetryOkCount +
pDevice->scStatistic.TxRetryOkCount +
pDevice->scStatistic.TxFailCount;
RxCnt = pDevice->scStatistic.RxFcsErrCnt +
pDevice->scStatistic.RxOkCnt;
TxOkRatio = (TxCnt < 6) ? 4000:((pDevice->scStatistic.TxNoRetryOkCount * 4000) / TxCnt);
RxOkRatio = (RxCnt < 6) ? 2000:((pDevice->scStatistic.RxOkCnt * 2000) / RxCnt);
//decide link quality
if(pDevice->bLinkPass !=TRUE)
{
pDevice->scStatistic.LinkQuality = 0;
pDevice->scStatistic.SignalStren = 0;
}
else
{
RFvRSSITodBm(pDevice, (BYTE)(pDevice->uCurrRSSI), &ldBm);
if(-ldBm < 50) {
RssiRatio = 4000;
}
else if(-ldBm > 90) {
RssiRatio = 0;
}
else {
RssiRatio = (40-(-ldBm-50))*4000/40;
}
pDevice->scStatistic.SignalStren = RssiRatio/40;
pDevice->scStatistic.LinkQuality = (RssiRatio+TxOkRatio+RxOkRatio)/100;
}
pDevice->scStatistic.RxFcsErrCnt = 0;
pDevice->scStatistic.RxOkCnt = 0;
pDevice->scStatistic.TxFailCount = 0;
pDevice->scStatistic.TxNoRetryOkCount = 0;
pDevice->scStatistic.TxRetryOkCount = 0;
}
void BSSvClearAnyBSSJoinRecord(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int ii;
for (ii = 0; ii < MAX_BSS_NUM; ii++)
pMgmt->sBSSList[ii].bSelected = FALSE;
}
void s_vCheckPreEDThreshold(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
PKnownBSS pBSSList = NULL;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
if ((pMgmt->eCurrState == WMAC_STATE_ASSOC) ||
((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && (pMgmt->eCurrState == WMAC_STATE_JOINTED))) {
pBSSList = BSSpAddrIsInBSSList(pDevice, pMgmt->abyCurrBSSID, (PWLAN_IE_SSID)pMgmt->abyCurrSSID);
if (pBSSList != NULL) {
pDevice->byBBPreEDRSSI = (BYTE) (~(pBSSList->ldBmAverRange) + 1);
BBvUpdatePreEDThreshold(pDevice, FALSE);
}
}
}
| gpl-2.0 |
xens0117/android_kernel_samsung_klte | drivers/net/ethernet/chelsio/cxgb3/sge.c | 5109 | 93465 | /*
* Copyright (c) 2005-2008 Chelsio, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/prefetch.h>
#include <net/arp.h>
#include "common.h"
#include "regs.h"
#include "sge_defs.h"
#include "t3_cpl.h"
#include "firmware_exports.h"
#include "cxgb3_offload.h"
#define USE_GTS 0
#define SGE_RX_SM_BUF_SIZE 1536
#define SGE_RX_COPY_THRES 256
#define SGE_RX_PULL_LEN 128
#define SGE_PG_RSVD SMP_CACHE_BYTES
/*
* Page chunk size for FL0 buffers if FL0 is to be populated with page chunks.
* It must be a divisor of PAGE_SIZE. If set to 0 FL0 will use sk_buffs
* directly.
*/
#define FL0_PG_CHUNK_SIZE 2048
#define FL0_PG_ORDER 0
#define FL0_PG_ALLOC_SIZE (PAGE_SIZE << FL0_PG_ORDER)
#define FL1_PG_CHUNK_SIZE (PAGE_SIZE > 8192 ? 16384 : 8192)
#define FL1_PG_ORDER (PAGE_SIZE > 8192 ? 0 : 1)
#define FL1_PG_ALLOC_SIZE (PAGE_SIZE << FL1_PG_ORDER)
#define SGE_RX_DROP_THRES 16
#define RX_RECLAIM_PERIOD (HZ/4)
/*
* Max number of Rx buffers we replenish at a time.
*/
#define MAX_RX_REFILL 16U
/*
* Period of the Tx buffer reclaim timer. This timer does not need to run
* frequently as Tx buffers are usually reclaimed by new Tx packets.
*/
#define TX_RECLAIM_PERIOD (HZ / 4)
#define TX_RECLAIM_TIMER_CHUNK 64U
#define TX_RECLAIM_CHUNK 16U
/* WR size in bytes */
#define WR_LEN (WR_FLITS * 8)
/*
* Types of Tx queues in each queue set. Order here matters, do not change.
*/
enum { TXQ_ETH, TXQ_OFLD, TXQ_CTRL };
/* Values for sge_txq.flags */
enum {
TXQ_RUNNING = 1 << 0, /* fetch engine is running */
TXQ_LAST_PKT_DB = 1 << 1, /* last packet rang the doorbell */
};
struct tx_desc {
__be64 flit[TX_DESC_FLITS];
};
struct rx_desc {
__be32 addr_lo;
__be32 len_gen;
__be32 gen2;
__be32 addr_hi;
};
struct tx_sw_desc { /* SW state per Tx descriptor */
struct sk_buff *skb;
u8 eop; /* set if last descriptor for packet */
u8 addr_idx; /* buffer index of first SGL entry in descriptor */
u8 fragidx; /* first page fragment associated with descriptor */
s8 sflit; /* start flit of first SGL entry in descriptor */
};
struct rx_sw_desc { /* SW state per Rx descriptor */
union {
struct sk_buff *skb;
struct fl_pg_chunk pg_chunk;
};
DEFINE_DMA_UNMAP_ADDR(dma_addr);
};
struct rsp_desc { /* response queue descriptor */
struct rss_header rss_hdr;
__be32 flags;
__be32 len_cq;
u8 imm_data[47];
u8 intr_gen;
};
/*
* Holds unmapping information for Tx packets that need deferred unmapping.
* This structure lives at skb->head and must be allocated by callers.
*/
struct deferred_unmap_info {
struct pci_dev *pdev;
dma_addr_t addr[MAX_SKB_FRAGS + 1];
};
/*
* Maps a number of flits to the number of Tx descriptors that can hold them.
* The formula is
*
* desc = 1 + (flits - 2) / (WR_FLITS - 1).
*
* HW allows up to 4 descriptors to be combined into a WR.
*/
static u8 flit_desc_map[] = {
0,
#if SGE_NUM_GENBITS == 1
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
#elif SGE_NUM_GENBITS == 2
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
#else
# error "SGE_NUM_GENBITS must be 1 or 2"
#endif
};
static inline struct sge_qset *fl_to_qset(const struct sge_fl *q, int qidx)
{
return container_of(q, struct sge_qset, fl[qidx]);
}
static inline struct sge_qset *rspq_to_qset(const struct sge_rspq *q)
{
return container_of(q, struct sge_qset, rspq);
}
static inline struct sge_qset *txq_to_qset(const struct sge_txq *q, int qidx)
{
return container_of(q, struct sge_qset, txq[qidx]);
}
/**
* refill_rspq - replenish an SGE response queue
* @adapter: the adapter
* @q: the response queue to replenish
* @credits: how many new responses to make available
*
* Replenishes a response queue by making the supplied number of responses
* available to HW.
*/
static inline void refill_rspq(struct adapter *adapter,
const struct sge_rspq *q, unsigned int credits)
{
rmb();
t3_write_reg(adapter, A_SG_RSPQ_CREDIT_RETURN,
V_RSPQ(q->cntxt_id) | V_CREDITS(credits));
}
/**
* need_skb_unmap - does the platform need unmapping of sk_buffs?
*
* Returns true if the platform needs sk_buff unmapping. The compiler
* optimizes away unnecessary code if this returns true.
*/
static inline int need_skb_unmap(void)
{
#ifdef CONFIG_NEED_DMA_MAP_STATE
return 1;
#else
return 0;
#endif
}
/**
* unmap_skb - unmap a packet main body and its page fragments
* @skb: the packet
* @q: the Tx queue containing Tx descriptors for the packet
* @cidx: index of Tx descriptor
* @pdev: the PCI device
*
* Unmap the main body of an sk_buff and its page fragments, if any.
* Because of the fairly complicated structure of our SGLs and the desire
* to conserve space for metadata, the information necessary to unmap an
* sk_buff is spread across the sk_buff itself (buffer lengths), the HW Tx
* descriptors (the physical addresses of the various data buffers), and
* the SW descriptor state (assorted indices). The send functions
* initialize the indices for the first packet descriptor so we can unmap
* the buffers held in the first Tx descriptor here, and we have enough
* information at this point to set the state for the next Tx descriptor.
*
* Note that it is possible to clean up the first descriptor of a packet
* before the send routines have written the next descriptors, but this
* race does not cause any problem. We just end up writing the unmapping
* info for the descriptor first.
*/
static inline void unmap_skb(struct sk_buff *skb, struct sge_txq *q,
unsigned int cidx, struct pci_dev *pdev)
{
const struct sg_ent *sgp;
struct tx_sw_desc *d = &q->sdesc[cidx];
int nfrags, frag_idx, curflit, j = d->addr_idx;
sgp = (struct sg_ent *)&q->desc[cidx].flit[d->sflit];
frag_idx = d->fragidx;
if (frag_idx == 0 && skb_headlen(skb)) {
pci_unmap_single(pdev, be64_to_cpu(sgp->addr[0]),
skb_headlen(skb), PCI_DMA_TODEVICE);
j = 1;
}
curflit = d->sflit + 1 + j;
nfrags = skb_shinfo(skb)->nr_frags;
while (frag_idx < nfrags && curflit < WR_FLITS) {
pci_unmap_page(pdev, be64_to_cpu(sgp->addr[j]),
skb_frag_size(&skb_shinfo(skb)->frags[frag_idx]),
PCI_DMA_TODEVICE);
j ^= 1;
if (j == 0) {
sgp++;
curflit++;
}
curflit++;
frag_idx++;
}
if (frag_idx < nfrags) { /* SGL continues into next Tx descriptor */
d = cidx + 1 == q->size ? q->sdesc : d + 1;
d->fragidx = frag_idx;
d->addr_idx = j;
d->sflit = curflit - WR_FLITS - j; /* sflit can be -1 */
}
}
/**
* free_tx_desc - reclaims Tx descriptors and their buffers
* @adapter: the adapter
* @q: the Tx queue to reclaim descriptors from
* @n: the number of descriptors to reclaim
*
* Reclaims Tx descriptors from an SGE Tx queue and frees the associated
* Tx buffers. Called with the Tx queue lock held.
*/
static void free_tx_desc(struct adapter *adapter, struct sge_txq *q,
unsigned int n)
{
struct tx_sw_desc *d;
struct pci_dev *pdev = adapter->pdev;
unsigned int cidx = q->cidx;
const int need_unmap = need_skb_unmap() &&
q->cntxt_id >= FW_TUNNEL_SGEEC_START;
d = &q->sdesc[cidx];
while (n--) {
if (d->skb) { /* an SGL is present */
if (need_unmap)
unmap_skb(d->skb, q, cidx, pdev);
if (d->eop) {
kfree_skb(d->skb);
d->skb = NULL;
}
}
++d;
if (++cidx == q->size) {
cidx = 0;
d = q->sdesc;
}
}
q->cidx = cidx;
}
/**
* reclaim_completed_tx - reclaims completed Tx descriptors
* @adapter: the adapter
* @q: the Tx queue to reclaim completed descriptors from
* @chunk: maximum number of descriptors to reclaim
*
* Reclaims Tx descriptors that the SGE has indicated it has processed,
* and frees the associated buffers if possible. Called with the Tx
* queue's lock held.
*/
static inline unsigned int reclaim_completed_tx(struct adapter *adapter,
struct sge_txq *q,
unsigned int chunk)
{
unsigned int reclaim = q->processed - q->cleaned;
reclaim = min(chunk, reclaim);
if (reclaim) {
free_tx_desc(adapter, q, reclaim);
q->cleaned += reclaim;
q->in_use -= reclaim;
}
return q->processed - q->cleaned;
}
/**
* should_restart_tx - are there enough resources to restart a Tx queue?
* @q: the Tx queue
*
* Checks if there are enough descriptors to restart a suspended Tx queue.
*/
static inline int should_restart_tx(const struct sge_txq *q)
{
unsigned int r = q->processed - q->cleaned;
return q->in_use - r < (q->size >> 1);
}
static void clear_rx_desc(struct pci_dev *pdev, const struct sge_fl *q,
struct rx_sw_desc *d)
{
if (q->use_pages && d->pg_chunk.page) {
(*d->pg_chunk.p_cnt)--;
if (!*d->pg_chunk.p_cnt)
pci_unmap_page(pdev,
d->pg_chunk.mapping,
q->alloc_size, PCI_DMA_FROMDEVICE);
put_page(d->pg_chunk.page);
d->pg_chunk.page = NULL;
} else {
pci_unmap_single(pdev, dma_unmap_addr(d, dma_addr),
q->buf_size, PCI_DMA_FROMDEVICE);
kfree_skb(d->skb);
d->skb = NULL;
}
}
/**
* free_rx_bufs - free the Rx buffers on an SGE free list
* @pdev: the PCI device associated with the adapter
* @rxq: the SGE free list to clean up
*
* Release the buffers on an SGE free-buffer Rx queue. HW fetching from
* this queue should be stopped before calling this function.
*/
static void free_rx_bufs(struct pci_dev *pdev, struct sge_fl *q)
{
unsigned int cidx = q->cidx;
while (q->credits--) {
struct rx_sw_desc *d = &q->sdesc[cidx];
clear_rx_desc(pdev, q, d);
if (++cidx == q->size)
cidx = 0;
}
if (q->pg_chunk.page) {
__free_pages(q->pg_chunk.page, q->order);
q->pg_chunk.page = NULL;
}
}
/**
* add_one_rx_buf - add a packet buffer to a free-buffer list
* @va: buffer start VA
* @len: the buffer length
* @d: the HW Rx descriptor to write
* @sd: the SW Rx descriptor to write
* @gen: the generation bit value
* @pdev: the PCI device associated with the adapter
*
* Add a buffer of the given length to the supplied HW and SW Rx
* descriptors.
*/
static inline int add_one_rx_buf(void *va, unsigned int len,
struct rx_desc *d, struct rx_sw_desc *sd,
unsigned int gen, struct pci_dev *pdev)
{
dma_addr_t mapping;
mapping = pci_map_single(pdev, va, len, PCI_DMA_FROMDEVICE);
if (unlikely(pci_dma_mapping_error(pdev, mapping)))
return -ENOMEM;
dma_unmap_addr_set(sd, dma_addr, mapping);
d->addr_lo = cpu_to_be32(mapping);
d->addr_hi = cpu_to_be32((u64) mapping >> 32);
wmb();
d->len_gen = cpu_to_be32(V_FLD_GEN1(gen));
d->gen2 = cpu_to_be32(V_FLD_GEN2(gen));
return 0;
}
static inline int add_one_rx_chunk(dma_addr_t mapping, struct rx_desc *d,
unsigned int gen)
{
d->addr_lo = cpu_to_be32(mapping);
d->addr_hi = cpu_to_be32((u64) mapping >> 32);
wmb();
d->len_gen = cpu_to_be32(V_FLD_GEN1(gen));
d->gen2 = cpu_to_be32(V_FLD_GEN2(gen));
return 0;
}
static int alloc_pg_chunk(struct adapter *adapter, struct sge_fl *q,
struct rx_sw_desc *sd, gfp_t gfp,
unsigned int order)
{
if (!q->pg_chunk.page) {
dma_addr_t mapping;
q->pg_chunk.page = alloc_pages(gfp, order);
if (unlikely(!q->pg_chunk.page))
return -ENOMEM;
q->pg_chunk.va = page_address(q->pg_chunk.page);
q->pg_chunk.p_cnt = q->pg_chunk.va + (PAGE_SIZE << order) -
SGE_PG_RSVD;
q->pg_chunk.offset = 0;
mapping = pci_map_page(adapter->pdev, q->pg_chunk.page,
0, q->alloc_size, PCI_DMA_FROMDEVICE);
q->pg_chunk.mapping = mapping;
}
sd->pg_chunk = q->pg_chunk;
prefetch(sd->pg_chunk.p_cnt);
q->pg_chunk.offset += q->buf_size;
if (q->pg_chunk.offset == (PAGE_SIZE << order))
q->pg_chunk.page = NULL;
else {
q->pg_chunk.va += q->buf_size;
get_page(q->pg_chunk.page);
}
if (sd->pg_chunk.offset == 0)
*sd->pg_chunk.p_cnt = 1;
else
*sd->pg_chunk.p_cnt += 1;
return 0;
}
static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
{
if (q->pend_cred >= q->credits / 4) {
q->pend_cred = 0;
wmb();
t3_write_reg(adap, A_SG_KDOORBELL, V_EGRCNTX(q->cntxt_id));
}
}
/**
* refill_fl - refill an SGE free-buffer list
* @adapter: the adapter
* @q: the free-list to refill
* @n: the number of new buffers to allocate
* @gfp: the gfp flags for allocating new buffers
*
* (Re)populate an SGE free-buffer list with up to @n new packet buffers,
* allocated with the supplied gfp flags. The caller must assure that
* @n does not exceed the queue's capacity.
*/
static int refill_fl(struct adapter *adap, struct sge_fl *q, int n, gfp_t gfp)
{
struct rx_sw_desc *sd = &q->sdesc[q->pidx];
struct rx_desc *d = &q->desc[q->pidx];
unsigned int count = 0;
while (n--) {
dma_addr_t mapping;
int err;
if (q->use_pages) {
if (unlikely(alloc_pg_chunk(adap, q, sd, gfp,
q->order))) {
nomem: q->alloc_failed++;
break;
}
mapping = sd->pg_chunk.mapping + sd->pg_chunk.offset;
dma_unmap_addr_set(sd, dma_addr, mapping);
add_one_rx_chunk(mapping, d, q->gen);
pci_dma_sync_single_for_device(adap->pdev, mapping,
q->buf_size - SGE_PG_RSVD,
PCI_DMA_FROMDEVICE);
} else {
void *buf_start;
struct sk_buff *skb = alloc_skb(q->buf_size, gfp);
if (!skb)
goto nomem;
sd->skb = skb;
buf_start = skb->data;
err = add_one_rx_buf(buf_start, q->buf_size, d, sd,
q->gen, adap->pdev);
if (unlikely(err)) {
clear_rx_desc(adap->pdev, q, sd);
break;
}
}
d++;
sd++;
if (++q->pidx == q->size) {
q->pidx = 0;
q->gen ^= 1;
sd = q->sdesc;
d = q->desc;
}
count++;
}
q->credits += count;
q->pend_cred += count;
ring_fl_db(adap, q);
return count;
}
static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
{
refill_fl(adap, fl, min(MAX_RX_REFILL, fl->size - fl->credits),
GFP_ATOMIC | __GFP_COMP);
}
/**
* recycle_rx_buf - recycle a receive buffer
* @adapter: the adapter
* @q: the SGE free list
* @idx: index of buffer to recycle
*
* Recycles the specified buffer on the given free list by adding it at
* the next available slot on the list.
*/
static void recycle_rx_buf(struct adapter *adap, struct sge_fl *q,
unsigned int idx)
{
struct rx_desc *from = &q->desc[idx];
struct rx_desc *to = &q->desc[q->pidx];
q->sdesc[q->pidx] = q->sdesc[idx];
to->addr_lo = from->addr_lo; /* already big endian */
to->addr_hi = from->addr_hi; /* likewise */
wmb();
to->len_gen = cpu_to_be32(V_FLD_GEN1(q->gen));
to->gen2 = cpu_to_be32(V_FLD_GEN2(q->gen));
if (++q->pidx == q->size) {
q->pidx = 0;
q->gen ^= 1;
}
q->credits++;
q->pend_cred++;
ring_fl_db(adap, q);
}
/**
* alloc_ring - allocate resources for an SGE descriptor ring
* @pdev: the PCI device
* @nelem: the number of descriptors
* @elem_size: the size of each descriptor
* @sw_size: the size of the SW state associated with each ring element
* @phys: the physical address of the allocated ring
* @metadata: address of the array holding the SW state for the ring
*
* Allocates resources for an SGE descriptor ring, such as Tx queues,
* free buffer lists, or response queues. Each SGE ring requires
* space for its HW descriptors plus, optionally, space for the SW state
* associated with each HW entry (the metadata). The function returns
* three values: the virtual address for the HW ring (the return value
* of the function), the physical address of the HW ring, and the address
* of the SW ring.
*/
static void *alloc_ring(struct pci_dev *pdev, size_t nelem, size_t elem_size,
size_t sw_size, dma_addr_t * phys, void *metadata)
{
size_t len = nelem * elem_size;
void *s = NULL;
void *p = dma_alloc_coherent(&pdev->dev, len, phys, GFP_KERNEL);
if (!p)
return NULL;
if (sw_size && metadata) {
s = kcalloc(nelem, sw_size, GFP_KERNEL);
if (!s) {
dma_free_coherent(&pdev->dev, len, p, *phys);
return NULL;
}
*(void **)metadata = s;
}
memset(p, 0, len);
return p;
}
/**
* t3_reset_qset - reset a sge qset
* @q: the queue set
*
* Reset the qset structure.
* the NAPI structure is preserved in the event of
* the qset's reincarnation, for example during EEH recovery.
*/
static void t3_reset_qset(struct sge_qset *q)
{
if (q->adap &&
!(q->adap->flags & NAPI_INIT)) {
memset(q, 0, sizeof(*q));
return;
}
q->adap = NULL;
memset(&q->rspq, 0, sizeof(q->rspq));
memset(q->fl, 0, sizeof(struct sge_fl) * SGE_RXQ_PER_SET);
memset(q->txq, 0, sizeof(struct sge_txq) * SGE_TXQ_PER_SET);
q->txq_stopped = 0;
q->tx_reclaim_timer.function = NULL; /* for t3_stop_sge_timers() */
q->rx_reclaim_timer.function = NULL;
q->nomem = 0;
napi_free_frags(&q->napi);
}
/**
* free_qset - free the resources of an SGE queue set
* @adapter: the adapter owning the queue set
* @q: the queue set
*
* Release the HW and SW resources associated with an SGE queue set, such
* as HW contexts, packet buffers, and descriptor rings. Traffic to the
* queue set must be quiesced prior to calling this.
*/
static void t3_free_qset(struct adapter *adapter, struct sge_qset *q)
{
int i;
struct pci_dev *pdev = adapter->pdev;
for (i = 0; i < SGE_RXQ_PER_SET; ++i)
if (q->fl[i].desc) {
spin_lock_irq(&adapter->sge.reg_lock);
t3_sge_disable_fl(adapter, q->fl[i].cntxt_id);
spin_unlock_irq(&adapter->sge.reg_lock);
free_rx_bufs(pdev, &q->fl[i]);
kfree(q->fl[i].sdesc);
dma_free_coherent(&pdev->dev,
q->fl[i].size *
sizeof(struct rx_desc), q->fl[i].desc,
q->fl[i].phys_addr);
}
for (i = 0; i < SGE_TXQ_PER_SET; ++i)
if (q->txq[i].desc) {
spin_lock_irq(&adapter->sge.reg_lock);
t3_sge_enable_ecntxt(adapter, q->txq[i].cntxt_id, 0);
spin_unlock_irq(&adapter->sge.reg_lock);
if (q->txq[i].sdesc) {
free_tx_desc(adapter, &q->txq[i],
q->txq[i].in_use);
kfree(q->txq[i].sdesc);
}
dma_free_coherent(&pdev->dev,
q->txq[i].size *
sizeof(struct tx_desc),
q->txq[i].desc, q->txq[i].phys_addr);
__skb_queue_purge(&q->txq[i].sendq);
}
if (q->rspq.desc) {
spin_lock_irq(&adapter->sge.reg_lock);
t3_sge_disable_rspcntxt(adapter, q->rspq.cntxt_id);
spin_unlock_irq(&adapter->sge.reg_lock);
dma_free_coherent(&pdev->dev,
q->rspq.size * sizeof(struct rsp_desc),
q->rspq.desc, q->rspq.phys_addr);
}
t3_reset_qset(q);
}
/**
* init_qset_cntxt - initialize an SGE queue set context info
* @qs: the queue set
* @id: the queue set id
*
* Initializes the TIDs and context ids for the queues of a queue set.
*/
static void init_qset_cntxt(struct sge_qset *qs, unsigned int id)
{
qs->rspq.cntxt_id = id;
qs->fl[0].cntxt_id = 2 * id;
qs->fl[1].cntxt_id = 2 * id + 1;
qs->txq[TXQ_ETH].cntxt_id = FW_TUNNEL_SGEEC_START + id;
qs->txq[TXQ_ETH].token = FW_TUNNEL_TID_START + id;
qs->txq[TXQ_OFLD].cntxt_id = FW_OFLD_SGEEC_START + id;
qs->txq[TXQ_CTRL].cntxt_id = FW_CTRL_SGEEC_START + id;
qs->txq[TXQ_CTRL].token = FW_CTRL_TID_START + id;
}
/**
* sgl_len - calculates the size of an SGL of the given capacity
* @n: the number of SGL entries
*
* Calculates the number of flits needed for a scatter/gather list that
* can hold the given number of entries.
*/
static inline unsigned int sgl_len(unsigned int n)
{
/* alternatively: 3 * (n / 2) + 2 * (n & 1) */
return (3 * n) / 2 + (n & 1);
}
/**
* flits_to_desc - returns the num of Tx descriptors for the given flits
* @n: the number of flits
*
* Calculates the number of Tx descriptors needed for the supplied number
* of flits.
*/
static inline unsigned int flits_to_desc(unsigned int n)
{
BUG_ON(n >= ARRAY_SIZE(flit_desc_map));
return flit_desc_map[n];
}
/**
* get_packet - return the next ingress packet buffer from a free list
* @adap: the adapter that received the packet
* @fl: the SGE free list holding the packet
* @len: the packet length including any SGE padding
* @drop_thres: # of remaining buffers before we start dropping packets
*
* Get the next packet from a free list and complete setup of the
* sk_buff. If the packet is small we make a copy and recycle the
* original buffer, otherwise we use the original buffer itself. If a
* positive drop threshold is supplied packets are dropped and their
* buffers recycled if (a) the number of remaining buffers is under the
* threshold and the packet is too big to copy, or (b) the packet should
* be copied but there is no memory for the copy.
*/
static struct sk_buff *get_packet(struct adapter *adap, struct sge_fl *fl,
unsigned int len, unsigned int drop_thres)
{
struct sk_buff *skb = NULL;
struct rx_sw_desc *sd = &fl->sdesc[fl->cidx];
prefetch(sd->skb->data);
fl->credits--;
if (len <= SGE_RX_COPY_THRES) {
skb = alloc_skb(len, GFP_ATOMIC);
if (likely(skb != NULL)) {
__skb_put(skb, len);
pci_dma_sync_single_for_cpu(adap->pdev,
dma_unmap_addr(sd, dma_addr), len,
PCI_DMA_FROMDEVICE);
memcpy(skb->data, sd->skb->data, len);
pci_dma_sync_single_for_device(adap->pdev,
dma_unmap_addr(sd, dma_addr), len,
PCI_DMA_FROMDEVICE);
} else if (!drop_thres)
goto use_orig_buf;
recycle:
recycle_rx_buf(adap, fl, fl->cidx);
return skb;
}
if (unlikely(fl->credits < drop_thres) &&
refill_fl(adap, fl, min(MAX_RX_REFILL, fl->size - fl->credits - 1),
GFP_ATOMIC | __GFP_COMP) == 0)
goto recycle;
use_orig_buf:
pci_unmap_single(adap->pdev, dma_unmap_addr(sd, dma_addr),
fl->buf_size, PCI_DMA_FROMDEVICE);
skb = sd->skb;
skb_put(skb, len);
__refill_fl(adap, fl);
return skb;
}
/**
* get_packet_pg - return the next ingress packet buffer from a free list
* @adap: the adapter that received the packet
* @fl: the SGE free list holding the packet
* @len: the packet length including any SGE padding
* @drop_thres: # of remaining buffers before we start dropping packets
*
* Get the next packet from a free list populated with page chunks.
* If the packet is small we make a copy and recycle the original buffer,
* otherwise we attach the original buffer as a page fragment to a fresh
* sk_buff. If a positive drop threshold is supplied packets are dropped
* and their buffers recycled if (a) the number of remaining buffers is
* under the threshold and the packet is too big to copy, or (b) there's
* no system memory.
*
* Note: this function is similar to @get_packet but deals with Rx buffers
* that are page chunks rather than sk_buffs.
*/
static struct sk_buff *get_packet_pg(struct adapter *adap, struct sge_fl *fl,
struct sge_rspq *q, unsigned int len,
unsigned int drop_thres)
{
struct sk_buff *newskb, *skb;
struct rx_sw_desc *sd = &fl->sdesc[fl->cidx];
dma_addr_t dma_addr = dma_unmap_addr(sd, dma_addr);
newskb = skb = q->pg_skb;
if (!skb && (len <= SGE_RX_COPY_THRES)) {
newskb = alloc_skb(len, GFP_ATOMIC);
if (likely(newskb != NULL)) {
__skb_put(newskb, len);
pci_dma_sync_single_for_cpu(adap->pdev, dma_addr, len,
PCI_DMA_FROMDEVICE);
memcpy(newskb->data, sd->pg_chunk.va, len);
pci_dma_sync_single_for_device(adap->pdev, dma_addr,
len,
PCI_DMA_FROMDEVICE);
} else if (!drop_thres)
return NULL;
recycle:
fl->credits--;
recycle_rx_buf(adap, fl, fl->cidx);
q->rx_recycle_buf++;
return newskb;
}
if (unlikely(q->rx_recycle_buf || (!skb && fl->credits <= drop_thres)))
goto recycle;
prefetch(sd->pg_chunk.p_cnt);
if (!skb)
newskb = alloc_skb(SGE_RX_PULL_LEN, GFP_ATOMIC);
if (unlikely(!newskb)) {
if (!drop_thres)
return NULL;
goto recycle;
}
pci_dma_sync_single_for_cpu(adap->pdev, dma_addr, len,
PCI_DMA_FROMDEVICE);
(*sd->pg_chunk.p_cnt)--;
if (!*sd->pg_chunk.p_cnt && sd->pg_chunk.page != fl->pg_chunk.page)
pci_unmap_page(adap->pdev,
sd->pg_chunk.mapping,
fl->alloc_size,
PCI_DMA_FROMDEVICE);
if (!skb) {
__skb_put(newskb, SGE_RX_PULL_LEN);
memcpy(newskb->data, sd->pg_chunk.va, SGE_RX_PULL_LEN);
skb_fill_page_desc(newskb, 0, sd->pg_chunk.page,
sd->pg_chunk.offset + SGE_RX_PULL_LEN,
len - SGE_RX_PULL_LEN);
newskb->len = len;
newskb->data_len = len - SGE_RX_PULL_LEN;
newskb->truesize += newskb->data_len;
} else {
skb_fill_page_desc(newskb, skb_shinfo(newskb)->nr_frags,
sd->pg_chunk.page,
sd->pg_chunk.offset, len);
newskb->len += len;
newskb->data_len += len;
newskb->truesize += len;
}
fl->credits--;
/*
* We do not refill FLs here, we let the caller do it to overlap a
* prefetch.
*/
return newskb;
}
/**
* get_imm_packet - return the next ingress packet buffer from a response
* @resp: the response descriptor containing the packet data
*
* Return a packet containing the immediate data of the given response.
*/
static inline struct sk_buff *get_imm_packet(const struct rsp_desc *resp)
{
struct sk_buff *skb = alloc_skb(IMMED_PKT_SIZE, GFP_ATOMIC);
if (skb) {
__skb_put(skb, IMMED_PKT_SIZE);
skb_copy_to_linear_data(skb, resp->imm_data, IMMED_PKT_SIZE);
}
return skb;
}
/**
* calc_tx_descs - calculate the number of Tx descriptors for a packet
* @skb: the packet
*
* Returns the number of Tx descriptors needed for the given Ethernet
* packet. Ethernet packets require addition of WR and CPL headers.
*/
static inline unsigned int calc_tx_descs(const struct sk_buff *skb)
{
unsigned int flits;
if (skb->len <= WR_LEN - sizeof(struct cpl_tx_pkt))
return 1;
flits = sgl_len(skb_shinfo(skb)->nr_frags + 1) + 2;
if (skb_shinfo(skb)->gso_size)
flits++;
return flits_to_desc(flits);
}
/**
* make_sgl - populate a scatter/gather list for a packet
* @skb: the packet
* @sgp: the SGL to populate
* @start: start address of skb main body data to include in the SGL
* @len: length of skb main body data to include in the SGL
* @pdev: the PCI device
*
* Generates a scatter/gather list for the buffers that make up a packet
* and returns the SGL size in 8-byte words. The caller must size the SGL
* appropriately.
*/
static inline unsigned int make_sgl(const struct sk_buff *skb,
struct sg_ent *sgp, unsigned char *start,
unsigned int len, struct pci_dev *pdev)
{
dma_addr_t mapping;
unsigned int i, j = 0, nfrags;
if (len) {
mapping = pci_map_single(pdev, start, len, PCI_DMA_TODEVICE);
sgp->len[0] = cpu_to_be32(len);
sgp->addr[0] = cpu_to_be64(mapping);
j = 1;
}
nfrags = skb_shinfo(skb)->nr_frags;
for (i = 0; i < nfrags; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
mapping = skb_frag_dma_map(&pdev->dev, frag, 0, skb_frag_size(frag),
DMA_TO_DEVICE);
sgp->len[j] = cpu_to_be32(skb_frag_size(frag));
sgp->addr[j] = cpu_to_be64(mapping);
j ^= 1;
if (j == 0)
++sgp;
}
if (j)
sgp->len[j] = 0;
return ((nfrags + (len != 0)) * 3) / 2 + j;
}
/**
* check_ring_tx_db - check and potentially ring a Tx queue's doorbell
* @adap: the adapter
* @q: the Tx queue
*
* Ring the doorbel if a Tx queue is asleep. There is a natural race,
* where the HW is going to sleep just after we checked, however,
* then the interrupt handler will detect the outstanding TX packet
* and ring the doorbell for us.
*
* When GTS is disabled we unconditionally ring the doorbell.
*/
static inline void check_ring_tx_db(struct adapter *adap, struct sge_txq *q)
{
#if USE_GTS
clear_bit(TXQ_LAST_PKT_DB, &q->flags);
if (test_and_set_bit(TXQ_RUNNING, &q->flags) == 0) {
set_bit(TXQ_LAST_PKT_DB, &q->flags);
t3_write_reg(adap, A_SG_KDOORBELL,
F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id));
}
#else
wmb(); /* write descriptors before telling HW */
t3_write_reg(adap, A_SG_KDOORBELL,
F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id));
#endif
}
static inline void wr_gen2(struct tx_desc *d, unsigned int gen)
{
#if SGE_NUM_GENBITS == 2
d->flit[TX_DESC_FLITS - 1] = cpu_to_be64(gen);
#endif
}
/**
* write_wr_hdr_sgl - write a WR header and, optionally, SGL
* @ndesc: number of Tx descriptors spanned by the SGL
* @skb: the packet corresponding to the WR
* @d: first Tx descriptor to be written
* @pidx: index of above descriptors
* @q: the SGE Tx queue
* @sgl: the SGL
* @flits: number of flits to the start of the SGL in the first descriptor
* @sgl_flits: the SGL size in flits
* @gen: the Tx descriptor generation
* @wr_hi: top 32 bits of WR header based on WR type (big endian)
* @wr_lo: low 32 bits of WR header based on WR type (big endian)
*
* Write a work request header and an associated SGL. If the SGL is
* small enough to fit into one Tx descriptor it has already been written
* and we just need to write the WR header. Otherwise we distribute the
* SGL across the number of descriptors it spans.
*/
static void write_wr_hdr_sgl(unsigned int ndesc, struct sk_buff *skb,
struct tx_desc *d, unsigned int pidx,
const struct sge_txq *q,
const struct sg_ent *sgl,
unsigned int flits, unsigned int sgl_flits,
unsigned int gen, __be32 wr_hi,
__be32 wr_lo)
{
struct work_request_hdr *wrp = (struct work_request_hdr *)d;
struct tx_sw_desc *sd = &q->sdesc[pidx];
sd->skb = skb;
if (need_skb_unmap()) {
sd->fragidx = 0;
sd->addr_idx = 0;
sd->sflit = flits;
}
if (likely(ndesc == 1)) {
sd->eop = 1;
wrp->wr_hi = htonl(F_WR_SOP | F_WR_EOP | V_WR_DATATYPE(1) |
V_WR_SGLSFLT(flits)) | wr_hi;
wmb();
wrp->wr_lo = htonl(V_WR_LEN(flits + sgl_flits) |
V_WR_GEN(gen)) | wr_lo;
wr_gen2(d, gen);
} else {
unsigned int ogen = gen;
const u64 *fp = (const u64 *)sgl;
struct work_request_hdr *wp = wrp;
wrp->wr_hi = htonl(F_WR_SOP | V_WR_DATATYPE(1) |
V_WR_SGLSFLT(flits)) | wr_hi;
while (sgl_flits) {
unsigned int avail = WR_FLITS - flits;
if (avail > sgl_flits)
avail = sgl_flits;
memcpy(&d->flit[flits], fp, avail * sizeof(*fp));
sgl_flits -= avail;
ndesc--;
if (!sgl_flits)
break;
fp += avail;
d++;
sd->eop = 0;
sd++;
if (++pidx == q->size) {
pidx = 0;
gen ^= 1;
d = q->desc;
sd = q->sdesc;
}
sd->skb = skb;
wrp = (struct work_request_hdr *)d;
wrp->wr_hi = htonl(V_WR_DATATYPE(1) |
V_WR_SGLSFLT(1)) | wr_hi;
wrp->wr_lo = htonl(V_WR_LEN(min(WR_FLITS,
sgl_flits + 1)) |
V_WR_GEN(gen)) | wr_lo;
wr_gen2(d, gen);
flits = 1;
}
sd->eop = 1;
wrp->wr_hi |= htonl(F_WR_EOP);
wmb();
wp->wr_lo = htonl(V_WR_LEN(WR_FLITS) | V_WR_GEN(ogen)) | wr_lo;
wr_gen2((struct tx_desc *)wp, ogen);
WARN_ON(ndesc != 0);
}
}
/**
* write_tx_pkt_wr - write a TX_PKT work request
* @adap: the adapter
* @skb: the packet to send
* @pi: the egress interface
* @pidx: index of the first Tx descriptor to write
* @gen: the generation value to use
* @q: the Tx queue
* @ndesc: number of descriptors the packet will occupy
* @compl: the value of the COMPL bit to use
*
* Generate a TX_PKT work request to send the supplied packet.
*/
static void write_tx_pkt_wr(struct adapter *adap, struct sk_buff *skb,
const struct port_info *pi,
unsigned int pidx, unsigned int gen,
struct sge_txq *q, unsigned int ndesc,
unsigned int compl)
{
unsigned int flits, sgl_flits, cntrl, tso_info;
struct sg_ent *sgp, sgl[MAX_SKB_FRAGS / 2 + 1];
struct tx_desc *d = &q->desc[pidx];
struct cpl_tx_pkt *cpl = (struct cpl_tx_pkt *)d;
cpl->len = htonl(skb->len);
cntrl = V_TXPKT_INTF(pi->port_id);
if (vlan_tx_tag_present(skb))
cntrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(vlan_tx_tag_get(skb));
tso_info = V_LSO_MSS(skb_shinfo(skb)->gso_size);
if (tso_info) {
int eth_type;
struct cpl_tx_pkt_lso *hdr = (struct cpl_tx_pkt_lso *)cpl;
d->flit[2] = 0;
cntrl |= V_TXPKT_OPCODE(CPL_TX_PKT_LSO);
hdr->cntrl = htonl(cntrl);
eth_type = skb_network_offset(skb) == ETH_HLEN ?
CPL_ETH_II : CPL_ETH_II_VLAN;
tso_info |= V_LSO_ETH_TYPE(eth_type) |
V_LSO_IPHDR_WORDS(ip_hdr(skb)->ihl) |
V_LSO_TCPHDR_WORDS(tcp_hdr(skb)->doff);
hdr->lso_info = htonl(tso_info);
flits = 3;
} else {
cntrl |= V_TXPKT_OPCODE(CPL_TX_PKT);
cntrl |= F_TXPKT_IPCSUM_DIS; /* SW calculates IP csum */
cntrl |= V_TXPKT_L4CSUM_DIS(skb->ip_summed != CHECKSUM_PARTIAL);
cpl->cntrl = htonl(cntrl);
if (skb->len <= WR_LEN - sizeof(*cpl)) {
q->sdesc[pidx].skb = NULL;
if (!skb->data_len)
skb_copy_from_linear_data(skb, &d->flit[2],
skb->len);
else
skb_copy_bits(skb, 0, &d->flit[2], skb->len);
flits = (skb->len + 7) / 8 + 2;
cpl->wr.wr_hi = htonl(V_WR_BCNTLFLT(skb->len & 7) |
V_WR_OP(FW_WROPCODE_TUNNEL_TX_PKT)
| F_WR_SOP | F_WR_EOP | compl);
wmb();
cpl->wr.wr_lo = htonl(V_WR_LEN(flits) | V_WR_GEN(gen) |
V_WR_TID(q->token));
wr_gen2(d, gen);
kfree_skb(skb);
return;
}
flits = 2;
}
sgp = ndesc == 1 ? (struct sg_ent *)&d->flit[flits] : sgl;
sgl_flits = make_sgl(skb, sgp, skb->data, skb_headlen(skb), adap->pdev);
write_wr_hdr_sgl(ndesc, skb, d, pidx, q, sgl, flits, sgl_flits, gen,
htonl(V_WR_OP(FW_WROPCODE_TUNNEL_TX_PKT) | compl),
htonl(V_WR_TID(q->token)));
}
static inline void t3_stop_tx_queue(struct netdev_queue *txq,
struct sge_qset *qs, struct sge_txq *q)
{
netif_tx_stop_queue(txq);
set_bit(TXQ_ETH, &qs->txq_stopped);
q->stops++;
}
/**
* eth_xmit - add a packet to the Ethernet Tx queue
* @skb: the packet
* @dev: the egress net device
*
* Add a packet to an SGE Tx queue. Runs with softirqs disabled.
*/
netdev_tx_t t3_eth_xmit(struct sk_buff *skb, struct net_device *dev)
{
int qidx;
unsigned int ndesc, pidx, credits, gen, compl;
const struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
struct netdev_queue *txq;
struct sge_qset *qs;
struct sge_txq *q;
/*
* The chip min packet length is 9 octets but play safe and reject
* anything shorter than an Ethernet header.
*/
if (unlikely(skb->len < ETH_HLEN)) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
qidx = skb_get_queue_mapping(skb);
qs = &pi->qs[qidx];
q = &qs->txq[TXQ_ETH];
txq = netdev_get_tx_queue(dev, qidx);
reclaim_completed_tx(adap, q, TX_RECLAIM_CHUNK);
credits = q->size - q->in_use;
ndesc = calc_tx_descs(skb);
if (unlikely(credits < ndesc)) {
t3_stop_tx_queue(txq, qs, q);
dev_err(&adap->pdev->dev,
"%s: Tx ring %u full while queue awake!\n",
dev->name, q->cntxt_id & 7);
return NETDEV_TX_BUSY;
}
q->in_use += ndesc;
if (unlikely(credits - ndesc < q->stop_thres)) {
t3_stop_tx_queue(txq, qs, q);
if (should_restart_tx(q) &&
test_and_clear_bit(TXQ_ETH, &qs->txq_stopped)) {
q->restarts++;
netif_tx_start_queue(txq);
}
}
gen = q->gen;
q->unacked += ndesc;
compl = (q->unacked & 8) << (S_WR_COMPL - 3);
q->unacked &= 7;
pidx = q->pidx;
q->pidx += ndesc;
if (q->pidx >= q->size) {
q->pidx -= q->size;
q->gen ^= 1;
}
/* update port statistics */
if (skb->ip_summed == CHECKSUM_COMPLETE)
qs->port_stats[SGE_PSTAT_TX_CSUM]++;
if (skb_shinfo(skb)->gso_size)
qs->port_stats[SGE_PSTAT_TSO]++;
if (vlan_tx_tag_present(skb))
qs->port_stats[SGE_PSTAT_VLANINS]++;
/*
* We do not use Tx completion interrupts to free DMAd Tx packets.
* This is good for performance but means that we rely on new Tx
* packets arriving to run the destructors of completed packets,
* which open up space in their sockets' send queues. Sometimes
* we do not get such new packets causing Tx to stall. A single
* UDP transmitter is a good example of this situation. We have
* a clean up timer that periodically reclaims completed packets
* but it doesn't run often enough (nor do we want it to) to prevent
* lengthy stalls. A solution to this problem is to run the
* destructor early, after the packet is queued but before it's DMAd.
* A cons is that we lie to socket memory accounting, but the amount
* of extra memory is reasonable (limited by the number of Tx
* descriptors), the packets do actually get freed quickly by new
* packets almost always, and for protocols like TCP that wait for
* acks to really free up the data the extra memory is even less.
* On the positive side we run the destructors on the sending CPU
* rather than on a potentially different completing CPU, usually a
* good thing. We also run them without holding our Tx queue lock,
* unlike what reclaim_completed_tx() would otherwise do.
*
* Run the destructor before telling the DMA engine about the packet
* to make sure it doesn't complete and get freed prematurely.
*/
if (likely(!skb_shared(skb)))
skb_orphan(skb);
write_tx_pkt_wr(adap, skb, pi, pidx, gen, q, ndesc, compl);
check_ring_tx_db(adap, q);
return NETDEV_TX_OK;
}
/**
* write_imm - write a packet into a Tx descriptor as immediate data
* @d: the Tx descriptor to write
* @skb: the packet
* @len: the length of packet data to write as immediate data
* @gen: the generation bit value to write
*
* Writes a packet as immediate data into a Tx descriptor. The packet
* contains a work request at its beginning. We must write the packet
* carefully so the SGE doesn't read it accidentally before it's written
* in its entirety.
*/
static inline void write_imm(struct tx_desc *d, struct sk_buff *skb,
unsigned int len, unsigned int gen)
{
struct work_request_hdr *from = (struct work_request_hdr *)skb->data;
struct work_request_hdr *to = (struct work_request_hdr *)d;
if (likely(!skb->data_len))
memcpy(&to[1], &from[1], len - sizeof(*from));
else
skb_copy_bits(skb, sizeof(*from), &to[1], len - sizeof(*from));
to->wr_hi = from->wr_hi | htonl(F_WR_SOP | F_WR_EOP |
V_WR_BCNTLFLT(len & 7));
wmb();
to->wr_lo = from->wr_lo | htonl(V_WR_GEN(gen) |
V_WR_LEN((len + 7) / 8));
wr_gen2(d, gen);
kfree_skb(skb);
}
/**
* check_desc_avail - check descriptor availability on a send queue
* @adap: the adapter
* @q: the send queue
* @skb: the packet needing the descriptors
* @ndesc: the number of Tx descriptors needed
* @qid: the Tx queue number in its queue set (TXQ_OFLD or TXQ_CTRL)
*
* Checks if the requested number of Tx descriptors is available on an
* SGE send queue. If the queue is already suspended or not enough
* descriptors are available the packet is queued for later transmission.
* Must be called with the Tx queue locked.
*
* Returns 0 if enough descriptors are available, 1 if there aren't
* enough descriptors and the packet has been queued, and 2 if the caller
* needs to retry because there weren't enough descriptors at the
* beginning of the call but some freed up in the mean time.
*/
static inline int check_desc_avail(struct adapter *adap, struct sge_txq *q,
struct sk_buff *skb, unsigned int ndesc,
unsigned int qid)
{
if (unlikely(!skb_queue_empty(&q->sendq))) {
addq_exit:__skb_queue_tail(&q->sendq, skb);
return 1;
}
if (unlikely(q->size - q->in_use < ndesc)) {
struct sge_qset *qs = txq_to_qset(q, qid);
set_bit(qid, &qs->txq_stopped);
smp_mb__after_clear_bit();
if (should_restart_tx(q) &&
test_and_clear_bit(qid, &qs->txq_stopped))
return 2;
q->stops++;
goto addq_exit;
}
return 0;
}
/**
* reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
* @q: the SGE control Tx queue
*
* This is a variant of reclaim_completed_tx() that is used for Tx queues
* that send only immediate data (presently just the control queues) and
* thus do not have any sk_buffs to release.
*/
static inline void reclaim_completed_tx_imm(struct sge_txq *q)
{
unsigned int reclaim = q->processed - q->cleaned;
q->in_use -= reclaim;
q->cleaned += reclaim;
}
static inline int immediate(const struct sk_buff *skb)
{
return skb->len <= WR_LEN;
}
/**
* ctrl_xmit - send a packet through an SGE control Tx queue
* @adap: the adapter
* @q: the control queue
* @skb: the packet
*
* Send a packet through an SGE control Tx queue. Packets sent through
* a control queue must fit entirely as immediate data in a single Tx
* descriptor and have no page fragments.
*/
static int ctrl_xmit(struct adapter *adap, struct sge_txq *q,
struct sk_buff *skb)
{
int ret;
struct work_request_hdr *wrp = (struct work_request_hdr *)skb->data;
if (unlikely(!immediate(skb))) {
WARN_ON(1);
dev_kfree_skb(skb);
return NET_XMIT_SUCCESS;
}
wrp->wr_hi |= htonl(F_WR_SOP | F_WR_EOP);
wrp->wr_lo = htonl(V_WR_TID(q->token));
spin_lock(&q->lock);
again:reclaim_completed_tx_imm(q);
ret = check_desc_avail(adap, q, skb, 1, TXQ_CTRL);
if (unlikely(ret)) {
if (ret == 1) {
spin_unlock(&q->lock);
return NET_XMIT_CN;
}
goto again;
}
write_imm(&q->desc[q->pidx], skb, skb->len, q->gen);
q->in_use++;
if (++q->pidx >= q->size) {
q->pidx = 0;
q->gen ^= 1;
}
spin_unlock(&q->lock);
wmb();
t3_write_reg(adap, A_SG_KDOORBELL,
F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id));
return NET_XMIT_SUCCESS;
}
/**
* restart_ctrlq - restart a suspended control queue
* @qs: the queue set cotaining the control queue
*
* Resumes transmission on a suspended Tx control queue.
*/
static void restart_ctrlq(unsigned long data)
{
struct sk_buff *skb;
struct sge_qset *qs = (struct sge_qset *)data;
struct sge_txq *q = &qs->txq[TXQ_CTRL];
spin_lock(&q->lock);
again:reclaim_completed_tx_imm(q);
while (q->in_use < q->size &&
(skb = __skb_dequeue(&q->sendq)) != NULL) {
write_imm(&q->desc[q->pidx], skb, skb->len, q->gen);
if (++q->pidx >= q->size) {
q->pidx = 0;
q->gen ^= 1;
}
q->in_use++;
}
if (!skb_queue_empty(&q->sendq)) {
set_bit(TXQ_CTRL, &qs->txq_stopped);
smp_mb__after_clear_bit();
if (should_restart_tx(q) &&
test_and_clear_bit(TXQ_CTRL, &qs->txq_stopped))
goto again;
q->stops++;
}
spin_unlock(&q->lock);
wmb();
t3_write_reg(qs->adap, A_SG_KDOORBELL,
F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id));
}
/*
* Send a management message through control queue 0
*/
int t3_mgmt_tx(struct adapter *adap, struct sk_buff *skb)
{
int ret;
local_bh_disable();
ret = ctrl_xmit(adap, &adap->sge.qs[0].txq[TXQ_CTRL], skb);
local_bh_enable();
return ret;
}
/**
* deferred_unmap_destructor - unmap a packet when it is freed
* @skb: the packet
*
* This is the packet destructor used for Tx packets that need to remain
* mapped until they are freed rather than until their Tx descriptors are
* freed.
*/
static void deferred_unmap_destructor(struct sk_buff *skb)
{
int i;
const dma_addr_t *p;
const struct skb_shared_info *si;
const struct deferred_unmap_info *dui;
dui = (struct deferred_unmap_info *)skb->head;
p = dui->addr;
if (skb->tail - skb->transport_header)
pci_unmap_single(dui->pdev, *p++,
skb->tail - skb->transport_header,
PCI_DMA_TODEVICE);
si = skb_shinfo(skb);
for (i = 0; i < si->nr_frags; i++)
pci_unmap_page(dui->pdev, *p++, skb_frag_size(&si->frags[i]),
PCI_DMA_TODEVICE);
}
static void setup_deferred_unmapping(struct sk_buff *skb, struct pci_dev *pdev,
const struct sg_ent *sgl, int sgl_flits)
{
dma_addr_t *p;
struct deferred_unmap_info *dui;
dui = (struct deferred_unmap_info *)skb->head;
dui->pdev = pdev;
for (p = dui->addr; sgl_flits >= 3; sgl++, sgl_flits -= 3) {
*p++ = be64_to_cpu(sgl->addr[0]);
*p++ = be64_to_cpu(sgl->addr[1]);
}
if (sgl_flits)
*p = be64_to_cpu(sgl->addr[0]);
}
/**
* write_ofld_wr - write an offload work request
* @adap: the adapter
* @skb: the packet to send
* @q: the Tx queue
* @pidx: index of the first Tx descriptor to write
* @gen: the generation value to use
* @ndesc: number of descriptors the packet will occupy
*
* Write an offload work request to send the supplied packet. The packet
* data already carry the work request with most fields populated.
*/
static void write_ofld_wr(struct adapter *adap, struct sk_buff *skb,
struct sge_txq *q, unsigned int pidx,
unsigned int gen, unsigned int ndesc)
{
unsigned int sgl_flits, flits;
struct work_request_hdr *from;
struct sg_ent *sgp, sgl[MAX_SKB_FRAGS / 2 + 1];
struct tx_desc *d = &q->desc[pidx];
if (immediate(skb)) {
q->sdesc[pidx].skb = NULL;
write_imm(d, skb, skb->len, gen);
return;
}
/* Only TX_DATA builds SGLs */
from = (struct work_request_hdr *)skb->data;
memcpy(&d->flit[1], &from[1],
skb_transport_offset(skb) - sizeof(*from));
flits = skb_transport_offset(skb) / 8;
sgp = ndesc == 1 ? (struct sg_ent *)&d->flit[flits] : sgl;
sgl_flits = make_sgl(skb, sgp, skb_transport_header(skb),
skb->tail - skb->transport_header,
adap->pdev);
if (need_skb_unmap()) {
setup_deferred_unmapping(skb, adap->pdev, sgp, sgl_flits);
skb->destructor = deferred_unmap_destructor;
}
write_wr_hdr_sgl(ndesc, skb, d, pidx, q, sgl, flits, sgl_flits,
gen, from->wr_hi, from->wr_lo);
}
/**
* calc_tx_descs_ofld - calculate # of Tx descriptors for an offload packet
* @skb: the packet
*
* Returns the number of Tx descriptors needed for the given offload
* packet. These packets are already fully constructed.
*/
static inline unsigned int calc_tx_descs_ofld(const struct sk_buff *skb)
{
unsigned int flits, cnt;
if (skb->len <= WR_LEN)
return 1; /* packet fits as immediate data */
flits = skb_transport_offset(skb) / 8; /* headers */
cnt = skb_shinfo(skb)->nr_frags;
if (skb->tail != skb->transport_header)
cnt++;
return flits_to_desc(flits + sgl_len(cnt));
}
/**
* ofld_xmit - send a packet through an offload queue
* @adap: the adapter
* @q: the Tx offload queue
* @skb: the packet
*
* Send an offload packet through an SGE offload queue.
*/
static int ofld_xmit(struct adapter *adap, struct sge_txq *q,
struct sk_buff *skb)
{
int ret;
unsigned int ndesc = calc_tx_descs_ofld(skb), pidx, gen;
spin_lock(&q->lock);
again: reclaim_completed_tx(adap, q, TX_RECLAIM_CHUNK);
ret = check_desc_avail(adap, q, skb, ndesc, TXQ_OFLD);
if (unlikely(ret)) {
if (ret == 1) {
skb->priority = ndesc; /* save for restart */
spin_unlock(&q->lock);
return NET_XMIT_CN;
}
goto again;
}
gen = q->gen;
q->in_use += ndesc;
pidx = q->pidx;
q->pidx += ndesc;
if (q->pidx >= q->size) {
q->pidx -= q->size;
q->gen ^= 1;
}
spin_unlock(&q->lock);
write_ofld_wr(adap, skb, q, pidx, gen, ndesc);
check_ring_tx_db(adap, q);
return NET_XMIT_SUCCESS;
}
/**
* restart_offloadq - restart a suspended offload queue
* @qs: the queue set cotaining the offload queue
*
* Resumes transmission on a suspended Tx offload queue.
*/
static void restart_offloadq(unsigned long data)
{
struct sk_buff *skb;
struct sge_qset *qs = (struct sge_qset *)data;
struct sge_txq *q = &qs->txq[TXQ_OFLD];
const struct port_info *pi = netdev_priv(qs->netdev);
struct adapter *adap = pi->adapter;
spin_lock(&q->lock);
again: reclaim_completed_tx(adap, q, TX_RECLAIM_CHUNK);
while ((skb = skb_peek(&q->sendq)) != NULL) {
unsigned int gen, pidx;
unsigned int ndesc = skb->priority;
if (unlikely(q->size - q->in_use < ndesc)) {
set_bit(TXQ_OFLD, &qs->txq_stopped);
smp_mb__after_clear_bit();
if (should_restart_tx(q) &&
test_and_clear_bit(TXQ_OFLD, &qs->txq_stopped))
goto again;
q->stops++;
break;
}
gen = q->gen;
q->in_use += ndesc;
pidx = q->pidx;
q->pidx += ndesc;
if (q->pidx >= q->size) {
q->pidx -= q->size;
q->gen ^= 1;
}
__skb_unlink(skb, &q->sendq);
spin_unlock(&q->lock);
write_ofld_wr(adap, skb, q, pidx, gen, ndesc);
spin_lock(&q->lock);
}
spin_unlock(&q->lock);
#if USE_GTS
set_bit(TXQ_RUNNING, &q->flags);
set_bit(TXQ_LAST_PKT_DB, &q->flags);
#endif
wmb();
t3_write_reg(adap, A_SG_KDOORBELL,
F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id));
}
/**
* queue_set - return the queue set a packet should use
* @skb: the packet
*
* Maps a packet to the SGE queue set it should use. The desired queue
* set is carried in bits 1-3 in the packet's priority.
*/
static inline int queue_set(const struct sk_buff *skb)
{
return skb->priority >> 1;
}
/**
* is_ctrl_pkt - return whether an offload packet is a control packet
* @skb: the packet
*
* Determines whether an offload packet should use an OFLD or a CTRL
* Tx queue. This is indicated by bit 0 in the packet's priority.
*/
static inline int is_ctrl_pkt(const struct sk_buff *skb)
{
return skb->priority & 1;
}
/**
* t3_offload_tx - send an offload packet
* @tdev: the offload device to send to
* @skb: the packet
*
* Sends an offload packet. We use the packet priority to select the
* appropriate Tx queue as follows: bit 0 indicates whether the packet
* should be sent as regular or control, bits 1-3 select the queue set.
*/
int t3_offload_tx(struct t3cdev *tdev, struct sk_buff *skb)
{
struct adapter *adap = tdev2adap(tdev);
struct sge_qset *qs = &adap->sge.qs[queue_set(skb)];
if (unlikely(is_ctrl_pkt(skb)))
return ctrl_xmit(adap, &qs->txq[TXQ_CTRL], skb);
return ofld_xmit(adap, &qs->txq[TXQ_OFLD], skb);
}
/**
* offload_enqueue - add an offload packet to an SGE offload receive queue
* @q: the SGE response queue
* @skb: the packet
*
* Add a new offload packet to an SGE response queue's offload packet
* queue. If the packet is the first on the queue it schedules the RX
* softirq to process the queue.
*/
static inline void offload_enqueue(struct sge_rspq *q, struct sk_buff *skb)
{
int was_empty = skb_queue_empty(&q->rx_queue);
__skb_queue_tail(&q->rx_queue, skb);
if (was_empty) {
struct sge_qset *qs = rspq_to_qset(q);
napi_schedule(&qs->napi);
}
}
/**
* deliver_partial_bundle - deliver a (partial) bundle of Rx offload pkts
* @tdev: the offload device that will be receiving the packets
* @q: the SGE response queue that assembled the bundle
* @skbs: the partial bundle
* @n: the number of packets in the bundle
*
* Delivers a (partial) bundle of Rx offload packets to an offload device.
*/
static inline void deliver_partial_bundle(struct t3cdev *tdev,
struct sge_rspq *q,
struct sk_buff *skbs[], int n)
{
if (n) {
q->offload_bundles++;
tdev->recv(tdev, skbs, n);
}
}
/**
* ofld_poll - NAPI handler for offload packets in interrupt mode
* @dev: the network device doing the polling
* @budget: polling budget
*
* The NAPI handler for offload packets when a response queue is serviced
* by the hard interrupt handler, i.e., when it's operating in non-polling
* mode. Creates small packet batches and sends them through the offload
* receive handler. Batches need to be of modest size as we do prefetches
* on the packets in each.
*/
static int ofld_poll(struct napi_struct *napi, int budget)
{
struct sge_qset *qs = container_of(napi, struct sge_qset, napi);
struct sge_rspq *q = &qs->rspq;
struct adapter *adapter = qs->adap;
int work_done = 0;
while (work_done < budget) {
struct sk_buff *skb, *tmp, *skbs[RX_BUNDLE_SIZE];
struct sk_buff_head queue;
int ngathered;
spin_lock_irq(&q->lock);
__skb_queue_head_init(&queue);
skb_queue_splice_init(&q->rx_queue, &queue);
if (skb_queue_empty(&queue)) {
napi_complete(napi);
spin_unlock_irq(&q->lock);
return work_done;
}
spin_unlock_irq(&q->lock);
ngathered = 0;
skb_queue_walk_safe(&queue, skb, tmp) {
if (work_done >= budget)
break;
work_done++;
__skb_unlink(skb, &queue);
prefetch(skb->data);
skbs[ngathered] = skb;
if (++ngathered == RX_BUNDLE_SIZE) {
q->offload_bundles++;
adapter->tdev.recv(&adapter->tdev, skbs,
ngathered);
ngathered = 0;
}
}
if (!skb_queue_empty(&queue)) {
/* splice remaining packets back onto Rx queue */
spin_lock_irq(&q->lock);
skb_queue_splice(&queue, &q->rx_queue);
spin_unlock_irq(&q->lock);
}
deliver_partial_bundle(&adapter->tdev, q, skbs, ngathered);
}
return work_done;
}
/**
* rx_offload - process a received offload packet
* @tdev: the offload device receiving the packet
* @rq: the response queue that received the packet
* @skb: the packet
* @rx_gather: a gather list of packets if we are building a bundle
* @gather_idx: index of the next available slot in the bundle
*
* Process an ingress offload pakcet and add it to the offload ingress
* queue. Returns the index of the next available slot in the bundle.
*/
static inline int rx_offload(struct t3cdev *tdev, struct sge_rspq *rq,
struct sk_buff *skb, struct sk_buff *rx_gather[],
unsigned int gather_idx)
{
skb_reset_mac_header(skb);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
if (rq->polling) {
rx_gather[gather_idx++] = skb;
if (gather_idx == RX_BUNDLE_SIZE) {
tdev->recv(tdev, rx_gather, RX_BUNDLE_SIZE);
gather_idx = 0;
rq->offload_bundles++;
}
} else
offload_enqueue(rq, skb);
return gather_idx;
}
/**
* restart_tx - check whether to restart suspended Tx queues
* @qs: the queue set to resume
*
* Restarts suspended Tx queues of an SGE queue set if they have enough
* free resources to resume operation.
*/
static void restart_tx(struct sge_qset *qs)
{
if (test_bit(TXQ_ETH, &qs->txq_stopped) &&
should_restart_tx(&qs->txq[TXQ_ETH]) &&
test_and_clear_bit(TXQ_ETH, &qs->txq_stopped)) {
qs->txq[TXQ_ETH].restarts++;
if (netif_running(qs->netdev))
netif_tx_wake_queue(qs->tx_q);
}
if (test_bit(TXQ_OFLD, &qs->txq_stopped) &&
should_restart_tx(&qs->txq[TXQ_OFLD]) &&
test_and_clear_bit(TXQ_OFLD, &qs->txq_stopped)) {
qs->txq[TXQ_OFLD].restarts++;
tasklet_schedule(&qs->txq[TXQ_OFLD].qresume_tsk);
}
if (test_bit(TXQ_CTRL, &qs->txq_stopped) &&
should_restart_tx(&qs->txq[TXQ_CTRL]) &&
test_and_clear_bit(TXQ_CTRL, &qs->txq_stopped)) {
qs->txq[TXQ_CTRL].restarts++;
tasklet_schedule(&qs->txq[TXQ_CTRL].qresume_tsk);
}
}
/**
* cxgb3_arp_process - process an ARP request probing a private IP address
* @adapter: the adapter
* @skb: the skbuff containing the ARP request
*
* Check if the ARP request is probing the private IP address
* dedicated to iSCSI, generate an ARP reply if so.
*/
static void cxgb3_arp_process(struct port_info *pi, struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct arphdr *arp;
unsigned char *arp_ptr;
unsigned char *sha;
__be32 sip, tip;
if (!dev)
return;
skb_reset_network_header(skb);
arp = arp_hdr(skb);
if (arp->ar_op != htons(ARPOP_REQUEST))
return;
arp_ptr = (unsigned char *)(arp + 1);
sha = arp_ptr;
arp_ptr += dev->addr_len;
memcpy(&sip, arp_ptr, sizeof(sip));
arp_ptr += sizeof(sip);
arp_ptr += dev->addr_len;
memcpy(&tip, arp_ptr, sizeof(tip));
if (tip != pi->iscsi_ipv4addr)
return;
arp_send(ARPOP_REPLY, ETH_P_ARP, sip, dev, tip, sha,
pi->iscsic.mac_addr, sha);
}
static inline int is_arp(struct sk_buff *skb)
{
return skb->protocol == htons(ETH_P_ARP);
}
static void cxgb3_process_iscsi_prov_pack(struct port_info *pi,
struct sk_buff *skb)
{
if (is_arp(skb)) {
cxgb3_arp_process(pi, skb);
return;
}
if (pi->iscsic.recv)
pi->iscsic.recv(pi, skb);
}
/**
* rx_eth - process an ingress ethernet packet
* @adap: the adapter
* @rq: the response queue that received the packet
* @skb: the packet
* @pad: amount of padding at the start of the buffer
*
* Process an ingress ethernet pakcet and deliver it to the stack.
* The padding is 2 if the packet was delivered in an Rx buffer and 0
* if it was immediate data in a response.
*/
static void rx_eth(struct adapter *adap, struct sge_rspq *rq,
struct sk_buff *skb, int pad, int lro)
{
struct cpl_rx_pkt *p = (struct cpl_rx_pkt *)(skb->data + pad);
struct sge_qset *qs = rspq_to_qset(rq);
struct port_info *pi;
skb_pull(skb, sizeof(*p) + pad);
skb->protocol = eth_type_trans(skb, adap->port[p->iff]);
pi = netdev_priv(skb->dev);
if ((skb->dev->features & NETIF_F_RXCSUM) && p->csum_valid &&
p->csum == htons(0xffff) && !p->fragment) {
qs->port_stats[SGE_PSTAT_RX_CSUM_GOOD]++;
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else
skb_checksum_none_assert(skb);
skb_record_rx_queue(skb, qs - &adap->sge.qs[pi->first_qset]);
if (p->vlan_valid) {
qs->port_stats[SGE_PSTAT_VLANEX]++;
__vlan_hwaccel_put_tag(skb, ntohs(p->vlan));
}
if (rq->polling) {
if (lro)
napi_gro_receive(&qs->napi, skb);
else {
if (unlikely(pi->iscsic.flags))
cxgb3_process_iscsi_prov_pack(pi, skb);
netif_receive_skb(skb);
}
} else
netif_rx(skb);
}
static inline int is_eth_tcp(u32 rss)
{
return G_HASHTYPE(ntohl(rss)) == RSS_HASH_4_TUPLE;
}
/**
* lro_add_page - add a page chunk to an LRO session
* @adap: the adapter
* @qs: the associated queue set
* @fl: the free list containing the page chunk to add
* @len: packet length
* @complete: Indicates the last fragment of a frame
*
* Add a received packet contained in a page chunk to an existing LRO
* session.
*/
static void lro_add_page(struct adapter *adap, struct sge_qset *qs,
struct sge_fl *fl, int len, int complete)
{
struct rx_sw_desc *sd = &fl->sdesc[fl->cidx];
struct port_info *pi = netdev_priv(qs->netdev);
struct sk_buff *skb = NULL;
struct cpl_rx_pkt *cpl;
struct skb_frag_struct *rx_frag;
int nr_frags;
int offset = 0;
if (!qs->nomem) {
skb = napi_get_frags(&qs->napi);
qs->nomem = !skb;
}
fl->credits--;
pci_dma_sync_single_for_cpu(adap->pdev,
dma_unmap_addr(sd, dma_addr),
fl->buf_size - SGE_PG_RSVD,
PCI_DMA_FROMDEVICE);
(*sd->pg_chunk.p_cnt)--;
if (!*sd->pg_chunk.p_cnt && sd->pg_chunk.page != fl->pg_chunk.page)
pci_unmap_page(adap->pdev,
sd->pg_chunk.mapping,
fl->alloc_size,
PCI_DMA_FROMDEVICE);
if (!skb) {
put_page(sd->pg_chunk.page);
if (complete)
qs->nomem = 0;
return;
}
rx_frag = skb_shinfo(skb)->frags;
nr_frags = skb_shinfo(skb)->nr_frags;
if (!nr_frags) {
offset = 2 + sizeof(struct cpl_rx_pkt);
cpl = qs->lro_va = sd->pg_chunk.va + 2;
if ((qs->netdev->features & NETIF_F_RXCSUM) &&
cpl->csum_valid && cpl->csum == htons(0xffff)) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
qs->port_stats[SGE_PSTAT_RX_CSUM_GOOD]++;
} else
skb->ip_summed = CHECKSUM_NONE;
} else
cpl = qs->lro_va;
len -= offset;
rx_frag += nr_frags;
__skb_frag_set_page(rx_frag, sd->pg_chunk.page);
rx_frag->page_offset = sd->pg_chunk.offset + offset;
skb_frag_size_set(rx_frag, len);
skb->len += len;
skb->data_len += len;
skb->truesize += len;
skb_shinfo(skb)->nr_frags++;
if (!complete)
return;
skb_record_rx_queue(skb, qs - &adap->sge.qs[pi->first_qset]);
if (cpl->vlan_valid)
__vlan_hwaccel_put_tag(skb, ntohs(cpl->vlan));
napi_gro_frags(&qs->napi);
}
/**
* handle_rsp_cntrl_info - handles control information in a response
* @qs: the queue set corresponding to the response
* @flags: the response control flags
*
* Handles the control information of an SGE response, such as GTS
* indications and completion credits for the queue set's Tx queues.
* HW coalesces credits, we don't do any extra SW coalescing.
*/
static inline void handle_rsp_cntrl_info(struct sge_qset *qs, u32 flags)
{
unsigned int credits;
#if USE_GTS
if (flags & F_RSPD_TXQ0_GTS)
clear_bit(TXQ_RUNNING, &qs->txq[TXQ_ETH].flags);
#endif
credits = G_RSPD_TXQ0_CR(flags);
if (credits)
qs->txq[TXQ_ETH].processed += credits;
credits = G_RSPD_TXQ2_CR(flags);
if (credits)
qs->txq[TXQ_CTRL].processed += credits;
# if USE_GTS
if (flags & F_RSPD_TXQ1_GTS)
clear_bit(TXQ_RUNNING, &qs->txq[TXQ_OFLD].flags);
# endif
credits = G_RSPD_TXQ1_CR(flags);
if (credits)
qs->txq[TXQ_OFLD].processed += credits;
}
/**
* check_ring_db - check if we need to ring any doorbells
* @adapter: the adapter
* @qs: the queue set whose Tx queues are to be examined
* @sleeping: indicates which Tx queue sent GTS
*
* Checks if some of a queue set's Tx queues need to ring their doorbells
* to resume transmission after idling while they still have unprocessed
* descriptors.
*/
static void check_ring_db(struct adapter *adap, struct sge_qset *qs,
unsigned int sleeping)
{
if (sleeping & F_RSPD_TXQ0_GTS) {
struct sge_txq *txq = &qs->txq[TXQ_ETH];
if (txq->cleaned + txq->in_use != txq->processed &&
!test_and_set_bit(TXQ_LAST_PKT_DB, &txq->flags)) {
set_bit(TXQ_RUNNING, &txq->flags);
t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX |
V_EGRCNTX(txq->cntxt_id));
}
}
if (sleeping & F_RSPD_TXQ1_GTS) {
struct sge_txq *txq = &qs->txq[TXQ_OFLD];
if (txq->cleaned + txq->in_use != txq->processed &&
!test_and_set_bit(TXQ_LAST_PKT_DB, &txq->flags)) {
set_bit(TXQ_RUNNING, &txq->flags);
t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX |
V_EGRCNTX(txq->cntxt_id));
}
}
}
/**
* is_new_response - check if a response is newly written
* @r: the response descriptor
* @q: the response queue
*
* Returns true if a response descriptor contains a yet unprocessed
* response.
*/
static inline int is_new_response(const struct rsp_desc *r,
const struct sge_rspq *q)
{
return (r->intr_gen & F_RSPD_GEN2) == q->gen;
}
static inline void clear_rspq_bufstate(struct sge_rspq * const q)
{
q->pg_skb = NULL;
q->rx_recycle_buf = 0;
}
#define RSPD_GTS_MASK (F_RSPD_TXQ0_GTS | F_RSPD_TXQ1_GTS)
#define RSPD_CTRL_MASK (RSPD_GTS_MASK | \
V_RSPD_TXQ0_CR(M_RSPD_TXQ0_CR) | \
V_RSPD_TXQ1_CR(M_RSPD_TXQ1_CR) | \
V_RSPD_TXQ2_CR(M_RSPD_TXQ2_CR))
/* How long to delay the next interrupt in case of memory shortage, in 0.1us. */
#define NOMEM_INTR_DELAY 2500
/**
* process_responses - process responses from an SGE response queue
* @adap: the adapter
* @qs: the queue set to which the response queue belongs
* @budget: how many responses can be processed in this round
*
* Process responses from an SGE response queue up to the supplied budget.
* Responses include received packets as well as credits and other events
* for the queues that belong to the response queue's queue set.
* A negative budget is effectively unlimited.
*
* Additionally choose the interrupt holdoff time for the next interrupt
* on this queue. If the system is under memory shortage use a fairly
* long delay to help recovery.
*/
static int process_responses(struct adapter *adap, struct sge_qset *qs,
int budget)
{
struct sge_rspq *q = &qs->rspq;
struct rsp_desc *r = &q->desc[q->cidx];
int budget_left = budget;
unsigned int sleeping = 0;
struct sk_buff *offload_skbs[RX_BUNDLE_SIZE];
int ngathered = 0;
q->next_holdoff = q->holdoff_tmr;
while (likely(budget_left && is_new_response(r, q))) {
int packet_complete, eth, ethpad = 2;
int lro = !!(qs->netdev->features & NETIF_F_GRO);
struct sk_buff *skb = NULL;
u32 len, flags;
__be32 rss_hi, rss_lo;
rmb();
eth = r->rss_hdr.opcode == CPL_RX_PKT;
rss_hi = *(const __be32 *)r;
rss_lo = r->rss_hdr.rss_hash_val;
flags = ntohl(r->flags);
if (unlikely(flags & F_RSPD_ASYNC_NOTIF)) {
skb = alloc_skb(AN_PKT_SIZE, GFP_ATOMIC);
if (!skb)
goto no_mem;
memcpy(__skb_put(skb, AN_PKT_SIZE), r, AN_PKT_SIZE);
skb->data[0] = CPL_ASYNC_NOTIF;
rss_hi = htonl(CPL_ASYNC_NOTIF << 24);
q->async_notif++;
} else if (flags & F_RSPD_IMM_DATA_VALID) {
skb = get_imm_packet(r);
if (unlikely(!skb)) {
no_mem:
q->next_holdoff = NOMEM_INTR_DELAY;
q->nomem++;
/* consume one credit since we tried */
budget_left--;
break;
}
q->imm_data++;
ethpad = 0;
} else if ((len = ntohl(r->len_cq)) != 0) {
struct sge_fl *fl;
lro &= eth && is_eth_tcp(rss_hi);
fl = (len & F_RSPD_FLQ) ? &qs->fl[1] : &qs->fl[0];
if (fl->use_pages) {
void *addr = fl->sdesc[fl->cidx].pg_chunk.va;
prefetch(addr);
#if L1_CACHE_BYTES < 128
prefetch(addr + L1_CACHE_BYTES);
#endif
__refill_fl(adap, fl);
if (lro > 0) {
lro_add_page(adap, qs, fl,
G_RSPD_LEN(len),
flags & F_RSPD_EOP);
goto next_fl;
}
skb = get_packet_pg(adap, fl, q,
G_RSPD_LEN(len),
eth ?
SGE_RX_DROP_THRES : 0);
q->pg_skb = skb;
} else
skb = get_packet(adap, fl, G_RSPD_LEN(len),
eth ? SGE_RX_DROP_THRES : 0);
if (unlikely(!skb)) {
if (!eth)
goto no_mem;
q->rx_drops++;
} else if (unlikely(r->rss_hdr.opcode == CPL_TRACE_PKT))
__skb_pull(skb, 2);
next_fl:
if (++fl->cidx == fl->size)
fl->cidx = 0;
} else
q->pure_rsps++;
if (flags & RSPD_CTRL_MASK) {
sleeping |= flags & RSPD_GTS_MASK;
handle_rsp_cntrl_info(qs, flags);
}
r++;
if (unlikely(++q->cidx == q->size)) {
q->cidx = 0;
q->gen ^= 1;
r = q->desc;
}
prefetch(r);
if (++q->credits >= (q->size / 4)) {
refill_rspq(adap, q, q->credits);
q->credits = 0;
}
packet_complete = flags &
(F_RSPD_EOP | F_RSPD_IMM_DATA_VALID |
F_RSPD_ASYNC_NOTIF);
if (skb != NULL && packet_complete) {
if (eth)
rx_eth(adap, q, skb, ethpad, lro);
else {
q->offload_pkts++;
/* Preserve the RSS info in csum & priority */
skb->csum = rss_hi;
skb->priority = rss_lo;
ngathered = rx_offload(&adap->tdev, q, skb,
offload_skbs,
ngathered);
}
if (flags & F_RSPD_EOP)
clear_rspq_bufstate(q);
}
--budget_left;
}
deliver_partial_bundle(&adap->tdev, q, offload_skbs, ngathered);
if (sleeping)
check_ring_db(adap, qs, sleeping);
smp_mb(); /* commit Tx queue .processed updates */
if (unlikely(qs->txq_stopped != 0))
restart_tx(qs);
budget -= budget_left;
return budget;
}
static inline int is_pure_response(const struct rsp_desc *r)
{
__be32 n = r->flags & htonl(F_RSPD_ASYNC_NOTIF | F_RSPD_IMM_DATA_VALID);
return (n | r->len_cq) == 0;
}
/**
* napi_rx_handler - the NAPI handler for Rx processing
* @napi: the napi instance
* @budget: how many packets we can process in this round
*
* Handler for new data events when using NAPI.
*/
static int napi_rx_handler(struct napi_struct *napi, int budget)
{
struct sge_qset *qs = container_of(napi, struct sge_qset, napi);
struct adapter *adap = qs->adap;
int work_done = process_responses(adap, qs, budget);
if (likely(work_done < budget)) {
napi_complete(napi);
/*
* Because we don't atomically flush the following
* write it is possible that in very rare cases it can
* reach the device in a way that races with a new
* response being written plus an error interrupt
* causing the NAPI interrupt handler below to return
* unhandled status to the OS. To protect against
* this would require flushing the write and doing
* both the write and the flush with interrupts off.
* Way too expensive and unjustifiable given the
* rarity of the race.
*
* The race cannot happen at all with MSI-X.
*/
t3_write_reg(adap, A_SG_GTS, V_RSPQ(qs->rspq.cntxt_id) |
V_NEWTIMER(qs->rspq.next_holdoff) |
V_NEWINDEX(qs->rspq.cidx));
}
return work_done;
}
/*
* Returns true if the device is already scheduled for polling.
*/
static inline int napi_is_scheduled(struct napi_struct *napi)
{
return test_bit(NAPI_STATE_SCHED, &napi->state);
}
/**
* process_pure_responses - process pure responses from a response queue
* @adap: the adapter
* @qs: the queue set owning the response queue
* @r: the first pure response to process
*
* A simpler version of process_responses() that handles only pure (i.e.,
* non data-carrying) responses. Such respones are too light-weight to
* justify calling a softirq under NAPI, so we handle them specially in
* the interrupt handler. The function is called with a pointer to a
* response, which the caller must ensure is a valid pure response.
*
* Returns 1 if it encounters a valid data-carrying response, 0 otherwise.
*/
static int process_pure_responses(struct adapter *adap, struct sge_qset *qs,
struct rsp_desc *r)
{
struct sge_rspq *q = &qs->rspq;
unsigned int sleeping = 0;
do {
u32 flags = ntohl(r->flags);
r++;
if (unlikely(++q->cidx == q->size)) {
q->cidx = 0;
q->gen ^= 1;
r = q->desc;
}
prefetch(r);
if (flags & RSPD_CTRL_MASK) {
sleeping |= flags & RSPD_GTS_MASK;
handle_rsp_cntrl_info(qs, flags);
}
q->pure_rsps++;
if (++q->credits >= (q->size / 4)) {
refill_rspq(adap, q, q->credits);
q->credits = 0;
}
if (!is_new_response(r, q))
break;
rmb();
} while (is_pure_response(r));
if (sleeping)
check_ring_db(adap, qs, sleeping);
smp_mb(); /* commit Tx queue .processed updates */
if (unlikely(qs->txq_stopped != 0))
restart_tx(qs);
return is_new_response(r, q);
}
/**
* handle_responses - decide what to do with new responses in NAPI mode
* @adap: the adapter
* @q: the response queue
*
* This is used by the NAPI interrupt handlers to decide what to do with
* new SGE responses. If there are no new responses it returns -1. If
* there are new responses and they are pure (i.e., non-data carrying)
* it handles them straight in hard interrupt context as they are very
* cheap and don't deliver any packets. Finally, if there are any data
* signaling responses it schedules the NAPI handler. Returns 1 if it
* schedules NAPI, 0 if all new responses were pure.
*
* The caller must ascertain NAPI is not already running.
*/
static inline int handle_responses(struct adapter *adap, struct sge_rspq *q)
{
struct sge_qset *qs = rspq_to_qset(q);
struct rsp_desc *r = &q->desc[q->cidx];
if (!is_new_response(r, q))
return -1;
rmb();
if (is_pure_response(r) && process_pure_responses(adap, qs, r) == 0) {
t3_write_reg(adap, A_SG_GTS, V_RSPQ(q->cntxt_id) |
V_NEWTIMER(q->holdoff_tmr) | V_NEWINDEX(q->cidx));
return 0;
}
napi_schedule(&qs->napi);
return 1;
}
/*
* The MSI-X interrupt handler for an SGE response queue for the non-NAPI case
* (i.e., response queue serviced in hard interrupt).
*/
static irqreturn_t t3_sge_intr_msix(int irq, void *cookie)
{
struct sge_qset *qs = cookie;
struct adapter *adap = qs->adap;
struct sge_rspq *q = &qs->rspq;
spin_lock(&q->lock);
if (process_responses(adap, qs, -1) == 0)
q->unhandled_irqs++;
t3_write_reg(adap, A_SG_GTS, V_RSPQ(q->cntxt_id) |
V_NEWTIMER(q->next_holdoff) | V_NEWINDEX(q->cidx));
spin_unlock(&q->lock);
return IRQ_HANDLED;
}
/*
* The MSI-X interrupt handler for an SGE response queue for the NAPI case
* (i.e., response queue serviced by NAPI polling).
*/
static irqreturn_t t3_sge_intr_msix_napi(int irq, void *cookie)
{
struct sge_qset *qs = cookie;
struct sge_rspq *q = &qs->rspq;
spin_lock(&q->lock);
if (handle_responses(qs->adap, q) < 0)
q->unhandled_irqs++;
spin_unlock(&q->lock);
return IRQ_HANDLED;
}
/*
* The non-NAPI MSI interrupt handler. This needs to handle data events from
* SGE response queues as well as error and other async events as they all use
* the same MSI vector. We use one SGE response queue per port in this mode
* and protect all response queues with queue 0's lock.
*/
static irqreturn_t t3_intr_msi(int irq, void *cookie)
{
int new_packets = 0;
struct adapter *adap = cookie;
struct sge_rspq *q = &adap->sge.qs[0].rspq;
spin_lock(&q->lock);
if (process_responses(adap, &adap->sge.qs[0], -1)) {
t3_write_reg(adap, A_SG_GTS, V_RSPQ(q->cntxt_id) |
V_NEWTIMER(q->next_holdoff) | V_NEWINDEX(q->cidx));
new_packets = 1;
}
if (adap->params.nports == 2 &&
process_responses(adap, &adap->sge.qs[1], -1)) {
struct sge_rspq *q1 = &adap->sge.qs[1].rspq;
t3_write_reg(adap, A_SG_GTS, V_RSPQ(q1->cntxt_id) |
V_NEWTIMER(q1->next_holdoff) |
V_NEWINDEX(q1->cidx));
new_packets = 1;
}
if (!new_packets && t3_slow_intr_handler(adap) == 0)
q->unhandled_irqs++;
spin_unlock(&q->lock);
return IRQ_HANDLED;
}
static int rspq_check_napi(struct sge_qset *qs)
{
struct sge_rspq *q = &qs->rspq;
if (!napi_is_scheduled(&qs->napi) &&
is_new_response(&q->desc[q->cidx], q)) {
napi_schedule(&qs->napi);
return 1;
}
return 0;
}
/*
* The MSI interrupt handler for the NAPI case (i.e., response queues serviced
* by NAPI polling). Handles data events from SGE response queues as well as
* error and other async events as they all use the same MSI vector. We use
* one SGE response queue per port in this mode and protect all response
* queues with queue 0's lock.
*/
static irqreturn_t t3_intr_msi_napi(int irq, void *cookie)
{
int new_packets;
struct adapter *adap = cookie;
struct sge_rspq *q = &adap->sge.qs[0].rspq;
spin_lock(&q->lock);
new_packets = rspq_check_napi(&adap->sge.qs[0]);
if (adap->params.nports == 2)
new_packets += rspq_check_napi(&adap->sge.qs[1]);
if (!new_packets && t3_slow_intr_handler(adap) == 0)
q->unhandled_irqs++;
spin_unlock(&q->lock);
return IRQ_HANDLED;
}
/*
* A helper function that processes responses and issues GTS.
*/
static inline int process_responses_gts(struct adapter *adap,
struct sge_rspq *rq)
{
int work;
work = process_responses(adap, rspq_to_qset(rq), -1);
t3_write_reg(adap, A_SG_GTS, V_RSPQ(rq->cntxt_id) |
V_NEWTIMER(rq->next_holdoff) | V_NEWINDEX(rq->cidx));
return work;
}
/*
* The legacy INTx interrupt handler. This needs to handle data events from
* SGE response queues as well as error and other async events as they all use
* the same interrupt pin. We use one SGE response queue per port in this mode
* and protect all response queues with queue 0's lock.
*/
static irqreturn_t t3_intr(int irq, void *cookie)
{
int work_done, w0, w1;
struct adapter *adap = cookie;
struct sge_rspq *q0 = &adap->sge.qs[0].rspq;
struct sge_rspq *q1 = &adap->sge.qs[1].rspq;
spin_lock(&q0->lock);
w0 = is_new_response(&q0->desc[q0->cidx], q0);
w1 = adap->params.nports == 2 &&
is_new_response(&q1->desc[q1->cidx], q1);
if (likely(w0 | w1)) {
t3_write_reg(adap, A_PL_CLI, 0);
t3_read_reg(adap, A_PL_CLI); /* flush */
if (likely(w0))
process_responses_gts(adap, q0);
if (w1)
process_responses_gts(adap, q1);
work_done = w0 | w1;
} else
work_done = t3_slow_intr_handler(adap);
spin_unlock(&q0->lock);
return IRQ_RETVAL(work_done != 0);
}
/*
* Interrupt handler for legacy INTx interrupts for T3B-based cards.
* Handles data events from SGE response queues as well as error and other
* async events as they all use the same interrupt pin. We use one SGE
* response queue per port in this mode and protect all response queues with
* queue 0's lock.
*/
static irqreturn_t t3b_intr(int irq, void *cookie)
{
u32 map;
struct adapter *adap = cookie;
struct sge_rspq *q0 = &adap->sge.qs[0].rspq;
t3_write_reg(adap, A_PL_CLI, 0);
map = t3_read_reg(adap, A_SG_DATA_INTR);
if (unlikely(!map)) /* shared interrupt, most likely */
return IRQ_NONE;
spin_lock(&q0->lock);
if (unlikely(map & F_ERRINTR))
t3_slow_intr_handler(adap);
if (likely(map & 1))
process_responses_gts(adap, q0);
if (map & 2)
process_responses_gts(adap, &adap->sge.qs[1].rspq);
spin_unlock(&q0->lock);
return IRQ_HANDLED;
}
/*
* NAPI interrupt handler for legacy INTx interrupts for T3B-based cards.
* Handles data events from SGE response queues as well as error and other
* async events as they all use the same interrupt pin. We use one SGE
* response queue per port in this mode and protect all response queues with
* queue 0's lock.
*/
static irqreturn_t t3b_intr_napi(int irq, void *cookie)
{
u32 map;
struct adapter *adap = cookie;
struct sge_qset *qs0 = &adap->sge.qs[0];
struct sge_rspq *q0 = &qs0->rspq;
t3_write_reg(adap, A_PL_CLI, 0);
map = t3_read_reg(adap, A_SG_DATA_INTR);
if (unlikely(!map)) /* shared interrupt, most likely */
return IRQ_NONE;
spin_lock(&q0->lock);
if (unlikely(map & F_ERRINTR))
t3_slow_intr_handler(adap);
if (likely(map & 1))
napi_schedule(&qs0->napi);
if (map & 2)
napi_schedule(&adap->sge.qs[1].napi);
spin_unlock(&q0->lock);
return IRQ_HANDLED;
}
/**
* t3_intr_handler - select the top-level interrupt handler
* @adap: the adapter
* @polling: whether using NAPI to service response queues
*
* Selects the top-level interrupt handler based on the type of interrupts
* (MSI-X, MSI, or legacy) and whether NAPI will be used to service the
* response queues.
*/
irq_handler_t t3_intr_handler(struct adapter *adap, int polling)
{
if (adap->flags & USING_MSIX)
return polling ? t3_sge_intr_msix_napi : t3_sge_intr_msix;
if (adap->flags & USING_MSI)
return polling ? t3_intr_msi_napi : t3_intr_msi;
if (adap->params.rev > 0)
return polling ? t3b_intr_napi : t3b_intr;
return t3_intr;
}
#define SGE_PARERR (F_CPPARITYERROR | F_OCPARITYERROR | F_RCPARITYERROR | \
F_IRPARITYERROR | V_ITPARITYERROR(M_ITPARITYERROR) | \
V_FLPARITYERROR(M_FLPARITYERROR) | F_LODRBPARITYERROR | \
F_HIDRBPARITYERROR | F_LORCQPARITYERROR | \
F_HIRCQPARITYERROR)
#define SGE_FRAMINGERR (F_UC_REQ_FRAMINGERROR | F_R_REQ_FRAMINGERROR)
#define SGE_FATALERR (SGE_PARERR | SGE_FRAMINGERR | F_RSPQCREDITOVERFOW | \
F_RSPQDISABLED)
/**
* t3_sge_err_intr_handler - SGE async event interrupt handler
* @adapter: the adapter
*
* Interrupt handler for SGE asynchronous (non-data) events.
*/
void t3_sge_err_intr_handler(struct adapter *adapter)
{
unsigned int v, status = t3_read_reg(adapter, A_SG_INT_CAUSE) &
~F_FLEMPTY;
if (status & SGE_PARERR)
CH_ALERT(adapter, "SGE parity error (0x%x)\n",
status & SGE_PARERR);
if (status & SGE_FRAMINGERR)
CH_ALERT(adapter, "SGE framing error (0x%x)\n",
status & SGE_FRAMINGERR);
if (status & F_RSPQCREDITOVERFOW)
CH_ALERT(adapter, "SGE response queue credit overflow\n");
if (status & F_RSPQDISABLED) {
v = t3_read_reg(adapter, A_SG_RSPQ_FL_STATUS);
CH_ALERT(adapter,
"packet delivered to disabled response queue "
"(0x%x)\n", (v >> S_RSPQ0DISABLED) & 0xff);
}
if (status & (F_HIPIODRBDROPERR | F_LOPIODRBDROPERR))
queue_work(cxgb3_wq, &adapter->db_drop_task);
if (status & (F_HIPRIORITYDBFULL | F_LOPRIORITYDBFULL))
queue_work(cxgb3_wq, &adapter->db_full_task);
if (status & (F_HIPRIORITYDBEMPTY | F_LOPRIORITYDBEMPTY))
queue_work(cxgb3_wq, &adapter->db_empty_task);
t3_write_reg(adapter, A_SG_INT_CAUSE, status);
if (status & SGE_FATALERR)
t3_fatal_err(adapter);
}
/**
* sge_timer_tx - perform periodic maintenance of an SGE qset
* @data: the SGE queue set to maintain
*
* Runs periodically from a timer to perform maintenance of an SGE queue
* set. It performs two tasks:
*
* Cleans up any completed Tx descriptors that may still be pending.
* Normal descriptor cleanup happens when new packets are added to a Tx
* queue so this timer is relatively infrequent and does any cleanup only
* if the Tx queue has not seen any new packets in a while. We make a
* best effort attempt to reclaim descriptors, in that we don't wait
* around if we cannot get a queue's lock (which most likely is because
* someone else is queueing new packets and so will also handle the clean
* up). Since control queues use immediate data exclusively we don't
* bother cleaning them up here.
*
*/
static void sge_timer_tx(unsigned long data)
{
struct sge_qset *qs = (struct sge_qset *)data;
struct port_info *pi = netdev_priv(qs->netdev);
struct adapter *adap = pi->adapter;
unsigned int tbd[SGE_TXQ_PER_SET] = {0, 0};
unsigned long next_period;
if (__netif_tx_trylock(qs->tx_q)) {
tbd[TXQ_ETH] = reclaim_completed_tx(adap, &qs->txq[TXQ_ETH],
TX_RECLAIM_TIMER_CHUNK);
__netif_tx_unlock(qs->tx_q);
}
if (spin_trylock(&qs->txq[TXQ_OFLD].lock)) {
tbd[TXQ_OFLD] = reclaim_completed_tx(adap, &qs->txq[TXQ_OFLD],
TX_RECLAIM_TIMER_CHUNK);
spin_unlock(&qs->txq[TXQ_OFLD].lock);
}
next_period = TX_RECLAIM_PERIOD >>
(max(tbd[TXQ_ETH], tbd[TXQ_OFLD]) /
TX_RECLAIM_TIMER_CHUNK);
mod_timer(&qs->tx_reclaim_timer, jiffies + next_period);
}
/*
* sge_timer_rx - perform periodic maintenance of an SGE qset
* @data: the SGE queue set to maintain
*
* a) Replenishes Rx queues that have run out due to memory shortage.
* Normally new Rx buffers are added when existing ones are consumed but
* when out of memory a queue can become empty. We try to add only a few
* buffers here, the queue will be replenished fully as these new buffers
* are used up if memory shortage has subsided.
*
* b) Return coalesced response queue credits in case a response queue is
* starved.
*
*/
static void sge_timer_rx(unsigned long data)
{
spinlock_t *lock;
struct sge_qset *qs = (struct sge_qset *)data;
struct port_info *pi = netdev_priv(qs->netdev);
struct adapter *adap = pi->adapter;
u32 status;
lock = adap->params.rev > 0 ?
&qs->rspq.lock : &adap->sge.qs[0].rspq.lock;
if (!spin_trylock_irq(lock))
goto out;
if (napi_is_scheduled(&qs->napi))
goto unlock;
if (adap->params.rev < 4) {
status = t3_read_reg(adap, A_SG_RSPQ_FL_STATUS);
if (status & (1 << qs->rspq.cntxt_id)) {
qs->rspq.starved++;
if (qs->rspq.credits) {
qs->rspq.credits--;
refill_rspq(adap, &qs->rspq, 1);
qs->rspq.restarted++;
t3_write_reg(adap, A_SG_RSPQ_FL_STATUS,
1 << qs->rspq.cntxt_id);
}
}
}
if (qs->fl[0].credits < qs->fl[0].size)
__refill_fl(adap, &qs->fl[0]);
if (qs->fl[1].credits < qs->fl[1].size)
__refill_fl(adap, &qs->fl[1]);
unlock:
spin_unlock_irq(lock);
out:
mod_timer(&qs->rx_reclaim_timer, jiffies + RX_RECLAIM_PERIOD);
}
/**
* t3_update_qset_coalesce - update coalescing settings for a queue set
* @qs: the SGE queue set
* @p: new queue set parameters
*
* Update the coalescing settings for an SGE queue set. Nothing is done
* if the queue set is not initialized yet.
*/
void t3_update_qset_coalesce(struct sge_qset *qs, const struct qset_params *p)
{
qs->rspq.holdoff_tmr = max(p->coalesce_usecs * 10, 1U);/* can't be 0 */
qs->rspq.polling = p->polling;
qs->napi.poll = p->polling ? napi_rx_handler : ofld_poll;
}
/**
* t3_sge_alloc_qset - initialize an SGE queue set
* @adapter: the adapter
* @id: the queue set id
* @nports: how many Ethernet ports will be using this queue set
* @irq_vec_idx: the IRQ vector index for response queue interrupts
* @p: configuration parameters for this queue set
* @ntxq: number of Tx queues for the queue set
* @netdev: net device associated with this queue set
* @netdevq: net device TX queue associated with this queue set
*
* Allocate resources and initialize an SGE queue set. A queue set
* comprises a response queue, two Rx free-buffer queues, and up to 3
* Tx queues. The Tx queues are assigned roles in the order Ethernet
* queue, offload queue, and control queue.
*/
int t3_sge_alloc_qset(struct adapter *adapter, unsigned int id, int nports,
int irq_vec_idx, const struct qset_params *p,
int ntxq, struct net_device *dev,
struct netdev_queue *netdevq)
{
int i, avail, ret = -ENOMEM;
struct sge_qset *q = &adapter->sge.qs[id];
init_qset_cntxt(q, id);
setup_timer(&q->tx_reclaim_timer, sge_timer_tx, (unsigned long)q);
setup_timer(&q->rx_reclaim_timer, sge_timer_rx, (unsigned long)q);
q->fl[0].desc = alloc_ring(adapter->pdev, p->fl_size,
sizeof(struct rx_desc),
sizeof(struct rx_sw_desc),
&q->fl[0].phys_addr, &q->fl[0].sdesc);
if (!q->fl[0].desc)
goto err;
q->fl[1].desc = alloc_ring(adapter->pdev, p->jumbo_size,
sizeof(struct rx_desc),
sizeof(struct rx_sw_desc),
&q->fl[1].phys_addr, &q->fl[1].sdesc);
if (!q->fl[1].desc)
goto err;
q->rspq.desc = alloc_ring(adapter->pdev, p->rspq_size,
sizeof(struct rsp_desc), 0,
&q->rspq.phys_addr, NULL);
if (!q->rspq.desc)
goto err;
for (i = 0; i < ntxq; ++i) {
/*
* The control queue always uses immediate data so does not
* need to keep track of any sk_buffs.
*/
size_t sz = i == TXQ_CTRL ? 0 : sizeof(struct tx_sw_desc);
q->txq[i].desc = alloc_ring(adapter->pdev, p->txq_size[i],
sizeof(struct tx_desc), sz,
&q->txq[i].phys_addr,
&q->txq[i].sdesc);
if (!q->txq[i].desc)
goto err;
q->txq[i].gen = 1;
q->txq[i].size = p->txq_size[i];
spin_lock_init(&q->txq[i].lock);
skb_queue_head_init(&q->txq[i].sendq);
}
tasklet_init(&q->txq[TXQ_OFLD].qresume_tsk, restart_offloadq,
(unsigned long)q);
tasklet_init(&q->txq[TXQ_CTRL].qresume_tsk, restart_ctrlq,
(unsigned long)q);
q->fl[0].gen = q->fl[1].gen = 1;
q->fl[0].size = p->fl_size;
q->fl[1].size = p->jumbo_size;
q->rspq.gen = 1;
q->rspq.size = p->rspq_size;
spin_lock_init(&q->rspq.lock);
skb_queue_head_init(&q->rspq.rx_queue);
q->txq[TXQ_ETH].stop_thres = nports *
flits_to_desc(sgl_len(MAX_SKB_FRAGS + 1) + 3);
#if FL0_PG_CHUNK_SIZE > 0
q->fl[0].buf_size = FL0_PG_CHUNK_SIZE;
#else
q->fl[0].buf_size = SGE_RX_SM_BUF_SIZE + sizeof(struct cpl_rx_data);
#endif
#if FL1_PG_CHUNK_SIZE > 0
q->fl[1].buf_size = FL1_PG_CHUNK_SIZE;
#else
q->fl[1].buf_size = is_offload(adapter) ?
(16 * 1024) - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) :
MAX_FRAME_SIZE + 2 + sizeof(struct cpl_rx_pkt);
#endif
q->fl[0].use_pages = FL0_PG_CHUNK_SIZE > 0;
q->fl[1].use_pages = FL1_PG_CHUNK_SIZE > 0;
q->fl[0].order = FL0_PG_ORDER;
q->fl[1].order = FL1_PG_ORDER;
q->fl[0].alloc_size = FL0_PG_ALLOC_SIZE;
q->fl[1].alloc_size = FL1_PG_ALLOC_SIZE;
spin_lock_irq(&adapter->sge.reg_lock);
/* FL threshold comparison uses < */
ret = t3_sge_init_rspcntxt(adapter, q->rspq.cntxt_id, irq_vec_idx,
q->rspq.phys_addr, q->rspq.size,
q->fl[0].buf_size - SGE_PG_RSVD, 1, 0);
if (ret)
goto err_unlock;
for (i = 0; i < SGE_RXQ_PER_SET; ++i) {
ret = t3_sge_init_flcntxt(adapter, q->fl[i].cntxt_id, 0,
q->fl[i].phys_addr, q->fl[i].size,
q->fl[i].buf_size - SGE_PG_RSVD,
p->cong_thres, 1, 0);
if (ret)
goto err_unlock;
}
ret = t3_sge_init_ecntxt(adapter, q->txq[TXQ_ETH].cntxt_id, USE_GTS,
SGE_CNTXT_ETH, id, q->txq[TXQ_ETH].phys_addr,
q->txq[TXQ_ETH].size, q->txq[TXQ_ETH].token,
1, 0);
if (ret)
goto err_unlock;
if (ntxq > 1) {
ret = t3_sge_init_ecntxt(adapter, q->txq[TXQ_OFLD].cntxt_id,
USE_GTS, SGE_CNTXT_OFLD, id,
q->txq[TXQ_OFLD].phys_addr,
q->txq[TXQ_OFLD].size, 0, 1, 0);
if (ret)
goto err_unlock;
}
if (ntxq > 2) {
ret = t3_sge_init_ecntxt(adapter, q->txq[TXQ_CTRL].cntxt_id, 0,
SGE_CNTXT_CTRL, id,
q->txq[TXQ_CTRL].phys_addr,
q->txq[TXQ_CTRL].size,
q->txq[TXQ_CTRL].token, 1, 0);
if (ret)
goto err_unlock;
}
spin_unlock_irq(&adapter->sge.reg_lock);
q->adap = adapter;
q->netdev = dev;
q->tx_q = netdevq;
t3_update_qset_coalesce(q, p);
avail = refill_fl(adapter, &q->fl[0], q->fl[0].size,
GFP_KERNEL | __GFP_COMP);
if (!avail) {
CH_ALERT(adapter, "free list queue 0 initialization failed\n");
goto err;
}
if (avail < q->fl[0].size)
CH_WARN(adapter, "free list queue 0 enabled with %d credits\n",
avail);
avail = refill_fl(adapter, &q->fl[1], q->fl[1].size,
GFP_KERNEL | __GFP_COMP);
if (avail < q->fl[1].size)
CH_WARN(adapter, "free list queue 1 enabled with %d credits\n",
avail);
refill_rspq(adapter, &q->rspq, q->rspq.size - 1);
t3_write_reg(adapter, A_SG_GTS, V_RSPQ(q->rspq.cntxt_id) |
V_NEWTIMER(q->rspq.holdoff_tmr));
return 0;
err_unlock:
spin_unlock_irq(&adapter->sge.reg_lock);
err:
t3_free_qset(adapter, q);
return ret;
}
/**
* t3_start_sge_timers - start SGE timer call backs
* @adap: the adapter
*
* Starts each SGE queue set's timer call back
*/
void t3_start_sge_timers(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; ++i) {
struct sge_qset *q = &adap->sge.qs[i];
if (q->tx_reclaim_timer.function)
mod_timer(&q->tx_reclaim_timer, jiffies + TX_RECLAIM_PERIOD);
if (q->rx_reclaim_timer.function)
mod_timer(&q->rx_reclaim_timer, jiffies + RX_RECLAIM_PERIOD);
}
}
/**
* t3_stop_sge_timers - stop SGE timer call backs
* @adap: the adapter
*
* Stops each SGE queue set's timer call back
*/
void t3_stop_sge_timers(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; ++i) {
struct sge_qset *q = &adap->sge.qs[i];
if (q->tx_reclaim_timer.function)
del_timer_sync(&q->tx_reclaim_timer);
if (q->rx_reclaim_timer.function)
del_timer_sync(&q->rx_reclaim_timer);
}
}
/**
* t3_free_sge_resources - free SGE resources
* @adap: the adapter
*
* Frees resources used by the SGE queue sets.
*/
void t3_free_sge_resources(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; ++i)
t3_free_qset(adap, &adap->sge.qs[i]);
}
/**
* t3_sge_start - enable SGE
* @adap: the adapter
*
* Enables the SGE for DMAs. This is the last step in starting packet
* transfers.
*/
void t3_sge_start(struct adapter *adap)
{
t3_set_reg_field(adap, A_SG_CONTROL, F_GLOBALENABLE, F_GLOBALENABLE);
}
/**
* t3_sge_stop - disable SGE operation
* @adap: the adapter
*
* Disables the DMA engine. This can be called in emeregencies (e.g.,
* from error interrupts) or from normal process context. In the latter
* case it also disables any pending queue restart tasklets. Note that
* if it is called in interrupt context it cannot disable the restart
* tasklets as it cannot wait, however the tasklets will have no effect
* since the doorbells are disabled and the driver will call this again
* later from process context, at which time the tasklets will be stopped
* if they are still running.
*/
void t3_sge_stop(struct adapter *adap)
{
t3_set_reg_field(adap, A_SG_CONTROL, F_GLOBALENABLE, 0);
if (!in_interrupt()) {
int i;
for (i = 0; i < SGE_QSETS; ++i) {
struct sge_qset *qs = &adap->sge.qs[i];
tasklet_kill(&qs->txq[TXQ_OFLD].qresume_tsk);
tasklet_kill(&qs->txq[TXQ_CTRL].qresume_tsk);
}
}
}
/**
* t3_sge_init - initialize SGE
* @adap: the adapter
* @p: the SGE parameters
*
* Performs SGE initialization needed every time after a chip reset.
* We do not initialize any of the queue sets here, instead the driver
* top-level must request those individually. We also do not enable DMA
* here, that should be done after the queues have been set up.
*/
void t3_sge_init(struct adapter *adap, struct sge_params *p)
{
unsigned int ctrl, ups = ffs(pci_resource_len(adap->pdev, 2) >> 12);
ctrl = F_DROPPKT | V_PKTSHIFT(2) | F_FLMODE | F_AVOIDCQOVFL |
F_CQCRDTCTRL | F_CONGMODE | F_TNLFLMODE | F_FATLPERREN |
V_HOSTPAGESIZE(PAGE_SHIFT - 11) | F_BIGENDIANINGRESS |
V_USERSPACESIZE(ups ? ups - 1 : 0) | F_ISCSICOALESCING;
#if SGE_NUM_GENBITS == 1
ctrl |= F_EGRGENCTRL;
#endif
if (adap->params.rev > 0) {
if (!(adap->flags & (USING_MSIX | USING_MSI)))
ctrl |= F_ONEINTMULTQ | F_OPTONEINTMULTQ;
}
t3_write_reg(adap, A_SG_CONTROL, ctrl);
t3_write_reg(adap, A_SG_EGR_RCQ_DRB_THRSH, V_HIRCQDRBTHRSH(512) |
V_LORCQDRBTHRSH(512));
t3_write_reg(adap, A_SG_TIMER_TICK, core_ticks_per_usec(adap) / 10);
t3_write_reg(adap, A_SG_CMDQ_CREDIT_TH, V_THRESHOLD(32) |
V_TIMEOUT(200 * core_ticks_per_usec(adap)));
t3_write_reg(adap, A_SG_HI_DRB_HI_THRSH,
adap->params.rev < T3_REV_C ? 1000 : 500);
t3_write_reg(adap, A_SG_HI_DRB_LO_THRSH, 256);
t3_write_reg(adap, A_SG_LO_DRB_HI_THRSH, 1000);
t3_write_reg(adap, A_SG_LO_DRB_LO_THRSH, 256);
t3_write_reg(adap, A_SG_OCO_BASE, V_BASE1(0xfff));
t3_write_reg(adap, A_SG_DRB_PRI_THRESH, 63 * 1024);
}
/**
* t3_sge_prep - one-time SGE initialization
* @adap: the associated adapter
* @p: SGE parameters
*
* Performs one-time initialization of SGE SW state. Includes determining
* defaults for the assorted SGE parameters, which admins can change until
* they are used to initialize the SGE.
*/
void t3_sge_prep(struct adapter *adap, struct sge_params *p)
{
int i;
p->max_pkt_size = (16 * 1024) - sizeof(struct cpl_rx_data) -
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
for (i = 0; i < SGE_QSETS; ++i) {
struct qset_params *q = p->qset + i;
q->polling = adap->params.rev > 0;
q->coalesce_usecs = 5;
q->rspq_size = 1024;
q->fl_size = 1024;
q->jumbo_size = 512;
q->txq_size[TXQ_ETH] = 1024;
q->txq_size[TXQ_OFLD] = 1024;
q->txq_size[TXQ_CTRL] = 256;
q->cong_thres = 0;
}
spin_lock_init(&adap->sge.reg_lock);
}
| gpl-2.0 |
TeamHorizon/android_kernel_htc_msm8960 | arch/hexagon/kernel/hexagon_ksyms.c | 5621 | 1410 | /*
* Export of symbols defined in assembly files and/or libgcc.
*
* Copyright (c) 2010-2011, 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <asm/hexagon_vm.h>
#include <asm/uaccess.h>
EXPORT_SYMBOL(__copy_from_user_hexagon);
EXPORT_SYMBOL(__copy_to_user_hexagon);
EXPORT_SYMBOL(__vmgetie);
EXPORT_SYMBOL(__vmsetie);
EXPORT_SYMBOL(memcpy);
EXPORT_SYMBOL(memset);
#define DECLARE_EXPORT(name) \
extern void name(void); EXPORT_SYMBOL(name)
/* Symbols found in libgcc that assorted kernel modules need */
DECLARE_EXPORT(__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes);
DECLARE_EXPORT(__hexagon_divsi3);
DECLARE_EXPORT(__hexagon_modsi3);
DECLARE_EXPORT(__hexagon_udivsi3);
DECLARE_EXPORT(__hexagon_umodsi3);
| gpl-2.0 |
flar2/ElementalX-m7-4.0 | fs/ncpfs/ncplib_kernel.c | 10997 | 33287 | /*
* ncplib_kernel.c
*
* Copyright (C) 1995, 1996 by Volker Lendecke
* Modified for big endian by J.F. Chadima and David S. Miller
* Modified 1997 Peter Waltenberg, Bill Hawes, David Woodhouse for 2.1 dcache
* Modified 1999 Wolfram Pienkoss for NLS
* Modified 2000 Ben Harris, University of Cambridge for NFS NS meta-info
*
*/
#include "ncp_fs.h"
static inline void assert_server_locked(struct ncp_server *server)
{
if (server->lock == 0) {
DPRINTK("ncpfs: server not locked!\n");
}
}
static void ncp_add_byte(struct ncp_server *server, __u8 x)
{
assert_server_locked(server);
*(__u8 *) (&(server->packet[server->current_size])) = x;
server->current_size += 1;
return;
}
static void ncp_add_word(struct ncp_server *server, __le16 x)
{
assert_server_locked(server);
put_unaligned(x, (__le16 *) (&(server->packet[server->current_size])));
server->current_size += 2;
return;
}
static void ncp_add_be16(struct ncp_server *server, __u16 x)
{
assert_server_locked(server);
put_unaligned(cpu_to_be16(x), (__be16 *) (&(server->packet[server->current_size])));
server->current_size += 2;
}
static void ncp_add_dword(struct ncp_server *server, __le32 x)
{
assert_server_locked(server);
put_unaligned(x, (__le32 *) (&(server->packet[server->current_size])));
server->current_size += 4;
return;
}
static void ncp_add_be32(struct ncp_server *server, __u32 x)
{
assert_server_locked(server);
put_unaligned(cpu_to_be32(x), (__be32 *)(&(server->packet[server->current_size])));
server->current_size += 4;
}
static inline void ncp_add_dword_lh(struct ncp_server *server, __u32 x) {
ncp_add_dword(server, cpu_to_le32(x));
}
static void ncp_add_mem(struct ncp_server *server, const void *source, int size)
{
assert_server_locked(server);
memcpy(&(server->packet[server->current_size]), source, size);
server->current_size += size;
return;
}
static void ncp_add_pstring(struct ncp_server *server, const char *s)
{
int len = strlen(s);
assert_server_locked(server);
if (len > 255) {
DPRINTK("ncpfs: string too long: %s\n", s);
len = 255;
}
ncp_add_byte(server, len);
ncp_add_mem(server, s, len);
return;
}
static inline void ncp_init_request(struct ncp_server *server)
{
ncp_lock_server(server);
server->current_size = sizeof(struct ncp_request_header);
server->has_subfunction = 0;
}
static inline void ncp_init_request_s(struct ncp_server *server, int subfunction)
{
ncp_lock_server(server);
server->current_size = sizeof(struct ncp_request_header) + 2;
ncp_add_byte(server, subfunction);
server->has_subfunction = 1;
}
static inline char *
ncp_reply_data(struct ncp_server *server, int offset)
{
return &(server->packet[sizeof(struct ncp_reply_header) + offset]);
}
static inline u8 BVAL(const void *data)
{
return *(const u8 *)data;
}
static u8 ncp_reply_byte(struct ncp_server *server, int offset)
{
return *(const u8 *)ncp_reply_data(server, offset);
}
static inline u16 WVAL_LH(const void *data)
{
return get_unaligned_le16(data);
}
static u16
ncp_reply_le16(struct ncp_server *server, int offset)
{
return get_unaligned_le16(ncp_reply_data(server, offset));
}
static u16
ncp_reply_be16(struct ncp_server *server, int offset)
{
return get_unaligned_be16(ncp_reply_data(server, offset));
}
static inline u32 DVAL_LH(const void *data)
{
return get_unaligned_le32(data);
}
static __le32
ncp_reply_dword(struct ncp_server *server, int offset)
{
return get_unaligned((__le32 *)ncp_reply_data(server, offset));
}
static inline __u32 ncp_reply_dword_lh(struct ncp_server* server, int offset) {
return le32_to_cpu(ncp_reply_dword(server, offset));
}
int
ncp_negotiate_buffersize(struct ncp_server *server, int size, int *target)
{
int result;
ncp_init_request(server);
ncp_add_be16(server, size);
if ((result = ncp_request(server, 33)) != 0) {
ncp_unlock_server(server);
return result;
}
*target = min_t(unsigned int, ncp_reply_be16(server, 0), size);
ncp_unlock_server(server);
return 0;
}
/* options:
* bit 0 ipx checksum
* bit 1 packet signing
*/
int
ncp_negotiate_size_and_options(struct ncp_server *server,
int size, int options, int *ret_size, int *ret_options) {
int result;
/* there is minimum */
if (size < NCP_BLOCK_SIZE) size = NCP_BLOCK_SIZE;
ncp_init_request(server);
ncp_add_be16(server, size);
ncp_add_byte(server, options);
if ((result = ncp_request(server, 0x61)) != 0)
{
ncp_unlock_server(server);
return result;
}
/* NCP over UDP returns 0 (!!!) */
result = ncp_reply_be16(server, 0);
if (result >= NCP_BLOCK_SIZE)
size = min(result, size);
*ret_size = size;
*ret_options = ncp_reply_byte(server, 4);
ncp_unlock_server(server);
return 0;
}
int ncp_get_volume_info_with_number(struct ncp_server* server,
int n, struct ncp_volume_info* target) {
int result;
int len;
ncp_init_request_s(server, 44);
ncp_add_byte(server, n);
if ((result = ncp_request(server, 22)) != 0) {
goto out;
}
target->total_blocks = ncp_reply_dword_lh(server, 0);
target->free_blocks = ncp_reply_dword_lh(server, 4);
target->purgeable_blocks = ncp_reply_dword_lh(server, 8);
target->not_yet_purgeable_blocks = ncp_reply_dword_lh(server, 12);
target->total_dir_entries = ncp_reply_dword_lh(server, 16);
target->available_dir_entries = ncp_reply_dword_lh(server, 20);
target->sectors_per_block = ncp_reply_byte(server, 28);
memset(&(target->volume_name), 0, sizeof(target->volume_name));
result = -EIO;
len = ncp_reply_byte(server, 29);
if (len > NCP_VOLNAME_LEN) {
DPRINTK("ncpfs: volume name too long: %d\n", len);
goto out;
}
memcpy(&(target->volume_name), ncp_reply_data(server, 30), len);
result = 0;
out:
ncp_unlock_server(server);
return result;
}
int ncp_get_directory_info(struct ncp_server* server, __u8 n,
struct ncp_volume_info* target) {
int result;
int len;
ncp_init_request_s(server, 45);
ncp_add_byte(server, n);
if ((result = ncp_request(server, 22)) != 0) {
goto out;
}
target->total_blocks = ncp_reply_dword_lh(server, 0);
target->free_blocks = ncp_reply_dword_lh(server, 4);
target->purgeable_blocks = 0;
target->not_yet_purgeable_blocks = 0;
target->total_dir_entries = ncp_reply_dword_lh(server, 8);
target->available_dir_entries = ncp_reply_dword_lh(server, 12);
target->sectors_per_block = ncp_reply_byte(server, 20);
memset(&(target->volume_name), 0, sizeof(target->volume_name));
result = -EIO;
len = ncp_reply_byte(server, 21);
if (len > NCP_VOLNAME_LEN) {
DPRINTK("ncpfs: volume name too long: %d\n", len);
goto out;
}
memcpy(&(target->volume_name), ncp_reply_data(server, 22), len);
result = 0;
out:
ncp_unlock_server(server);
return result;
}
int
ncp_close_file(struct ncp_server *server, const char *file_id)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 0);
ncp_add_mem(server, file_id, 6);
result = ncp_request(server, 66);
ncp_unlock_server(server);
return result;
}
int
ncp_make_closed(struct inode *inode)
{
int err;
err = 0;
mutex_lock(&NCP_FINFO(inode)->open_mutex);
if (atomic_read(&NCP_FINFO(inode)->opened) == 1) {
atomic_set(&NCP_FINFO(inode)->opened, 0);
err = ncp_close_file(NCP_SERVER(inode), NCP_FINFO(inode)->file_handle);
if (!err)
PPRINTK("ncp_make_closed: volnum=%d, dirent=%u, error=%d\n",
NCP_FINFO(inode)->volNumber,
NCP_FINFO(inode)->dirEntNum, err);
}
mutex_unlock(&NCP_FINFO(inode)->open_mutex);
return err;
}
static void ncp_add_handle_path(struct ncp_server *server, __u8 vol_num,
__le32 dir_base, int have_dir_base,
const char *path)
{
ncp_add_byte(server, vol_num);
ncp_add_dword(server, dir_base);
if (have_dir_base != 0) {
ncp_add_byte(server, 1); /* dir_base */
} else {
ncp_add_byte(server, 0xff); /* no handle */
}
if (path != NULL) {
ncp_add_byte(server, 1); /* 1 component */
ncp_add_pstring(server, path);
} else {
ncp_add_byte(server, 0);
}
}
int ncp_dirhandle_alloc(struct ncp_server* server, __u8 volnum, __le32 dirent,
__u8* dirhandle) {
int result;
ncp_init_request(server);
ncp_add_byte(server, 12); /* subfunction */
ncp_add_byte(server, NW_NS_DOS);
ncp_add_byte(server, 0);
ncp_add_word(server, 0);
ncp_add_handle_path(server, volnum, dirent, 1, NULL);
if ((result = ncp_request(server, 87)) == 0) {
*dirhandle = ncp_reply_byte(server, 0);
}
ncp_unlock_server(server);
return result;
}
int ncp_dirhandle_free(struct ncp_server* server, __u8 dirhandle) {
int result;
ncp_init_request_s(server, 20);
ncp_add_byte(server, dirhandle);
result = ncp_request(server, 22);
ncp_unlock_server(server);
return result;
}
void ncp_extract_file_info(const void *structure, struct nw_info_struct *target)
{
const __u8 *name_len;
const int info_struct_size = offsetof(struct nw_info_struct, nameLen);
memcpy(target, structure, info_struct_size);
name_len = structure + info_struct_size;
target->nameLen = *name_len;
memcpy(target->entryName, name_len + 1, *name_len);
target->entryName[*name_len] = '\0';
target->volNumber = le32_to_cpu(target->volNumber);
return;
}
#ifdef CONFIG_NCPFS_NFS_NS
static inline void ncp_extract_nfs_info(const unsigned char *structure,
struct nw_nfs_info *target)
{
target->mode = DVAL_LH(structure);
target->rdev = DVAL_LH(structure + 8);
}
#endif
int ncp_obtain_nfs_info(struct ncp_server *server,
struct nw_info_struct *target)
{
int result = 0;
#ifdef CONFIG_NCPFS_NFS_NS
__u32 volnum = target->volNumber;
if (ncp_is_nfs_extras(server, volnum)) {
ncp_init_request(server);
ncp_add_byte(server, 19); /* subfunction */
ncp_add_byte(server, server->name_space[volnum]);
ncp_add_byte(server, NW_NS_NFS);
ncp_add_byte(server, 0);
ncp_add_byte(server, volnum);
ncp_add_dword(server, target->dirEntNum);
/* We must retrieve both nlinks and rdev, otherwise some server versions
report zeroes instead of valid data */
ncp_add_dword_lh(server, NSIBM_NFS_MODE | NSIBM_NFS_NLINKS | NSIBM_NFS_RDEV);
if ((result = ncp_request(server, 87)) == 0) {
ncp_extract_nfs_info(ncp_reply_data(server, 0), &target->nfs);
DPRINTK(KERN_DEBUG
"ncp_obtain_nfs_info: (%s) mode=0%o, rdev=0x%x\n",
target->entryName, target->nfs.mode,
target->nfs.rdev);
} else {
target->nfs.mode = 0;
target->nfs.rdev = 0;
}
ncp_unlock_server(server);
} else
#endif
{
target->nfs.mode = 0;
target->nfs.rdev = 0;
}
return result;
}
/*
* Returns information for a (one-component) name relative to
* the specified directory.
*/
int ncp_obtain_info(struct ncp_server *server, struct inode *dir, const char *path,
struct nw_info_struct *target)
{
__u8 volnum = NCP_FINFO(dir)->volNumber;
__le32 dirent = NCP_FINFO(dir)->dirEntNum;
int result;
if (target == NULL) {
printk(KERN_ERR "ncp_obtain_info: invalid call\n");
return -EINVAL;
}
ncp_init_request(server);
ncp_add_byte(server, 6); /* subfunction */
ncp_add_byte(server, server->name_space[volnum]);
ncp_add_byte(server, server->name_space[volnum]); /* N.B. twice ?? */
ncp_add_word(server, cpu_to_le16(0x8006)); /* get all */
ncp_add_dword(server, RIM_ALL);
ncp_add_handle_path(server, volnum, dirent, 1, path);
if ((result = ncp_request(server, 87)) != 0)
goto out;
ncp_extract_file_info(ncp_reply_data(server, 0), target);
ncp_unlock_server(server);
result = ncp_obtain_nfs_info(server, target);
return result;
out:
ncp_unlock_server(server);
return result;
}
#ifdef CONFIG_NCPFS_NFS_NS
static int
ncp_obtain_DOS_dir_base(struct ncp_server *server,
__u8 ns, __u8 volnum, __le32 dirent,
const char *path, /* At most 1 component */
__le32 *DOS_dir_base)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 6); /* subfunction */
ncp_add_byte(server, ns);
ncp_add_byte(server, ns);
ncp_add_word(server, cpu_to_le16(0x8006)); /* get all */
ncp_add_dword(server, RIM_DIRECTORY);
ncp_add_handle_path(server, volnum, dirent, 1, path);
if ((result = ncp_request(server, 87)) == 0)
{
if (DOS_dir_base) *DOS_dir_base=ncp_reply_dword(server, 0x34);
}
ncp_unlock_server(server);
return result;
}
#endif /* CONFIG_NCPFS_NFS_NS */
static inline int
ncp_get_known_namespace(struct ncp_server *server, __u8 volume)
{
#if defined(CONFIG_NCPFS_OS2_NS) || defined(CONFIG_NCPFS_NFS_NS)
int result;
__u8 *namespace;
__u16 no_namespaces;
ncp_init_request(server);
ncp_add_byte(server, 24); /* Subfunction: Get Name Spaces Loaded */
ncp_add_word(server, 0);
ncp_add_byte(server, volume);
if ((result = ncp_request(server, 87)) != 0) {
ncp_unlock_server(server);
return NW_NS_DOS; /* not result ?? */
}
result = NW_NS_DOS;
no_namespaces = ncp_reply_le16(server, 0);
namespace = ncp_reply_data(server, 2);
while (no_namespaces > 0) {
DPRINTK("get_namespaces: found %d on %d\n", *namespace, volume);
#ifdef CONFIG_NCPFS_NFS_NS
if ((*namespace == NW_NS_NFS) && !(server->m.flags&NCP_MOUNT_NO_NFS))
{
result = NW_NS_NFS;
break;
}
#endif /* CONFIG_NCPFS_NFS_NS */
#ifdef CONFIG_NCPFS_OS2_NS
if ((*namespace == NW_NS_OS2) && !(server->m.flags&NCP_MOUNT_NO_OS2))
{
result = NW_NS_OS2;
}
#endif /* CONFIG_NCPFS_OS2_NS */
namespace += 1;
no_namespaces -= 1;
}
ncp_unlock_server(server);
return result;
#else /* neither OS2 nor NFS - only DOS */
return NW_NS_DOS;
#endif /* defined(CONFIG_NCPFS_OS2_NS) || defined(CONFIG_NCPFS_NFS_NS) */
}
int
ncp_update_known_namespace(struct ncp_server *server, __u8 volume, int *ret_ns)
{
int ns = ncp_get_known_namespace(server, volume);
if (ret_ns)
*ret_ns = ns;
DPRINTK("lookup_vol: namespace[%d] = %d\n",
volume, server->name_space[volume]);
if (server->name_space[volume] == ns)
return 0;
server->name_space[volume] = ns;
return 1;
}
static int
ncp_ObtainSpecificDirBase(struct ncp_server *server,
__u8 nsSrc, __u8 nsDst, __u8 vol_num, __le32 dir_base,
const char *path, /* At most 1 component */
__le32 *dirEntNum, __le32 *DosDirNum)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 6); /* subfunction */
ncp_add_byte(server, nsSrc);
ncp_add_byte(server, nsDst);
ncp_add_word(server, cpu_to_le16(0x8006)); /* get all */
ncp_add_dword(server, RIM_ALL);
ncp_add_handle_path(server, vol_num, dir_base, 1, path);
if ((result = ncp_request(server, 87)) != 0)
{
ncp_unlock_server(server);
return result;
}
if (dirEntNum)
*dirEntNum = ncp_reply_dword(server, 0x30);
if (DosDirNum)
*DosDirNum = ncp_reply_dword(server, 0x34);
ncp_unlock_server(server);
return 0;
}
int
ncp_mount_subdir(struct ncp_server *server,
__u8 volNumber, __u8 srcNS, __le32 dirEntNum,
__u32* volume, __le32* newDirEnt, __le32* newDosEnt)
{
int dstNS;
int result;
ncp_update_known_namespace(server, volNumber, &dstNS);
if ((result = ncp_ObtainSpecificDirBase(server, srcNS, dstNS, volNumber,
dirEntNum, NULL, newDirEnt, newDosEnt)) != 0)
{
return result;
}
*volume = volNumber;
server->m.mounted_vol[1] = 0;
server->m.mounted_vol[0] = 'X';
return 0;
}
int
ncp_get_volume_root(struct ncp_server *server,
const char *volname, __u32* volume, __le32* dirent, __le32* dosdirent)
{
int result;
DPRINTK("ncp_get_volume_root: looking up vol %s\n", volname);
ncp_init_request(server);
ncp_add_byte(server, 22); /* Subfunction: Generate dir handle */
ncp_add_byte(server, 0); /* DOS namespace */
ncp_add_byte(server, 0); /* reserved */
ncp_add_byte(server, 0); /* reserved */
ncp_add_byte(server, 0); /* reserved */
ncp_add_byte(server, 0); /* faked volume number */
ncp_add_dword(server, 0); /* faked dir_base */
ncp_add_byte(server, 0xff); /* Don't have a dir_base */
ncp_add_byte(server, 1); /* 1 path component */
ncp_add_pstring(server, volname);
if ((result = ncp_request(server, 87)) != 0) {
ncp_unlock_server(server);
return result;
}
*dirent = *dosdirent = ncp_reply_dword(server, 4);
*volume = ncp_reply_byte(server, 8);
ncp_unlock_server(server);
return 0;
}
int
ncp_lookup_volume(struct ncp_server *server,
const char *volname, struct nw_info_struct *target)
{
int result;
memset(target, 0, sizeof(*target));
result = ncp_get_volume_root(server, volname,
&target->volNumber, &target->dirEntNum, &target->DosDirNum);
if (result) {
return result;
}
ncp_update_known_namespace(server, target->volNumber, NULL);
target->nameLen = strlen(volname);
memcpy(target->entryName, volname, target->nameLen+1);
target->attributes = aDIR;
/* set dates to Jan 1, 1986 00:00 */
target->creationTime = target->modifyTime = cpu_to_le16(0x0000);
target->creationDate = target->modifyDate = target->lastAccessDate = cpu_to_le16(0x0C21);
target->nfs.mode = 0;
return 0;
}
int ncp_modify_file_or_subdir_dos_info_path(struct ncp_server *server,
struct inode *dir,
const char *path,
__le32 info_mask,
const struct nw_modify_dos_info *info)
{
__u8 volnum = NCP_FINFO(dir)->volNumber;
__le32 dirent = NCP_FINFO(dir)->dirEntNum;
int result;
ncp_init_request(server);
ncp_add_byte(server, 7); /* subfunction */
ncp_add_byte(server, server->name_space[volnum]);
ncp_add_byte(server, 0); /* reserved */
ncp_add_word(server, cpu_to_le16(0x8006)); /* search attribs: all */
ncp_add_dword(server, info_mask);
ncp_add_mem(server, info, sizeof(*info));
ncp_add_handle_path(server, volnum, dirent, 1, path);
result = ncp_request(server, 87);
ncp_unlock_server(server);
return result;
}
int ncp_modify_file_or_subdir_dos_info(struct ncp_server *server,
struct inode *dir,
__le32 info_mask,
const struct nw_modify_dos_info *info)
{
return ncp_modify_file_or_subdir_dos_info_path(server, dir, NULL,
info_mask, info);
}
#ifdef CONFIG_NCPFS_NFS_NS
int ncp_modify_nfs_info(struct ncp_server *server, __u8 volnum, __le32 dirent,
__u32 mode, __u32 rdev)
{
int result = 0;
ncp_init_request(server);
if (server->name_space[volnum] == NW_NS_NFS) {
ncp_add_byte(server, 25); /* subfunction */
ncp_add_byte(server, server->name_space[volnum]);
ncp_add_byte(server, NW_NS_NFS);
ncp_add_byte(server, volnum);
ncp_add_dword(server, dirent);
/* we must always operate on both nlinks and rdev, otherwise
rdev is not set */
ncp_add_dword_lh(server, NSIBM_NFS_MODE | NSIBM_NFS_NLINKS | NSIBM_NFS_RDEV);
ncp_add_dword_lh(server, mode);
ncp_add_dword_lh(server, 1); /* nlinks */
ncp_add_dword_lh(server, rdev);
result = ncp_request(server, 87);
}
ncp_unlock_server(server);
return result;
}
#endif
static int
ncp_DeleteNSEntry(struct ncp_server *server,
__u8 have_dir_base, __u8 volnum, __le32 dirent,
const char* name, __u8 ns, __le16 attr)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 8); /* subfunction */
ncp_add_byte(server, ns);
ncp_add_byte(server, 0); /* reserved */
ncp_add_word(server, attr); /* search attribs: all */
ncp_add_handle_path(server, volnum, dirent, have_dir_base, name);
result = ncp_request(server, 87);
ncp_unlock_server(server);
return result;
}
int
ncp_del_file_or_subdir2(struct ncp_server *server,
struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
__u8 volnum;
__le32 dirent;
if (!inode) {
return 0xFF; /* Any error */
}
volnum = NCP_FINFO(inode)->volNumber;
dirent = NCP_FINFO(inode)->DosDirNum;
return ncp_DeleteNSEntry(server, 1, volnum, dirent, NULL, NW_NS_DOS, cpu_to_le16(0x8006));
}
int
ncp_del_file_or_subdir(struct ncp_server *server,
struct inode *dir, const char *name)
{
__u8 volnum = NCP_FINFO(dir)->volNumber;
__le32 dirent = NCP_FINFO(dir)->dirEntNum;
int name_space;
name_space = server->name_space[volnum];
#ifdef CONFIG_NCPFS_NFS_NS
if (name_space == NW_NS_NFS)
{
int result;
result=ncp_obtain_DOS_dir_base(server, name_space, volnum, dirent, name, &dirent);
if (result) return result;
name = NULL;
name_space = NW_NS_DOS;
}
#endif /* CONFIG_NCPFS_NFS_NS */
return ncp_DeleteNSEntry(server, 1, volnum, dirent, name, name_space, cpu_to_le16(0x8006));
}
static inline void ConvertToNWfromDWORD(__u16 v0, __u16 v1, __u8 ret[6])
{
__le16 *dest = (__le16 *) ret;
dest[1] = cpu_to_le16(v0);
dest[2] = cpu_to_le16(v1);
dest[0] = cpu_to_le16(v0 + 1);
return;
}
/* If both dir and name are NULL, then in target there's already a
looked-up entry that wants to be opened. */
int ncp_open_create_file_or_subdir(struct ncp_server *server,
struct inode *dir, const char *name,
int open_create_mode,
__le32 create_attributes,
__le16 desired_acc_rights,
struct ncp_entry_info *target)
{
__le16 search_attribs = cpu_to_le16(0x0006);
__u8 volnum;
__le32 dirent;
int result;
volnum = NCP_FINFO(dir)->volNumber;
dirent = NCP_FINFO(dir)->dirEntNum;
if ((create_attributes & aDIR) != 0) {
search_attribs |= cpu_to_le16(0x8000);
}
ncp_init_request(server);
ncp_add_byte(server, 1); /* subfunction */
ncp_add_byte(server, server->name_space[volnum]);
ncp_add_byte(server, open_create_mode);
ncp_add_word(server, search_attribs);
ncp_add_dword(server, RIM_ALL);
ncp_add_dword(server, create_attributes);
/* The desired acc rights seem to be the inherited rights mask
for directories */
ncp_add_word(server, desired_acc_rights);
ncp_add_handle_path(server, volnum, dirent, 1, name);
if ((result = ncp_request(server, 87)) != 0)
goto out;
if (!(create_attributes & aDIR))
target->opened = 1;
/* in target there's a new finfo to fill */
ncp_extract_file_info(ncp_reply_data(server, 6), &(target->i));
target->volume = target->i.volNumber;
ConvertToNWfromDWORD(ncp_reply_le16(server, 0),
ncp_reply_le16(server, 2),
target->file_handle);
ncp_unlock_server(server);
(void)ncp_obtain_nfs_info(server, &(target->i));
return 0;
out:
ncp_unlock_server(server);
return result;
}
int
ncp_initialize_search(struct ncp_server *server, struct inode *dir,
struct nw_search_sequence *target)
{
__u8 volnum = NCP_FINFO(dir)->volNumber;
__le32 dirent = NCP_FINFO(dir)->dirEntNum;
int result;
ncp_init_request(server);
ncp_add_byte(server, 2); /* subfunction */
ncp_add_byte(server, server->name_space[volnum]);
ncp_add_byte(server, 0); /* reserved */
ncp_add_handle_path(server, volnum, dirent, 1, NULL);
result = ncp_request(server, 87);
if (result)
goto out;
memcpy(target, ncp_reply_data(server, 0), sizeof(*target));
out:
ncp_unlock_server(server);
return result;
}
int ncp_search_for_fileset(struct ncp_server *server,
struct nw_search_sequence *seq,
int* more,
int* cnt,
char* buffer,
size_t bufsize,
char** rbuf,
size_t* rsize)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 20);
ncp_add_byte(server, server->name_space[seq->volNumber]);
ncp_add_byte(server, 0); /* datastream */
ncp_add_word(server, cpu_to_le16(0x8006));
ncp_add_dword(server, RIM_ALL);
ncp_add_word(server, cpu_to_le16(32767)); /* max returned items */
ncp_add_mem(server, seq, 9);
#ifdef CONFIG_NCPFS_NFS_NS
if (server->name_space[seq->volNumber] == NW_NS_NFS) {
ncp_add_byte(server, 0); /* 0 byte pattern */
} else
#endif
{
ncp_add_byte(server, 2); /* 2 byte pattern */
ncp_add_byte(server, 0xff); /* following is a wildcard */
ncp_add_byte(server, '*');
}
result = ncp_request2(server, 87, buffer, bufsize);
if (result) {
ncp_unlock_server(server);
return result;
}
if (server->ncp_reply_size < 12) {
ncp_unlock_server(server);
return 0xFF;
}
*rsize = server->ncp_reply_size - 12;
ncp_unlock_server(server);
buffer = buffer + sizeof(struct ncp_reply_header);
*rbuf = buffer + 12;
*cnt = WVAL_LH(buffer + 10);
*more = BVAL(buffer + 9);
memcpy(seq, buffer, 9);
return 0;
}
static int
ncp_RenameNSEntry(struct ncp_server *server,
struct inode *old_dir, const char *old_name, __le16 old_type,
struct inode *new_dir, const char *new_name)
{
int result = -EINVAL;
if ((old_dir == NULL) || (old_name == NULL) ||
(new_dir == NULL) || (new_name == NULL))
goto out;
ncp_init_request(server);
ncp_add_byte(server, 4); /* subfunction */
ncp_add_byte(server, server->name_space[NCP_FINFO(old_dir)->volNumber]);
ncp_add_byte(server, 1); /* rename flag */
ncp_add_word(server, old_type); /* search attributes */
/* source Handle Path */
ncp_add_byte(server, NCP_FINFO(old_dir)->volNumber);
ncp_add_dword(server, NCP_FINFO(old_dir)->dirEntNum);
ncp_add_byte(server, 1);
ncp_add_byte(server, 1); /* 1 source component */
/* dest Handle Path */
ncp_add_byte(server, NCP_FINFO(new_dir)->volNumber);
ncp_add_dword(server, NCP_FINFO(new_dir)->dirEntNum);
ncp_add_byte(server, 1);
ncp_add_byte(server, 1); /* 1 destination component */
/* source path string */
ncp_add_pstring(server, old_name);
/* dest path string */
ncp_add_pstring(server, new_name);
result = ncp_request(server, 87);
ncp_unlock_server(server);
out:
return result;
}
int ncp_ren_or_mov_file_or_subdir(struct ncp_server *server,
struct inode *old_dir, const char *old_name,
struct inode *new_dir, const char *new_name)
{
int result;
__le16 old_type = cpu_to_le16(0x06);
/* If somebody can do it atomic, call me... vandrove@vc.cvut.cz */
result = ncp_RenameNSEntry(server, old_dir, old_name, old_type,
new_dir, new_name);
if (result == 0xFF) /* File Not Found, try directory */
{
old_type = cpu_to_le16(0x16);
result = ncp_RenameNSEntry(server, old_dir, old_name, old_type,
new_dir, new_name);
}
if (result != 0x92) return result; /* All except NO_FILES_RENAMED */
result = ncp_del_file_or_subdir(server, new_dir, new_name);
if (result != 0) return -EACCES;
result = ncp_RenameNSEntry(server, old_dir, old_name, old_type,
new_dir, new_name);
return result;
}
/* We have to transfer to/from user space */
int
ncp_read_kernel(struct ncp_server *server, const char *file_id,
__u32 offset, __u16 to_read, char *target, int *bytes_read)
{
const char *source;
int result;
ncp_init_request(server);
ncp_add_byte(server, 0);
ncp_add_mem(server, file_id, 6);
ncp_add_be32(server, offset);
ncp_add_be16(server, to_read);
if ((result = ncp_request(server, 72)) != 0) {
goto out;
}
*bytes_read = ncp_reply_be16(server, 0);
source = ncp_reply_data(server, 2 + (offset & 1));
memcpy(target, source, *bytes_read);
out:
ncp_unlock_server(server);
return result;
}
/* There is a problem... egrep and some other silly tools do:
x = mmap(NULL, MAP_PRIVATE, PROT_READ|PROT_WRITE, <ncpfs fd>, 32768);
read(<ncpfs fd>, x, 32768);
Now copying read result by copy_to_user causes pagefault. This pagefault
could not be handled because of server was locked due to read. So we have
to use temporary buffer. So ncp_unlock_server must be done before
copy_to_user (and for write, copy_from_user must be done before
ncp_init_request... same applies for send raw packet ioctl). Because of
file is normally read in bigger chunks, caller provides kmalloced
(vmalloced) chunk of memory with size >= to_read...
*/
int
ncp_read_bounce(struct ncp_server *server, const char *file_id,
__u32 offset, __u16 to_read, char __user *target, int *bytes_read,
void* bounce, __u32 bufsize)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 0);
ncp_add_mem(server, file_id, 6);
ncp_add_be32(server, offset);
ncp_add_be16(server, to_read);
result = ncp_request2(server, 72, bounce, bufsize);
ncp_unlock_server(server);
if (!result) {
int len = get_unaligned_be16((char *)bounce +
sizeof(struct ncp_reply_header));
result = -EIO;
if (len <= to_read) {
char* source;
source = (char*)bounce +
sizeof(struct ncp_reply_header) + 2 +
(offset & 1);
*bytes_read = len;
result = 0;
if (copy_to_user(target, source, len))
result = -EFAULT;
}
}
return result;
}
int
ncp_write_kernel(struct ncp_server *server, const char *file_id,
__u32 offset, __u16 to_write,
const char *source, int *bytes_written)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 0);
ncp_add_mem(server, file_id, 6);
ncp_add_be32(server, offset);
ncp_add_be16(server, to_write);
ncp_add_mem(server, source, to_write);
if ((result = ncp_request(server, 73)) == 0)
*bytes_written = to_write;
ncp_unlock_server(server);
return result;
}
#ifdef CONFIG_NCPFS_IOCTL_LOCKING
int
ncp_LogPhysicalRecord(struct ncp_server *server, const char *file_id,
__u8 locktype, __u32 offset, __u32 length, __u16 timeout)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, locktype);
ncp_add_mem(server, file_id, 6);
ncp_add_be32(server, offset);
ncp_add_be32(server, length);
ncp_add_be16(server, timeout);
if ((result = ncp_request(server, 0x1A)) != 0)
{
ncp_unlock_server(server);
return result;
}
ncp_unlock_server(server);
return 0;
}
int
ncp_ClearPhysicalRecord(struct ncp_server *server, const char *file_id,
__u32 offset, __u32 length)
{
int result;
ncp_init_request(server);
ncp_add_byte(server, 0); /* who knows... lanalyzer says that */
ncp_add_mem(server, file_id, 6);
ncp_add_be32(server, offset);
ncp_add_be32(server, length);
if ((result = ncp_request(server, 0x1E)) != 0)
{
ncp_unlock_server(server);
return result;
}
ncp_unlock_server(server);
return 0;
}
#endif /* CONFIG_NCPFS_IOCTL_LOCKING */
#ifdef CONFIG_NCPFS_NLS
/* This are the NLS conversion routines with inspirations and code parts
* from the vfat file system and hints from Petr Vandrovec.
*/
int
ncp__io2vol(struct ncp_server *server, unsigned char *vname, unsigned int *vlen,
const unsigned char *iname, unsigned int ilen, int cc)
{
struct nls_table *in = server->nls_io;
struct nls_table *out = server->nls_vol;
unsigned char *vname_start;
unsigned char *vname_end;
const unsigned char *iname_end;
iname_end = iname + ilen;
vname_start = vname;
vname_end = vname + *vlen - 1;
while (iname < iname_end) {
int chl;
wchar_t ec;
if (NCP_IS_FLAG(server, NCP_FLAG_UTF8)) {
int k;
unicode_t u;
k = utf8_to_utf32(iname, iname_end - iname, &u);
if (k < 0 || u > MAX_WCHAR_T)
return -EINVAL;
iname += k;
ec = u;
} else {
if (*iname == NCP_ESC) {
int k;
if (iname_end - iname < 5)
goto nospec;
ec = 0;
for (k = 1; k < 5; k++) {
unsigned char nc;
nc = iname[k] - '0';
if (nc >= 10) {
nc -= 'A' - '0' - 10;
if ((nc < 10) || (nc > 15)) {
goto nospec;
}
}
ec = (ec << 4) | nc;
}
iname += 5;
} else {
nospec:;
if ( (chl = in->char2uni(iname, iname_end - iname, &ec)) < 0)
return chl;
iname += chl;
}
}
/* unitoupper should be here! */
chl = out->uni2char(ec, vname, vname_end - vname);
if (chl < 0)
return chl;
/* this is wrong... */
if (cc) {
int chi;
for (chi = 0; chi < chl; chi++){
vname[chi] = ncp_toupper(out, vname[chi]);
}
}
vname += chl;
}
*vname = 0;
*vlen = vname - vname_start;
return 0;
}
int
ncp__vol2io(struct ncp_server *server, unsigned char *iname, unsigned int *ilen,
const unsigned char *vname, unsigned int vlen, int cc)
{
struct nls_table *in = server->nls_vol;
struct nls_table *out = server->nls_io;
const unsigned char *vname_end;
unsigned char *iname_start;
unsigned char *iname_end;
unsigned char *vname_cc;
int err;
vname_cc = NULL;
if (cc) {
int i;
/* this is wrong! */
vname_cc = kmalloc(vlen, GFP_KERNEL);
if (!vname_cc)
return -ENOMEM;
for (i = 0; i < vlen; i++)
vname_cc[i] = ncp_tolower(in, vname[i]);
vname = vname_cc;
}
iname_start = iname;
iname_end = iname + *ilen - 1;
vname_end = vname + vlen;
while (vname < vname_end) {
wchar_t ec;
int chl;
if ( (chl = in->char2uni(vname, vname_end - vname, &ec)) < 0) {
err = chl;
goto quit;
}
vname += chl;
/* unitolower should be here! */
if (NCP_IS_FLAG(server, NCP_FLAG_UTF8)) {
int k;
k = utf32_to_utf8(ec, iname, iname_end - iname);
if (k < 0) {
err = -ENAMETOOLONG;
goto quit;
}
iname += k;
} else {
if ( (chl = out->uni2char(ec, iname, iname_end - iname)) >= 0) {
iname += chl;
} else {
int k;
if (iname_end - iname < 5) {
err = -ENAMETOOLONG;
goto quit;
}
*iname = NCP_ESC;
for (k = 4; k > 0; k--) {
unsigned char v;
v = (ec & 0xF) + '0';
if (v > '9') {
v += 'A' - '9' - 1;
}
iname[k] = v;
ec >>= 4;
}
iname += 5;
}
}
}
*iname = 0;
*ilen = iname - iname_start;
err = 0;
quit:;
if (cc)
kfree(vname_cc);
return err;
}
#else
int
ncp__io2vol(unsigned char *vname, unsigned int *vlen,
const unsigned char *iname, unsigned int ilen, int cc)
{
int i;
if (*vlen <= ilen)
return -ENAMETOOLONG;
if (cc)
for (i = 0; i < ilen; i++) {
*vname = toupper(*iname);
vname++;
iname++;
}
else {
memmove(vname, iname, ilen);
vname += ilen;
}
*vlen = ilen;
*vname = 0;
return 0;
}
int
ncp__vol2io(unsigned char *iname, unsigned int *ilen,
const unsigned char *vname, unsigned int vlen, int cc)
{
int i;
if (*ilen <= vlen)
return -ENAMETOOLONG;
if (cc)
for (i = 0; i < vlen; i++) {
*iname = tolower(*vname);
iname++;
vname++;
}
else {
memmove(iname, vname, vlen);
iname += vlen;
}
*ilen = vlen;
*iname = 0;
return 0;
}
#endif
| gpl-2.0 |
TheWhisp/android_kernel_samsung_msm8916-caf | arch/mips/lasat/at93c.c | 11765 | 2613 | /*
* Atmel AT93C46 serial eeprom driver
*
* Brian Murphy <brian.murphy@eicon.com>
*
*/
#include <linux/kernel.h>
#include <linux/delay.h>
#include <asm/lasat/lasat.h>
#include <linux/module.h>
#include <linux/init.h>
#include "at93c.h"
#define AT93C_ADDR_SHIFT 7
#define AT93C_ADDR_MAX ((1 << AT93C_ADDR_SHIFT) - 1)
#define AT93C_RCMD (0x6 << AT93C_ADDR_SHIFT)
#define AT93C_WCMD (0x5 << AT93C_ADDR_SHIFT)
#define AT93C_WENCMD 0x260
#define AT93C_WDSCMD 0x200
struct at93c_defs *at93c;
static void at93c_reg_write(u32 val)
{
*at93c->reg = val;
}
static u32 at93c_reg_read(void)
{
u32 tmp = *at93c->reg;
return tmp;
}
static u32 at93c_datareg_read(void)
{
u32 tmp = *at93c->rdata_reg;
return tmp;
}
static void at93c_cycle_clk(u32 data)
{
at93c_reg_write(data | at93c->clk);
lasat_ndelay(250);
at93c_reg_write(data & ~at93c->clk);
lasat_ndelay(250);
}
static void at93c_write_databit(u8 bit)
{
u32 data = at93c_reg_read();
if (bit)
data |= 1 << at93c->wdata_shift;
else
data &= ~(1 << at93c->wdata_shift);
at93c_reg_write(data);
lasat_ndelay(100);
at93c_cycle_clk(data);
}
static unsigned int at93c_read_databit(void)
{
u32 data;
at93c_cycle_clk(at93c_reg_read());
data = (at93c_datareg_read() >> at93c->rdata_shift) & 1;
return data;
}
static u8 at93c_read_byte(void)
{
int i;
u8 data = 0;
for (i = 0; i <= 7; i++) {
data <<= 1;
data |= at93c_read_databit();
}
return data;
}
static void at93c_write_bits(u32 data, int size)
{
int i;
int shift = size - 1;
u32 mask = (1 << shift);
for (i = 0; i < size; i++) {
at93c_write_databit((data & mask) >> shift);
data <<= 1;
}
}
static void at93c_init_op(void)
{
at93c_reg_write((at93c_reg_read() | at93c->cs) &
~at93c->clk & ~(1 << at93c->rdata_shift));
lasat_ndelay(50);
}
static void at93c_end_op(void)
{
at93c_reg_write(at93c_reg_read() & ~at93c->cs);
lasat_ndelay(250);
}
static void at93c_wait(void)
{
at93c_init_op();
while (!at93c_read_databit())
;
at93c_end_op();
};
static void at93c_disable_wp(void)
{
at93c_init_op();
at93c_write_bits(AT93C_WENCMD, 10);
at93c_end_op();
}
static void at93c_enable_wp(void)
{
at93c_init_op();
at93c_write_bits(AT93C_WDSCMD, 10);
at93c_end_op();
}
u8 at93c_read(u8 addr)
{
u8 byte;
at93c_init_op();
at93c_write_bits((addr & AT93C_ADDR_MAX)|AT93C_RCMD, 10);
byte = at93c_read_byte();
at93c_end_op();
return byte;
}
void at93c_write(u8 addr, u8 data)
{
at93c_disable_wp();
at93c_init_op();
at93c_write_bits((addr & AT93C_ADDR_MAX)|AT93C_WCMD, 10);
at93c_write_bits(data, 8);
at93c_end_op();
at93c_wait();
at93c_enable_wp();
}
| gpl-2.0 |
wingrime/android_kernel_swift | crypto/michael_mic.c | 12277 | 3701 | /*
* Cryptographic API
*
* Michael MIC (IEEE 802.11i/TKIP) keyed digest
*
* Copyright (c) 2004 Jouni Malinen <j@w1.fi>
*
* 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 <crypto/internal/hash.h>
#include <asm/byteorder.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/types.h>
struct michael_mic_ctx {
u32 l, r;
};
struct michael_mic_desc_ctx {
u8 pending[4];
size_t pending_len;
u32 l, r;
};
static inline u32 xswap(u32 val)
{
return ((val & 0x00ff00ff) << 8) | ((val & 0xff00ff00) >> 8);
}
#define michael_block(l, r) \
do { \
r ^= rol32(l, 17); \
l += r; \
r ^= xswap(l); \
l += r; \
r ^= rol32(l, 3); \
l += r; \
r ^= ror32(l, 2); \
l += r; \
} while (0)
static int michael_init(struct shash_desc *desc)
{
struct michael_mic_desc_ctx *mctx = shash_desc_ctx(desc);
struct michael_mic_ctx *ctx = crypto_shash_ctx(desc->tfm);
mctx->pending_len = 0;
mctx->l = ctx->l;
mctx->r = ctx->r;
return 0;
}
static int michael_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
struct michael_mic_desc_ctx *mctx = shash_desc_ctx(desc);
const __le32 *src;
if (mctx->pending_len) {
int flen = 4 - mctx->pending_len;
if (flen > len)
flen = len;
memcpy(&mctx->pending[mctx->pending_len], data, flen);
mctx->pending_len += flen;
data += flen;
len -= flen;
if (mctx->pending_len < 4)
return 0;
src = (const __le32 *)mctx->pending;
mctx->l ^= le32_to_cpup(src);
michael_block(mctx->l, mctx->r);
mctx->pending_len = 0;
}
src = (const __le32 *)data;
while (len >= 4) {
mctx->l ^= le32_to_cpup(src++);
michael_block(mctx->l, mctx->r);
len -= 4;
}
if (len > 0) {
mctx->pending_len = len;
memcpy(mctx->pending, src, len);
}
return 0;
}
static int michael_final(struct shash_desc *desc, u8 *out)
{
struct michael_mic_desc_ctx *mctx = shash_desc_ctx(desc);
u8 *data = mctx->pending;
__le32 *dst = (__le32 *)out;
/* Last block and padding (0x5a, 4..7 x 0) */
switch (mctx->pending_len) {
case 0:
mctx->l ^= 0x5a;
break;
case 1:
mctx->l ^= data[0] | 0x5a00;
break;
case 2:
mctx->l ^= data[0] | (data[1] << 8) | 0x5a0000;
break;
case 3:
mctx->l ^= data[0] | (data[1] << 8) | (data[2] << 16) |
0x5a000000;
break;
}
michael_block(mctx->l, mctx->r);
/* l ^= 0; */
michael_block(mctx->l, mctx->r);
dst[0] = cpu_to_le32(mctx->l);
dst[1] = cpu_to_le32(mctx->r);
return 0;
}
static int michael_setkey(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
struct michael_mic_ctx *mctx = crypto_shash_ctx(tfm);
const __le32 *data = (const __le32 *)key;
if (keylen != 8) {
crypto_shash_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
mctx->l = le32_to_cpu(data[0]);
mctx->r = le32_to_cpu(data[1]);
return 0;
}
static struct shash_alg alg = {
.digestsize = 8,
.setkey = michael_setkey,
.init = michael_init,
.update = michael_update,
.final = michael_final,
.descsize = sizeof(struct michael_mic_desc_ctx),
.base = {
.cra_name = "michael_mic",
.cra_blocksize = 8,
.cra_alignmask = 3,
.cra_ctxsize = sizeof(struct michael_mic_ctx),
.cra_module = THIS_MODULE,
}
};
static int __init michael_mic_init(void)
{
return crypto_register_shash(&alg);
}
static void __exit michael_mic_exit(void)
{
crypto_unregister_shash(&alg);
}
module_init(michael_mic_init);
module_exit(michael_mic_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Michael MIC");
MODULE_AUTHOR("Jouni Malinen <j@w1.fi>");
| gpl-2.0 |
eckucukoglu/sober-kernel | drivers/net/irda/old_belkin-sir.c | 12533 | 4838 | /*********************************************************************
*
* Filename: old_belkin.c
* Version: 1.1
* Description: Driver for the Belkin (old) SmartBeam dongle
* Status: Experimental...
* Author: Jean Tourrilhes <jt@hpl.hp.com>
* Created at: 22/11/99
* Modified at: Fri Dec 17 09:13:32 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1999 Jean Tourrilhes, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <net/irda/irda.h>
// #include <net/irda/irda_device.h>
#include "sir-dev.h"
/*
* Belkin is selling a dongle called the SmartBeam.
* In fact, there is two hardware version of this dongle, of course with
* the same name and looking the exactly same (grrr...).
* I guess that I've got the old one, because inside I don't have
* a jumper for IrDA/ASK...
*
* As far as I can make it from info on their web site, the old dongle
* support only 9600 b/s, which make our life much simpler as far as
* the driver is concerned, but you might not like it very much ;-)
* The new SmartBeam does 115 kb/s, and I've not tested it...
*
* Belkin claim that the correct driver for the old dongle (in Windows)
* is the generic Parallax 9500a driver, but the Linux LiteLink driver
* fails for me (probably because Linux-IrDA doesn't rate fallback),
* so I created this really dumb driver...
*
* In fact, this driver doesn't do much. The only thing it does is to
* prevent Linux-IrDA to use any other speed than 9600 b/s ;-) This
* driver is called "old_belkin" so that when the new SmartBeam is supported
* its driver can be called "belkin" instead of "new_belkin".
*
* Note : this driver was written without any info/help from Belkin,
* so a lot of info here might be totally wrong. Blame me ;-)
*/
static int old_belkin_open(struct sir_dev *dev);
static int old_belkin_close(struct sir_dev *dev);
static int old_belkin_change_speed(struct sir_dev *dev, unsigned speed);
static int old_belkin_reset(struct sir_dev *dev);
static struct dongle_driver old_belkin = {
.owner = THIS_MODULE,
.driver_name = "Old Belkin SmartBeam",
.type = IRDA_OLD_BELKIN_DONGLE,
.open = old_belkin_open,
.close = old_belkin_close,
.reset = old_belkin_reset,
.set_speed = old_belkin_change_speed,
};
static int __init old_belkin_sir_init(void)
{
return irda_register_dongle(&old_belkin);
}
static void __exit old_belkin_sir_cleanup(void)
{
irda_unregister_dongle(&old_belkin);
}
static int old_belkin_open(struct sir_dev *dev)
{
struct qos_info *qos = &dev->qos;
IRDA_DEBUG(2, "%s()\n", __func__);
/* Power on dongle */
sirdev_set_dtr_rts(dev, TRUE, TRUE);
/* Not too fast, please... */
qos->baud_rate.bits &= IR_9600;
/* Needs at least 10 ms (totally wild guess, can do probably better) */
qos->min_turn_time.bits = 0x01;
irda_qos_bits_to_value(qos);
/* irda thread waits 50 msec for power settling */
return 0;
}
static int old_belkin_close(struct sir_dev *dev)
{
IRDA_DEBUG(2, "%s()\n", __func__);
/* Power off dongle */
sirdev_set_dtr_rts(dev, FALSE, FALSE);
return 0;
}
/*
* Function old_belkin_change_speed (task)
*
* With only one speed available, not much to do...
*/
static int old_belkin_change_speed(struct sir_dev *dev, unsigned speed)
{
IRDA_DEBUG(2, "%s()\n", __func__);
dev->speed = 9600;
return (speed==dev->speed) ? 0 : -EINVAL;
}
/*
* Function old_belkin_reset (task)
*
* Reset the Old-Belkin type dongle.
*
*/
static int old_belkin_reset(struct sir_dev *dev)
{
IRDA_DEBUG(2, "%s()\n", __func__);
/* This dongles speed "defaults" to 9600 bps ;-) */
dev->speed = 9600;
return 0;
}
MODULE_AUTHOR("Jean Tourrilhes <jt@hpl.hp.com>");
MODULE_DESCRIPTION("Belkin (old) SmartBeam dongle driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("irda-dongle-7"); /* IRDA_OLD_BELKIN_DONGLE */
module_init(old_belkin_sir_init);
module_exit(old_belkin_sir_cleanup);
| gpl-2.0 |
keily90/tf101-nv-linux | arch/m68k/lib/checksum_mm.c | 14069 | 10633 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* IP/TCP/UDP checksumming routines
*
* Authors: Jorge Cwik, <jorge@laser.satlink.net>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Tom May, <ftom@netcom.com>
* Andreas Schwab, <schwab@issan.informatik.uni-dortmund.de>
* Lots of code moved from tcp.c and ip.c; see those files
* for more names.
*
* 03/02/96 Jes Sorensen, Andreas Schwab, Roman Hodek:
* Fixed some nasty bugs, causing some horrible crashes.
* A: At some points, the sum (%0) was used as
* length-counter instead of the length counter
* (%1). Thanks to Roman Hodek for pointing this out.
* B: GCC seems to mess up if one uses too many
* data-registers to hold input values and one tries to
* specify d0 and d1 as scratch registers. Letting gcc
* choose these registers itself solves the problem.
*
* 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.
*
* 1998/8/31 Andreas Schwab:
* Zero out rest of buffer on exception in
* csum_partial_copy_from_user.
*/
#include <linux/module.h>
#include <net/checksum.h>
/*
* computes a partial checksum, e.g. for TCP/UDP fragments
*/
__wsum csum_partial(const void *buff, int len, __wsum sum)
{
unsigned long tmp1, tmp2;
/*
* Experiments with ethernet and slip connections show that buff
* is aligned on either a 2-byte or 4-byte boundary.
*/
__asm__("movel %2,%3\n\t"
"btst #1,%3\n\t" /* Check alignment */
"jeq 2f\n\t"
"subql #2,%1\n\t" /* buff%4==2: treat first word */
"jgt 1f\n\t"
"addql #2,%1\n\t" /* len was == 2, treat only rest */
"jra 4f\n"
"1:\t"
"addw %2@+,%0\n\t" /* add first word to sum */
"clrl %3\n\t"
"addxl %3,%0\n" /* add X bit */
"2:\t"
/* unrolled loop for the main part: do 8 longs at once */
"movel %1,%3\n\t" /* save len in tmp1 */
"lsrl #5,%1\n\t" /* len/32 */
"jeq 2f\n\t" /* not enough... */
"subql #1,%1\n"
"1:\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"dbra %1,1b\n\t"
"clrl %4\n\t"
"addxl %4,%0\n\t" /* add X bit */
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 1b\n"
"2:\t"
"movel %3,%1\n\t" /* restore len from tmp1 */
"andw #0x1c,%3\n\t" /* number of rest longs */
"jeq 4f\n\t"
"lsrw #2,%3\n\t"
"subqw #1,%3\n"
"3:\t"
/* loop for rest longs */
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"dbra %3,3b\n\t"
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"4:\t"
/* now check for rest bytes that do not fit into longs */
"andw #3,%1\n\t"
"jeq 7f\n\t"
"clrl %4\n\t" /* clear tmp2 for rest bytes */
"subqw #2,%1\n\t"
"jlt 5f\n\t"
"movew %2@+,%4\n\t" /* have rest >= 2: get word */
"swap %4\n\t" /* into bits 16..31 */
"tstw %1\n\t" /* another byte? */
"jeq 6f\n"
"5:\t"
"moveb %2@,%4\n\t" /* have odd rest: get byte */
"lslw #8,%4\n\t" /* into bits 8..15; 16..31 untouched */
"6:\t"
"addl %4,%0\n\t" /* now add rest long to sum */
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"7:\t"
: "=d" (sum), "=d" (len), "=a" (buff),
"=&d" (tmp1), "=&d" (tmp2)
: "0" (sum), "1" (len), "2" (buff)
);
return(sum);
}
EXPORT_SYMBOL(csum_partial);
/*
* copy from user space while checksumming, with exception handling.
*/
__wsum
csum_partial_copy_from_user(const void __user *src, void *dst,
int len, __wsum sum, int *csum_err)
{
/*
* GCC doesn't like more than 10 operands for the asm
* statements so we have to use tmp2 for the error
* code.
*/
unsigned long tmp1, tmp2;
__asm__("movel %2,%4\n\t"
"btst #1,%4\n\t" /* Check alignment */
"jeq 2f\n\t"
"subql #2,%1\n\t" /* buff%4==2: treat first word */
"jgt 1f\n\t"
"addql #2,%1\n\t" /* len was == 2, treat only rest */
"jra 4f\n"
"1:\n"
"10:\t"
"movesw %2@+,%4\n\t" /* add first word to sum */
"addw %4,%0\n\t"
"movew %4,%3@+\n\t"
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"2:\t"
/* unrolled loop for the main part: do 8 longs at once */
"movel %1,%4\n\t" /* save len in tmp1 */
"lsrl #5,%1\n\t" /* len/32 */
"jeq 2f\n\t" /* not enough... */
"subql #1,%1\n"
"1:\n"
"11:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"12:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"13:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"14:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"15:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"16:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"17:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"18:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %1,1b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n\t" /* add X bit */
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 1b\n"
"2:\t"
"movel %4,%1\n\t" /* restore len from tmp1 */
"andw #0x1c,%4\n\t" /* number of rest longs */
"jeq 4f\n\t"
"lsrw #2,%4\n\t"
"subqw #1,%4\n"
"3:\n"
/* loop for rest longs */
"19:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %4,3b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n" /* add X bit */
"4:\t"
/* now check for rest bytes that do not fit into longs */
"andw #3,%1\n\t"
"jeq 7f\n\t"
"clrl %5\n\t" /* clear tmp2 for rest bytes */
"subqw #2,%1\n\t"
"jlt 5f\n\t"
"20:\t"
"movesw %2@+,%5\n\t" /* have rest >= 2: get word */
"movew %5,%3@+\n\t"
"swap %5\n\t" /* into bits 16..31 */
"tstw %1\n\t" /* another byte? */
"jeq 6f\n"
"5:\n"
"21:\t"
"movesb %2@,%5\n\t" /* have odd rest: get byte */
"moveb %5,%3@+\n\t"
"lslw #8,%5\n\t" /* into bits 8..15; 16..31 untouched */
"6:\t"
"addl %5,%0\n\t" /* now add rest long to sum */
"clrl %5\n\t"
"addxl %5,%0\n\t" /* add X bit */
"7:\t"
"clrl %5\n" /* no error - clear return value */
"8:\n"
".section .fixup,\"ax\"\n"
".even\n"
/* If any exception occurs zero out the rest.
Similarities with the code above are intentional :-) */
"90:\t"
"clrw %3@+\n\t"
"movel %1,%4\n\t"
"lsrl #5,%1\n\t"
"jeq 1f\n\t"
"subql #1,%1\n"
"91:\t"
"clrl %3@+\n"
"92:\t"
"clrl %3@+\n"
"93:\t"
"clrl %3@+\n"
"94:\t"
"clrl %3@+\n"
"95:\t"
"clrl %3@+\n"
"96:\t"
"clrl %3@+\n"
"97:\t"
"clrl %3@+\n"
"98:\t"
"clrl %3@+\n\t"
"dbra %1,91b\n\t"
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 91b\n"
"1:\t"
"movel %4,%1\n\t"
"andw #0x1c,%4\n\t"
"jeq 1f\n\t"
"lsrw #2,%4\n\t"
"subqw #1,%4\n"
"99:\t"
"clrl %3@+\n\t"
"dbra %4,99b\n\t"
"1:\t"
"andw #3,%1\n\t"
"jeq 9f\n"
"100:\t"
"clrw %3@+\n\t"
"tstw %1\n\t"
"jeq 9f\n"
"101:\t"
"clrb %3@+\n"
"9:\t"
#define STR(X) STR1(X)
#define STR1(X) #X
"moveq #-" STR(EFAULT) ",%5\n\t"
"jra 8b\n"
".previous\n"
".section __ex_table,\"a\"\n"
".long 10b,90b\n"
".long 11b,91b\n"
".long 12b,92b\n"
".long 13b,93b\n"
".long 14b,94b\n"
".long 15b,95b\n"
".long 16b,96b\n"
".long 17b,97b\n"
".long 18b,98b\n"
".long 19b,99b\n"
".long 20b,100b\n"
".long 21b,101b\n"
".previous"
: "=d" (sum), "=d" (len), "=a" (src), "=a" (dst),
"=&d" (tmp1), "=d" (tmp2)
: "0" (sum), "1" (len), "2" (src), "3" (dst)
);
*csum_err = tmp2;
return(sum);
}
EXPORT_SYMBOL(csum_partial_copy_from_user);
/*
* copy from kernel space while checksumming, otherwise like csum_partial
*/
__wsum
csum_partial_copy_nocheck(const void *src, void *dst, int len, __wsum sum)
{
unsigned long tmp1, tmp2;
__asm__("movel %2,%4\n\t"
"btst #1,%4\n\t" /* Check alignment */
"jeq 2f\n\t"
"subql #2,%1\n\t" /* buff%4==2: treat first word */
"jgt 1f\n\t"
"addql #2,%1\n\t" /* len was == 2, treat only rest */
"jra 4f\n"
"1:\t"
"movew %2@+,%4\n\t" /* add first word to sum */
"addw %4,%0\n\t"
"movew %4,%3@+\n\t"
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"2:\t"
/* unrolled loop for the main part: do 8 longs at once */
"movel %1,%4\n\t" /* save len in tmp1 */
"lsrl #5,%1\n\t" /* len/32 */
"jeq 2f\n\t" /* not enough... */
"subql #1,%1\n"
"1:\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %1,1b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n\t" /* add X bit */
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 1b\n"
"2:\t"
"movel %4,%1\n\t" /* restore len from tmp1 */
"andw #0x1c,%4\n\t" /* number of rest longs */
"jeq 4f\n\t"
"lsrw #2,%4\n\t"
"subqw #1,%4\n"
"3:\t"
/* loop for rest longs */
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %4,3b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n" /* add X bit */
"4:\t"
/* now check for rest bytes that do not fit into longs */
"andw #3,%1\n\t"
"jeq 7f\n\t"
"clrl %5\n\t" /* clear tmp2 for rest bytes */
"subqw #2,%1\n\t"
"jlt 5f\n\t"
"movew %2@+,%5\n\t" /* have rest >= 2: get word */
"movew %5,%3@+\n\t"
"swap %5\n\t" /* into bits 16..31 */
"tstw %1\n\t" /* another byte? */
"jeq 6f\n"
"5:\t"
"moveb %2@,%5\n\t" /* have odd rest: get byte */
"moveb %5,%3@+\n\t"
"lslw #8,%5\n" /* into bits 8..15; 16..31 untouched */
"6:\t"
"addl %5,%0\n\t" /* now add rest long to sum */
"clrl %5\n\t"
"addxl %5,%0\n" /* add X bit */
"7:\t"
: "=d" (sum), "=d" (len), "=a" (src), "=a" (dst),
"=&d" (tmp1), "=&d" (tmp2)
: "0" (sum), "1" (len), "2" (src), "3" (dst)
);
return(sum);
}
EXPORT_SYMBOL(csum_partial_copy_nocheck);
| gpl-2.0 |
TeamBliss-Devices/kernel_xiaomi_cancro | drivers/usb/dwc3/debugfs.c | 502 | 29137 | /**
* debugfs.c - DesignWare USB3 DRD Controller DebugFS file
*
* Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
*
* Authors: Felipe Balbi <balbi@ti.com>,
* Sebastian Andrzej Siewior <bigeasy@linutronix.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The names of the above-listed copyright holders may not be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2, as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/ptrace.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include <linux/usb/ch9.h>
#include "core.h"
#include "gadget.h"
#include "io.h"
#include "debug.h"
#define dump_register(nm) \
{ \
.name = __stringify(nm), \
.offset = DWC3_ ##nm - DWC3_GLOBALS_REGS_START, \
}
static const struct debugfs_reg32 dwc3_regs[] = {
dump_register(GSBUSCFG0),
dump_register(GSBUSCFG1),
dump_register(GTXTHRCFG),
dump_register(GRXTHRCFG),
dump_register(GCTL),
dump_register(GEVTEN),
dump_register(GSTS),
dump_register(GSNPSID),
dump_register(GGPIO),
dump_register(GUID),
dump_register(GUCTL),
dump_register(GBUSERRADDR0),
dump_register(GBUSERRADDR1),
dump_register(GPRTBIMAP0),
dump_register(GPRTBIMAP1),
dump_register(GHWPARAMS0),
dump_register(GHWPARAMS1),
dump_register(GHWPARAMS2),
dump_register(GHWPARAMS3),
dump_register(GHWPARAMS4),
dump_register(GHWPARAMS5),
dump_register(GHWPARAMS6),
dump_register(GHWPARAMS7),
dump_register(GDBGFIFOSPACE),
dump_register(GDBGLTSSM),
dump_register(GPRTBIMAP_HS0),
dump_register(GPRTBIMAP_HS1),
dump_register(GPRTBIMAP_FS0),
dump_register(GPRTBIMAP_FS1),
dump_register(GUSB2PHYCFG(0)),
dump_register(GUSB2PHYCFG(1)),
dump_register(GUSB2PHYCFG(2)),
dump_register(GUSB2PHYCFG(3)),
dump_register(GUSB2PHYCFG(4)),
dump_register(GUSB2PHYCFG(5)),
dump_register(GUSB2PHYCFG(6)),
dump_register(GUSB2PHYCFG(7)),
dump_register(GUSB2PHYCFG(8)),
dump_register(GUSB2PHYCFG(9)),
dump_register(GUSB2PHYCFG(10)),
dump_register(GUSB2PHYCFG(11)),
dump_register(GUSB2PHYCFG(12)),
dump_register(GUSB2PHYCFG(13)),
dump_register(GUSB2PHYCFG(14)),
dump_register(GUSB2PHYCFG(15)),
dump_register(GUSB2I2CCTL(0)),
dump_register(GUSB2I2CCTL(1)),
dump_register(GUSB2I2CCTL(2)),
dump_register(GUSB2I2CCTL(3)),
dump_register(GUSB2I2CCTL(4)),
dump_register(GUSB2I2CCTL(5)),
dump_register(GUSB2I2CCTL(6)),
dump_register(GUSB2I2CCTL(7)),
dump_register(GUSB2I2CCTL(8)),
dump_register(GUSB2I2CCTL(9)),
dump_register(GUSB2I2CCTL(10)),
dump_register(GUSB2I2CCTL(11)),
dump_register(GUSB2I2CCTL(12)),
dump_register(GUSB2I2CCTL(13)),
dump_register(GUSB2I2CCTL(14)),
dump_register(GUSB2I2CCTL(15)),
dump_register(GUSB2PHYACC(0)),
dump_register(GUSB2PHYACC(1)),
dump_register(GUSB2PHYACC(2)),
dump_register(GUSB2PHYACC(3)),
dump_register(GUSB2PHYACC(4)),
dump_register(GUSB2PHYACC(5)),
dump_register(GUSB2PHYACC(6)),
dump_register(GUSB2PHYACC(7)),
dump_register(GUSB2PHYACC(8)),
dump_register(GUSB2PHYACC(9)),
dump_register(GUSB2PHYACC(10)),
dump_register(GUSB2PHYACC(11)),
dump_register(GUSB2PHYACC(12)),
dump_register(GUSB2PHYACC(13)),
dump_register(GUSB2PHYACC(14)),
dump_register(GUSB2PHYACC(15)),
dump_register(GUSB3PIPECTL(0)),
dump_register(GUSB3PIPECTL(1)),
dump_register(GUSB3PIPECTL(2)),
dump_register(GUSB3PIPECTL(3)),
dump_register(GUSB3PIPECTL(4)),
dump_register(GUSB3PIPECTL(5)),
dump_register(GUSB3PIPECTL(6)),
dump_register(GUSB3PIPECTL(7)),
dump_register(GUSB3PIPECTL(8)),
dump_register(GUSB3PIPECTL(9)),
dump_register(GUSB3PIPECTL(10)),
dump_register(GUSB3PIPECTL(11)),
dump_register(GUSB3PIPECTL(12)),
dump_register(GUSB3PIPECTL(13)),
dump_register(GUSB3PIPECTL(14)),
dump_register(GUSB3PIPECTL(15)),
dump_register(GTXFIFOSIZ(0)),
dump_register(GTXFIFOSIZ(1)),
dump_register(GTXFIFOSIZ(2)),
dump_register(GTXFIFOSIZ(3)),
dump_register(GTXFIFOSIZ(4)),
dump_register(GTXFIFOSIZ(5)),
dump_register(GTXFIFOSIZ(6)),
dump_register(GTXFIFOSIZ(7)),
dump_register(GTXFIFOSIZ(8)),
dump_register(GTXFIFOSIZ(9)),
dump_register(GTXFIFOSIZ(10)),
dump_register(GTXFIFOSIZ(11)),
dump_register(GTXFIFOSIZ(12)),
dump_register(GTXFIFOSIZ(13)),
dump_register(GTXFIFOSIZ(14)),
dump_register(GTXFIFOSIZ(15)),
dump_register(GTXFIFOSIZ(16)),
dump_register(GTXFIFOSIZ(17)),
dump_register(GTXFIFOSIZ(18)),
dump_register(GTXFIFOSIZ(19)),
dump_register(GTXFIFOSIZ(20)),
dump_register(GTXFIFOSIZ(21)),
dump_register(GTXFIFOSIZ(22)),
dump_register(GTXFIFOSIZ(23)),
dump_register(GTXFIFOSIZ(24)),
dump_register(GTXFIFOSIZ(25)),
dump_register(GTXFIFOSIZ(26)),
dump_register(GTXFIFOSIZ(27)),
dump_register(GTXFIFOSIZ(28)),
dump_register(GTXFIFOSIZ(29)),
dump_register(GTXFIFOSIZ(30)),
dump_register(GTXFIFOSIZ(31)),
dump_register(GRXFIFOSIZ(0)),
dump_register(GRXFIFOSIZ(1)),
dump_register(GRXFIFOSIZ(2)),
dump_register(GRXFIFOSIZ(3)),
dump_register(GRXFIFOSIZ(4)),
dump_register(GRXFIFOSIZ(5)),
dump_register(GRXFIFOSIZ(6)),
dump_register(GRXFIFOSIZ(7)),
dump_register(GRXFIFOSIZ(8)),
dump_register(GRXFIFOSIZ(9)),
dump_register(GRXFIFOSIZ(10)),
dump_register(GRXFIFOSIZ(11)),
dump_register(GRXFIFOSIZ(12)),
dump_register(GRXFIFOSIZ(13)),
dump_register(GRXFIFOSIZ(14)),
dump_register(GRXFIFOSIZ(15)),
dump_register(GRXFIFOSIZ(16)),
dump_register(GRXFIFOSIZ(17)),
dump_register(GRXFIFOSIZ(18)),
dump_register(GRXFIFOSIZ(19)),
dump_register(GRXFIFOSIZ(20)),
dump_register(GRXFIFOSIZ(21)),
dump_register(GRXFIFOSIZ(22)),
dump_register(GRXFIFOSIZ(23)),
dump_register(GRXFIFOSIZ(24)),
dump_register(GRXFIFOSIZ(25)),
dump_register(GRXFIFOSIZ(26)),
dump_register(GRXFIFOSIZ(27)),
dump_register(GRXFIFOSIZ(28)),
dump_register(GRXFIFOSIZ(29)),
dump_register(GRXFIFOSIZ(30)),
dump_register(GRXFIFOSIZ(31)),
dump_register(GEVNTADRLO(0)),
dump_register(GEVNTADRHI(0)),
dump_register(GEVNTSIZ(0)),
dump_register(GEVNTCOUNT(0)),
dump_register(GHWPARAMS8),
dump_register(GFLADJ),
dump_register(DCFG),
dump_register(DCTL),
dump_register(DEVTEN),
dump_register(DSTS),
dump_register(DGCMDPAR),
dump_register(DGCMD),
dump_register(DALEPENA),
dump_register(DEPCMDPAR2(0)),
dump_register(DEPCMDPAR2(1)),
dump_register(DEPCMDPAR2(2)),
dump_register(DEPCMDPAR2(3)),
dump_register(DEPCMDPAR2(4)),
dump_register(DEPCMDPAR2(5)),
dump_register(DEPCMDPAR2(6)),
dump_register(DEPCMDPAR2(7)),
dump_register(DEPCMDPAR2(8)),
dump_register(DEPCMDPAR2(9)),
dump_register(DEPCMDPAR2(10)),
dump_register(DEPCMDPAR2(11)),
dump_register(DEPCMDPAR2(12)),
dump_register(DEPCMDPAR2(13)),
dump_register(DEPCMDPAR2(14)),
dump_register(DEPCMDPAR2(15)),
dump_register(DEPCMDPAR2(16)),
dump_register(DEPCMDPAR2(17)),
dump_register(DEPCMDPAR2(18)),
dump_register(DEPCMDPAR2(19)),
dump_register(DEPCMDPAR2(20)),
dump_register(DEPCMDPAR2(21)),
dump_register(DEPCMDPAR2(22)),
dump_register(DEPCMDPAR2(23)),
dump_register(DEPCMDPAR2(24)),
dump_register(DEPCMDPAR2(25)),
dump_register(DEPCMDPAR2(26)),
dump_register(DEPCMDPAR2(27)),
dump_register(DEPCMDPAR2(28)),
dump_register(DEPCMDPAR2(29)),
dump_register(DEPCMDPAR2(30)),
dump_register(DEPCMDPAR2(31)),
dump_register(DEPCMDPAR1(0)),
dump_register(DEPCMDPAR1(1)),
dump_register(DEPCMDPAR1(2)),
dump_register(DEPCMDPAR1(3)),
dump_register(DEPCMDPAR1(4)),
dump_register(DEPCMDPAR1(5)),
dump_register(DEPCMDPAR1(6)),
dump_register(DEPCMDPAR1(7)),
dump_register(DEPCMDPAR1(8)),
dump_register(DEPCMDPAR1(9)),
dump_register(DEPCMDPAR1(10)),
dump_register(DEPCMDPAR1(11)),
dump_register(DEPCMDPAR1(12)),
dump_register(DEPCMDPAR1(13)),
dump_register(DEPCMDPAR1(14)),
dump_register(DEPCMDPAR1(15)),
dump_register(DEPCMDPAR1(16)),
dump_register(DEPCMDPAR1(17)),
dump_register(DEPCMDPAR1(18)),
dump_register(DEPCMDPAR1(19)),
dump_register(DEPCMDPAR1(20)),
dump_register(DEPCMDPAR1(21)),
dump_register(DEPCMDPAR1(22)),
dump_register(DEPCMDPAR1(23)),
dump_register(DEPCMDPAR1(24)),
dump_register(DEPCMDPAR1(25)),
dump_register(DEPCMDPAR1(26)),
dump_register(DEPCMDPAR1(27)),
dump_register(DEPCMDPAR1(28)),
dump_register(DEPCMDPAR1(29)),
dump_register(DEPCMDPAR1(30)),
dump_register(DEPCMDPAR1(31)),
dump_register(DEPCMDPAR0(0)),
dump_register(DEPCMDPAR0(1)),
dump_register(DEPCMDPAR0(2)),
dump_register(DEPCMDPAR0(3)),
dump_register(DEPCMDPAR0(4)),
dump_register(DEPCMDPAR0(5)),
dump_register(DEPCMDPAR0(6)),
dump_register(DEPCMDPAR0(7)),
dump_register(DEPCMDPAR0(8)),
dump_register(DEPCMDPAR0(9)),
dump_register(DEPCMDPAR0(10)),
dump_register(DEPCMDPAR0(11)),
dump_register(DEPCMDPAR0(12)),
dump_register(DEPCMDPAR0(13)),
dump_register(DEPCMDPAR0(14)),
dump_register(DEPCMDPAR0(15)),
dump_register(DEPCMDPAR0(16)),
dump_register(DEPCMDPAR0(17)),
dump_register(DEPCMDPAR0(18)),
dump_register(DEPCMDPAR0(19)),
dump_register(DEPCMDPAR0(20)),
dump_register(DEPCMDPAR0(21)),
dump_register(DEPCMDPAR0(22)),
dump_register(DEPCMDPAR0(23)),
dump_register(DEPCMDPAR0(24)),
dump_register(DEPCMDPAR0(25)),
dump_register(DEPCMDPAR0(26)),
dump_register(DEPCMDPAR0(27)),
dump_register(DEPCMDPAR0(28)),
dump_register(DEPCMDPAR0(29)),
dump_register(DEPCMDPAR0(30)),
dump_register(DEPCMDPAR0(31)),
dump_register(DEPCMD(0)),
dump_register(DEPCMD(1)),
dump_register(DEPCMD(2)),
dump_register(DEPCMD(3)),
dump_register(DEPCMD(4)),
dump_register(DEPCMD(5)),
dump_register(DEPCMD(6)),
dump_register(DEPCMD(7)),
dump_register(DEPCMD(8)),
dump_register(DEPCMD(9)),
dump_register(DEPCMD(10)),
dump_register(DEPCMD(11)),
dump_register(DEPCMD(12)),
dump_register(DEPCMD(13)),
dump_register(DEPCMD(14)),
dump_register(DEPCMD(15)),
dump_register(DEPCMD(16)),
dump_register(DEPCMD(17)),
dump_register(DEPCMD(18)),
dump_register(DEPCMD(19)),
dump_register(DEPCMD(20)),
dump_register(DEPCMD(21)),
dump_register(DEPCMD(22)),
dump_register(DEPCMD(23)),
dump_register(DEPCMD(24)),
dump_register(DEPCMD(25)),
dump_register(DEPCMD(26)),
dump_register(DEPCMD(27)),
dump_register(DEPCMD(28)),
dump_register(DEPCMD(29)),
dump_register(DEPCMD(30)),
dump_register(DEPCMD(31)),
dump_register(OCFG),
dump_register(OCTL),
dump_register(OEVTEN),
dump_register(OSTS),
};
static int dwc3_regdump_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
seq_printf(s, "DesignWare USB3 Core Register Dump\n");
debugfs_print_regs32(s, dwc3_regs, ARRAY_SIZE(dwc3_regs),
dwc->regs, "");
return 0;
}
static int dwc3_regdump_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_regdump_show, inode->i_private);
}
static const struct file_operations dwc3_regdump_fops = {
.open = dwc3_regdump_open,
.read = seq_read,
.release = single_release,
};
static int dwc3_mode_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
unsigned long flags;
u32 reg;
spin_lock_irqsave(&dwc->lock, flags);
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
spin_unlock_irqrestore(&dwc->lock, flags);
switch (DWC3_GCTL_PRTCAP(reg)) {
case DWC3_GCTL_PRTCAP_HOST:
seq_printf(s, "host\n");
break;
case DWC3_GCTL_PRTCAP_DEVICE:
seq_printf(s, "device\n");
break;
case DWC3_GCTL_PRTCAP_OTG:
seq_printf(s, "OTG\n");
break;
default:
seq_printf(s, "UNKNOWN %08x\n", DWC3_GCTL_PRTCAP(reg));
}
return 0;
}
static int dwc3_mode_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_mode_show, inode->i_private);
}
static ssize_t dwc3_mode_write(struct file *file,
const char __user *ubuf, size_t count, loff_t *ppos)
{
struct seq_file *s = file->private_data;
struct dwc3 *dwc = s->private;
unsigned long flags;
u32 mode = 0;
char buf[32];
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
if (!strncmp(buf, "host", 4))
mode |= DWC3_GCTL_PRTCAP_HOST;
if (!strncmp(buf, "device", 6))
mode |= DWC3_GCTL_PRTCAP_DEVICE;
if (!strncmp(buf, "otg", 3))
mode |= DWC3_GCTL_PRTCAP_OTG;
if (mode) {
spin_lock_irqsave(&dwc->lock, flags);
dwc3_set_mode(dwc, mode);
spin_unlock_irqrestore(&dwc->lock, flags);
}
return count;
}
static const struct file_operations dwc3_mode_fops = {
.open = dwc3_mode_open,
.write = dwc3_mode_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int dwc3_testmode_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
unsigned long flags;
u32 reg;
spin_lock_irqsave(&dwc->lock, flags);
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
reg &= DWC3_DCTL_TSTCTRL_MASK;
reg >>= 1;
spin_unlock_irqrestore(&dwc->lock, flags);
switch (reg) {
case 0:
seq_printf(s, "no test\n");
break;
case TEST_J:
seq_printf(s, "test_j\n");
break;
case TEST_K:
seq_printf(s, "test_k\n");
break;
case TEST_SE0_NAK:
seq_printf(s, "test_se0_nak\n");
break;
case TEST_PACKET:
seq_printf(s, "test_packet\n");
break;
case TEST_FORCE_EN:
seq_printf(s, "test_force_enable\n");
break;
default:
seq_printf(s, "UNKNOWN %d\n", reg);
}
return 0;
}
static int dwc3_testmode_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_testmode_show, inode->i_private);
}
static ssize_t dwc3_testmode_write(struct file *file,
const char __user *ubuf, size_t count, loff_t *ppos)
{
struct seq_file *s = file->private_data;
struct dwc3 *dwc = s->private;
unsigned long flags;
u32 testmode = 0;
char buf[32];
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
if (!strncmp(buf, "test_j", 6))
testmode = TEST_J;
else if (!strncmp(buf, "test_k", 6))
testmode = TEST_K;
else if (!strncmp(buf, "test_se0_nak", 12))
testmode = TEST_SE0_NAK;
else if (!strncmp(buf, "test_packet", 11))
testmode = TEST_PACKET;
else if (!strncmp(buf, "test_force_enable", 17))
testmode = TEST_FORCE_EN;
else
testmode = 0;
spin_lock_irqsave(&dwc->lock, flags);
dwc3_gadget_set_test_mode(dwc, testmode);
spin_unlock_irqrestore(&dwc->lock, flags);
return count;
}
static const struct file_operations dwc3_testmode_fops = {
.open = dwc3_testmode_open,
.write = dwc3_testmode_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int dwc3_link_state_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
unsigned long flags;
enum dwc3_link_state state;
u32 reg;
spin_lock_irqsave(&dwc->lock, flags);
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
state = DWC3_DSTS_USBLNKST(reg);
spin_unlock_irqrestore(&dwc->lock, flags);
switch (state) {
case DWC3_LINK_STATE_U0:
seq_printf(s, "U0\n");
break;
case DWC3_LINK_STATE_U1:
seq_printf(s, "U1\n");
break;
case DWC3_LINK_STATE_U2:
seq_printf(s, "U2\n");
break;
case DWC3_LINK_STATE_U3:
seq_printf(s, "U3\n");
break;
case DWC3_LINK_STATE_SS_DIS:
seq_printf(s, "SS.Disabled\n");
break;
case DWC3_LINK_STATE_RX_DET:
seq_printf(s, "Rx.Detect\n");
break;
case DWC3_LINK_STATE_SS_INACT:
seq_printf(s, "SS.Inactive\n");
break;
case DWC3_LINK_STATE_POLL:
seq_printf(s, "Poll\n");
break;
case DWC3_LINK_STATE_RECOV:
seq_printf(s, "Recovery\n");
break;
case DWC3_LINK_STATE_HRESET:
seq_printf(s, "HRESET\n");
break;
case DWC3_LINK_STATE_CMPLY:
seq_printf(s, "Compliance\n");
break;
case DWC3_LINK_STATE_LPBK:
seq_printf(s, "Loopback\n");
break;
default:
seq_printf(s, "UNKNOWN %d\n", reg);
}
return 0;
}
static int dwc3_link_state_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_link_state_show, inode->i_private);
}
static ssize_t dwc3_link_state_write(struct file *file,
const char __user *ubuf, size_t count, loff_t *ppos)
{
struct seq_file *s = file->private_data;
struct dwc3 *dwc = s->private;
unsigned long flags;
enum dwc3_link_state state = 0;
char buf[32];
if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
return -EFAULT;
if (!strncmp(buf, "SS.Disabled", 11))
state = DWC3_LINK_STATE_SS_DIS;
else if (!strncmp(buf, "Rx.Detect", 9))
state = DWC3_LINK_STATE_RX_DET;
else if (!strncmp(buf, "SS.Inactive", 11))
state = DWC3_LINK_STATE_SS_INACT;
else if (!strncmp(buf, "Recovery", 8))
state = DWC3_LINK_STATE_RECOV;
else if (!strncmp(buf, "Compliance", 10))
state = DWC3_LINK_STATE_CMPLY;
else if (!strncmp(buf, "Loopback", 8))
state = DWC3_LINK_STATE_LPBK;
else
return -EINVAL;
spin_lock_irqsave(&dwc->lock, flags);
dwc3_gadget_set_link_state(dwc, state);
spin_unlock_irqrestore(&dwc->lock, flags);
return count;
}
static const struct file_operations dwc3_link_state_fops = {
.open = dwc3_link_state_open,
.write = dwc3_link_state_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int ep_num;
static ssize_t dwc3_store_ep_num(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct seq_file *s = file->private_data;
struct dwc3 *dwc = s->private;
char kbuf[10];
unsigned int num, dir;
unsigned long flags;
memset(kbuf, 0, 10);
if (copy_from_user(kbuf, ubuf, count > 10 ? 10 : count))
return -EFAULT;
if (sscanf(kbuf, "%u %u", &num, &dir) != 2)
return -EINVAL;
spin_lock_irqsave(&dwc->lock, flags);
ep_num = (num << 1) + dir;
spin_unlock_irqrestore(&dwc->lock, flags);
return count;
}
static int dwc3_ep_req_list_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
struct dwc3_ep *dep;
struct dwc3_request *req = NULL;
struct list_head *ptr = NULL;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
dep = dwc->eps[ep_num];
seq_printf(s, "%s request list: flags: 0x%x\n", dep->name, dep->flags);
list_for_each(ptr, &dep->request_list) {
req = list_entry(ptr, struct dwc3_request, list);
seq_printf(s,
"req:0x%p len: %d sts: %d dma:0x%pa num_sgs: %d\n",
req, req->request.length, req->request.status,
&req->request.dma, req->request.num_sgs);
}
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
static int dwc3_ep_req_list_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_ep_req_list_show, inode->i_private);
}
static const struct file_operations dwc3_ep_req_list_fops = {
.open = dwc3_ep_req_list_open,
.write = dwc3_store_ep_num,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int dwc3_ep_queued_req_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
struct dwc3_ep *dep;
struct dwc3_request *req = NULL;
struct list_head *ptr = NULL;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
dep = dwc->eps[ep_num];
seq_printf(s, "%s queued reqs to HW: flags:0x%x\n", dep->name,
dep->flags);
list_for_each(ptr, &dep->req_queued) {
req = list_entry(ptr, struct dwc3_request, list);
seq_printf(s,
"req:0x%p len:%d sts:%d dma:%pa nsg:%d trb:0x%p\n",
req, req->request.length, req->request.status,
&req->request.dma, req->request.num_sgs, req->trb);
}
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
static int dwc3_ep_queued_req_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_ep_queued_req_show, inode->i_private);
}
const struct file_operations dwc3_ep_req_queued_fops = {
.open = dwc3_ep_queued_req_open,
.write = dwc3_store_ep_num,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int dwc3_ep_trbs_show(struct seq_file *s, void *unused)
{
struct dwc3 *dwc = s->private;
struct dwc3_ep *dep;
struct dwc3_trb *trb;
unsigned long flags;
int j;
if (!ep_num)
return 0;
spin_lock_irqsave(&dwc->lock, flags);
dep = dwc->eps[ep_num];
seq_printf(s, "%s trb pool: flags:0x%x freeslot:%d busyslot:%d\n",
dep->name, dep->flags, dep->free_slot, dep->busy_slot);
for (j = 0; j < DWC3_TRB_NUM; j++) {
trb = &dep->trb_pool[j];
seq_printf(s, "trb:0x%p bph:0x%x bpl:0x%x size:0x%x ctrl: %x\n",
trb, trb->bph, trb->bpl, trb->size, trb->ctrl);
}
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
static int dwc3_ep_trbs_list_open(struct inode *inode, struct file *file)
{
return single_open(file, dwc3_ep_trbs_show, inode->i_private);
}
const struct file_operations dwc3_ep_trb_list_fops = {
.open = dwc3_ep_trbs_list_open,
.write = dwc3_store_ep_num,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static unsigned int ep_addr_rxdbg_mask = 1;
module_param(ep_addr_rxdbg_mask, uint, S_IRUGO | S_IWUSR);
static unsigned int ep_addr_txdbg_mask = 1;
module_param(ep_addr_txdbg_mask, uint, S_IRUGO | S_IWUSR);
/* Maximum debug message length */
#define DBG_DATA_MSG 64UL
/* Maximum number of messages */
#define DBG_DATA_MAX 128UL
static struct {
char (buf[DBG_DATA_MAX])[DBG_DATA_MSG]; /* buffer */
unsigned idx; /* index */
unsigned tty; /* print to console? */
rwlock_t lck; /* lock */
} dbg_dwc3_data = {
.idx = 0,
.tty = 0,
.lck = __RW_LOCK_UNLOCKED(lck)
};
/**
* dbg_dec: decrements debug event index
* @idx: buffer index
*/
static inline void __maybe_unused dbg_dec(unsigned *idx)
{
*idx = (*idx - 1) % DBG_DATA_MAX;
}
/**
* dbg_inc: increments debug event index
* @idx: buffer index
*/
static inline void dbg_inc(unsigned *idx)
{
*idx = (*idx + 1) % DBG_DATA_MAX;
}
#define TIME_BUF_LEN 20
/*get_timestamp - returns time of day in us */
static char *get_timestamp(char *tbuf)
{
unsigned long long t;
unsigned long nanosec_rem;
t = cpu_clock(smp_processor_id());
nanosec_rem = do_div(t, 1000000000)/1000;
scnprintf(tbuf, TIME_BUF_LEN, "[%5lu.%06lu] ", (unsigned long)t,
nanosec_rem);
return tbuf;
}
static int allow_dbg_print(u8 ep_num)
{
int dir, num;
/* allow bus wide events */
if (ep_num == 0xff)
return 1;
dir = ep_num & 0x1;
num = ep_num >> 1;
num = 1 << num;
if (dir && (num & ep_addr_txdbg_mask))
return 1;
if (!dir && (num & ep_addr_rxdbg_mask))
return 1;
return 0;
}
/**
* dbg_print: prints the common part of the event
* @addr: endpoint address
* @name: event name
* @status: status
* @extra: extra information
*/
void dbg_print(u8 ep_num, const char *name, int status, const char *extra)
{
unsigned long flags;
char tbuf[TIME_BUF_LEN];
if (!allow_dbg_print(ep_num))
return;
write_lock_irqsave(&dbg_dwc3_data.lck, flags);
scnprintf(dbg_dwc3_data.buf[dbg_dwc3_data.idx], DBG_DATA_MSG,
"%s\t? %02X %-7.7s %4i ?\t%s\n",
get_timestamp(tbuf), ep_num, name, status, extra);
dbg_inc(&dbg_dwc3_data.idx);
write_unlock_irqrestore(&dbg_dwc3_data.lck, flags);
if (dbg_dwc3_data.tty != 0)
pr_notice("%s\t? %02X %-7.7s %4i ?\t%s\n",
get_timestamp(tbuf), ep_num, name, status, extra);
}
/**
* dbg_done: prints a DONE event
* @addr: endpoint address
* @td: transfer descriptor
* @status: status
*/
void dbg_done(u8 ep_num, const u32 count, int status)
{
char msg[DBG_DATA_MSG];
if (!allow_dbg_print(ep_num))
return;
scnprintf(msg, sizeof(msg), "%d", count);
dbg_print(ep_num, "DONE", status, msg);
}
/**
* dbg_event: prints a generic event
* @addr: endpoint address
* @name: event name
* @status: status
*/
void dbg_event(u8 ep_num, const char *name, int status)
{
if (!allow_dbg_print(ep_num))
return;
if (name != NULL)
dbg_print(ep_num, name, status, "");
}
/*
* dbg_queue: prints a QUEUE event
* @addr: endpoint address
* @req: USB request
* @status: status
*/
void dbg_queue(u8 ep_num, const struct usb_request *req, int status)
{
char msg[DBG_DATA_MSG];
if (!allow_dbg_print(ep_num))
return;
if (req != NULL) {
scnprintf(msg, sizeof(msg),
"%d %d", !req->no_interrupt, req->length);
dbg_print(ep_num, "QUEUE", status, msg);
}
}
/**
* dbg_setup: prints a SETUP event
* @addr: endpoint address
* @req: setup request
*/
void dbg_setup(u8 ep_num, const struct usb_ctrlrequest *req)
{
char msg[DBG_DATA_MSG];
if (!allow_dbg_print(ep_num))
return;
if (req != NULL) {
scnprintf(msg, sizeof(msg),
"%02X %02X %04X %04X %d", req->bRequestType,
req->bRequest, le16_to_cpu(req->wValue),
le16_to_cpu(req->wIndex), le16_to_cpu(req->wLength));
dbg_print(ep_num, "SETUP", 0, msg);
}
}
/**
* dbg_print_reg: prints a reg value
* @name: reg name
* @reg: reg value to be printed
*/
void dbg_print_reg(const char *name, int reg)
{
unsigned long flags;
write_lock_irqsave(&dbg_dwc3_data.lck, flags);
scnprintf(dbg_dwc3_data.buf[dbg_dwc3_data.idx], DBG_DATA_MSG,
"%s = 0x%08x\n", name, reg);
dbg_inc(&dbg_dwc3_data.idx);
write_unlock_irqrestore(&dbg_dwc3_data.lck, flags);
if (dbg_dwc3_data.tty != 0)
pr_notice("%s = 0x%08x\n", name, reg);
}
/**
* store_events: configure if events are going to be also printed to console
*
*/
static ssize_t dwc3_store_events(struct file *file,
const char __user *buf, size_t count, loff_t *ppos)
{
unsigned tty;
if (buf == NULL) {
pr_err("[%s] EINVAL\n", __func__);
goto done;
}
if (sscanf(buf, "%u", &tty) != 1 || tty > 1) {
pr_err("<1|0>: enable|disable console log\n");
goto done;
}
dbg_dwc3_data.tty = tty;
pr_info("tty = %u", dbg_dwc3_data.tty);
done:
return count;
}
static int dwc3_gadget_data_events_show(struct seq_file *s, void *unused)
{
unsigned long flags;
unsigned i;
read_lock_irqsave(&dbg_dwc3_data.lck, flags);
i = dbg_dwc3_data.idx;
if (strnlen(dbg_dwc3_data.buf[i], DBG_DATA_MSG))
seq_printf(s, "%s\n", dbg_dwc3_data.buf[i]);
for (dbg_inc(&i); i != dbg_dwc3_data.idx; dbg_inc(&i)) {
if (!strnlen(dbg_dwc3_data.buf[i], DBG_DATA_MSG))
continue;
seq_printf(s, "%s\n", dbg_dwc3_data.buf[i]);
}
read_unlock_irqrestore(&dbg_dwc3_data.lck, flags);
return 0;
}
static int dwc3_gadget_data_events_open(struct inode *inode, struct file *f)
{
return single_open(f, dwc3_gadget_data_events_show, inode->i_private);
}
const struct file_operations dwc3_gadget_dbg_data_fops = {
.open = dwc3_gadget_data_events_open,
.read = seq_read,
.write = dwc3_store_events,
.llseek = seq_lseek,
.release = single_release,
};
int __devinit dwc3_debugfs_init(struct dwc3 *dwc)
{
struct dentry *root;
struct dentry *file;
int ret;
root = debugfs_create_dir(dev_name(dwc->dev), NULL);
if (!root) {
ret = -ENOMEM;
goto err0;
}
dwc->root = root;
file = debugfs_create_file("regdump", S_IRUGO, root, dwc,
&dwc3_regdump_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("mode", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_mode_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("testmode", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_testmode_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("link_state", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_link_state_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("trbs", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_ep_trb_list_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("requests", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_ep_req_list_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("queued_reqs", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_ep_req_queued_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
file = debugfs_create_file("events", S_IRUGO | S_IWUSR, root,
dwc, &dwc3_gadget_dbg_data_fops);
if (!file) {
ret = -ENOMEM;
goto err1;
}
return 0;
err1:
debugfs_remove_recursive(root);
err0:
return ret;
}
void __devexit dwc3_debugfs_exit(struct dwc3 *dwc)
{
debugfs_remove_recursive(dwc->root);
dwc->root = NULL;
}
| gpl-2.0 |
MTDEV-KERNEL/MOTO-KERNEL | mm/swap_state.c | 502 | 10674 | /*
* linux/mm/swap_state.c
*
* Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
* Swap reorganised 29.12.95, Stephen Tweedie
*
* Rewritten to use page cache, (C) 1998 Stephen Tweedie
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/kernel_stat.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/buffer_head.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include <linux/migrate.h>
#include <linux/page_cgroup.h>
#include <asm/pgtable.h>
/*
* swapper_space is a fiction, retained to simplify the path through
* vmscan's shrink_page_list, to make sync_page look nicer, and to allow
* future use of radix_tree tags in the swap cache.
*/
static const struct address_space_operations swap_aops = {
.writepage = swap_writepage,
.sync_page = block_sync_page,
.set_page_dirty = __set_page_dirty_nobuffers,
.migratepage = migrate_page,
};
static struct backing_dev_info swap_backing_dev_info = {
.name = "swap",
.capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK | BDI_CAP_SWAP_BACKED,
.unplug_io_fn = swap_unplug_io_fn,
};
struct address_space swapper_space = {
.page_tree = RADIX_TREE_INIT(GFP_ATOMIC|__GFP_NOWARN),
.tree_lock = __SPIN_LOCK_UNLOCKED(swapper_space.tree_lock),
.a_ops = &swap_aops,
.i_mmap_nonlinear = LIST_HEAD_INIT(swapper_space.i_mmap_nonlinear),
.backing_dev_info = &swap_backing_dev_info,
};
#define INC_CACHE_INFO(x) do { swap_cache_info.x++; } while (0)
static struct {
unsigned long add_total;
unsigned long del_total;
unsigned long find_success;
unsigned long find_total;
} swap_cache_info;
void show_swap_cache_info(void)
{
printk("%lu pages in swap cache\n", total_swapcache_pages);
printk("Swap cache stats: add %lu, delete %lu, find %lu/%lu\n",
swap_cache_info.add_total, swap_cache_info.del_total,
swap_cache_info.find_success, swap_cache_info.find_total);
printk("Free swap = %ldkB\n", nr_swap_pages << (PAGE_SHIFT - 10));
printk("Total swap = %lukB\n", total_swap_pages << (PAGE_SHIFT - 10));
}
/*
* __add_to_swap_cache resembles add_to_page_cache_locked on swapper_space,
* but sets SwapCache flag and private instead of mapping and index.
*/
static int __add_to_swap_cache(struct page *page, swp_entry_t entry)
{
int error;
VM_BUG_ON(!PageLocked(page));
VM_BUG_ON(PageSwapCache(page));
VM_BUG_ON(!PageSwapBacked(page));
page_cache_get(page);
SetPageSwapCache(page);
set_page_private(page, entry.val);
spin_lock_irq(&swapper_space.tree_lock);
error = radix_tree_insert(&swapper_space.page_tree, entry.val, page);
if (likely(!error)) {
total_swapcache_pages++;
__inc_zone_page_state(page, NR_FILE_PAGES);
INC_CACHE_INFO(add_total);
}
spin_unlock_irq(&swapper_space.tree_lock);
if (unlikely(error)) {
/*
* Only the context which have set SWAP_HAS_CACHE flag
* would call add_to_swap_cache().
* So add_to_swap_cache() doesn't returns -EEXIST.
*/
VM_BUG_ON(error == -EEXIST);
set_page_private(page, 0UL);
ClearPageSwapCache(page);
page_cache_release(page);
}
return error;
}
int add_to_swap_cache(struct page *page, swp_entry_t entry, gfp_t gfp_mask)
{
int error;
error = radix_tree_preload(gfp_mask);
if (!error) {
error = __add_to_swap_cache(page, entry);
radix_tree_preload_end();
}
return error;
}
/*
* This must be called only on pages that have
* been verified to be in the swap cache.
*/
void __delete_from_swap_cache(struct page *page)
{
VM_BUG_ON(!PageLocked(page));
VM_BUG_ON(!PageSwapCache(page));
VM_BUG_ON(PageWriteback(page));
radix_tree_delete(&swapper_space.page_tree, page_private(page));
set_page_private(page, 0);
ClearPageSwapCache(page);
total_swapcache_pages--;
__dec_zone_page_state(page, NR_FILE_PAGES);
INC_CACHE_INFO(del_total);
}
/**
* add_to_swap - allocate swap space for a page
* @page: page we want to move to swap
*
* Allocate swap space for the page and add the page to the
* swap cache. Caller needs to hold the page lock.
*/
int add_to_swap(struct page *page)
{
swp_entry_t entry;
int err;
VM_BUG_ON(!PageLocked(page));
VM_BUG_ON(!PageUptodate(page));
entry = get_swap_page();
if (!entry.val)
return 0;
/*
* Radix-tree node allocations from PF_MEMALLOC contexts could
* completely exhaust the page allocator. __GFP_NOMEMALLOC
* stops emergency reserves from being allocated.
*
* TODO: this could cause a theoretical memory reclaim
* deadlock in the swap out path.
*/
/*
* Add it to the swap cache and mark it dirty
*/
err = add_to_swap_cache(page, entry,
__GFP_HIGH|__GFP_NOMEMALLOC|__GFP_NOWARN);
if (!err) { /* Success */
SetPageDirty(page);
return 1;
} else { /* -ENOMEM radix-tree allocation failure */
/*
* add_to_swap_cache() doesn't return -EEXIST, so we can safely
* clear SWAP_HAS_CACHE flag.
*/
swapcache_free(entry, NULL);
return 0;
}
}
/*
* This must be called only on pages that have
* been verified to be in the swap cache and locked.
* It will never put the page into the free list,
* the caller has a reference on the page.
*/
void delete_from_swap_cache(struct page *page)
{
swp_entry_t entry;
entry.val = page_private(page);
spin_lock_irq(&swapper_space.tree_lock);
__delete_from_swap_cache(page);
spin_unlock_irq(&swapper_space.tree_lock);
swapcache_free(entry, page);
page_cache_release(page);
}
/*
* If we are the only user, then try to free up the swap cache.
*
* Its ok to check for PageSwapCache without the page lock
* here because we are going to recheck again inside
* try_to_free_swap() _with_ the lock.
* - Marcelo
*/
static inline void free_swap_cache(struct page *page)
{
if (PageSwapCache(page) && !page_mapped(page) && trylock_page(page)) {
try_to_free_swap(page);
unlock_page(page);
}
}
/*
* Perform a free_page(), also freeing any swap cache associated with
* this page if it is the last user of the page.
*/
void free_page_and_swap_cache(struct page *page)
{
free_swap_cache(page);
page_cache_release(page);
}
/*
* Passed an array of pages, drop them all from swapcache and then release
* them. They are removed from the LRU and freed if this is their last use.
*/
void free_pages_and_swap_cache(struct page **pages, int nr)
{
struct page **pagep = pages;
lru_add_drain();
while (nr) {
int todo = min(nr, PAGEVEC_SIZE);
int i;
for (i = 0; i < todo; i++)
free_swap_cache(pagep[i]);
release_pages(pagep, todo, 0);
pagep += todo;
nr -= todo;
}
}
/*
* Lookup a swap entry in the swap cache. A found page will be returned
* unlocked and with its refcount incremented - we rely on the kernel
* lock getting page table operations atomic even if we drop the page
* lock before returning.
*/
struct page * lookup_swap_cache(swp_entry_t entry)
{
struct page *page;
page = find_get_page(&swapper_space, entry.val);
if (page)
INC_CACHE_INFO(find_success);
INC_CACHE_INFO(find_total);
return page;
}
/*
* Locate a page of swap in physical memory, reserving swap cache space
* and reading the disk if it is not already cached.
* A failure return means that either the page allocation failed or that
* the swap entry is no longer in use.
*/
struct page *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
struct vm_area_struct *vma, unsigned long addr)
{
struct page *found_page, *new_page = NULL;
int err;
do {
/*
* First check the swap cache. Since this is normally
* called after lookup_swap_cache() failed, re-calling
* that would confuse statistics.
*/
found_page = find_get_page(&swapper_space, entry.val);
if (found_page)
break;
/*
* Get a new page to read into from swap.
*/
if (!new_page) {
new_page = alloc_page_vma(gfp_mask, vma, addr);
if (!new_page)
break; /* Out of memory */
}
/*
* call radix_tree_preload() while we can wait.
*/
err = radix_tree_preload(gfp_mask & GFP_KERNEL);
if (err)
break;
/*
* Swap entry may have been freed since our caller observed it.
*/
err = swapcache_prepare(entry);
if (err == -EEXIST) { /* seems racy */
radix_tree_preload_end();
continue;
}
if (err) { /* swp entry is obsolete ? */
radix_tree_preload_end();
break;
}
/* May fail (-ENOMEM) if radix-tree node allocation failed. */
__set_page_locked(new_page);
SetPageSwapBacked(new_page);
err = __add_to_swap_cache(new_page, entry);
if (likely(!err)) {
radix_tree_preload_end();
/*
* Initiate read into locked page and return.
*/
lru_cache_add_anon(new_page);
swap_readpage(new_page);
return new_page;
}
radix_tree_preload_end();
ClearPageSwapBacked(new_page);
__clear_page_locked(new_page);
/*
* add_to_swap_cache() doesn't return -EEXIST, so we can safely
* clear SWAP_HAS_CACHE flag.
*/
swapcache_free(entry, NULL);
} while (err != -ENOMEM);
if (new_page)
page_cache_release(new_page);
return found_page;
}
/**
* swapin_readahead - swap in pages in hope we need them soon
* @entry: swap entry of this memory
* @gfp_mask: memory allocation flags
* @vma: user vma this address belongs to
* @addr: target address for mempolicy
*
* Returns the struct page for entry and addr, after queueing swapin.
*
* Primitive swap readahead code. We simply read an aligned block of
* (1 << page_cluster) entries in the swap area. This method is chosen
* because it doesn't cost us any seek time. We also make sure to queue
* the 'original' request together with the readahead ones...
*
* This has been extended to use the NUMA policies from the mm triggering
* the readahead.
*
* Caller must hold down_read on the vma->vm_mm if vma is not NULL.
*/
struct page *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
struct vm_area_struct *vma, unsigned long addr)
{
int nr_pages;
struct page *page;
unsigned long offset;
unsigned long end_offset;
/*
* Get starting offset for readaround, and number of pages to read.
* Adjust starting address by readbehind (for NUMA interleave case)?
* No, it's very unlikely that swap layout would follow vma layout,
* more likely that neighbouring swap pages came from the same node:
* so use the same "addr" to choose the same node for each swap read.
*/
nr_pages = valid_swaphandles(entry, &offset);
for (end_offset = offset + nr_pages; offset < end_offset; offset++) {
/* Ok, do the async read-ahead now */
page = read_swap_cache_async(swp_entry(swp_type(entry), offset),
gfp_mask, vma, addr);
if (!page)
break;
page_cache_release(page);
}
lru_add_drain(); /* Push any new pages onto the LRU now */
return read_swap_cache_async(entry, gfp_mask, vma, addr);
}
| gpl-2.0 |
netico-solutions/linux-amxx | drivers/usb/serial/visor.c | 758 | 19069 | /*
* USB HandSpring Visor, Palm m50x, and Sony Clie driver
* (supports all of the Palm OS USB devices)
*
* Copyright (C) 1999 - 2004
* Greg Kroah-Hartman (greg@kroah.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.
*
* See Documentation/usb/usb-serial.txt for more information on using this
* driver
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/usb/cdc.h>
#include "visor.h"
/*
* Version Information
*/
#define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com>"
#define DRIVER_DESC "USB HandSpring Visor / Palm OS driver"
/* function prototypes for a handspring visor */
static int visor_open(struct tty_struct *tty, struct usb_serial_port *port);
static void visor_close(struct usb_serial_port *port);
static int visor_probe(struct usb_serial *serial,
const struct usb_device_id *id);
static int visor_calc_num_ports(struct usb_serial *serial);
static void visor_read_int_callback(struct urb *urb);
static int clie_3_5_startup(struct usb_serial *serial);
static int treo_attach(struct usb_serial *serial);
static int clie_5_attach(struct usb_serial *serial);
static int palm_os_3_probe(struct usb_serial *serial,
const struct usb_device_id *id);
static int palm_os_4_probe(struct usb_serial *serial,
const struct usb_device_id *id);
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(HANDSPRING_VENDOR_ID, HANDSPRING_VISOR_ID),
.driver_info = (kernel_ulong_t)&palm_os_3_probe },
{ USB_DEVICE(HANDSPRING_VENDOR_ID, HANDSPRING_TREO_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(HANDSPRING_VENDOR_ID, HANDSPRING_TREO600_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(GSPDA_VENDOR_ID, GSPDA_XPLORE_M68_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M500_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M505_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M515_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_I705_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M100_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M125_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M130_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_TUNGSTEN_T_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_TREO_650),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_TUNGSTEN_Z_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_ZIRE_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_4_0_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_S360_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_4_1_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_NX60_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_NZ90V_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_TJ25_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(ACER_VENDOR_ID, ACER_S10_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SAMSUNG_VENDOR_ID, SAMSUNG_SCH_I330_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(SAMSUNG_VENDOR_ID, SAMSUNG_SPH_I500_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(TAPWAVE_VENDOR_ID, TAPWAVE_ZODIAC_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(GARMIN_VENDOR_ID, GARMIN_IQUE_3600_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(ACEECA_VENDOR_ID, ACEECA_MEZ1000_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(KYOCERA_VENDOR_ID, KYOCERA_7135_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ USB_DEVICE(FOSSIL_VENDOR_ID, FOSSIL_ABACUS_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ } /* Terminating entry */
};
static const struct usb_device_id clie_id_5_table[] = {
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_UX50_ID),
.driver_info = (kernel_ulong_t)&palm_os_4_probe },
{ } /* Terminating entry */
};
static const struct usb_device_id clie_id_3_5_table[] = {
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_3_5_ID) },
{ } /* Terminating entry */
};
static const struct usb_device_id id_table_combined[] = {
{ USB_DEVICE(HANDSPRING_VENDOR_ID, HANDSPRING_VISOR_ID) },
{ USB_DEVICE(HANDSPRING_VENDOR_ID, HANDSPRING_TREO_ID) },
{ USB_DEVICE(HANDSPRING_VENDOR_ID, HANDSPRING_TREO600_ID) },
{ USB_DEVICE(GSPDA_VENDOR_ID, GSPDA_XPLORE_M68_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M500_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M505_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M515_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_I705_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M100_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M125_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_M130_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_TUNGSTEN_T_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_TREO_650) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_TUNGSTEN_Z_ID) },
{ USB_DEVICE(PALM_VENDOR_ID, PALM_ZIRE_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_3_5_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_4_0_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_S360_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_4_1_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_NX60_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_NZ90V_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_UX50_ID) },
{ USB_DEVICE(SONY_VENDOR_ID, SONY_CLIE_TJ25_ID) },
{ USB_DEVICE(SAMSUNG_VENDOR_ID, SAMSUNG_SCH_I330_ID) },
{ USB_DEVICE(SAMSUNG_VENDOR_ID, SAMSUNG_SPH_I500_ID) },
{ USB_DEVICE(TAPWAVE_VENDOR_ID, TAPWAVE_ZODIAC_ID) },
{ USB_DEVICE(GARMIN_VENDOR_ID, GARMIN_IQUE_3600_ID) },
{ USB_DEVICE(ACEECA_VENDOR_ID, ACEECA_MEZ1000_ID) },
{ USB_DEVICE(KYOCERA_VENDOR_ID, KYOCERA_7135_ID) },
{ USB_DEVICE(FOSSIL_VENDOR_ID, FOSSIL_ABACUS_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
/* All of the device info needed for the Handspring Visor,
and Palm 4.0 devices */
static struct usb_serial_driver handspring_device = {
.driver = {
.owner = THIS_MODULE,
.name = "visor",
},
.description = "Handspring Visor / Palm OS",
.id_table = id_table,
.num_ports = 2,
.bulk_out_size = 256,
.open = visor_open,
.close = visor_close,
.throttle = usb_serial_generic_throttle,
.unthrottle = usb_serial_generic_unthrottle,
.attach = treo_attach,
.probe = visor_probe,
.calc_num_ports = visor_calc_num_ports,
.read_int_callback = visor_read_int_callback,
};
/* All of the device info needed for the Clie UX50, TH55 Palm 5.0 devices */
static struct usb_serial_driver clie_5_device = {
.driver = {
.owner = THIS_MODULE,
.name = "clie_5",
},
.description = "Sony Clie 5.0",
.id_table = clie_id_5_table,
.num_ports = 2,
.bulk_out_size = 256,
.open = visor_open,
.close = visor_close,
.throttle = usb_serial_generic_throttle,
.unthrottle = usb_serial_generic_unthrottle,
.attach = clie_5_attach,
.probe = visor_probe,
.calc_num_ports = visor_calc_num_ports,
.read_int_callback = visor_read_int_callback,
};
/* device info for the Sony Clie OS version 3.5 */
static struct usb_serial_driver clie_3_5_device = {
.driver = {
.owner = THIS_MODULE,
.name = "clie_3.5",
},
.description = "Sony Clie 3.5",
.id_table = clie_id_3_5_table,
.num_ports = 1,
.bulk_out_size = 256,
.open = visor_open,
.close = visor_close,
.throttle = usb_serial_generic_throttle,
.unthrottle = usb_serial_generic_unthrottle,
.attach = clie_3_5_startup,
};
static struct usb_serial_driver * const serial_drivers[] = {
&handspring_device, &clie_5_device, &clie_3_5_device, NULL
};
/******************************************************************************
* Handspring Visor specific driver functions
******************************************************************************/
static int visor_open(struct tty_struct *tty, struct usb_serial_port *port)
{
int result = 0;
if (!port->read_urb) {
/* this is needed for some brain dead Sony devices */
dev_err(&port->dev, "Device lied about number of ports, please use a lower one.\n");
return -ENODEV;
}
/* Start reading from the device */
result = usb_serial_generic_open(tty, port);
if (result)
goto exit;
if (port->interrupt_in_urb) {
dev_dbg(&port->dev, "adding interrupt input for treo\n");
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result)
dev_err(&port->dev,
"%s - failed submitting interrupt urb, error %d\n",
__func__, result);
}
exit:
return result;
}
static void visor_close(struct usb_serial_port *port)
{
unsigned char *transfer_buffer;
usb_serial_generic_close(port);
usb_kill_urb(port->interrupt_in_urb);
transfer_buffer = kmalloc(0x12, GFP_KERNEL);
if (!transfer_buffer)
return;
usb_control_msg(port->serial->dev,
usb_rcvctrlpipe(port->serial->dev, 0),
VISOR_CLOSE_NOTIFICATION, 0xc2,
0x0000, 0x0000,
transfer_buffer, 0x12, 300);
kfree(transfer_buffer);
}
static void visor_read_int_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
int status = urb->status;
int result;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&port->dev, "%s - urb shutting down with status: %d\n",
__func__, status);
return;
default:
dev_dbg(&port->dev, "%s - nonzero urb status received: %d\n",
__func__, status);
goto exit;
}
/*
* This information is still unknown what it can be used for.
* If anyone has an idea, please let the author know...
*
* Rumor has it this endpoint is used to notify when data
* is ready to be read from the bulk ones.
*/
usb_serial_debug_data(&port->dev, __func__, urb->actual_length,
urb->transfer_buffer);
exit:
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_err(&urb->dev->dev,
"%s - Error %d submitting interrupt urb\n",
__func__, result);
}
static int palm_os_3_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
struct device *dev = &serial->dev->dev;
struct visor_connection_info *connection_info;
unsigned char *transfer_buffer;
char *string;
int retval = 0;
int i;
int num_ports = 0;
transfer_buffer = kmalloc(sizeof(*connection_info), GFP_KERNEL);
if (!transfer_buffer)
return -ENOMEM;
/* send a get connection info request */
retval = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
VISOR_GET_CONNECTION_INFORMATION,
0xc2, 0x0000, 0x0000, transfer_buffer,
sizeof(*connection_info), 300);
if (retval < 0) {
dev_err(dev, "%s - error %d getting connection information\n",
__func__, retval);
goto exit;
}
if (retval == sizeof(*connection_info)) {
connection_info = (struct visor_connection_info *)
transfer_buffer;
num_ports = le16_to_cpu(connection_info->num_ports);
for (i = 0; i < num_ports; ++i) {
switch (
connection_info->connections[i].port_function_id) {
case VISOR_FUNCTION_GENERIC:
string = "Generic";
break;
case VISOR_FUNCTION_DEBUGGER:
string = "Debugger";
break;
case VISOR_FUNCTION_HOTSYNC:
string = "HotSync";
break;
case VISOR_FUNCTION_CONSOLE:
string = "Console";
break;
case VISOR_FUNCTION_REMOTE_FILE_SYS:
string = "Remote File System";
break;
default:
string = "unknown";
break;
}
dev_info(dev, "%s: port %d, is for %s use\n",
serial->type->description,
connection_info->connections[i].port, string);
}
}
/*
* Handle devices that report invalid stuff here.
*/
if (num_ports == 0 || num_ports > 2) {
dev_warn(dev, "%s: No valid connect info available\n",
serial->type->description);
num_ports = 2;
}
dev_info(dev, "%s: Number of ports: %d\n", serial->type->description,
num_ports);
/*
* save off our num_ports info so that we can use it in the
* calc_num_ports callback
*/
usb_set_serial_data(serial, (void *)(long)num_ports);
/* ask for the number of bytes available, but ignore the
response as it is broken */
retval = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
VISOR_REQUEST_BYTES_AVAILABLE,
0xc2, 0x0000, 0x0005, transfer_buffer,
0x02, 300);
if (retval < 0)
dev_err(dev, "%s - error %d getting bytes available request\n",
__func__, retval);
retval = 0;
exit:
kfree(transfer_buffer);
return retval;
}
static int palm_os_4_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
struct device *dev = &serial->dev->dev;
struct palm_ext_connection_info *connection_info;
unsigned char *transfer_buffer;
int retval;
transfer_buffer = kmalloc(sizeof(*connection_info), GFP_KERNEL);
if (!transfer_buffer)
return -ENOMEM;
retval = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
PALM_GET_EXT_CONNECTION_INFORMATION,
0xc2, 0x0000, 0x0000, transfer_buffer,
sizeof(*connection_info), 300);
if (retval < 0)
dev_err(dev, "%s - error %d getting connection info\n",
__func__, retval);
else
usb_serial_debug_data(dev, __func__, retval, transfer_buffer);
kfree(transfer_buffer);
return 0;
}
static int visor_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
int retval = 0;
int (*startup)(struct usb_serial *serial,
const struct usb_device_id *id);
/*
* some Samsung Android phones in modem mode have the same ID
* as SPH-I500, but they are ACM devices, so dont bind to them
*/
if (id->idVendor == SAMSUNG_VENDOR_ID &&
id->idProduct == SAMSUNG_SPH_I500_ID &&
serial->dev->descriptor.bDeviceClass == USB_CLASS_COMM &&
serial->dev->descriptor.bDeviceSubClass ==
USB_CDC_SUBCLASS_ACM)
return -ENODEV;
if (serial->dev->actconfig->desc.bConfigurationValue != 1) {
dev_err(&serial->dev->dev, "active config #%d != 1 ??\n",
serial->dev->actconfig->desc.bConfigurationValue);
return -ENODEV;
}
if (id->driver_info) {
startup = (void *)id->driver_info;
retval = startup(serial, id);
}
return retval;
}
static int visor_calc_num_ports(struct usb_serial *serial)
{
int num_ports = (int)(long)(usb_get_serial_data(serial));
if (num_ports)
usb_set_serial_data(serial, NULL);
return num_ports;
}
static int clie_3_5_startup(struct usb_serial *serial)
{
struct device *dev = &serial->dev->dev;
int result;
u8 *data;
data = kmalloc(1, GFP_KERNEL);
if (!data)
return -ENOMEM;
/*
* Note that PEG-300 series devices expect the following two calls.
*/
/* get the config number */
result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
USB_REQ_GET_CONFIGURATION, USB_DIR_IN,
0, 0, data, 1, 3000);
if (result < 0) {
dev_err(dev, "%s: get config number failed: %d\n",
__func__, result);
goto out;
}
if (result != 1) {
dev_err(dev, "%s: get config number bad return length: %d\n",
__func__, result);
result = -EIO;
goto out;
}
/* get the interface number */
result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
USB_REQ_GET_INTERFACE,
USB_DIR_IN | USB_RECIP_INTERFACE,
0, 0, data, 1, 3000);
if (result < 0) {
dev_err(dev, "%s: get interface number failed: %d\n",
__func__, result);
goto out;
}
if (result != 1) {
dev_err(dev,
"%s: get interface number bad return length: %d\n",
__func__, result);
result = -EIO;
goto out;
}
result = 0;
out:
kfree(data);
return result;
}
static int treo_attach(struct usb_serial *serial)
{
struct usb_serial_port *swap_port;
/* Only do this endpoint hack for the Handspring devices with
* interrupt in endpoints, which for now are the Treo devices. */
if (!((le16_to_cpu(serial->dev->descriptor.idVendor)
== HANDSPRING_VENDOR_ID) ||
(le16_to_cpu(serial->dev->descriptor.idVendor)
== KYOCERA_VENDOR_ID)) ||
(serial->num_interrupt_in == 0))
return 0;
/*
* It appears that Treos and Kyoceras want to use the
* 1st bulk in endpoint to communicate with the 2nd bulk out endpoint,
* so let's swap the 1st and 2nd bulk in and interrupt endpoints.
* Note that swapping the bulk out endpoints would break lots of
* apps that want to communicate on the second port.
*/
#define COPY_PORT(dest, src) \
do { \
int i; \
\
for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \
dest->read_urbs[i] = src->read_urbs[i]; \
dest->read_urbs[i]->context = dest; \
dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \
} \
dest->read_urb = src->read_urb; \
dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\
dest->bulk_in_buffer = src->bulk_in_buffer; \
dest->bulk_in_size = src->bulk_in_size; \
dest->interrupt_in_urb = src->interrupt_in_urb; \
dest->interrupt_in_urb->context = dest; \
dest->interrupt_in_endpointAddress = \
src->interrupt_in_endpointAddress;\
dest->interrupt_in_buffer = src->interrupt_in_buffer; \
} while (0);
swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL);
if (!swap_port)
return -ENOMEM;
COPY_PORT(swap_port, serial->port[0]);
COPY_PORT(serial->port[0], serial->port[1]);
COPY_PORT(serial->port[1], swap_port);
kfree(swap_port);
return 0;
}
static int clie_5_attach(struct usb_serial *serial)
{
struct usb_serial_port *port;
unsigned int pipe;
int j;
/* TH55 registers 2 ports.
Communication in from the UX50/TH55 uses bulk_in_endpointAddress
from port 0. Communication out to the UX50/TH55 uses
bulk_out_endpointAddress from port 1
Lets do a quick and dirty mapping
*/
/* some sanity check */
if (serial->num_ports < 2)
return -1;
/* port 0 now uses the modified endpoint Address */
port = serial->port[0];
port->bulk_out_endpointAddress =
serial->port[1]->bulk_out_endpointAddress;
pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress);
for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j)
port->write_urbs[j]->pipe = pipe;
return 0;
}
module_usb_serial_driver(serial_drivers, id_table_combined);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
rumirand/GalaxyPlayer5-kernel | drivers/staging/comedi/drivers/adl_pci9111.c | 758 | 38950 | /*
comedi/drivers/adl_pci9111.c
Hardware driver for PCI9111 ADLink cards:
PCI-9111HR
Copyright (C) 2002-2005 Emmanuel Pacaud <emmanuel.pacaud@univ-poitiers.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: adl_pci9111
Description: Adlink PCI-9111HR
Author: Emmanuel Pacaud <emmanuel.pacaud@univ-poitiers.fr>
Devices: [ADLink] PCI-9111HR (adl_pci9111)
Status: experimental
Supports:
- ai_insn read
- ao_insn read/write
- di_insn read
- do_insn read/write
- ai_do_cmd mode with the following sources:
- start_src TRIG_NOW
- scan_begin_src TRIG_FOLLOW TRIG_TIMER TRIG_EXT
- convert_src TRIG_TIMER TRIG_EXT
- scan_end_src TRIG_COUNT
- stop_src TRIG_COUNT TRIG_NONE
The scanned channels must be consecutive and start from 0. They must
all have the same range and aref.
Configuration options:
[0] - PCI bus number (optional)
[1] - PCI slot number (optional)
If bus/slot is not specified, the first available PCI
device will be used.
*/
/*
CHANGELOG:
2005/02/17 Extend AI streaming capabilities. Now, scan_begin_arg can be
a multiple of chanlist_len*convert_arg.
2002/02/19 Fixed the two's complement conversion in pci9111_(hr_)ai_get_data.
2002/02/18 Added external trigger support for analog input.
TODO:
- Really test implemented functionality.
- Add support for the PCI-9111DG with a probe routine to identify the card type
(perhaps with the help of the channel number readback of the A/D Data register).
- Add external multiplexer support.
*/
#include "../comedidev.h"
#include <linux/delay.h>
#include <linux/interrupt.h>
#include "8253.h"
#include "comedi_pci.h"
#include "comedi_fc.h"
#define PCI9111_DRIVER_NAME "adl_pci9111"
#define PCI9111_HR_DEVICE_ID 0x9111
/* TODO: Add other pci9111 board id */
#define PCI9111_IO_RANGE 0x0100
#define PCI9111_FIFO_HALF_SIZE 512
#define PCI9111_AI_CHANNEL_NBR 16
#define PCI9111_AI_RESOLUTION 12
#define PCI9111_AI_RESOLUTION_MASK 0x0FFF
#define PCI9111_AI_RESOLUTION_2_CMP_BIT 0x0800
#define PCI9111_HR_AI_RESOLUTION 16
#define PCI9111_HR_AI_RESOLUTION_MASK 0xFFFF
#define PCI9111_HR_AI_RESOLUTION_2_CMP_BIT 0x8000
#define PCI9111_AI_ACQUISITION_PERIOD_MIN_NS 10000
#define PCI9111_AO_CHANNEL_NBR 1
#define PCI9111_AO_RESOLUTION 12
#define PCI9111_AO_RESOLUTION_MASK 0x0FFF
#define PCI9111_DI_CHANNEL_NBR 16
#define PCI9111_DO_CHANNEL_NBR 16
#define PCI9111_DO_MASK 0xFFFF
#define PCI9111_RANGE_SETTING_DELAY 10
#define PCI9111_AI_INSTANT_READ_UDELAY_US 2
#define PCI9111_AI_INSTANT_READ_TIMEOUT 100
#define PCI9111_8254_CLOCK_PERIOD_NS 500
#define PCI9111_8254_COUNTER_0 0x00
#define PCI9111_8254_COUNTER_1 0x40
#define PCI9111_8254_COUNTER_2 0x80
#define PCI9111_8254_COUNTER_LATCH 0x00
#define PCI9111_8254_READ_LOAD_LSB_ONLY 0x10
#define PCI9111_8254_READ_LOAD_MSB_ONLY 0x20
#define PCI9111_8254_READ_LOAD_LSB_MSB 0x30
#define PCI9111_8254_MODE_0 0x00
#define PCI9111_8254_MODE_1 0x02
#define PCI9111_8254_MODE_2 0x04
#define PCI9111_8254_MODE_3 0x06
#define PCI9111_8254_MODE_4 0x08
#define PCI9111_8254_MODE_5 0x0A
#define PCI9111_8254_BINARY_COUNTER 0x00
#define PCI9111_8254_BCD_COUNTER 0x01
/* IO address map */
#define PCI9111_REGISTER_AD_FIFO_VALUE 0x00 /* AD Data stored in FIFO */
#define PCI9111_REGISTER_DA_OUTPUT 0x00
#define PCI9111_REGISTER_DIGITAL_IO 0x02
#define PCI9111_REGISTER_EXTENDED_IO_PORTS 0x04
#define PCI9111_REGISTER_AD_CHANNEL_CONTROL 0x06 /* Channel selection */
#define PCI9111_REGISTER_AD_CHANNEL_READBACK 0x06
#define PCI9111_REGISTER_INPUT_SIGNAL_RANGE 0x08
#define PCI9111_REGISTER_RANGE_STATUS_READBACK 0x08
#define PCI9111_REGISTER_TRIGGER_MODE_CONTROL 0x0A
#define PCI9111_REGISTER_AD_MODE_INTERRUPT_READBACK 0x0A
#define PCI9111_REGISTER_SOFTWARE_TRIGGER 0x0E
#define PCI9111_REGISTER_INTERRUPT_CONTROL 0x0C
#define PCI9111_REGISTER_8254_COUNTER_0 0x40
#define PCI9111_REGISTER_8254_COUNTER_1 0x42
#define PCI9111_REGISTER_8254_COUNTER_2 0X44
#define PCI9111_REGISTER_8254_CONTROL 0x46
#define PCI9111_REGISTER_INTERRUPT_CLEAR 0x48
#define PCI9111_TRIGGER_MASK 0x0F
#define PCI9111_PTRG_OFF (0 << 3)
#define PCI9111_PTRG_ON (1 << 3)
#define PCI9111_EITS_EXTERNAL (1 << 2)
#define PCI9111_EITS_INTERNAL (0 << 2)
#define PCI9111_TPST_SOFTWARE_TRIGGER (0 << 1)
#define PCI9111_TPST_TIMER_PACER (1 << 1)
#define PCI9111_ASCAN_ON (1 << 0)
#define PCI9111_ASCAN_OFF (0 << 0)
#define PCI9111_ISC0_SET_IRQ_ON_ENDING_OF_AD_CONVERSION (0 << 0)
#define PCI9111_ISC0_SET_IRQ_ON_FIFO_HALF_FULL (1 << 0)
#define PCI9111_ISC1_SET_IRQ_ON_TIMER_TICK (0 << 1)
#define PCI9111_ISC1_SET_IRQ_ON_EXT_TRG (1 << 1)
#define PCI9111_FFEN_SET_FIFO_ENABLE (0 << 2)
#define PCI9111_FFEN_SET_FIFO_DISABLE (1 << 2)
#define PCI9111_CHANNEL_MASK 0x0F
#define PCI9111_RANGE_MASK 0x07
#define PCI9111_FIFO_EMPTY_MASK 0x10
#define PCI9111_FIFO_HALF_FULL_MASK 0x20
#define PCI9111_FIFO_FULL_MASK 0x40
#define PCI9111_AD_BUSY_MASK 0x80
#define PCI9111_IO_BASE dev->iobase
/*
* Define inlined function
*/
#define pci9111_trigger_and_autoscan_get() \
(inb(PCI9111_IO_BASE+PCI9111_REGISTER_AD_MODE_INTERRUPT_READBACK)&0x0F)
#define pci9111_trigger_and_autoscan_set(flags) \
outb(flags, PCI9111_IO_BASE+PCI9111_REGISTER_TRIGGER_MODE_CONTROL)
#define pci9111_interrupt_and_fifo_get() \
((inb(PCI9111_IO_BASE+PCI9111_REGISTER_AD_MODE_INTERRUPT_READBACK) >> 4) &0x03)
#define pci9111_interrupt_and_fifo_set(flags) \
outb(flags, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL)
#define pci9111_interrupt_clear() \
outb(0, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CLEAR)
#define pci9111_software_trigger() \
outb(0, PCI9111_IO_BASE+PCI9111_REGISTER_SOFTWARE_TRIGGER)
#define pci9111_fifo_reset() \
outb(PCI9111_FFEN_SET_FIFO_ENABLE, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL); \
outb(PCI9111_FFEN_SET_FIFO_DISABLE, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL); \
outb(PCI9111_FFEN_SET_FIFO_ENABLE, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL)
#define pci9111_is_fifo_full() \
((inb(PCI9111_IO_BASE+PCI9111_REGISTER_RANGE_STATUS_READBACK)& \
PCI9111_FIFO_FULL_MASK)==0)
#define pci9111_is_fifo_half_full() \
((inb(PCI9111_IO_BASE+PCI9111_REGISTER_RANGE_STATUS_READBACK)& \
PCI9111_FIFO_HALF_FULL_MASK)==0)
#define pci9111_is_fifo_empty() \
((inb(PCI9111_IO_BASE+PCI9111_REGISTER_RANGE_STATUS_READBACK)& \
PCI9111_FIFO_EMPTY_MASK)==0)
#define pci9111_ai_channel_set(channel) \
outb((channel)&PCI9111_CHANNEL_MASK, PCI9111_IO_BASE+PCI9111_REGISTER_AD_CHANNEL_CONTROL)
#define pci9111_ai_channel_get() \
inb(PCI9111_IO_BASE+PCI9111_REGISTER_AD_CHANNEL_READBACK)&PCI9111_CHANNEL_MASK
#define pci9111_ai_range_set(range) \
outb((range)&PCI9111_RANGE_MASK, PCI9111_IO_BASE+PCI9111_REGISTER_INPUT_SIGNAL_RANGE)
#define pci9111_ai_range_get() \
inb(PCI9111_IO_BASE+PCI9111_REGISTER_RANGE_STATUS_READBACK)&PCI9111_RANGE_MASK
#define pci9111_ai_get_data() \
((inw(PCI9111_IO_BASE+PCI9111_REGISTER_AD_FIFO_VALUE)>>4)&PCI9111_AI_RESOLUTION_MASK) \
^ PCI9111_AI_RESOLUTION_2_CMP_BIT
#define pci9111_hr_ai_get_data() \
(inw(PCI9111_IO_BASE+PCI9111_REGISTER_AD_FIFO_VALUE) & PCI9111_HR_AI_RESOLUTION_MASK) \
^ PCI9111_HR_AI_RESOLUTION_2_CMP_BIT
#define pci9111_ao_set_data(data) \
outw(data&PCI9111_AO_RESOLUTION_MASK, PCI9111_IO_BASE+PCI9111_REGISTER_DA_OUTPUT)
#define pci9111_di_get_bits() \
inw(PCI9111_IO_BASE+PCI9111_REGISTER_DIGITAL_IO)
#define pci9111_do_set_bits(bits) \
outw(bits, PCI9111_IO_BASE+PCI9111_REGISTER_DIGITAL_IO)
#define pci9111_8254_control_set(flags) \
outb(flags, PCI9111_IO_BASE+PCI9111_REGISTER_8254_CONTROL)
#define pci9111_8254_counter_0_set(data) \
outb(data & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_0); \
outb((data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_0)
#define pci9111_8254_counter_1_set(data) \
outb(data & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_1); \
outb((data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_1)
#define pci9111_8254_counter_2_set(data) \
outb(data & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_2); \
outb((data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_2)
/* Function prototypes */
static int pci9111_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int pci9111_detach(struct comedi_device *dev);
static void pci9111_ai_munge(struct comedi_device *dev,
struct comedi_subdevice *s, void *data,
unsigned int num_bytes,
unsigned int start_chan_index);
static const struct comedi_lrange pci9111_hr_ai_range = {
5,
{
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
BIP_RANGE(0.625)
}
};
static DEFINE_PCI_DEVICE_TABLE(pci9111_pci_table) = {
{
PCI_VENDOR_ID_ADLINK, PCI9111_HR_DEVICE_ID, PCI_ANY_ID,
PCI_ANY_ID, 0, 0, 0},
/* { PCI_VENDOR_ID_ADLINK, PCI9111_HG_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, */
{
0}
};
MODULE_DEVICE_TABLE(pci, pci9111_pci_table);
/* */
/* Board specification structure */
/* */
struct pci9111_board {
const char *name; /* driver name */
int device_id;
int ai_channel_nbr; /* num of A/D chans */
int ao_channel_nbr; /* num of D/A chans */
int ai_resolution; /* resolution of A/D */
int ai_resolution_mask;
int ao_resolution; /* resolution of D/A */
int ao_resolution_mask;
const struct comedi_lrange *ai_range_list; /* rangelist for A/D */
const struct comedi_lrange *ao_range_list; /* rangelist for D/A */
unsigned int ai_acquisition_period_min_ns;
};
static const struct pci9111_board pci9111_boards[] = {
{
.name = "pci9111_hr",
.device_id = PCI9111_HR_DEVICE_ID,
.ai_channel_nbr = PCI9111_AI_CHANNEL_NBR,
.ao_channel_nbr = PCI9111_AO_CHANNEL_NBR,
.ai_resolution = PCI9111_HR_AI_RESOLUTION,
.ai_resolution_mask = PCI9111_HR_AI_RESOLUTION_MASK,
.ao_resolution = PCI9111_AO_RESOLUTION,
.ao_resolution_mask = PCI9111_AO_RESOLUTION_MASK,
.ai_range_list = &pci9111_hr_ai_range,
.ao_range_list = &range_bipolar10,
.ai_acquisition_period_min_ns = PCI9111_AI_ACQUISITION_PERIOD_MIN_NS}
};
#define pci9111_board_nbr \
(sizeof(pci9111_boards)/sizeof(struct pci9111_board))
static struct comedi_driver pci9111_driver = {
.driver_name = PCI9111_DRIVER_NAME,
.module = THIS_MODULE,
.attach = pci9111_attach,
.detach = pci9111_detach,
};
COMEDI_PCI_INITCLEANUP(pci9111_driver, pci9111_pci_table);
/* Private data structure */
struct pci9111_private_data {
struct pci_dev *pci_device;
unsigned long io_range; /* PCI6503 io range */
unsigned long lcr_io_base; /* Local configuration register base address */
unsigned long lcr_io_range;
int stop_counter;
int stop_is_none;
unsigned int scan_delay;
unsigned int chanlist_len;
unsigned int chunk_counter;
unsigned int chunk_num_samples;
int ao_readback; /* Last written analog output data */
unsigned int timer_divisor_1; /* Divisor values for the 8254 timer pacer */
unsigned int timer_divisor_2;
int is_valid; /* Is device valid */
short ai_bounce_buffer[2 * PCI9111_FIFO_HALF_SIZE];
};
#define dev_private ((struct pci9111_private_data *)dev->private)
/* ------------------------------------------------------------------ */
/* PLX9050 SECTION */
/* ------------------------------------------------------------------ */
#define PLX9050_REGISTER_INTERRUPT_CONTROL 0x4c
#define PLX9050_LINTI1_ENABLE (1 << 0)
#define PLX9050_LINTI1_ACTIVE_HIGH (1 << 1)
#define PLX9050_LINTI1_STATUS (1 << 2)
#define PLX9050_LINTI2_ENABLE (1 << 3)
#define PLX9050_LINTI2_ACTIVE_HIGH (1 << 4)
#define PLX9050_LINTI2_STATUS (1 << 5)
#define PLX9050_PCI_INTERRUPT_ENABLE (1 << 6)
#define PLX9050_SOFTWARE_INTERRUPT (1 << 7)
static void plx9050_interrupt_control(unsigned long io_base,
bool LINTi1_enable,
bool LINTi1_active_high,
bool LINTi2_enable,
bool LINTi2_active_high,
bool interrupt_enable)
{
int flags = 0;
if (LINTi1_enable)
flags |= PLX9050_LINTI1_ENABLE;
if (LINTi1_active_high)
flags |= PLX9050_LINTI1_ACTIVE_HIGH;
if (LINTi2_enable)
flags |= PLX9050_LINTI2_ENABLE;
if (LINTi2_active_high)
flags |= PLX9050_LINTI2_ACTIVE_HIGH;
if (interrupt_enable)
flags |= PLX9050_PCI_INTERRUPT_ENABLE;
outb(flags, io_base + PLX9050_REGISTER_INTERRUPT_CONTROL);
}
/* ------------------------------------------------------------------ */
/* MISCELLANEOUS SECTION */
/* ------------------------------------------------------------------ */
/* 8254 timer */
static void pci9111_timer_set(struct comedi_device *dev)
{
pci9111_8254_control_set(PCI9111_8254_COUNTER_0 |
PCI9111_8254_READ_LOAD_LSB_MSB |
PCI9111_8254_MODE_0 |
PCI9111_8254_BINARY_COUNTER);
pci9111_8254_control_set(PCI9111_8254_COUNTER_1 |
PCI9111_8254_READ_LOAD_LSB_MSB |
PCI9111_8254_MODE_2 |
PCI9111_8254_BINARY_COUNTER);
pci9111_8254_control_set(PCI9111_8254_COUNTER_2 |
PCI9111_8254_READ_LOAD_LSB_MSB |
PCI9111_8254_MODE_2 |
PCI9111_8254_BINARY_COUNTER);
udelay(1);
pci9111_8254_counter_2_set(dev_private->timer_divisor_2);
pci9111_8254_counter_1_set(dev_private->timer_divisor_1);
}
enum pci9111_trigger_sources {
software,
timer_pacer,
external
};
static void pci9111_trigger_source_set(struct comedi_device *dev,
enum pci9111_trigger_sources source)
{
int flags;
flags = pci9111_trigger_and_autoscan_get() & 0x09;
switch (source) {
case software:
flags |= PCI9111_EITS_INTERNAL | PCI9111_TPST_SOFTWARE_TRIGGER;
break;
case timer_pacer:
flags |= PCI9111_EITS_INTERNAL | PCI9111_TPST_TIMER_PACER;
break;
case external:
flags |= PCI9111_EITS_EXTERNAL;
break;
}
pci9111_trigger_and_autoscan_set(flags);
}
static void pci9111_pretrigger_set(struct comedi_device *dev, bool pretrigger)
{
int flags;
flags = pci9111_trigger_and_autoscan_get() & 0x07;
if (pretrigger)
flags |= PCI9111_PTRG_ON;
pci9111_trigger_and_autoscan_set(flags);
}
static void pci9111_autoscan_set(struct comedi_device *dev, bool autoscan)
{
int flags;
flags = pci9111_trigger_and_autoscan_get() & 0x0e;
if (autoscan)
flags |= PCI9111_ASCAN_ON;
pci9111_trigger_and_autoscan_set(flags);
}
enum pci9111_ISC0_sources {
irq_on_eoc,
irq_on_fifo_half_full
};
enum pci9111_ISC1_sources {
irq_on_timer_tick,
irq_on_external_trigger
};
static void pci9111_interrupt_source_set(struct comedi_device *dev,
enum pci9111_ISC0_sources irq_0_source,
enum pci9111_ISC1_sources irq_1_source)
{
int flags;
flags = pci9111_interrupt_and_fifo_get() & 0x04;
if (irq_0_source == irq_on_fifo_half_full)
flags |= PCI9111_ISC0_SET_IRQ_ON_FIFO_HALF_FULL;
if (irq_1_source == irq_on_external_trigger)
flags |= PCI9111_ISC1_SET_IRQ_ON_EXT_TRG;
pci9111_interrupt_and_fifo_set(flags);
}
/* ------------------------------------------------------------------ */
/* HARDWARE TRIGGERED ANALOG INPUT SECTION */
/* ------------------------------------------------------------------ */
/* Cancel analog input autoscan */
#undef AI_DO_CMD_DEBUG
static int pci9111_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
/* Disable interrupts */
plx9050_interrupt_control(dev_private->lcr_io_base, true, true, true,
true, false);
pci9111_trigger_source_set(dev, software);
pci9111_autoscan_set(dev, false);
pci9111_fifo_reset();
#ifdef AI_DO_CMD_DEBUG
printk(PCI9111_DRIVER_NAME ": ai_cancel\n");
#endif
return 0;
}
/* Test analog input command */
#define pci9111_check_trigger_src(src, flags) \
tmp = src; \
src &= flags; \
if (!src || tmp != src) error++
static int
pci9111_ai_do_cmd_test(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int tmp;
int error = 0;
int range, reference;
int i;
struct pci9111_board *board = (struct pci9111_board *)dev->board_ptr;
/* Step 1 : check if trigger are trivialy valid */
pci9111_check_trigger_src(cmd->start_src, TRIG_NOW);
pci9111_check_trigger_src(cmd->scan_begin_src,
TRIG_TIMER | TRIG_FOLLOW | TRIG_EXT);
pci9111_check_trigger_src(cmd->convert_src, TRIG_TIMER | TRIG_EXT);
pci9111_check_trigger_src(cmd->scan_end_src, TRIG_COUNT);
pci9111_check_trigger_src(cmd->stop_src, TRIG_COUNT | TRIG_NONE);
if (error)
return 1;
/* step 2 : make sure trigger sources are unique and mutually compatible */
if (cmd->start_src != TRIG_NOW)
error++;
if ((cmd->scan_begin_src != TRIG_TIMER) &&
(cmd->scan_begin_src != TRIG_FOLLOW) &&
(cmd->scan_begin_src != TRIG_EXT))
error++;
if ((cmd->convert_src != TRIG_TIMER) && (cmd->convert_src != TRIG_EXT))
error++;
if ((cmd->convert_src == TRIG_TIMER) &&
!((cmd->scan_begin_src == TRIG_TIMER) ||
(cmd->scan_begin_src == TRIG_FOLLOW)))
error++;
if ((cmd->convert_src == TRIG_EXT) &&
!((cmd->scan_begin_src == TRIG_EXT) ||
(cmd->scan_begin_src == TRIG_FOLLOW)))
error++;
if (cmd->scan_end_src != TRIG_COUNT)
error++;
if ((cmd->stop_src != TRIG_COUNT) && (cmd->stop_src != TRIG_NONE))
error++;
if (error)
return 2;
/* Step 3 : make sure arguments are trivialy compatible */
if (cmd->chanlist_len < 1) {
cmd->chanlist_len = 1;
error++;
}
if (cmd->chanlist_len > board->ai_channel_nbr) {
cmd->chanlist_len = board->ai_channel_nbr;
error++;
}
if ((cmd->start_src == TRIG_NOW) && (cmd->start_arg != 0)) {
cmd->start_arg = 0;
error++;
}
if ((cmd->convert_src == TRIG_TIMER) &&
(cmd->convert_arg < board->ai_acquisition_period_min_ns)) {
cmd->convert_arg = board->ai_acquisition_period_min_ns;
error++;
}
if ((cmd->convert_src == TRIG_EXT) && (cmd->convert_arg != 0)) {
cmd->convert_arg = 0;
error++;
}
if ((cmd->scan_begin_src == TRIG_TIMER) &&
(cmd->scan_begin_arg < board->ai_acquisition_period_min_ns)) {
cmd->scan_begin_arg = board->ai_acquisition_period_min_ns;
error++;
}
if ((cmd->scan_begin_src == TRIG_FOLLOW) && (cmd->scan_begin_arg != 0)) {
cmd->scan_begin_arg = 0;
error++;
}
if ((cmd->scan_begin_src == TRIG_EXT) && (cmd->scan_begin_arg != 0)) {
cmd->scan_begin_arg = 0;
error++;
}
if ((cmd->scan_end_src == TRIG_COUNT) &&
(cmd->scan_end_arg != cmd->chanlist_len)) {
cmd->scan_end_arg = cmd->chanlist_len;
error++;
}
if ((cmd->stop_src == TRIG_COUNT) && (cmd->stop_arg < 1)) {
cmd->stop_arg = 1;
error++;
}
if ((cmd->stop_src == TRIG_NONE) && (cmd->stop_arg != 0)) {
cmd->stop_arg = 0;
error++;
}
if (error)
return 3;
/* Step 4 : fix up any arguments */
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
i8253_cascade_ns_to_timer_2div(PCI9111_8254_CLOCK_PERIOD_NS,
&(dev_private->timer_divisor_1),
&(dev_private->timer_divisor_2),
&(cmd->convert_arg),
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
error++;
}
/* There's only one timer on this card, so the scan_begin timer must */
/* be a multiple of chanlist_len*convert_arg */
if (cmd->scan_begin_src == TRIG_TIMER) {
unsigned int scan_begin_min;
unsigned int scan_begin_arg;
unsigned int scan_factor;
scan_begin_min = cmd->chanlist_len * cmd->convert_arg;
if (cmd->scan_begin_arg != scan_begin_min) {
if (scan_begin_min < cmd->scan_begin_arg) {
scan_factor =
cmd->scan_begin_arg / scan_begin_min;
scan_begin_arg = scan_factor * scan_begin_min;
if (cmd->scan_begin_arg != scan_begin_arg) {
cmd->scan_begin_arg = scan_begin_arg;
error++;
}
} else {
cmd->scan_begin_arg = scan_begin_min;
error++;
}
}
}
if (error)
return 4;
/* Step 5 : check channel list */
if (cmd->chanlist) {
range = CR_RANGE(cmd->chanlist[0]);
reference = CR_AREF(cmd->chanlist[0]);
if (cmd->chanlist_len > 1) {
for (i = 0; i < cmd->chanlist_len; i++) {
if (CR_CHAN(cmd->chanlist[i]) != i) {
comedi_error(dev,
"entries in chanlist must be consecutive "
"channels,counting upwards from 0\n");
error++;
}
if (CR_RANGE(cmd->chanlist[i]) != range) {
comedi_error(dev,
"entries in chanlist must all have the same gain\n");
error++;
}
if (CR_AREF(cmd->chanlist[i]) != reference) {
comedi_error(dev,
"entries in chanlist must all have the same reference\n");
error++;
}
}
} else {
if ((CR_CHAN(cmd->chanlist[0]) >
(board->ai_channel_nbr - 1))
|| (CR_CHAN(cmd->chanlist[0]) < 0)) {
comedi_error(dev,
"channel number is out of limits\n");
error++;
}
}
}
if (error)
return 5;
return 0;
}
/* Analog input command */
static int pci9111_ai_do_cmd(struct comedi_device *dev,
struct comedi_subdevice *subdevice)
{
struct comedi_cmd *async_cmd = &subdevice->async->cmd;
if (!dev->irq) {
comedi_error(dev,
"no irq assigned for PCI9111, cannot do hardware conversion");
return -1;
}
/* Set channel scan limit */
/* PCI9111 allows only scanning from channel 0 to channel n */
/* TODO: handle the case of an external multiplexer */
if (async_cmd->chanlist_len > 1) {
pci9111_ai_channel_set((async_cmd->chanlist_len) - 1);
pci9111_autoscan_set(dev, true);
} else {
pci9111_ai_channel_set(CR_CHAN(async_cmd->chanlist[0]));
pci9111_autoscan_set(dev, false);
}
/* Set gain */
/* This is the same gain on every channel */
pci9111_ai_range_set(CR_RANGE(async_cmd->chanlist[0]));
/* Set counter */
switch (async_cmd->stop_src) {
case TRIG_COUNT:
dev_private->stop_counter =
async_cmd->stop_arg * async_cmd->chanlist_len;
dev_private->stop_is_none = 0;
break;
case TRIG_NONE:
dev_private->stop_counter = 0;
dev_private->stop_is_none = 1;
break;
default:
comedi_error(dev, "Invalid stop trigger");
return -1;
}
/* Set timer pacer */
dev_private->scan_delay = 0;
switch (async_cmd->convert_src) {
case TRIG_TIMER:
i8253_cascade_ns_to_timer_2div(PCI9111_8254_CLOCK_PERIOD_NS,
&(dev_private->timer_divisor_1),
&(dev_private->timer_divisor_2),
&(async_cmd->convert_arg),
async_cmd->
flags & TRIG_ROUND_MASK);
#ifdef AI_DO_CMD_DEBUG
printk(PCI9111_DRIVER_NAME ": divisors = %d, %d\n",
dev_private->timer_divisor_1,
dev_private->timer_divisor_2);
#endif
pci9111_trigger_source_set(dev, software);
pci9111_timer_set(dev);
pci9111_fifo_reset();
pci9111_interrupt_source_set(dev, irq_on_fifo_half_full,
irq_on_timer_tick);
pci9111_trigger_source_set(dev, timer_pacer);
plx9050_interrupt_control(dev_private->lcr_io_base, true, true,
false, true, true);
if (async_cmd->scan_begin_src == TRIG_TIMER) {
dev_private->scan_delay =
(async_cmd->scan_begin_arg /
(async_cmd->convert_arg *
async_cmd->chanlist_len)) - 1;
}
break;
case TRIG_EXT:
pci9111_trigger_source_set(dev, external);
pci9111_fifo_reset();
pci9111_interrupt_source_set(dev, irq_on_fifo_half_full,
irq_on_timer_tick);
plx9050_interrupt_control(dev_private->lcr_io_base, true, true,
false, true, true);
break;
default:
comedi_error(dev, "Invalid convert trigger");
return -1;
}
dev_private->stop_counter *= (1 + dev_private->scan_delay);
dev_private->chanlist_len = async_cmd->chanlist_len;
dev_private->chunk_counter = 0;
dev_private->chunk_num_samples =
dev_private->chanlist_len * (1 + dev_private->scan_delay);
#ifdef AI_DO_CMD_DEBUG
printk(PCI9111_DRIVER_NAME ": start interruptions!\n");
printk(PCI9111_DRIVER_NAME ": trigger source = %2x\n",
pci9111_trigger_and_autoscan_get());
printk(PCI9111_DRIVER_NAME ": irq source = %2x\n",
pci9111_interrupt_and_fifo_get());
printk(PCI9111_DRIVER_NAME ": ai_do_cmd\n");
printk(PCI9111_DRIVER_NAME ": stop counter = %d\n",
dev_private->stop_counter);
printk(PCI9111_DRIVER_NAME ": scan delay = %d\n",
dev_private->scan_delay);
printk(PCI9111_DRIVER_NAME ": chanlist_len = %d\n",
dev_private->chanlist_len);
printk(PCI9111_DRIVER_NAME ": chunk num samples = %d\n",
dev_private->chunk_num_samples);
#endif
return 0;
}
static void pci9111_ai_munge(struct comedi_device *dev,
struct comedi_subdevice *s, void *data,
unsigned int num_bytes,
unsigned int start_chan_index)
{
unsigned int i, num_samples = num_bytes / sizeof(short);
short *array = data;
int resolution =
((struct pci9111_board *)dev->board_ptr)->ai_resolution;
for (i = 0; i < num_samples; i++) {
if (resolution == PCI9111_HR_AI_RESOLUTION)
array[i] =
(array[i] & PCI9111_HR_AI_RESOLUTION_MASK) ^
PCI9111_HR_AI_RESOLUTION_2_CMP_BIT;
else
array[i] =
((array[i] >> 4) & PCI9111_AI_RESOLUTION_MASK) ^
PCI9111_AI_RESOLUTION_2_CMP_BIT;
}
}
/* ------------------------------------------------------------------ */
/* INTERRUPT SECTION */
/* ------------------------------------------------------------------ */
#undef INTERRUPT_DEBUG
static irqreturn_t pci9111_interrupt(int irq, void *p_device)
{
struct comedi_device *dev = p_device;
struct comedi_subdevice *subdevice = dev->read_subdev;
struct comedi_async *async;
unsigned long irq_flags;
unsigned char intcsr;
if (!dev->attached) {
/* Ignore interrupt before device fully attached. */
/* Might not even have allocated subdevices yet! */
return IRQ_NONE;
}
async = subdevice->async;
spin_lock_irqsave(&dev->spinlock, irq_flags);
/* Check if we are source of interrupt */
intcsr = inb(dev_private->lcr_io_base +
PLX9050_REGISTER_INTERRUPT_CONTROL);
if (!(((intcsr & PLX9050_PCI_INTERRUPT_ENABLE) != 0)
&& (((intcsr & (PLX9050_LINTI1_ENABLE | PLX9050_LINTI1_STATUS))
== (PLX9050_LINTI1_ENABLE | PLX9050_LINTI1_STATUS))
|| ((intcsr & (PLX9050_LINTI2_ENABLE | PLX9050_LINTI2_STATUS))
== (PLX9050_LINTI2_ENABLE | PLX9050_LINTI2_STATUS))))) {
/* Not the source of the interrupt. */
/* (N.B. not using PLX9050_SOFTWARE_INTERRUPT) */
spin_unlock_irqrestore(&dev->spinlock, irq_flags);
return IRQ_NONE;
}
if ((intcsr & (PLX9050_LINTI1_ENABLE | PLX9050_LINTI1_STATUS)) ==
(PLX9050_LINTI1_ENABLE | PLX9050_LINTI1_STATUS)) {
/* Interrupt comes from fifo_half-full signal */
if (pci9111_is_fifo_full()) {
spin_unlock_irqrestore(&dev->spinlock, irq_flags);
comedi_error(dev, PCI9111_DRIVER_NAME " fifo overflow");
pci9111_interrupt_clear();
pci9111_ai_cancel(dev, subdevice);
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
comedi_event(dev, subdevice);
return IRQ_HANDLED;
}
if (pci9111_is_fifo_half_full()) {
unsigned int num_samples;
unsigned int bytes_written = 0;
#ifdef INTERRUPT_DEBUG
printk(PCI9111_DRIVER_NAME ": fifo is half full\n");
#endif
num_samples =
PCI9111_FIFO_HALF_SIZE >
dev_private->stop_counter
&& !dev_private->
stop_is_none ? dev_private->stop_counter :
PCI9111_FIFO_HALF_SIZE;
insw(PCI9111_IO_BASE + PCI9111_REGISTER_AD_FIFO_VALUE,
dev_private->ai_bounce_buffer, num_samples);
if (dev_private->scan_delay < 1) {
bytes_written =
cfc_write_array_to_buffer(subdevice,
dev_private->
ai_bounce_buffer,
num_samples *
sizeof(short));
} else {
int position = 0;
int to_read;
while (position < num_samples) {
if (dev_private->chunk_counter <
dev_private->chanlist_len) {
to_read =
dev_private->chanlist_len -
dev_private->chunk_counter;
if (to_read >
num_samples - position)
to_read =
num_samples -
position;
bytes_written +=
cfc_write_array_to_buffer
(subdevice,
dev_private->ai_bounce_buffer
+ position,
to_read * sizeof(short));
} else {
to_read =
dev_private->chunk_num_samples
-
dev_private->chunk_counter;
if (to_read >
num_samples - position)
to_read =
num_samples -
position;
bytes_written +=
sizeof(short) * to_read;
}
position += to_read;
dev_private->chunk_counter += to_read;
if (dev_private->chunk_counter >=
dev_private->chunk_num_samples)
dev_private->chunk_counter = 0;
}
}
dev_private->stop_counter -=
bytes_written / sizeof(short);
}
}
if ((dev_private->stop_counter == 0) && (!dev_private->stop_is_none)) {
async->events |= COMEDI_CB_EOA;
pci9111_ai_cancel(dev, subdevice);
}
/* Very important, otherwise another interrupt request will be inserted
* and will cause driver hangs on processing interrupt event. */
pci9111_interrupt_clear();
spin_unlock_irqrestore(&dev->spinlock, irq_flags);
comedi_event(dev, subdevice);
return IRQ_HANDLED;
}
/* ------------------------------------------------------------------ */
/* INSTANT ANALOG INPUT OUTPUT SECTION */
/* ------------------------------------------------------------------ */
/* analog instant input */
#undef AI_INSN_DEBUG
static int pci9111_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *subdevice,
struct comedi_insn *insn, unsigned int *data)
{
int resolution =
((struct pci9111_board *)dev->board_ptr)->ai_resolution;
int timeout, i;
#ifdef AI_INSN_DEBUG
printk(PCI9111_DRIVER_NAME ": ai_insn set c/r/n = %2x/%2x/%2x\n",
CR_CHAN((&insn->chanspec)[0]),
CR_RANGE((&insn->chanspec)[0]), insn->n);
#endif
pci9111_ai_channel_set(CR_CHAN((&insn->chanspec)[0]));
if ((pci9111_ai_range_get()) != CR_RANGE((&insn->chanspec)[0]))
pci9111_ai_range_set(CR_RANGE((&insn->chanspec)[0]));
pci9111_fifo_reset();
for (i = 0; i < insn->n; i++) {
pci9111_software_trigger();
timeout = PCI9111_AI_INSTANT_READ_TIMEOUT;
while (timeout--) {
if (!pci9111_is_fifo_empty())
goto conversion_done;
}
comedi_error(dev, "A/D read timeout");
data[i] = 0;
pci9111_fifo_reset();
return -ETIME;
conversion_done:
if (resolution == PCI9111_HR_AI_RESOLUTION)
data[i] = pci9111_hr_ai_get_data();
else
data[i] = pci9111_ai_get_data();
}
#ifdef AI_INSN_DEBUG
printk(PCI9111_DRIVER_NAME ": ai_insn get c/r/t = %2x/%2x/%2x\n",
pci9111_ai_channel_get(),
pci9111_ai_range_get(), pci9111_trigger_and_autoscan_get());
#endif
return i;
}
/* Analog instant output */
static int
pci9111_ao_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data)
{
int i;
for (i = 0; i < insn->n; i++) {
pci9111_ao_set_data(data[i]);
dev_private->ao_readback = data[i];
}
return i;
}
/* Analog output readback */
static int pci9111_ao_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
for (i = 0; i < insn->n; i++)
data[i] = dev_private->ao_readback & PCI9111_AO_RESOLUTION_MASK;
return i;
}
/* ------------------------------------------------------------------ */
/* DIGITAL INPUT OUTPUT SECTION */
/* ------------------------------------------------------------------ */
/* Digital inputs */
static int pci9111_di_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *subdevice,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int bits;
bits = pci9111_di_get_bits();
data[1] = bits;
return 2;
}
/* Digital outputs */
static int pci9111_do_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *subdevice,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int bits;
/* Only set bits that have been masked */
/* data[0] = mask */
/* data[1] = bit state */
data[0] &= PCI9111_DO_MASK;
bits = subdevice->state;
bits &= ~data[0];
bits |= data[0] & data[1];
subdevice->state = bits;
pci9111_do_set_bits(bits);
data[1] = bits;
return 2;
}
/* ------------------------------------------------------------------ */
/* INITIALISATION SECTION */
/* ------------------------------------------------------------------ */
/* Reset device */
static int pci9111_reset(struct comedi_device *dev)
{
/* Set trigger source to software */
plx9050_interrupt_control(dev_private->lcr_io_base, true, true, true,
true, false);
pci9111_trigger_source_set(dev, software);
pci9111_pretrigger_set(dev, false);
pci9111_autoscan_set(dev, false);
/* Reset 8254 chip */
dev_private->timer_divisor_1 = 0;
dev_private->timer_divisor_2 = 0;
pci9111_timer_set(dev);
return 0;
}
/* Attach */
/* - Register PCI device */
/* - Declare device driver capability */
static int pci9111_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *subdevice;
unsigned long io_base, io_range, lcr_io_base, lcr_io_range;
struct pci_dev *pci_device;
int error, i;
const struct pci9111_board *board;
if (alloc_private(dev, sizeof(struct pci9111_private_data)) < 0)
return -ENOMEM;
/* Probe the device to determine what device in the series it is. */
printk("comedi%d: " PCI9111_DRIVER_NAME " driver\n", dev->minor);
for (pci_device = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
pci_device != NULL;
pci_device = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pci_device)) {
if (pci_device->vendor == PCI_VENDOR_ID_ADLINK) {
for (i = 0; i < pci9111_board_nbr; i++) {
if (pci9111_boards[i].device_id ==
pci_device->device) {
/* was a particular bus/slot requested? */
if ((it->options[0] != 0)
|| (it->options[1] != 0)) {
/* are we on the wrong bus/slot? */
if (pci_device->bus->number !=
it->options[0]
||
PCI_SLOT(pci_device->devfn)
!= it->options[1]) {
continue;
}
}
dev->board_ptr = pci9111_boards + i;
board =
(struct pci9111_board *)
dev->board_ptr;
dev_private->pci_device = pci_device;
goto found;
}
}
}
}
printk("comedi%d: no supported board found! (req. bus/slot : %d/%d)\n",
dev->minor, it->options[0], it->options[1]);
return -EIO;
found:
printk("comedi%d: found %s (b:s:f=%d:%d:%d) , irq=%d\n",
dev->minor,
pci9111_boards[i].name,
pci_device->bus->number,
PCI_SLOT(pci_device->devfn),
PCI_FUNC(pci_device->devfn), pci_device->irq);
/* TODO: Warn about non-tested boards. */
/* Read local configuration register base address [PCI_BASE_ADDRESS #1]. */
lcr_io_base = pci_resource_start(pci_device, 1);
lcr_io_range = pci_resource_len(pci_device, 1);
printk
("comedi%d: local configuration registers at address 0x%4lx [0x%4lx]\n",
dev->minor, lcr_io_base, lcr_io_range);
/* Enable PCI device and request regions */
if (comedi_pci_enable(pci_device, PCI9111_DRIVER_NAME) < 0) {
printk
("comedi%d: Failed to enable PCI device and request regions\n",
dev->minor);
return -EIO;
}
/* Read PCI6308 register base address [PCI_BASE_ADDRESS #2]. */
io_base = pci_resource_start(pci_device, 2);
io_range = pci_resource_len(pci_device, 2);
printk("comedi%d: 6503 registers at address 0x%4lx [0x%4lx]\n",
dev->minor, io_base, io_range);
dev->iobase = io_base;
dev->board_name = board->name;
dev_private->io_range = io_range;
dev_private->is_valid = 0;
dev_private->lcr_io_base = lcr_io_base;
dev_private->lcr_io_range = lcr_io_range;
pci9111_reset(dev);
/* Irq setup */
dev->irq = 0;
if (pci_device->irq > 0) {
if (request_irq(pci_device->irq, pci9111_interrupt,
IRQF_SHARED, PCI9111_DRIVER_NAME, dev) != 0) {
printk("comedi%d: unable to allocate irq %u\n",
dev->minor, pci_device->irq);
return -EINVAL;
}
}
dev->irq = pci_device->irq;
/* TODO: Add external multiplexer setup (according to option[2]). */
error = alloc_subdevices(dev, 4);
if (error < 0)
return error;
subdevice = dev->subdevices + 0;
dev->read_subdev = subdevice;
subdevice->type = COMEDI_SUBD_AI;
subdevice->subdev_flags = SDF_READABLE | SDF_COMMON | SDF_CMD_READ;
/* TODO: Add external multiplexer data */
/* if (devpriv->usemux) { subdevice->n_chan = devpriv->usemux; } */
/* else { subdevice->n_chan = this_board->n_aichan; } */
subdevice->n_chan = board->ai_channel_nbr;
subdevice->maxdata = board->ai_resolution_mask;
subdevice->len_chanlist = board->ai_channel_nbr;
subdevice->range_table = board->ai_range_list;
subdevice->cancel = pci9111_ai_cancel;
subdevice->insn_read = pci9111_ai_insn_read;
subdevice->do_cmdtest = pci9111_ai_do_cmd_test;
subdevice->do_cmd = pci9111_ai_do_cmd;
subdevice->munge = pci9111_ai_munge;
subdevice = dev->subdevices + 1;
subdevice->type = COMEDI_SUBD_AO;
subdevice->subdev_flags = SDF_WRITABLE | SDF_COMMON;
subdevice->n_chan = board->ao_channel_nbr;
subdevice->maxdata = board->ao_resolution_mask;
subdevice->len_chanlist = board->ao_channel_nbr;
subdevice->range_table = board->ao_range_list;
subdevice->insn_write = pci9111_ao_insn_write;
subdevice->insn_read = pci9111_ao_insn_read;
subdevice = dev->subdevices + 2;
subdevice->type = COMEDI_SUBD_DI;
subdevice->subdev_flags = SDF_READABLE;
subdevice->n_chan = PCI9111_DI_CHANNEL_NBR;
subdevice->maxdata = 1;
subdevice->range_table = &range_digital;
subdevice->insn_bits = pci9111_di_insn_bits;
subdevice = dev->subdevices + 3;
subdevice->type = COMEDI_SUBD_DO;
subdevice->subdev_flags = SDF_READABLE | SDF_WRITABLE;
subdevice->n_chan = PCI9111_DO_CHANNEL_NBR;
subdevice->maxdata = 1;
subdevice->range_table = &range_digital;
subdevice->insn_bits = pci9111_do_insn_bits;
dev_private->is_valid = 1;
return 0;
}
/* Detach */
static int pci9111_detach(struct comedi_device *dev)
{
/* Reset device */
if (dev->private != NULL) {
if (dev_private->is_valid)
pci9111_reset(dev);
}
/* Release previously allocated irq */
if (dev->irq != 0)
free_irq(dev->irq, dev);
if (dev_private != NULL && dev_private->pci_device != NULL) {
if (dev->iobase)
comedi_pci_disable(dev_private->pci_device);
pci_dev_put(dev_private->pci_device);
}
return 0;
}
| gpl-2.0 |
FroX/Cutrekernel | drivers/net/wireless/iwlwifi/iwl-debugfs.c | 758 | 49798 | /******************************************************************************
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2010 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* 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.GPL.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*****************************************************************************/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/ieee80211.h>
#include <net/mac80211.h>
#include "iwl-dev.h"
#include "iwl-debug.h"
#include "iwl-core.h"
#include "iwl-io.h"
#include "iwl-calib.h"
/* create and remove of files */
#define DEBUGFS_ADD_FILE(name, parent, mode) do { \
if (!debugfs_create_file(#name, mode, parent, priv, \
&iwl_dbgfs_##name##_ops)) \
goto err; \
} while (0)
#define DEBUGFS_ADD_BOOL(name, parent, ptr) do { \
struct dentry *__tmp; \
__tmp = debugfs_create_bool(#name, S_IWUSR | S_IRUSR, \
parent, ptr); \
if (IS_ERR(__tmp) || !__tmp) \
goto err; \
} while (0)
#define DEBUGFS_ADD_X32(name, parent, ptr) do { \
struct dentry *__tmp; \
__tmp = debugfs_create_x32(#name, S_IWUSR | S_IRUSR, \
parent, ptr); \
if (IS_ERR(__tmp) || !__tmp) \
goto err; \
} while (0)
/* file operation */
#define DEBUGFS_READ_FUNC(name) \
static ssize_t iwl_dbgfs_##name##_read(struct file *file, \
char __user *user_buf, \
size_t count, loff_t *ppos);
#define DEBUGFS_WRITE_FUNC(name) \
static ssize_t iwl_dbgfs_##name##_write(struct file *file, \
const char __user *user_buf, \
size_t count, loff_t *ppos);
static int iwl_dbgfs_open_file_generic(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
#define DEBUGFS_READ_FILE_OPS(name) \
DEBUGFS_READ_FUNC(name); \
static const struct file_operations iwl_dbgfs_##name##_ops = { \
.read = iwl_dbgfs_##name##_read, \
.open = iwl_dbgfs_open_file_generic, \
};
#define DEBUGFS_WRITE_FILE_OPS(name) \
DEBUGFS_WRITE_FUNC(name); \
static const struct file_operations iwl_dbgfs_##name##_ops = { \
.write = iwl_dbgfs_##name##_write, \
.open = iwl_dbgfs_open_file_generic, \
};
#define DEBUGFS_READ_WRITE_FILE_OPS(name) \
DEBUGFS_READ_FUNC(name); \
DEBUGFS_WRITE_FUNC(name); \
static const struct file_operations iwl_dbgfs_##name##_ops = { \
.write = iwl_dbgfs_##name##_write, \
.read = iwl_dbgfs_##name##_read, \
.open = iwl_dbgfs_open_file_generic, \
};
int iwl_dbgfs_statistics_flag(struct iwl_priv *priv, char *buf, int bufsz)
{
int p = 0;
p += scnprintf(buf + p, bufsz - p, "Statistics Flag(0x%X):\n",
le32_to_cpu(priv->statistics.flag));
if (le32_to_cpu(priv->statistics.flag) & UCODE_STATISTICS_CLEAR_MSK)
p += scnprintf(buf + p, bufsz - p,
"\tStatistics have been cleared\n");
p += scnprintf(buf + p, bufsz - p, "\tOperational Frequency: %s\n",
(le32_to_cpu(priv->statistics.flag) &
UCODE_STATISTICS_FREQUENCY_MSK)
? "2.4 GHz" : "5.2 GHz");
p += scnprintf(buf + p, bufsz - p, "\tTGj Narrow Band: %s\n",
(le32_to_cpu(priv->statistics.flag) &
UCODE_STATISTICS_NARROW_BAND_MSK)
? "enabled" : "disabled");
return p;
}
EXPORT_SYMBOL(iwl_dbgfs_statistics_flag);
static ssize_t iwl_dbgfs_tx_statistics_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
char *buf;
int pos = 0;
int cnt;
ssize_t ret;
const size_t bufsz = 100 +
sizeof(char) * 50 * (MANAGEMENT_MAX + CONTROL_MAX);
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf)
return -ENOMEM;
pos += scnprintf(buf + pos, bufsz - pos, "Management:\n");
for (cnt = 0; cnt < MANAGEMENT_MAX; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos,
"\t%25s\t\t: %u\n",
get_mgmt_string(cnt),
priv->tx_stats.mgmt[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "Control\n");
for (cnt = 0; cnt < CONTROL_MAX; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos,
"\t%25s\t\t: %u\n",
get_ctrl_string(cnt),
priv->tx_stats.ctrl[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "Data:\n");
pos += scnprintf(buf + pos, bufsz - pos, "\tcnt: %u\n",
priv->tx_stats.data_cnt);
pos += scnprintf(buf + pos, bufsz - pos, "\tbytes: %llu\n",
priv->tx_stats.data_bytes);
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_clear_traffic_statistics_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
u32 clear_flag;
char buf[8];
int buf_size;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%x", &clear_flag) != 1)
return -EFAULT;
iwl_clear_traffic_stats(priv);
return count;
}
static ssize_t iwl_dbgfs_rx_statistics_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
char *buf;
int pos = 0;
int cnt;
ssize_t ret;
const size_t bufsz = 100 +
sizeof(char) * 50 * (MANAGEMENT_MAX + CONTROL_MAX);
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf)
return -ENOMEM;
pos += scnprintf(buf + pos, bufsz - pos, "Management:\n");
for (cnt = 0; cnt < MANAGEMENT_MAX; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos,
"\t%25s\t\t: %u\n",
get_mgmt_string(cnt),
priv->rx_stats.mgmt[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "Control:\n");
for (cnt = 0; cnt < CONTROL_MAX; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos,
"\t%25s\t\t: %u\n",
get_ctrl_string(cnt),
priv->rx_stats.ctrl[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "Data:\n");
pos += scnprintf(buf + pos, bufsz - pos, "\tcnt: %u\n",
priv->rx_stats.data_cnt);
pos += scnprintf(buf + pos, bufsz - pos, "\tbytes: %llu\n",
priv->rx_stats.data_bytes);
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
#define BYTE1_MASK 0x000000ff;
#define BYTE2_MASK 0x0000ffff;
#define BYTE3_MASK 0x00ffffff;
static ssize_t iwl_dbgfs_sram_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
u32 val;
char *buf;
ssize_t ret;
int i;
int pos = 0;
struct iwl_priv *priv = file->private_data;
size_t bufsz;
/* default is to dump the entire data segment */
if (!priv->dbgfs_sram_offset && !priv->dbgfs_sram_len) {
priv->dbgfs_sram_offset = 0x800000;
if (priv->ucode_type == UCODE_INIT)
priv->dbgfs_sram_len = priv->ucode_init_data.len;
else
priv->dbgfs_sram_len = priv->ucode_data.len;
}
bufsz = 30 + priv->dbgfs_sram_len * sizeof(char) * 10;
buf = kmalloc(bufsz, GFP_KERNEL);
if (!buf)
return -ENOMEM;
pos += scnprintf(buf + pos, bufsz - pos, "sram_len: 0x%x\n",
priv->dbgfs_sram_len);
pos += scnprintf(buf + pos, bufsz - pos, "sram_offset: 0x%x\n",
priv->dbgfs_sram_offset);
for (i = priv->dbgfs_sram_len; i > 0; i -= 4) {
val = iwl_read_targ_mem(priv, priv->dbgfs_sram_offset + \
priv->dbgfs_sram_len - i);
if (i < 4) {
switch (i) {
case 1:
val &= BYTE1_MASK;
break;
case 2:
val &= BYTE2_MASK;
break;
case 3:
val &= BYTE3_MASK;
break;
}
}
if (!(i % 16))
pos += scnprintf(buf + pos, bufsz - pos, "\n");
pos += scnprintf(buf + pos, bufsz - pos, "0x%08x ", val);
}
pos += scnprintf(buf + pos, bufsz - pos, "\n");
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_sram_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[64];
int buf_size;
u32 offset, len;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%x,%x", &offset, &len) == 2) {
priv->dbgfs_sram_offset = offset;
priv->dbgfs_sram_len = len;
} else {
priv->dbgfs_sram_offset = 0;
priv->dbgfs_sram_len = 0;
}
return count;
}
static ssize_t iwl_dbgfs_stations_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
struct iwl_station_entry *station;
int max_sta = priv->hw_params.max_stations;
char *buf;
int i, j, pos = 0;
ssize_t ret;
/* Add 30 for initial string */
const size_t bufsz = 30 + sizeof(char) * 500 * (priv->num_stations);
buf = kmalloc(bufsz, GFP_KERNEL);
if (!buf)
return -ENOMEM;
pos += scnprintf(buf + pos, bufsz - pos, "num of stations: %d\n\n",
priv->num_stations);
for (i = 0; i < max_sta; i++) {
station = &priv->stations[i];
if (station->used) {
pos += scnprintf(buf + pos, bufsz - pos,
"station %d:\ngeneral data:\n", i+1);
pos += scnprintf(buf + pos, bufsz - pos, "id: %u\n",
station->sta.sta.sta_id);
pos += scnprintf(buf + pos, bufsz - pos, "mode: %u\n",
station->sta.mode);
pos += scnprintf(buf + pos, bufsz - pos,
"flags: 0x%x\n",
station->sta.station_flags_msk);
pos += scnprintf(buf + pos, bufsz - pos, "tid data:\n");
pos += scnprintf(buf + pos, bufsz - pos,
"seq_num\t\ttxq_id");
pos += scnprintf(buf + pos, bufsz - pos,
"\tframe_count\twait_for_ba\t");
pos += scnprintf(buf + pos, bufsz - pos,
"start_idx\tbitmap0\t");
pos += scnprintf(buf + pos, bufsz - pos,
"bitmap1\trate_n_flags");
pos += scnprintf(buf + pos, bufsz - pos, "\n");
for (j = 0; j < MAX_TID_COUNT; j++) {
pos += scnprintf(buf + pos, bufsz - pos,
"[%d]:\t\t%u", j,
station->tid[j].seq_number);
pos += scnprintf(buf + pos, bufsz - pos,
"\t%u\t\t%u\t\t%u\t\t",
station->tid[j].agg.txq_id,
station->tid[j].agg.frame_count,
station->tid[j].agg.wait_for_ba);
pos += scnprintf(buf + pos, bufsz - pos,
"%u\t%llu\t%u",
station->tid[j].agg.start_idx,
(unsigned long long)station->tid[j].agg.bitmap,
station->tid[j].agg.rate_n_flags);
pos += scnprintf(buf + pos, bufsz - pos, "\n");
}
pos += scnprintf(buf + pos, bufsz - pos, "\n");
}
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_nvm_read(struct file *file,
char __user *user_buf,
size_t count,
loff_t *ppos)
{
ssize_t ret;
struct iwl_priv *priv = file->private_data;
int pos = 0, ofs = 0, buf_size = 0;
const u8 *ptr;
char *buf;
u16 eeprom_ver;
size_t eeprom_len = priv->cfg->eeprom_size;
buf_size = 4 * eeprom_len + 256;
if (eeprom_len % 16) {
IWL_ERR(priv, "NVM size is not multiple of 16.\n");
return -ENODATA;
}
ptr = priv->eeprom;
if (!ptr) {
IWL_ERR(priv, "Invalid EEPROM/OTP memory\n");
return -ENOMEM;
}
/* 4 characters for byte 0xYY */
buf = kzalloc(buf_size, GFP_KERNEL);
if (!buf) {
IWL_ERR(priv, "Can not allocate Buffer\n");
return -ENOMEM;
}
eeprom_ver = iwl_eeprom_query16(priv, EEPROM_VERSION);
pos += scnprintf(buf + pos, buf_size - pos, "NVM Type: %s, "
"version: 0x%x\n",
(priv->nvm_device_type == NVM_DEVICE_TYPE_OTP)
? "OTP" : "EEPROM", eeprom_ver);
for (ofs = 0 ; ofs < eeprom_len ; ofs += 16) {
pos += scnprintf(buf + pos, buf_size - pos, "0x%.4x ", ofs);
hex_dump_to_buffer(ptr + ofs, 16 , 16, 2, buf + pos,
buf_size - pos, 0);
pos += strlen(buf + pos);
if (buf_size - pos > 0)
buf[pos++] = '\n';
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_log_event_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char *buf;
int pos = 0;
ssize_t ret = -ENOMEM;
ret = pos = priv->cfg->ops->lib->dump_nic_event_log(
priv, true, &buf, true);
if (buf) {
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
}
return ret;
}
static ssize_t iwl_dbgfs_log_event_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
u32 event_log_flag;
char buf[8];
int buf_size;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &event_log_flag) != 1)
return -EFAULT;
if (event_log_flag == 1)
priv->cfg->ops->lib->dump_nic_event_log(priv, true,
NULL, false);
return count;
}
static ssize_t iwl_dbgfs_channels_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
struct ieee80211_channel *channels = NULL;
const struct ieee80211_supported_band *supp_band = NULL;
int pos = 0, i, bufsz = PAGE_SIZE;
char *buf;
ssize_t ret;
if (!test_bit(STATUS_GEO_CONFIGURED, &priv->status))
return -EAGAIN;
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf) {
IWL_ERR(priv, "Can not allocate Buffer\n");
return -ENOMEM;
}
supp_band = iwl_get_hw_mode(priv, IEEE80211_BAND_2GHZ);
if (supp_band) {
channels = supp_band->channels;
pos += scnprintf(buf + pos, bufsz - pos,
"Displaying %d channels in 2.4GHz band 802.11bg):\n",
supp_band->n_channels);
for (i = 0; i < supp_band->n_channels; i++)
pos += scnprintf(buf + pos, bufsz - pos,
"%d: %ddBm: BSS%s%s, %s.\n",
ieee80211_frequency_to_channel(
channels[i].center_freq),
channels[i].max_power,
channels[i].flags & IEEE80211_CHAN_RADAR ?
" (IEEE 802.11h required)" : "",
((channels[i].flags & IEEE80211_CHAN_NO_IBSS)
|| (channels[i].flags &
IEEE80211_CHAN_RADAR)) ? "" :
", IBSS",
channels[i].flags &
IEEE80211_CHAN_PASSIVE_SCAN ?
"passive only" : "active/passive");
}
supp_band = iwl_get_hw_mode(priv, IEEE80211_BAND_5GHZ);
if (supp_band) {
channels = supp_band->channels;
pos += scnprintf(buf + pos, bufsz - pos,
"Displaying %d channels in 5.2GHz band (802.11a)\n",
supp_band->n_channels);
for (i = 0; i < supp_band->n_channels; i++)
pos += scnprintf(buf + pos, bufsz - pos,
"%d: %ddBm: BSS%s%s, %s.\n",
ieee80211_frequency_to_channel(
channels[i].center_freq),
channels[i].max_power,
channels[i].flags & IEEE80211_CHAN_RADAR ?
" (IEEE 802.11h required)" : "",
((channels[i].flags & IEEE80211_CHAN_NO_IBSS)
|| (channels[i].flags &
IEEE80211_CHAN_RADAR)) ? "" :
", IBSS",
channels[i].flags &
IEEE80211_CHAN_PASSIVE_SCAN ?
"passive only" : "active/passive");
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_status_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
char buf[512];
int pos = 0;
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_HCMD_ACTIVE:\t %d\n",
test_bit(STATUS_HCMD_ACTIVE, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_INT_ENABLED:\t %d\n",
test_bit(STATUS_INT_ENABLED, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_RF_KILL_HW:\t %d\n",
test_bit(STATUS_RF_KILL_HW, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_CT_KILL:\t\t %d\n",
test_bit(STATUS_CT_KILL, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_INIT:\t\t %d\n",
test_bit(STATUS_INIT, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_ALIVE:\t\t %d\n",
test_bit(STATUS_ALIVE, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_READY:\t\t %d\n",
test_bit(STATUS_READY, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_TEMPERATURE:\t %d\n",
test_bit(STATUS_TEMPERATURE, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_GEO_CONFIGURED:\t %d\n",
test_bit(STATUS_GEO_CONFIGURED, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_EXIT_PENDING:\t %d\n",
test_bit(STATUS_EXIT_PENDING, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_STATISTICS:\t %d\n",
test_bit(STATUS_STATISTICS, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_SCANNING:\t %d\n",
test_bit(STATUS_SCANNING, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_SCAN_ABORTING:\t %d\n",
test_bit(STATUS_SCAN_ABORTING, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_SCAN_HW:\t\t %d\n",
test_bit(STATUS_SCAN_HW, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_POWER_PMI:\t %d\n",
test_bit(STATUS_POWER_PMI, &priv->status));
pos += scnprintf(buf + pos, bufsz - pos, "STATUS_FW_ERROR:\t %d\n",
test_bit(STATUS_FW_ERROR, &priv->status));
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_interrupt_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
int pos = 0;
int cnt = 0;
char *buf;
int bufsz = 24 * 64; /* 24 items * 64 char per item */
ssize_t ret;
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf) {
IWL_ERR(priv, "Can not allocate Buffer\n");
return -ENOMEM;
}
pos += scnprintf(buf + pos, bufsz - pos,
"Interrupt Statistics Report:\n");
pos += scnprintf(buf + pos, bufsz - pos, "HW Error:\t\t\t %u\n",
priv->isr_stats.hw);
pos += scnprintf(buf + pos, bufsz - pos, "SW Error:\t\t\t %u\n",
priv->isr_stats.sw);
if (priv->isr_stats.sw > 0) {
pos += scnprintf(buf + pos, bufsz - pos,
"\tLast Restarting Code: 0x%X\n",
priv->isr_stats.sw_err);
}
#ifdef CONFIG_IWLWIFI_DEBUG
pos += scnprintf(buf + pos, bufsz - pos, "Frame transmitted:\t\t %u\n",
priv->isr_stats.sch);
pos += scnprintf(buf + pos, bufsz - pos, "Alive interrupt:\t\t %u\n",
priv->isr_stats.alive);
#endif
pos += scnprintf(buf + pos, bufsz - pos,
"HW RF KILL switch toggled:\t %u\n",
priv->isr_stats.rfkill);
pos += scnprintf(buf + pos, bufsz - pos, "CT KILL:\t\t\t %u\n",
priv->isr_stats.ctkill);
pos += scnprintf(buf + pos, bufsz - pos, "Wakeup Interrupt:\t\t %u\n",
priv->isr_stats.wakeup);
pos += scnprintf(buf + pos, bufsz - pos,
"Rx command responses:\t\t %u\n",
priv->isr_stats.rx);
for (cnt = 0; cnt < REPLY_MAX; cnt++) {
if (priv->isr_stats.rx_handlers[cnt] > 0)
pos += scnprintf(buf + pos, bufsz - pos,
"\tRx handler[%36s]:\t\t %u\n",
get_cmd_string(cnt),
priv->isr_stats.rx_handlers[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "Tx/FH interrupt:\t\t %u\n",
priv->isr_stats.tx);
pos += scnprintf(buf + pos, bufsz - pos, "Unexpected INTA:\t\t %u\n",
priv->isr_stats.unhandled);
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_interrupt_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
u32 reset_flag;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%x", &reset_flag) != 1)
return -EFAULT;
if (reset_flag == 0)
iwl_clear_isr_stats(priv);
return count;
}
static ssize_t iwl_dbgfs_qos_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
int pos = 0, i;
char buf[256];
const size_t bufsz = sizeof(buf);
for (i = 0; i < AC_NUM; i++) {
pos += scnprintf(buf + pos, bufsz - pos,
"\tcw_min\tcw_max\taifsn\ttxop\n");
pos += scnprintf(buf + pos, bufsz - pos,
"AC[%d]\t%u\t%u\t%u\t%u\n", i,
priv->qos_data.def_qos_parm.ac[i].cw_min,
priv->qos_data.def_qos_parm.ac[i].cw_max,
priv->qos_data.def_qos_parm.ac[i].aifsn,
priv->qos_data.def_qos_parm.ac[i].edca_txop);
}
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_led_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
int pos = 0;
char buf[256];
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos,
"allow blinking: %s\n",
(priv->allow_blinking) ? "True" : "False");
if (priv->allow_blinking) {
pos += scnprintf(buf + pos, bufsz - pos,
"Led blinking rate: %u\n",
priv->last_blink_rate);
pos += scnprintf(buf + pos, bufsz - pos,
"Last blink time: %lu\n",
priv->last_blink_time);
}
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_thermal_throttling_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
struct iwl_tt_mgmt *tt = &priv->thermal_throttle;
struct iwl_tt_restriction *restriction;
char buf[100];
int pos = 0;
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos,
"Thermal Throttling Mode: %s\n",
tt->advanced_tt ? "Advance" : "Legacy");
pos += scnprintf(buf + pos, bufsz - pos,
"Thermal Throttling State: %d\n",
tt->state);
if (tt->advanced_tt) {
restriction = tt->restriction + tt->state;
pos += scnprintf(buf + pos, bufsz - pos,
"Tx mode: %d\n",
restriction->tx_stream);
pos += scnprintf(buf + pos, bufsz - pos,
"Rx mode: %d\n",
restriction->rx_stream);
pos += scnprintf(buf + pos, bufsz - pos,
"HT mode: %d\n",
restriction->is_ht);
}
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_disable_ht40_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int ht40;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &ht40) != 1)
return -EFAULT;
if (!iwl_is_associated(priv))
priv->disable_ht40 = ht40 ? true : false;
else {
IWL_ERR(priv, "Sta associated with AP - "
"Change to 40MHz channel support is not allowed\n");
return -EINVAL;
}
return count;
}
static ssize_t iwl_dbgfs_disable_ht40_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[100];
int pos = 0;
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos,
"11n 40MHz Mode: %s\n",
priv->disable_ht40 ? "Disabled" : "Enabled");
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_sleep_level_override_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int value;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &value) != 1)
return -EINVAL;
/*
* Our users expect 0 to be "CAM", but 0 isn't actually
* valid here. However, let's not confuse them and present
* IWL_POWER_INDEX_1 as "1", not "0".
*/
if (value == 0)
return -EINVAL;
else if (value > 0)
value -= 1;
if (value != -1 && (value < 0 || value >= IWL_POWER_NUM))
return -EINVAL;
if (!iwl_is_ready_rf(priv))
return -EAGAIN;
priv->power_data.debug_sleep_level_override = value;
mutex_lock(&priv->mutex);
iwl_power_update_mode(priv, true);
mutex_unlock(&priv->mutex);
return count;
}
static ssize_t iwl_dbgfs_sleep_level_override_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[10];
int pos, value;
const size_t bufsz = sizeof(buf);
/* see the write function */
value = priv->power_data.debug_sleep_level_override;
if (value >= 0)
value += 1;
pos = scnprintf(buf, bufsz, "%d\n", value);
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_current_sleep_command_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[200];
int pos = 0, i;
const size_t bufsz = sizeof(buf);
struct iwl_powertable_cmd *cmd = &priv->power_data.sleep_cmd;
pos += scnprintf(buf + pos, bufsz - pos,
"flags: %#.2x\n", le16_to_cpu(cmd->flags));
pos += scnprintf(buf + pos, bufsz - pos,
"RX/TX timeout: %d/%d usec\n",
le32_to_cpu(cmd->rx_data_timeout),
le32_to_cpu(cmd->tx_data_timeout));
for (i = 0; i < IWL_POWER_VEC_SIZE; i++)
pos += scnprintf(buf + pos, bufsz - pos,
"sleep_interval[%d]: %d\n", i,
le32_to_cpu(cmd->sleep_interval[i]));
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
DEBUGFS_READ_WRITE_FILE_OPS(sram);
DEBUGFS_READ_WRITE_FILE_OPS(log_event);
DEBUGFS_READ_FILE_OPS(nvm);
DEBUGFS_READ_FILE_OPS(stations);
DEBUGFS_READ_FILE_OPS(channels);
DEBUGFS_READ_FILE_OPS(status);
DEBUGFS_READ_WRITE_FILE_OPS(interrupt);
DEBUGFS_READ_FILE_OPS(qos);
DEBUGFS_READ_FILE_OPS(led);
DEBUGFS_READ_FILE_OPS(thermal_throttling);
DEBUGFS_READ_WRITE_FILE_OPS(disable_ht40);
DEBUGFS_READ_WRITE_FILE_OPS(sleep_level_override);
DEBUGFS_READ_FILE_OPS(current_sleep_command);
static ssize_t iwl_dbgfs_traffic_log_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
int pos = 0, ofs = 0;
int cnt = 0, entry;
struct iwl_tx_queue *txq;
struct iwl_queue *q;
struct iwl_rx_queue *rxq = &priv->rxq;
char *buf;
int bufsz = ((IWL_TRAFFIC_ENTRIES * IWL_TRAFFIC_ENTRY_SIZE * 64) * 2) +
(priv->cfg->num_of_queues * 32 * 8) + 400;
const u8 *ptr;
ssize_t ret;
if (!priv->txq) {
IWL_ERR(priv, "txq not ready\n");
return -EAGAIN;
}
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf) {
IWL_ERR(priv, "Can not allocate buffer\n");
return -ENOMEM;
}
pos += scnprintf(buf + pos, bufsz - pos, "Tx Queue\n");
for (cnt = 0; cnt < priv->hw_params.max_txq_num; cnt++) {
txq = &priv->txq[cnt];
q = &txq->q;
pos += scnprintf(buf + pos, bufsz - pos,
"q[%d]: read_ptr: %u, write_ptr: %u\n",
cnt, q->read_ptr, q->write_ptr);
}
if (priv->tx_traffic && (iwl_debug_level & IWL_DL_TX)) {
ptr = priv->tx_traffic;
pos += scnprintf(buf + pos, bufsz - pos,
"Tx Traffic idx: %u\n", priv->tx_traffic_idx);
for (cnt = 0, ofs = 0; cnt < IWL_TRAFFIC_ENTRIES; cnt++) {
for (entry = 0; entry < IWL_TRAFFIC_ENTRY_SIZE / 16;
entry++, ofs += 16) {
pos += scnprintf(buf + pos, bufsz - pos,
"0x%.4x ", ofs);
hex_dump_to_buffer(ptr + ofs, 16, 16, 2,
buf + pos, bufsz - pos, 0);
pos += strlen(buf + pos);
if (bufsz - pos > 0)
buf[pos++] = '\n';
}
}
}
pos += scnprintf(buf + pos, bufsz - pos, "Rx Queue\n");
pos += scnprintf(buf + pos, bufsz - pos,
"read: %u, write: %u\n",
rxq->read, rxq->write);
if (priv->rx_traffic && (iwl_debug_level & IWL_DL_RX)) {
ptr = priv->rx_traffic;
pos += scnprintf(buf + pos, bufsz - pos,
"Rx Traffic idx: %u\n", priv->rx_traffic_idx);
for (cnt = 0, ofs = 0; cnt < IWL_TRAFFIC_ENTRIES; cnt++) {
for (entry = 0; entry < IWL_TRAFFIC_ENTRY_SIZE / 16;
entry++, ofs += 16) {
pos += scnprintf(buf + pos, bufsz - pos,
"0x%.4x ", ofs);
hex_dump_to_buffer(ptr + ofs, 16, 16, 2,
buf + pos, bufsz - pos, 0);
pos += strlen(buf + pos);
if (bufsz - pos > 0)
buf[pos++] = '\n';
}
}
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_traffic_log_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int traffic_log;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &traffic_log) != 1)
return -EFAULT;
if (traffic_log == 0)
iwl_reset_traffic_log(priv);
return count;
}
static ssize_t iwl_dbgfs_tx_queue_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
struct iwl_tx_queue *txq;
struct iwl_queue *q;
char *buf;
int pos = 0;
int cnt;
int ret;
const size_t bufsz = sizeof(char) * 64 * priv->cfg->num_of_queues;
if (!priv->txq) {
IWL_ERR(priv, "txq not ready\n");
return -EAGAIN;
}
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf)
return -ENOMEM;
for (cnt = 0; cnt < priv->hw_params.max_txq_num; cnt++) {
txq = &priv->txq[cnt];
q = &txq->q;
pos += scnprintf(buf + pos, bufsz - pos,
"hwq %.2d: read=%u write=%u stop=%d"
" swq_id=%#.2x (ac %d/hwq %d)\n",
cnt, q->read_ptr, q->write_ptr,
!!test_bit(cnt, priv->queue_stopped),
txq->swq_id,
txq->swq_id & 0x80 ? txq->swq_id & 3 :
txq->swq_id,
txq->swq_id & 0x80 ? (txq->swq_id >> 2) &
0x1f : txq->swq_id);
if (cnt >= 4)
continue;
/* for the ACs, display the stop count too */
pos += scnprintf(buf + pos, bufsz - pos,
" stop-count: %d\n",
atomic_read(&priv->queue_stop_count[cnt]));
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_rx_queue_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
struct iwl_rx_queue *rxq = &priv->rxq;
char buf[256];
int pos = 0;
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos, "read: %u\n",
rxq->read);
pos += scnprintf(buf + pos, bufsz - pos, "write: %u\n",
rxq->write);
pos += scnprintf(buf + pos, bufsz - pos, "free_count: %u\n",
rxq->free_count);
pos += scnprintf(buf + pos, bufsz - pos, "closed_rb_num: %u\n",
le16_to_cpu(rxq->rb_stts->closed_rb_num) & 0x0FFF);
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_ucode_rx_stats_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
return priv->cfg->ops->lib->debugfs_ops.rx_stats_read(file,
user_buf, count, ppos);
}
static ssize_t iwl_dbgfs_ucode_tx_stats_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
return priv->cfg->ops->lib->debugfs_ops.tx_stats_read(file,
user_buf, count, ppos);
}
static ssize_t iwl_dbgfs_ucode_general_stats_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
return priv->cfg->ops->lib->debugfs_ops.general_stats_read(file,
user_buf, count, ppos);
}
static ssize_t iwl_dbgfs_sensitivity_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
int pos = 0;
int cnt = 0;
char *buf;
int bufsz = sizeof(struct iwl_sensitivity_data) * 4 + 100;
ssize_t ret;
struct iwl_sensitivity_data *data;
data = &priv->sensitivity_data;
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf) {
IWL_ERR(priv, "Can not allocate Buffer\n");
return -ENOMEM;
}
pos += scnprintf(buf + pos, bufsz - pos, "auto_corr_ofdm:\t\t\t %u\n",
data->auto_corr_ofdm);
pos += scnprintf(buf + pos, bufsz - pos,
"auto_corr_ofdm_mrc:\t\t %u\n",
data->auto_corr_ofdm_mrc);
pos += scnprintf(buf + pos, bufsz - pos, "auto_corr_ofdm_x1:\t\t %u\n",
data->auto_corr_ofdm_x1);
pos += scnprintf(buf + pos, bufsz - pos,
"auto_corr_ofdm_mrc_x1:\t\t %u\n",
data->auto_corr_ofdm_mrc_x1);
pos += scnprintf(buf + pos, bufsz - pos, "auto_corr_cck:\t\t\t %u\n",
data->auto_corr_cck);
pos += scnprintf(buf + pos, bufsz - pos, "auto_corr_cck_mrc:\t\t %u\n",
data->auto_corr_cck_mrc);
pos += scnprintf(buf + pos, bufsz - pos,
"last_bad_plcp_cnt_ofdm:\t\t %u\n",
data->last_bad_plcp_cnt_ofdm);
pos += scnprintf(buf + pos, bufsz - pos, "last_fa_cnt_ofdm:\t\t %u\n",
data->last_fa_cnt_ofdm);
pos += scnprintf(buf + pos, bufsz - pos,
"last_bad_plcp_cnt_cck:\t\t %u\n",
data->last_bad_plcp_cnt_cck);
pos += scnprintf(buf + pos, bufsz - pos, "last_fa_cnt_cck:\t\t %u\n",
data->last_fa_cnt_cck);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_curr_state:\t\t\t %u\n",
data->nrg_curr_state);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_prev_state:\t\t\t %u\n",
data->nrg_prev_state);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_value:\t\t\t");
for (cnt = 0; cnt < 10; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos, " %u",
data->nrg_value[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "\n");
pos += scnprintf(buf + pos, bufsz - pos, "nrg_silence_rssi:\t\t");
for (cnt = 0; cnt < NRG_NUM_PREV_STAT_L; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos, " %u",
data->nrg_silence_rssi[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "\n");
pos += scnprintf(buf + pos, bufsz - pos, "nrg_silence_ref:\t\t %u\n",
data->nrg_silence_ref);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_energy_idx:\t\t\t %u\n",
data->nrg_energy_idx);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_silence_idx:\t\t %u\n",
data->nrg_silence_idx);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_th_cck:\t\t\t %u\n",
data->nrg_th_cck);
pos += scnprintf(buf + pos, bufsz - pos,
"nrg_auto_corr_silence_diff:\t %u\n",
data->nrg_auto_corr_silence_diff);
pos += scnprintf(buf + pos, bufsz - pos, "num_in_cck_no_fa:\t\t %u\n",
data->num_in_cck_no_fa);
pos += scnprintf(buf + pos, bufsz - pos, "nrg_th_ofdm:\t\t\t %u\n",
data->nrg_th_ofdm);
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_chain_noise_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
int pos = 0;
int cnt = 0;
char *buf;
int bufsz = sizeof(struct iwl_chain_noise_data) * 4 + 100;
ssize_t ret;
struct iwl_chain_noise_data *data;
data = &priv->chain_noise_data;
buf = kzalloc(bufsz, GFP_KERNEL);
if (!buf) {
IWL_ERR(priv, "Can not allocate Buffer\n");
return -ENOMEM;
}
pos += scnprintf(buf + pos, bufsz - pos, "active_chains:\t\t\t %u\n",
data->active_chains);
pos += scnprintf(buf + pos, bufsz - pos, "chain_noise_a:\t\t\t %u\n",
data->chain_noise_a);
pos += scnprintf(buf + pos, bufsz - pos, "chain_noise_b:\t\t\t %u\n",
data->chain_noise_b);
pos += scnprintf(buf + pos, bufsz - pos, "chain_noise_c:\t\t\t %u\n",
data->chain_noise_c);
pos += scnprintf(buf + pos, bufsz - pos, "chain_signal_a:\t\t\t %u\n",
data->chain_signal_a);
pos += scnprintf(buf + pos, bufsz - pos, "chain_signal_b:\t\t\t %u\n",
data->chain_signal_b);
pos += scnprintf(buf + pos, bufsz - pos, "chain_signal_c:\t\t\t %u\n",
data->chain_signal_c);
pos += scnprintf(buf + pos, bufsz - pos, "beacon_count:\t\t\t %u\n",
data->beacon_count);
pos += scnprintf(buf + pos, bufsz - pos, "disconn_array:\t\t\t");
for (cnt = 0; cnt < NUM_RX_CHAINS; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos, " %u",
data->disconn_array[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "\n");
pos += scnprintf(buf + pos, bufsz - pos, "delta_gain_code:\t\t");
for (cnt = 0; cnt < NUM_RX_CHAINS; cnt++) {
pos += scnprintf(buf + pos, bufsz - pos, " %u",
data->delta_gain_code[cnt]);
}
pos += scnprintf(buf + pos, bufsz - pos, "\n");
pos += scnprintf(buf + pos, bufsz - pos, "radio_write:\t\t\t %u\n",
data->radio_write);
pos += scnprintf(buf + pos, bufsz - pos, "state:\t\t\t\t %u\n",
data->state);
ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
kfree(buf);
return ret;
}
static ssize_t iwl_dbgfs_power_save_status_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[60];
int pos = 0;
const size_t bufsz = sizeof(buf);
u32 pwrsave_status;
pwrsave_status = iwl_read32(priv, CSR_GP_CNTRL) &
CSR_GP_REG_POWER_SAVE_STATUS_MSK;
pos += scnprintf(buf + pos, bufsz - pos, "Power Save Status: ");
pos += scnprintf(buf + pos, bufsz - pos, "%s\n",
(pwrsave_status == CSR_GP_REG_NO_POWER_SAVE) ? "none" :
(pwrsave_status == CSR_GP_REG_MAC_POWER_SAVE) ? "MAC" :
(pwrsave_status == CSR_GP_REG_PHY_POWER_SAVE) ? "PHY" :
"error");
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_clear_ucode_statistics_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int clear;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &clear) != 1)
return -EFAULT;
/* make request to uCode to retrieve statistics information */
mutex_lock(&priv->mutex);
iwl_send_statistics_request(priv, CMD_SYNC, true);
mutex_unlock(&priv->mutex);
return count;
}
static ssize_t iwl_dbgfs_csr_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int csr;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &csr) != 1)
return -EFAULT;
if (priv->cfg->ops->lib->dump_csr)
priv->cfg->ops->lib->dump_csr(priv);
return count;
}
static ssize_t iwl_dbgfs_ucode_tracing_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = (struct iwl_priv *)file->private_data;
int pos = 0;
char buf[128];
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos, "ucode trace timer is %s\n",
priv->event_log.ucode_trace ? "On" : "Off");
pos += scnprintf(buf + pos, bufsz - pos, "non_wraps_count:\t\t %u\n",
priv->event_log.non_wraps_count);
pos += scnprintf(buf + pos, bufsz - pos, "wraps_once_count:\t\t %u\n",
priv->event_log.wraps_once_count);
pos += scnprintf(buf + pos, bufsz - pos, "wraps_more_count:\t\t %u\n",
priv->event_log.wraps_more_count);
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_ucode_tracing_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int trace;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &trace) != 1)
return -EFAULT;
if (trace) {
priv->event_log.ucode_trace = true;
/* schedule the ucode timer to occur in UCODE_TRACE_PERIOD */
mod_timer(&priv->ucode_trace,
jiffies + msecs_to_jiffies(UCODE_TRACE_PERIOD));
} else {
priv->event_log.ucode_trace = false;
del_timer_sync(&priv->ucode_trace);
}
return count;
}
static ssize_t iwl_dbgfs_rxon_flags_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = (struct iwl_priv *)file->private_data;
int len = 0;
char buf[20];
len = sprintf(buf, "0x%04X\n", le32_to_cpu(priv->active_rxon.flags));
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t iwl_dbgfs_rxon_filter_flags_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = (struct iwl_priv *)file->private_data;
int len = 0;
char buf[20];
len = sprintf(buf, "0x%04X\n",
le32_to_cpu(priv->active_rxon.filter_flags));
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t iwl_dbgfs_fh_reg_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = (struct iwl_priv *)file->private_data;
char *buf;
int pos = 0;
ssize_t ret = -EFAULT;
if (priv->cfg->ops->lib->dump_fh) {
ret = pos = priv->cfg->ops->lib->dump_fh(priv, &buf, true);
if (buf) {
ret = simple_read_from_buffer(user_buf,
count, ppos, buf, pos);
kfree(buf);
}
}
return ret;
}
static ssize_t iwl_dbgfs_missed_beacon_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
int pos = 0;
char buf[12];
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos, "%d\n",
priv->missed_beacon_threshold);
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_missed_beacon_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int missed;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &missed) != 1)
return -EINVAL;
if (missed < IWL_MISSED_BEACON_THRESHOLD_MIN ||
missed > IWL_MISSED_BEACON_THRESHOLD_MAX)
priv->missed_beacon_threshold =
IWL_MISSED_BEACON_THRESHOLD_DEF;
else
priv->missed_beacon_threshold = missed;
return count;
}
static ssize_t iwl_dbgfs_plcp_delta_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = (struct iwl_priv *)file->private_data;
int pos = 0;
char buf[12];
const size_t bufsz = sizeof(buf);
pos += scnprintf(buf + pos, bufsz - pos, "%u\n",
priv->cfg->plcp_delta_threshold);
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_plcp_delta_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int plcp;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &plcp) != 1)
return -EINVAL;
if ((plcp <= IWL_MAX_PLCP_ERR_THRESHOLD_MIN) ||
(plcp > IWL_MAX_PLCP_ERR_THRESHOLD_MAX))
priv->cfg->plcp_delta_threshold =
IWL_MAX_PLCP_ERR_THRESHOLD_DEF;
else
priv->cfg->plcp_delta_threshold = plcp;
return count;
}
static ssize_t iwl_dbgfs_force_reset_read(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
int i, pos = 0;
char buf[300];
const size_t bufsz = sizeof(buf);
struct iwl_force_reset *force_reset;
for (i = 0; i < IWL_MAX_FORCE_RESET; i++) {
force_reset = &priv->force_reset[i];
pos += scnprintf(buf + pos, bufsz - pos,
"Force reset method %d\n", i);
pos += scnprintf(buf + pos, bufsz - pos,
"\tnumber of reset request: %d\n",
force_reset->reset_request_count);
pos += scnprintf(buf + pos, bufsz - pos,
"\tnumber of reset request success: %d\n",
force_reset->reset_success_count);
pos += scnprintf(buf + pos, bufsz - pos,
"\tnumber of reset request reject: %d\n",
force_reset->reset_reject_count);
pos += scnprintf(buf + pos, bufsz - pos,
"\treset duration: %lu\n",
force_reset->reset_duration);
}
return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
}
static ssize_t iwl_dbgfs_force_reset_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos) {
struct iwl_priv *priv = file->private_data;
char buf[8];
int buf_size;
int reset, ret;
memset(buf, 0, sizeof(buf));
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (sscanf(buf, "%d", &reset) != 1)
return -EINVAL;
switch (reset) {
case IWL_RF_RESET:
case IWL_FW_RESET:
ret = iwl_force_reset(priv, reset);
break;
default:
return -EINVAL;
}
return ret ? ret : count;
}
DEBUGFS_READ_FILE_OPS(rx_statistics);
DEBUGFS_READ_FILE_OPS(tx_statistics);
DEBUGFS_READ_WRITE_FILE_OPS(traffic_log);
DEBUGFS_READ_FILE_OPS(rx_queue);
DEBUGFS_READ_FILE_OPS(tx_queue);
DEBUGFS_READ_FILE_OPS(ucode_rx_stats);
DEBUGFS_READ_FILE_OPS(ucode_tx_stats);
DEBUGFS_READ_FILE_OPS(ucode_general_stats);
DEBUGFS_READ_FILE_OPS(sensitivity);
DEBUGFS_READ_FILE_OPS(chain_noise);
DEBUGFS_READ_FILE_OPS(power_save_status);
DEBUGFS_WRITE_FILE_OPS(clear_ucode_statistics);
DEBUGFS_WRITE_FILE_OPS(clear_traffic_statistics);
DEBUGFS_WRITE_FILE_OPS(csr);
DEBUGFS_READ_WRITE_FILE_OPS(ucode_tracing);
DEBUGFS_READ_FILE_OPS(fh_reg);
DEBUGFS_READ_WRITE_FILE_OPS(missed_beacon);
DEBUGFS_READ_WRITE_FILE_OPS(plcp_delta);
DEBUGFS_READ_WRITE_FILE_OPS(force_reset);
DEBUGFS_READ_FILE_OPS(rxon_flags);
DEBUGFS_READ_FILE_OPS(rxon_filter_flags);
/*
* Create the debugfs files and directories
*
*/
int iwl_dbgfs_register(struct iwl_priv *priv, const char *name)
{
struct dentry *phyd = priv->hw->wiphy->debugfsdir;
struct dentry *dir_drv, *dir_data, *dir_rf, *dir_debug;
dir_drv = debugfs_create_dir(name, phyd);
if (!dir_drv)
return -ENOMEM;
priv->debugfs_dir = dir_drv;
dir_data = debugfs_create_dir("data", dir_drv);
if (!dir_data)
goto err;
dir_rf = debugfs_create_dir("rf", dir_drv);
if (!dir_rf)
goto err;
dir_debug = debugfs_create_dir("debug", dir_drv);
if (!dir_debug)
goto err;
DEBUGFS_ADD_FILE(nvm, dir_data, S_IRUSR);
DEBUGFS_ADD_FILE(sram, dir_data, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(log_event, dir_data, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(stations, dir_data, S_IRUSR);
DEBUGFS_ADD_FILE(channels, dir_data, S_IRUSR);
DEBUGFS_ADD_FILE(status, dir_data, S_IRUSR);
DEBUGFS_ADD_FILE(interrupt, dir_data, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(qos, dir_data, S_IRUSR);
DEBUGFS_ADD_FILE(led, dir_data, S_IRUSR);
if (!priv->cfg->broken_powersave) {
DEBUGFS_ADD_FILE(sleep_level_override, dir_data,
S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(current_sleep_command, dir_data, S_IRUSR);
}
DEBUGFS_ADD_FILE(thermal_throttling, dir_data, S_IRUSR);
DEBUGFS_ADD_FILE(disable_ht40, dir_data, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(rx_statistics, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(tx_statistics, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(traffic_log, dir_debug, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(rx_queue, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(tx_queue, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(power_save_status, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(clear_ucode_statistics, dir_debug, S_IWUSR);
DEBUGFS_ADD_FILE(clear_traffic_statistics, dir_debug, S_IWUSR);
DEBUGFS_ADD_FILE(csr, dir_debug, S_IWUSR);
DEBUGFS_ADD_FILE(fh_reg, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(missed_beacon, dir_debug, S_IWUSR);
DEBUGFS_ADD_FILE(plcp_delta, dir_debug, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(force_reset, dir_debug, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(ucode_rx_stats, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(ucode_tx_stats, dir_debug, S_IRUSR);
DEBUGFS_ADD_FILE(ucode_general_stats, dir_debug, S_IRUSR);
if (priv->cfg->sensitivity_calib_by_driver)
DEBUGFS_ADD_FILE(sensitivity, dir_debug, S_IRUSR);
if (priv->cfg->chain_noise_calib_by_driver)
DEBUGFS_ADD_FILE(chain_noise, dir_debug, S_IRUSR);
if (priv->cfg->ucode_tracing)
DEBUGFS_ADD_FILE(ucode_tracing, dir_debug, S_IWUSR | S_IRUSR);
DEBUGFS_ADD_FILE(rxon_flags, dir_debug, S_IWUSR);
DEBUGFS_ADD_FILE(rxon_filter_flags, dir_debug, S_IWUSR);
if (priv->cfg->sensitivity_calib_by_driver)
DEBUGFS_ADD_BOOL(disable_sensitivity, dir_rf,
&priv->disable_sens_cal);
if (priv->cfg->chain_noise_calib_by_driver)
DEBUGFS_ADD_BOOL(disable_chain_noise, dir_rf,
&priv->disable_chain_noise_cal);
if (priv->cfg->tx_power_by_driver)
DEBUGFS_ADD_BOOL(disable_tx_power, dir_rf,
&priv->disable_tx_power_cal);
return 0;
err:
IWL_ERR(priv, "Can't create the debugfs directory\n");
iwl_dbgfs_unregister(priv);
return -ENOMEM;
}
EXPORT_SYMBOL(iwl_dbgfs_register);
/**
* Remove the debugfs files and directories
*
*/
void iwl_dbgfs_unregister(struct iwl_priv *priv)
{
if (!priv->debugfs_dir)
return;
debugfs_remove_recursive(priv->debugfs_dir);
priv->debugfs_dir = NULL;
}
EXPORT_SYMBOL(iwl_dbgfs_unregister);
| gpl-2.0 |
aaronknister/linux-stable | arch/mips/jazz/irq.c | 1014 | 4141 | /*
* 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) 1992 Linus Torvalds
* Copyright (C) 1994 - 2001, 2003, 07 Ralf Baechle
*/
#include <linux/clockchips.h>
#include <linux/i8253.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/smp.h>
#include <linux/spinlock.h>
#include <linux/irq.h>
#include <asm/irq_cpu.h>
#include <asm/i8259.h>
#include <asm/io.h>
#include <asm/jazz.h>
#include <asm/pgtable.h>
#include <asm/tlbmisc.h>
static DEFINE_RAW_SPINLOCK(r4030_lock);
static void enable_r4030_irq(struct irq_data *d)
{
unsigned int mask = 1 << (d->irq - JAZZ_IRQ_START);
unsigned long flags;
raw_spin_lock_irqsave(&r4030_lock, flags);
mask |= r4030_read_reg16(JAZZ_IO_IRQ_ENABLE);
r4030_write_reg16(JAZZ_IO_IRQ_ENABLE, mask);
raw_spin_unlock_irqrestore(&r4030_lock, flags);
}
void disable_r4030_irq(struct irq_data *d)
{
unsigned int mask = ~(1 << (d->irq - JAZZ_IRQ_START));
unsigned long flags;
raw_spin_lock_irqsave(&r4030_lock, flags);
mask &= r4030_read_reg16(JAZZ_IO_IRQ_ENABLE);
r4030_write_reg16(JAZZ_IO_IRQ_ENABLE, mask);
raw_spin_unlock_irqrestore(&r4030_lock, flags);
}
static struct irq_chip r4030_irq_type = {
.name = "R4030",
.irq_mask = disable_r4030_irq,
.irq_unmask = enable_r4030_irq,
};
void __init init_r4030_ints(void)
{
int i;
for (i = JAZZ_IRQ_START; i <= JAZZ_IRQ_END; i++)
irq_set_chip_and_handler(i, &r4030_irq_type, handle_level_irq);
r4030_write_reg16(JAZZ_IO_IRQ_ENABLE, 0);
r4030_read_reg16(JAZZ_IO_IRQ_SOURCE); /* clear pending IRQs */
r4030_read_reg32(JAZZ_R4030_INVAL_ADDR); /* clear error bits */
}
/*
* On systems with i8259-style interrupt controllers we assume for
* driver compatibility reasons interrupts 0 - 15 to be the i8259
* interrupts even if the hardware uses a different interrupt numbering.
*/
void __init arch_init_irq(void)
{
/*
* this is a hack to get back the still needed wired mapping
* killed by init_mm()
*/
/* Map 0xe0000000 -> 0x0:800005C0, 0xe0010000 -> 0x1:30000580 */
add_wired_entry(0x02000017, 0x03c00017, 0xe0000000, PM_64K);
/* Map 0xe2000000 -> 0x0:900005C0, 0xe3010000 -> 0x0:910005C0 */
add_wired_entry(0x02400017, 0x02440017, 0xe2000000, PM_16M);
/* Map 0xe4000000 -> 0x0:600005C0, 0xe4100000 -> 400005C0 */
add_wired_entry(0x01800017, 0x01000017, 0xe4000000, PM_4M);
init_i8259_irqs(); /* Integrated i8259 */
mips_cpu_irq_init();
init_r4030_ints();
change_c0_status(ST0_IM, IE_IRQ2 | IE_IRQ1);
}
asmlinkage void plat_irq_dispatch(void)
{
unsigned int pending = read_c0_cause() & read_c0_status();
unsigned int irq;
if (pending & IE_IRQ4) {
r4030_read_reg32(JAZZ_TIMER_REGISTER);
do_IRQ(JAZZ_TIMER_IRQ);
} else if (pending & IE_IRQ2) {
irq = *(volatile u8 *)JAZZ_EISA_IRQ_ACK;
do_IRQ(irq);
} else if (pending & IE_IRQ1) {
irq = *(volatile u8 *)JAZZ_IO_IRQ_SOURCE >> 2;
if (likely(irq > 0))
do_IRQ(irq + JAZZ_IRQ_START - 1);
else
panic("Unimplemented loc_no_irq handler");
}
}
struct clock_event_device r4030_clockevent = {
.name = "r4030",
.features = CLOCK_EVT_FEAT_PERIODIC,
.rating = 300,
.irq = JAZZ_TIMER_IRQ,
};
static irqreturn_t r4030_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *cd = dev_id;
cd->event_handler(cd);
return IRQ_HANDLED;
}
static struct irqaction r4030_timer_irqaction = {
.handler = r4030_timer_interrupt,
.flags = IRQF_TIMER,
.name = "R4030 timer",
};
void __init plat_time_init(void)
{
struct clock_event_device *cd = &r4030_clockevent;
struct irqaction *action = &r4030_timer_irqaction;
unsigned int cpu = smp_processor_id();
BUG_ON(HZ != 100);
cd->cpumask = cpumask_of(cpu);
clockevents_register_device(cd);
action->dev_id = cd;
setup_irq(JAZZ_TIMER_IRQ, action);
/*
* Set clock to 100Hz.
*
* The R4030 timer receives an input clock of 1kHz which is divieded by
* a programmable 4-bit divider. This makes it fairly inflexible.
*/
r4030_write_reg32(JAZZ_TIMER_INTERVAL, 9);
setup_pit_timer();
}
| gpl-2.0 |
mtitinger/linux-next | drivers/pwm/pwm-lp3943.c | 1270 | 7674 | /*
* TI/National Semiconductor LP3943 PWM driver
*
* Copyright 2013 Texas Instruments
*
* Author: Milo Kim <milo.kim@ti.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.
*/
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/mfd/lp3943.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pwm.h>
#include <linux/slab.h>
#define LP3943_MAX_DUTY 255
#define LP3943_MIN_PERIOD 6250
#define LP3943_MAX_PERIOD 1600000
struct lp3943_pwm {
struct pwm_chip chip;
struct lp3943 *lp3943;
struct lp3943_platform_data *pdata;
};
static inline struct lp3943_pwm *to_lp3943_pwm(struct pwm_chip *_chip)
{
return container_of(_chip, struct lp3943_pwm, chip);
}
static struct lp3943_pwm_map *
lp3943_pwm_request_map(struct lp3943_pwm *lp3943_pwm, int hwpwm)
{
struct lp3943_platform_data *pdata = lp3943_pwm->pdata;
struct lp3943 *lp3943 = lp3943_pwm->lp3943;
struct lp3943_pwm_map *pwm_map;
int i, offset;
pwm_map = kzalloc(sizeof(*pwm_map), GFP_KERNEL);
if (!pwm_map)
return ERR_PTR(-ENOMEM);
pwm_map->output = pdata->pwms[hwpwm]->output;
pwm_map->num_outputs = pdata->pwms[hwpwm]->num_outputs;
for (i = 0; i < pwm_map->num_outputs; i++) {
offset = pwm_map->output[i];
/* Return an error if the pin is already assigned */
if (test_and_set_bit(offset, &lp3943->pin_used)) {
kfree(pwm_map);
return ERR_PTR(-EBUSY);
}
}
return pwm_map;
}
static int lp3943_pwm_request(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct lp3943_pwm *lp3943_pwm = to_lp3943_pwm(chip);
struct lp3943_pwm_map *pwm_map;
pwm_map = lp3943_pwm_request_map(lp3943_pwm, pwm->hwpwm);
if (IS_ERR(pwm_map))
return PTR_ERR(pwm_map);
return pwm_set_chip_data(pwm, pwm_map);
}
static void lp3943_pwm_free_map(struct lp3943_pwm *lp3943_pwm,
struct lp3943_pwm_map *pwm_map)
{
struct lp3943 *lp3943 = lp3943_pwm->lp3943;
int i, offset;
for (i = 0; i < pwm_map->num_outputs; i++) {
offset = pwm_map->output[i];
clear_bit(offset, &lp3943->pin_used);
}
kfree(pwm_map);
}
static void lp3943_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct lp3943_pwm *lp3943_pwm = to_lp3943_pwm(chip);
struct lp3943_pwm_map *pwm_map = pwm_get_chip_data(pwm);
lp3943_pwm_free_map(lp3943_pwm, pwm_map);
}
static int lp3943_pwm_config(struct pwm_chip *chip, struct pwm_device *pwm,
int duty_ns, int period_ns)
{
struct lp3943_pwm *lp3943_pwm = to_lp3943_pwm(chip);
struct lp3943 *lp3943 = lp3943_pwm->lp3943;
u8 val, reg_duty, reg_prescale;
int err;
/*
* How to configure the LP3943 PWMs
*
* 1) Period = 6250 ~ 1600000
* 2) Prescale = period / 6250 -1
* 3) Duty = input duty
*
* Prescale and duty are register values
*/
if (pwm->hwpwm == 0) {
reg_prescale = LP3943_REG_PRESCALE0;
reg_duty = LP3943_REG_PWM0;
} else {
reg_prescale = LP3943_REG_PRESCALE1;
reg_duty = LP3943_REG_PWM1;
}
period_ns = clamp(period_ns, LP3943_MIN_PERIOD, LP3943_MAX_PERIOD);
val = (u8)(period_ns / LP3943_MIN_PERIOD - 1);
err = lp3943_write_byte(lp3943, reg_prescale, val);
if (err)
return err;
val = (u8)(duty_ns * LP3943_MAX_DUTY / period_ns);
return lp3943_write_byte(lp3943, reg_duty, val);
}
static int lp3943_pwm_set_mode(struct lp3943_pwm *lp3943_pwm,
struct lp3943_pwm_map *pwm_map,
u8 val)
{
struct lp3943 *lp3943 = lp3943_pwm->lp3943;
const struct lp3943_reg_cfg *mux = lp3943->mux_cfg;
int i, index, err;
for (i = 0; i < pwm_map->num_outputs; i++) {
index = pwm_map->output[i];
err = lp3943_update_bits(lp3943, mux[index].reg,
mux[index].mask,
val << mux[index].shift);
if (err)
return err;
}
return 0;
}
static int lp3943_pwm_enable(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct lp3943_pwm *lp3943_pwm = to_lp3943_pwm(chip);
struct lp3943_pwm_map *pwm_map = pwm_get_chip_data(pwm);
u8 val;
if (pwm->hwpwm == 0)
val = LP3943_DIM_PWM0;
else
val = LP3943_DIM_PWM1;
/*
* Each PWM generator is set to control any of outputs of LP3943.
* To enable/disable the PWM, these output pins should be configured.
*/
return lp3943_pwm_set_mode(lp3943_pwm, pwm_map, val);
}
static void lp3943_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct lp3943_pwm *lp3943_pwm = to_lp3943_pwm(chip);
struct lp3943_pwm_map *pwm_map = pwm_get_chip_data(pwm);
/*
* LP3943 outputs are open-drain, so the pin should be configured
* when the PWM is disabled.
*/
lp3943_pwm_set_mode(lp3943_pwm, pwm_map, LP3943_GPIO_OUT_HIGH);
}
static const struct pwm_ops lp3943_pwm_ops = {
.request = lp3943_pwm_request,
.free = lp3943_pwm_free,
.config = lp3943_pwm_config,
.enable = lp3943_pwm_enable,
.disable = lp3943_pwm_disable,
.owner = THIS_MODULE,
};
static int lp3943_pwm_parse_dt(struct device *dev,
struct lp3943_pwm *lp3943_pwm)
{
static const char * const name[] = { "ti,pwm0", "ti,pwm1", };
struct device_node *node = dev->of_node;
struct lp3943_platform_data *pdata;
struct lp3943_pwm_map *pwm_map;
enum lp3943_pwm_output *output;
int i, err, proplen, count = 0;
u32 num_outputs;
if (!node)
return -EINVAL;
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
/*
* Read the output map configuration from the device tree.
* Each of the two PWM generators can drive zero or more outputs.
*/
for (i = 0; i < LP3943_NUM_PWMS; i++) {
if (!of_get_property(node, name[i], &proplen))
continue;
num_outputs = proplen / sizeof(u32);
if (num_outputs == 0)
continue;
output = devm_kzalloc(dev, sizeof(*output) * num_outputs,
GFP_KERNEL);
if (!output)
return -ENOMEM;
err = of_property_read_u32_array(node, name[i], output,
num_outputs);
if (err)
return err;
pwm_map = devm_kzalloc(dev, sizeof(*pwm_map), GFP_KERNEL);
if (!pwm_map)
return -ENOMEM;
pwm_map->output = output;
pwm_map->num_outputs = num_outputs;
pdata->pwms[i] = pwm_map;
count++;
}
if (count == 0)
return -ENODATA;
lp3943_pwm->pdata = pdata;
return 0;
}
static int lp3943_pwm_probe(struct platform_device *pdev)
{
struct lp3943 *lp3943 = dev_get_drvdata(pdev->dev.parent);
struct lp3943_pwm *lp3943_pwm;
int ret;
lp3943_pwm = devm_kzalloc(&pdev->dev, sizeof(*lp3943_pwm), GFP_KERNEL);
if (!lp3943_pwm)
return -ENOMEM;
lp3943_pwm->pdata = lp3943->pdata;
if (!lp3943_pwm->pdata) {
if (IS_ENABLED(CONFIG_OF))
ret = lp3943_pwm_parse_dt(&pdev->dev, lp3943_pwm);
else
ret = -ENODEV;
if (ret)
return ret;
}
lp3943_pwm->lp3943 = lp3943;
lp3943_pwm->chip.dev = &pdev->dev;
lp3943_pwm->chip.ops = &lp3943_pwm_ops;
lp3943_pwm->chip.npwm = LP3943_NUM_PWMS;
lp3943_pwm->chip.can_sleep = true;
platform_set_drvdata(pdev, lp3943_pwm);
return pwmchip_add(&lp3943_pwm->chip);
}
static int lp3943_pwm_remove(struct platform_device *pdev)
{
struct lp3943_pwm *lp3943_pwm = platform_get_drvdata(pdev);
return pwmchip_remove(&lp3943_pwm->chip);
}
#ifdef CONFIG_OF
static const struct of_device_id lp3943_pwm_of_match[] = {
{ .compatible = "ti,lp3943-pwm", },
{ }
};
MODULE_DEVICE_TABLE(of, lp3943_pwm_of_match);
#endif
static struct platform_driver lp3943_pwm_driver = {
.probe = lp3943_pwm_probe,
.remove = lp3943_pwm_remove,
.driver = {
.name = "lp3943-pwm",
.of_match_table = of_match_ptr(lp3943_pwm_of_match),
},
};
module_platform_driver(lp3943_pwm_driver);
MODULE_DESCRIPTION("LP3943 PWM driver");
MODULE_ALIAS("platform:lp3943-pwm");
MODULE_AUTHOR("Milo Kim");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ArtemTeleshev/linux | drivers/regulator/rc5t583-regulator.c | 1270 | 6455 | /*
* Regulator driver for RICOH RC5T583 power management chip.
*
* Copyright (c) 2011-2012, NVIDIA CORPORATION. All rights reserved.
* Author: Laxman dewangan <ldewangan@nvidia.com>
*
* based on code
* Copyright (C) 2011 RICOH COMPANY,LTD
*
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/gpio.h>
#include <linux/mfd/rc5t583.h>
struct rc5t583_regulator_info {
int deepsleep_id;
/* Regulator register address.*/
uint8_t reg_disc_reg;
uint8_t disc_bit;
uint8_t deepsleep_reg;
/* Regulator specific turn-on delay and voltage settling time*/
int enable_uv_per_us;
/* Used by regulator core */
struct regulator_desc desc;
};
struct rc5t583_regulator {
struct rc5t583_regulator_info *reg_info;
struct regulator_dev *rdev;
};
static int rc5t583_regulator_enable_time(struct regulator_dev *rdev)
{
struct rc5t583_regulator *reg = rdev_get_drvdata(rdev);
int vsel = regulator_get_voltage_sel_regmap(rdev);
int curr_uV = regulator_list_voltage_linear(rdev, vsel);
return DIV_ROUND_UP(curr_uV, reg->reg_info->enable_uv_per_us);
}
static struct regulator_ops rc5t583_ops = {
.is_enabled = regulator_is_enabled_regmap,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
.enable_time = rc5t583_regulator_enable_time,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
.list_voltage = regulator_list_voltage_linear,
.map_voltage = regulator_map_voltage_linear,
.set_voltage_time_sel = regulator_set_voltage_time_sel,
};
#define RC5T583_REG(_id, _en_reg, _en_bit, _disc_reg, _disc_bit, \
_vout_mask, _min_mv, _max_mv, _step_uV, _enable_mv) \
{ \
.reg_disc_reg = RC5T583_REG_##_disc_reg, \
.disc_bit = _disc_bit, \
.deepsleep_reg = RC5T583_REG_##_id##DAC_DS, \
.enable_uv_per_us = _enable_mv * 1000, \
.deepsleep_id = RC5T583_DS_##_id, \
.desc = { \
.name = "rc5t583-regulator-"#_id, \
.id = RC5T583_REGULATOR_##_id, \
.n_voltages = (_max_mv - _min_mv) * 1000 / _step_uV + 1, \
.ops = &rc5t583_ops, \
.type = REGULATOR_VOLTAGE, \
.owner = THIS_MODULE, \
.vsel_reg = RC5T583_REG_##_id##DAC, \
.vsel_mask = _vout_mask, \
.enable_reg = RC5T583_REG_##_en_reg, \
.enable_mask = BIT(_en_bit), \
.min_uV = _min_mv * 1000, \
.uV_step = _step_uV, \
.ramp_delay = 40 * 1000, \
}, \
}
static struct rc5t583_regulator_info rc5t583_reg_info[RC5T583_REGULATOR_MAX] = {
RC5T583_REG(DC0, DC0CTL, 0, DC0CTL, 1, 0x7F, 700, 1500, 12500, 4),
RC5T583_REG(DC1, DC1CTL, 0, DC1CTL, 1, 0x7F, 700, 1500, 12500, 14),
RC5T583_REG(DC2, DC2CTL, 0, DC2CTL, 1, 0x7F, 900, 2400, 12500, 14),
RC5T583_REG(DC3, DC3CTL, 0, DC3CTL, 1, 0x7F, 900, 2400, 12500, 14),
RC5T583_REG(LDO0, LDOEN2, 0, LDODIS2, 0, 0x7F, 900, 3400, 25000, 160),
RC5T583_REG(LDO1, LDOEN2, 1, LDODIS2, 1, 0x7F, 900, 3400, 25000, 160),
RC5T583_REG(LDO2, LDOEN2, 2, LDODIS2, 2, 0x7F, 900, 3400, 25000, 160),
RC5T583_REG(LDO3, LDOEN2, 3, LDODIS2, 3, 0x7F, 900, 3400, 25000, 160),
RC5T583_REG(LDO4, LDOEN2, 4, LDODIS2, 4, 0x3F, 750, 1500, 12500, 133),
RC5T583_REG(LDO5, LDOEN2, 5, LDODIS2, 5, 0x7F, 900, 3400, 25000, 267),
RC5T583_REG(LDO6, LDOEN2, 6, LDODIS2, 6, 0x7F, 900, 3400, 25000, 133),
RC5T583_REG(LDO7, LDOEN2, 7, LDODIS2, 7, 0x7F, 900, 3400, 25000, 233),
RC5T583_REG(LDO8, LDOEN1, 0, LDODIS1, 0, 0x7F, 900, 3400, 25000, 233),
RC5T583_REG(LDO9, LDOEN1, 1, LDODIS1, 1, 0x7F, 900, 3400, 25000, 133),
};
static int rc5t583_regulator_probe(struct platform_device *pdev)
{
struct rc5t583 *rc5t583 = dev_get_drvdata(pdev->dev.parent);
struct rc5t583_platform_data *pdata = dev_get_platdata(rc5t583->dev);
struct regulator_config config = { };
struct rc5t583_regulator *reg = NULL;
struct rc5t583_regulator *regs;
struct regulator_dev *rdev;
struct rc5t583_regulator_info *ri;
int ret;
int id;
if (!pdata) {
dev_err(&pdev->dev, "No platform data, exiting...\n");
return -ENODEV;
}
regs = devm_kzalloc(&pdev->dev, RC5T583_REGULATOR_MAX *
sizeof(struct rc5t583_regulator), GFP_KERNEL);
if (!regs)
return -ENOMEM;
for (id = 0; id < RC5T583_REGULATOR_MAX; ++id) {
reg = ®s[id];
ri = &rc5t583_reg_info[id];
reg->reg_info = ri;
if (ri->deepsleep_id == RC5T583_DS_NONE)
goto skip_ext_pwr_config;
ret = rc5t583_ext_power_req_config(rc5t583->dev,
ri->deepsleep_id,
pdata->regulator_ext_pwr_control[id],
pdata->regulator_deepsleep_slot[id]);
/*
* Configuring external control is not a major issue,
* just give warning.
*/
if (ret < 0)
dev_warn(&pdev->dev,
"Failed to configure ext control %d\n", id);
skip_ext_pwr_config:
config.dev = &pdev->dev;
config.init_data = pdata->reg_init_data[id];
config.driver_data = reg;
config.regmap = rc5t583->regmap;
rdev = devm_regulator_register(&pdev->dev, &ri->desc, &config);
if (IS_ERR(rdev)) {
dev_err(&pdev->dev, "Failed to register regulator %s\n",
ri->desc.name);
return PTR_ERR(rdev);
}
reg->rdev = rdev;
}
platform_set_drvdata(pdev, regs);
return 0;
}
static struct platform_driver rc5t583_regulator_driver = {
.driver = {
.name = "rc5t583-regulator",
},
.probe = rc5t583_regulator_probe,
};
static int __init rc5t583_regulator_init(void)
{
return platform_driver_register(&rc5t583_regulator_driver);
}
subsys_initcall(rc5t583_regulator_init);
static void __exit rc5t583_regulator_exit(void)
{
platform_driver_unregister(&rc5t583_regulator_driver);
}
module_exit(rc5t583_regulator_exit);
MODULE_AUTHOR("Laxman Dewangan <ldewangan@nvidia.com>");
MODULE_DESCRIPTION("RC5T583 regulator driver");
MODULE_ALIAS("platform:rc5t583-regulator");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ElectryDev/android_kernel_grouper | arch/arm/mach-omap2/dma.c | 2806 | 8059 | /*
* OMAP2+ DMA driver
*
* Copyright (C) 2003 - 2008 Nokia Corporation
* Author: Juha Yrjölä <juha.yrjola@nokia.com>
* DMA channel linking for 1610 by Samuel Ortiz <samuel.ortiz@nokia.com>
* Graphics DMA and LCD DMA graphics tranformations
* by Imre Deak <imre.deak@nokia.com>
* OMAP2/3 support Copyright (C) 2004-2007 Texas Instruments, Inc.
* Some functions based on earlier dma-omap.c Copyright (C) 2001 RidgeRun, Inc.
*
* Copyright (C) 2009 Texas Instruments
* Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
* Converted DMA library into platform driver
* - G, Manjunath Kondaiah <manjugk@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/err.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <plat/omap_hwmod.h>
#include <plat/omap_device.h>
#include <plat/dma.h>
#define OMAP2_DMA_STRIDE 0x60
static u32 errata;
static u8 dma_stride;
static struct omap_dma_dev_attr *d;
static enum omap_reg_offsets dma_common_ch_start, dma_common_ch_end;
static u16 reg_map[] = {
[REVISION] = 0x00,
[GCR] = 0x78,
[IRQSTATUS_L0] = 0x08,
[IRQSTATUS_L1] = 0x0c,
[IRQSTATUS_L2] = 0x10,
[IRQSTATUS_L3] = 0x14,
[IRQENABLE_L0] = 0x18,
[IRQENABLE_L1] = 0x1c,
[IRQENABLE_L2] = 0x20,
[IRQENABLE_L3] = 0x24,
[SYSSTATUS] = 0x28,
[OCP_SYSCONFIG] = 0x2c,
[CAPS_0] = 0x64,
[CAPS_2] = 0x6c,
[CAPS_3] = 0x70,
[CAPS_4] = 0x74,
/* Common register offsets */
[CCR] = 0x80,
[CLNK_CTRL] = 0x84,
[CICR] = 0x88,
[CSR] = 0x8c,
[CSDP] = 0x90,
[CEN] = 0x94,
[CFN] = 0x98,
[CSEI] = 0xa4,
[CSFI] = 0xa8,
[CDEI] = 0xac,
[CDFI] = 0xb0,
[CSAC] = 0xb4,
[CDAC] = 0xb8,
/* Channel specific register offsets */
[CSSA] = 0x9c,
[CDSA] = 0xa0,
[CCEN] = 0xbc,
[CCFN] = 0xc0,
[COLOR] = 0xc4,
/* OMAP4 specific registers */
[CDP] = 0xd0,
[CNDP] = 0xd4,
[CCDN] = 0xd8,
};
static struct omap_device_pm_latency omap2_dma_latency[] = {
{
.deactivate_func = omap_device_idle_hwmods,
.activate_func = omap_device_enable_hwmods,
.flags = OMAP_DEVICE_LATENCY_AUTO_ADJUST,
},
};
static void __iomem *dma_base;
static inline void dma_write(u32 val, int reg, int lch)
{
u8 stride;
u32 offset;
stride = (reg >= dma_common_ch_start) ? dma_stride : 0;
offset = reg_map[reg] + (stride * lch);
__raw_writel(val, dma_base + offset);
}
static inline u32 dma_read(int reg, int lch)
{
u8 stride;
u32 offset, val;
stride = (reg >= dma_common_ch_start) ? dma_stride : 0;
offset = reg_map[reg] + (stride * lch);
val = __raw_readl(dma_base + offset);
return val;
}
static inline void omap2_disable_irq_lch(int lch)
{
u32 val;
val = dma_read(IRQENABLE_L0, lch);
val &= ~(1 << lch);
dma_write(val, IRQENABLE_L0, lch);
}
static void omap2_clear_dma(int lch)
{
int i = dma_common_ch_start;
for (; i <= dma_common_ch_end; i += 1)
dma_write(0, i, lch);
}
static void omap2_show_dma_caps(void)
{
u8 revision = dma_read(REVISION, 0) & 0xff;
printk(KERN_INFO "OMAP DMA hardware revision %d.%d\n",
revision >> 4, revision & 0xf);
return;
}
static u32 configure_dma_errata(void)
{
/*
* Errata applicable for OMAP2430ES1.0 and all omap2420
*
* I.
* Erratum ID: Not Available
* Inter Frame DMA buffering issue DMA will wrongly
* buffer elements if packing and bursting is enabled. This might
* result in data gets stalled in FIFO at the end of the block.
* Workaround: DMA channels must have BUFFERING_DISABLED bit set to
* guarantee no data will stay in the DMA FIFO in case inter frame
* buffering occurs
*
* II.
* Erratum ID: Not Available
* DMA may hang when several channels are used in parallel
* In the following configuration, DMA channel hanging can occur:
* a. Channel i, hardware synchronized, is enabled
* b. Another channel (Channel x), software synchronized, is enabled.
* c. Channel i is disabled before end of transfer
* d. Channel i is reenabled.
* e. Steps 1 to 4 are repeated a certain number of times.
* f. A third channel (Channel y), software synchronized, is enabled.
* Channel x and Channel y may hang immediately after step 'f'.
* Workaround:
* For any channel used - make sure NextLCH_ID is set to the value j.
*/
if (cpu_is_omap2420() || (cpu_is_omap2430() &&
(omap_type() == OMAP2430_REV_ES1_0))) {
SET_DMA_ERRATA(DMA_ERRATA_IFRAME_BUFFERING);
SET_DMA_ERRATA(DMA_ERRATA_PARALLEL_CHANNELS);
}
/*
* Erratum ID: i378: OMAP2+: sDMA Channel is not disabled
* after a transaction error.
* Workaround: SW should explicitely disable the channel.
*/
if (cpu_class_is_omap2())
SET_DMA_ERRATA(DMA_ERRATA_i378);
/*
* Erratum ID: i541: sDMA FIFO draining does not finish
* If sDMA channel is disabled on the fly, sDMA enters standby even
* through FIFO Drain is still in progress
* Workaround: Put sDMA in NoStandby more before a logical channel is
* disabled, then put it back to SmartStandby right after the channel
* finishes FIFO draining.
*/
if (cpu_is_omap34xx())
SET_DMA_ERRATA(DMA_ERRATA_i541);
/*
* Erratum ID: i88 : Special programming model needed to disable DMA
* before end of block.
* Workaround: software must ensure that the DMA is configured in No
* Standby mode(DMAx_OCP_SYSCONFIG.MIDLEMODE = "01")
*/
if (omap_type() == OMAP3430_REV_ES1_0)
SET_DMA_ERRATA(DMA_ERRATA_i88);
/*
* Erratum 3.2/3.3: sometimes 0 is returned if CSAC/CDAC is
* read before the DMA controller finished disabling the channel.
*/
SET_DMA_ERRATA(DMA_ERRATA_3_3);
/*
* Erratum ID: Not Available
* A bug in ROM code leaves IRQ status for channels 0 and 1 uncleared
* after secure sram context save and restore.
* Work around: Hence we need to manually clear those IRQs to avoid
* spurious interrupts. This affects only secure devices.
*/
if (cpu_is_omap34xx() && (omap_type() != OMAP2_DEVICE_TYPE_GP))
SET_DMA_ERRATA(DMA_ROMCODE_BUG);
return errata;
}
/* One time initializations */
static int __init omap2_system_dma_init_dev(struct omap_hwmod *oh, void *unused)
{
struct omap_device *od;
struct omap_system_dma_plat_info *p;
struct resource *mem;
char *name = "omap_dma_system";
dma_stride = OMAP2_DMA_STRIDE;
dma_common_ch_start = CSDP;
if (cpu_is_omap3630() || cpu_is_omap4430())
dma_common_ch_end = CCDN;
else
dma_common_ch_end = CCFN;
p = kzalloc(sizeof(struct omap_system_dma_plat_info), GFP_KERNEL);
if (!p) {
pr_err("%s: Unable to allocate pdata for %s:%s\n",
__func__, name, oh->name);
return -ENOMEM;
}
p->dma_attr = (struct omap_dma_dev_attr *)oh->dev_attr;
p->disable_irq_lch = omap2_disable_irq_lch;
p->show_dma_caps = omap2_show_dma_caps;
p->clear_dma = omap2_clear_dma;
p->dma_write = dma_write;
p->dma_read = dma_read;
p->clear_lch_regs = NULL;
p->errata = configure_dma_errata();
od = omap_device_build(name, 0, oh, p, sizeof(*p),
omap2_dma_latency, ARRAY_SIZE(omap2_dma_latency), 0);
kfree(p);
if (IS_ERR(od)) {
pr_err("%s: Can't build omap_device for %s:%s.\n",
__func__, name, oh->name);
return PTR_ERR(od);
}
mem = platform_get_resource(&od->pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&od->pdev.dev, "%s: no mem resource\n", __func__);
return -EINVAL;
}
dma_base = ioremap(mem->start, resource_size(mem));
if (!dma_base) {
dev_err(&od->pdev.dev, "%s: ioremap fail\n", __func__);
return -ENOMEM;
}
d = oh->dev_attr;
d->chan = kzalloc(sizeof(struct omap_dma_lch) *
(d->lch_count), GFP_KERNEL);
if (!d->chan) {
dev_err(&od->pdev.dev, "%s: kzalloc fail\n", __func__);
return -ENOMEM;
}
return 0;
}
static int __init omap2_system_dma_init(void)
{
return omap_hwmod_for_each_by_class("dma",
omap2_system_dma_init_dev, NULL);
}
arch_initcall(omap2_system_dma_init);
| gpl-2.0 |
noobnl/msm-jf-kernel | sound/soc/soc-utils.c | 4598 | 3758 | /*
* soc-util.c -- ALSA SoC Audio Layer utility functions
*
* Copyright 2009 Wolfson Microelectronics PLC.
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
* Liam Girdwood <lrg@slimlogic.co.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.
*/
#include <linux/platform_device.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
int snd_soc_calc_frame_size(int sample_size, int channels, int tdm_slots)
{
return sample_size * channels * tdm_slots;
}
EXPORT_SYMBOL_GPL(snd_soc_calc_frame_size);
int snd_soc_params_to_frame_size(struct snd_pcm_hw_params *params)
{
int sample_size;
sample_size = snd_pcm_format_width(params_format(params));
if (sample_size < 0)
return sample_size;
return snd_soc_calc_frame_size(sample_size, params_channels(params),
1);
}
EXPORT_SYMBOL_GPL(snd_soc_params_to_frame_size);
int snd_soc_calc_bclk(int fs, int sample_size, int channels, int tdm_slots)
{
return fs * snd_soc_calc_frame_size(sample_size, channels, tdm_slots);
}
EXPORT_SYMBOL_GPL(snd_soc_calc_bclk);
int snd_soc_params_to_bclk(struct snd_pcm_hw_params *params)
{
int ret;
ret = snd_soc_params_to_frame_size(params);
if (ret > 0)
return ret * params_rate(params);
else
return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_params_to_bclk);
static const struct snd_pcm_hardware dummy_dma_hardware = {
.formats = 0xffffffff,
.channels_min = 1,
.channels_max = UINT_MAX,
/* Random values to keep userspace happy when checking constraints */
.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER,
.buffer_bytes_max = 128*1024,
.period_bytes_min = PAGE_SIZE,
.period_bytes_max = PAGE_SIZE*2,
.periods_min = 2,
.periods_max = 128,
};
static int dummy_dma_open(struct snd_pcm_substream *substream)
{
snd_soc_set_runtime_hwparams(substream, &dummy_dma_hardware);
return 0;
}
static struct snd_pcm_ops dummy_dma_ops = {
.open = dummy_dma_open,
.ioctl = snd_pcm_lib_ioctl,
};
static struct snd_soc_platform_driver dummy_platform = {
.ops = &dummy_dma_ops,
};
static struct snd_soc_codec_driver dummy_codec;
static struct snd_soc_dai_driver dummy_dai = {
.name = "snd-soc-dummy-dai",
};
static __devinit int snd_soc_dummy_probe(struct platform_device *pdev)
{
int ret;
ret = snd_soc_register_codec(&pdev->dev, &dummy_codec, &dummy_dai, 1);
if (ret < 0)
return ret;
ret = snd_soc_register_platform(&pdev->dev, &dummy_platform);
if (ret < 0) {
snd_soc_unregister_codec(&pdev->dev);
return ret;
}
return ret;
}
static __devexit int snd_soc_dummy_remove(struct platform_device *pdev)
{
snd_soc_unregister_platform(&pdev->dev);
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver soc_dummy_driver = {
.driver = {
.name = "snd-soc-dummy",
.owner = THIS_MODULE,
},
.probe = snd_soc_dummy_probe,
.remove = __devexit_p(snd_soc_dummy_remove),
};
static struct platform_device *soc_dummy_dev;
int __init snd_soc_util_init(void)
{
int ret;
soc_dummy_dev = platform_device_alloc("snd-soc-dummy", -1);
if (!soc_dummy_dev)
return -ENOMEM;
ret = platform_device_add(soc_dummy_dev);
if (ret != 0) {
platform_device_put(soc_dummy_dev);
return ret;
}
ret = platform_driver_register(&soc_dummy_driver);
if (ret != 0)
platform_device_unregister(soc_dummy_dev);
return ret;
}
void __exit snd_soc_util_exit(void)
{
platform_device_unregister(soc_dummy_dev);
platform_driver_unregister(&soc_dummy_driver);
}
| gpl-2.0 |
davtse/i9505 | drivers/platform/x86/ideapad-laptop.c | 4598 | 19939 | /*
* ideapad-laptop.c - Lenovo IdeaPad ACPI Extras
*
* Copyright © 2010 Intel Corporation
* Copyright © 2010 David Woodhouse <dwmw2@infradead.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include <linux/rfkill.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#define IDEAPAD_RFKILL_DEV_NUM (3)
#define CFG_BT_BIT (16)
#define CFG_3G_BIT (17)
#define CFG_WIFI_BIT (18)
#define CFG_CAMERA_BIT (19)
enum {
VPCCMD_R_VPC1 = 0x10,
VPCCMD_R_BL_MAX,
VPCCMD_R_BL,
VPCCMD_W_BL,
VPCCMD_R_WIFI,
VPCCMD_W_WIFI,
VPCCMD_R_BT,
VPCCMD_W_BT,
VPCCMD_R_BL_POWER,
VPCCMD_R_NOVO,
VPCCMD_R_VPC2,
VPCCMD_R_TOUCHPAD,
VPCCMD_W_TOUCHPAD,
VPCCMD_R_CAMERA,
VPCCMD_W_CAMERA,
VPCCMD_R_3G,
VPCCMD_W_3G,
VPCCMD_R_ODD, /* 0x21 */
VPCCMD_R_RF = 0x23,
VPCCMD_W_RF,
VPCCMD_W_BL_POWER = 0x33,
};
struct ideapad_private {
struct rfkill *rfk[IDEAPAD_RFKILL_DEV_NUM];
struct platform_device *platform_device;
struct input_dev *inputdev;
struct backlight_device *blightdev;
struct dentry *debug;
unsigned long cfg;
};
static acpi_handle ideapad_handle;
static struct ideapad_private *ideapad_priv;
static bool no_bt_rfkill;
module_param(no_bt_rfkill, bool, 0444);
MODULE_PARM_DESC(no_bt_rfkill, "No rfkill for bluetooth.");
/*
* ACPI Helpers
*/
#define IDEAPAD_EC_TIMEOUT (100) /* in ms */
static int read_method_int(acpi_handle handle, const char *method, int *val)
{
acpi_status status;
unsigned long long result;
status = acpi_evaluate_integer(handle, (char *)method, NULL, &result);
if (ACPI_FAILURE(status)) {
*val = -1;
return -1;
} else {
*val = result;
return 0;
}
}
static int method_vpcr(acpi_handle handle, int cmd, int *ret)
{
acpi_status status;
unsigned long long result;
struct acpi_object_list params;
union acpi_object in_obj;
params.count = 1;
params.pointer = &in_obj;
in_obj.type = ACPI_TYPE_INTEGER;
in_obj.integer.value = cmd;
status = acpi_evaluate_integer(handle, "VPCR", ¶ms, &result);
if (ACPI_FAILURE(status)) {
*ret = -1;
return -1;
} else {
*ret = result;
return 0;
}
}
static int method_vpcw(acpi_handle handle, int cmd, int data)
{
struct acpi_object_list params;
union acpi_object in_obj[2];
acpi_status status;
params.count = 2;
params.pointer = in_obj;
in_obj[0].type = ACPI_TYPE_INTEGER;
in_obj[0].integer.value = cmd;
in_obj[1].type = ACPI_TYPE_INTEGER;
in_obj[1].integer.value = data;
status = acpi_evaluate_object(handle, "VPCW", ¶ms, NULL);
if (status != AE_OK)
return -1;
return 0;
}
static int read_ec_data(acpi_handle handle, int cmd, unsigned long *data)
{
int val;
unsigned long int end_jiffies;
if (method_vpcw(handle, 1, cmd))
return -1;
for (end_jiffies = jiffies+(HZ)*IDEAPAD_EC_TIMEOUT/1000+1;
time_before(jiffies, end_jiffies);) {
schedule();
if (method_vpcr(handle, 1, &val))
return -1;
if (val == 0) {
if (method_vpcr(handle, 0, &val))
return -1;
*data = val;
return 0;
}
}
pr_err("timeout in read_ec_cmd\n");
return -1;
}
static int write_ec_cmd(acpi_handle handle, int cmd, unsigned long data)
{
int val;
unsigned long int end_jiffies;
if (method_vpcw(handle, 0, data))
return -1;
if (method_vpcw(handle, 1, cmd))
return -1;
for (end_jiffies = jiffies+(HZ)*IDEAPAD_EC_TIMEOUT/1000+1;
time_before(jiffies, end_jiffies);) {
schedule();
if (method_vpcr(handle, 1, &val))
return -1;
if (val == 0)
return 0;
}
pr_err("timeout in write_ec_cmd\n");
return -1;
}
/*
* debugfs
*/
#define DEBUGFS_EVENT_LEN (4096)
static int debugfs_status_show(struct seq_file *s, void *data)
{
unsigned long value;
if (!read_ec_data(ideapad_handle, VPCCMD_R_BL_MAX, &value))
seq_printf(s, "Backlight max:\t%lu\n", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_BL, &value))
seq_printf(s, "Backlight now:\t%lu\n", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_BL_POWER, &value))
seq_printf(s, "BL power value:\t%s\n", value ? "On" : "Off");
seq_printf(s, "=====================\n");
if (!read_ec_data(ideapad_handle, VPCCMD_R_RF, &value))
seq_printf(s, "Radio status:\t%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_WIFI, &value))
seq_printf(s, "Wifi status:\t%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_BT, &value))
seq_printf(s, "BT status:\t%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_3G, &value))
seq_printf(s, "3G status:\t%s(%lu)\n",
value ? "On" : "Off", value);
seq_printf(s, "=====================\n");
if (!read_ec_data(ideapad_handle, VPCCMD_R_TOUCHPAD, &value))
seq_printf(s, "Touchpad status:%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_CAMERA, &value))
seq_printf(s, "Camera status:\t%s(%lu)\n",
value ? "On" : "Off", value);
return 0;
}
static int debugfs_status_open(struct inode *inode, struct file *file)
{
return single_open(file, debugfs_status_show, NULL);
}
static const struct file_operations debugfs_status_fops = {
.owner = THIS_MODULE,
.open = debugfs_status_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int debugfs_cfg_show(struct seq_file *s, void *data)
{
if (!ideapad_priv) {
seq_printf(s, "cfg: N/A\n");
} else {
seq_printf(s, "cfg: 0x%.8lX\n\nCapability: ",
ideapad_priv->cfg);
if (test_bit(CFG_BT_BIT, &ideapad_priv->cfg))
seq_printf(s, "Bluetooth ");
if (test_bit(CFG_3G_BIT, &ideapad_priv->cfg))
seq_printf(s, "3G ");
if (test_bit(CFG_WIFI_BIT, &ideapad_priv->cfg))
seq_printf(s, "Wireless ");
if (test_bit(CFG_CAMERA_BIT, &ideapad_priv->cfg))
seq_printf(s, "Camera ");
seq_printf(s, "\nGraphic: ");
switch ((ideapad_priv->cfg)&0x700) {
case 0x100:
seq_printf(s, "Intel");
break;
case 0x200:
seq_printf(s, "ATI");
break;
case 0x300:
seq_printf(s, "Nvidia");
break;
case 0x400:
seq_printf(s, "Intel and ATI");
break;
case 0x500:
seq_printf(s, "Intel and Nvidia");
break;
}
seq_printf(s, "\n");
}
return 0;
}
static int debugfs_cfg_open(struct inode *inode, struct file *file)
{
return single_open(file, debugfs_cfg_show, NULL);
}
static const struct file_operations debugfs_cfg_fops = {
.owner = THIS_MODULE,
.open = debugfs_cfg_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __devinit ideapad_debugfs_init(struct ideapad_private *priv)
{
struct dentry *node;
priv->debug = debugfs_create_dir("ideapad", NULL);
if (priv->debug == NULL) {
pr_err("failed to create debugfs directory");
goto errout;
}
node = debugfs_create_file("cfg", S_IRUGO, priv->debug, NULL,
&debugfs_cfg_fops);
if (!node) {
pr_err("failed to create cfg in debugfs");
goto errout;
}
node = debugfs_create_file("status", S_IRUGO, priv->debug, NULL,
&debugfs_status_fops);
if (!node) {
pr_err("failed to create event in debugfs");
goto errout;
}
return 0;
errout:
return -ENOMEM;
}
static void ideapad_debugfs_exit(struct ideapad_private *priv)
{
debugfs_remove_recursive(priv->debug);
priv->debug = NULL;
}
/*
* sysfs
*/
static ssize_t show_ideapad_cam(struct device *dev,
struct device_attribute *attr,
char *buf)
{
unsigned long result;
if (read_ec_data(ideapad_handle, VPCCMD_R_CAMERA, &result))
return sprintf(buf, "-1\n");
return sprintf(buf, "%lu\n", result);
}
static ssize_t store_ideapad_cam(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int ret, state;
if (!count)
return 0;
if (sscanf(buf, "%i", &state) != 1)
return -EINVAL;
ret = write_ec_cmd(ideapad_handle, VPCCMD_W_CAMERA, state);
if (ret < 0)
return ret;
return count;
}
static DEVICE_ATTR(camera_power, 0644, show_ideapad_cam, store_ideapad_cam);
static struct attribute *ideapad_attributes[] = {
&dev_attr_camera_power.attr,
NULL
};
static umode_t ideapad_is_visible(struct kobject *kobj,
struct attribute *attr,
int idx)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct ideapad_private *priv = dev_get_drvdata(dev);
bool supported;
if (attr == &dev_attr_camera_power.attr)
supported = test_bit(CFG_CAMERA_BIT, &(priv->cfg));
else
supported = true;
return supported ? attr->mode : 0;
}
static struct attribute_group ideapad_attribute_group = {
.is_visible = ideapad_is_visible,
.attrs = ideapad_attributes
};
/*
* Rfkill
*/
struct ideapad_rfk_data {
char *name;
int cfgbit;
int opcode;
int type;
};
const struct ideapad_rfk_data ideapad_rfk_data[] = {
{ "ideapad_wlan", CFG_WIFI_BIT, VPCCMD_W_WIFI, RFKILL_TYPE_WLAN },
{ "ideapad_bluetooth", CFG_BT_BIT, VPCCMD_W_BT, RFKILL_TYPE_BLUETOOTH },
{ "ideapad_3g", CFG_3G_BIT, VPCCMD_W_3G, RFKILL_TYPE_WWAN },
};
static int ideapad_rfk_set(void *data, bool blocked)
{
unsigned long opcode = (unsigned long)data;
return write_ec_cmd(ideapad_handle, opcode, !blocked);
}
static struct rfkill_ops ideapad_rfk_ops = {
.set_block = ideapad_rfk_set,
};
static void ideapad_sync_rfk_state(struct ideapad_private *priv)
{
unsigned long hw_blocked;
int i;
if (read_ec_data(ideapad_handle, VPCCMD_R_RF, &hw_blocked))
return;
hw_blocked = !hw_blocked;
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++)
if (priv->rfk[i])
rfkill_set_hw_state(priv->rfk[i], hw_blocked);
}
static int __devinit ideapad_register_rfkill(struct acpi_device *adevice,
int dev)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
int ret;
unsigned long sw_blocked;
if (no_bt_rfkill &&
(ideapad_rfk_data[dev].type == RFKILL_TYPE_BLUETOOTH)) {
/* Force to enable bluetooth when no_bt_rfkill=1 */
write_ec_cmd(ideapad_handle,
ideapad_rfk_data[dev].opcode, 1);
return 0;
}
priv->rfk[dev] = rfkill_alloc(ideapad_rfk_data[dev].name, &adevice->dev,
ideapad_rfk_data[dev].type, &ideapad_rfk_ops,
(void *)(long)dev);
if (!priv->rfk[dev])
return -ENOMEM;
if (read_ec_data(ideapad_handle, ideapad_rfk_data[dev].opcode-1,
&sw_blocked)) {
rfkill_init_sw_state(priv->rfk[dev], 0);
} else {
sw_blocked = !sw_blocked;
rfkill_init_sw_state(priv->rfk[dev], sw_blocked);
}
ret = rfkill_register(priv->rfk[dev]);
if (ret) {
rfkill_destroy(priv->rfk[dev]);
return ret;
}
return 0;
}
static void ideapad_unregister_rfkill(struct acpi_device *adevice, int dev)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
if (!priv->rfk[dev])
return;
rfkill_unregister(priv->rfk[dev]);
rfkill_destroy(priv->rfk[dev]);
}
/*
* Platform device
*/
static int __devinit ideapad_platform_init(struct ideapad_private *priv)
{
int result;
priv->platform_device = platform_device_alloc("ideapad", -1);
if (!priv->platform_device)
return -ENOMEM;
platform_set_drvdata(priv->platform_device, priv);
result = platform_device_add(priv->platform_device);
if (result)
goto fail_platform_device;
result = sysfs_create_group(&priv->platform_device->dev.kobj,
&ideapad_attribute_group);
if (result)
goto fail_sysfs;
return 0;
fail_sysfs:
platform_device_del(priv->platform_device);
fail_platform_device:
platform_device_put(priv->platform_device);
return result;
}
static void ideapad_platform_exit(struct ideapad_private *priv)
{
sysfs_remove_group(&priv->platform_device->dev.kobj,
&ideapad_attribute_group);
platform_device_unregister(priv->platform_device);
}
/*
* input device
*/
static const struct key_entry ideapad_keymap[] = {
{ KE_KEY, 6, { KEY_SWITCHVIDEOMODE } },
{ KE_KEY, 13, { KEY_WLAN } },
{ KE_KEY, 16, { KEY_PROG1 } },
{ KE_KEY, 17, { KEY_PROG2 } },
{ KE_END, 0 },
};
static int __devinit ideapad_input_init(struct ideapad_private *priv)
{
struct input_dev *inputdev;
int error;
inputdev = input_allocate_device();
if (!inputdev) {
pr_info("Unable to allocate input device\n");
return -ENOMEM;
}
inputdev->name = "Ideapad extra buttons";
inputdev->phys = "ideapad/input0";
inputdev->id.bustype = BUS_HOST;
inputdev->dev.parent = &priv->platform_device->dev;
error = sparse_keymap_setup(inputdev, ideapad_keymap, NULL);
if (error) {
pr_err("Unable to setup input device keymap\n");
goto err_free_dev;
}
error = input_register_device(inputdev);
if (error) {
pr_err("Unable to register input device\n");
goto err_free_keymap;
}
priv->inputdev = inputdev;
return 0;
err_free_keymap:
sparse_keymap_free(inputdev);
err_free_dev:
input_free_device(inputdev);
return error;
}
static void ideapad_input_exit(struct ideapad_private *priv)
{
sparse_keymap_free(priv->inputdev);
input_unregister_device(priv->inputdev);
priv->inputdev = NULL;
}
static void ideapad_input_report(struct ideapad_private *priv,
unsigned long scancode)
{
sparse_keymap_report_event(priv->inputdev, scancode, 1, true);
}
static void ideapad_input_novokey(struct ideapad_private *priv)
{
unsigned long long_pressed;
if (read_ec_data(ideapad_handle, VPCCMD_R_NOVO, &long_pressed))
return;
if (long_pressed)
ideapad_input_report(priv, 17);
else
ideapad_input_report(priv, 16);
}
/*
* backlight
*/
static int ideapad_backlight_get_brightness(struct backlight_device *blightdev)
{
unsigned long now;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL, &now))
return -EIO;
return now;
}
static int ideapad_backlight_update_status(struct backlight_device *blightdev)
{
if (write_ec_cmd(ideapad_handle, VPCCMD_W_BL,
blightdev->props.brightness))
return -EIO;
if (write_ec_cmd(ideapad_handle, VPCCMD_W_BL_POWER,
blightdev->props.power == FB_BLANK_POWERDOWN ? 0 : 1))
return -EIO;
return 0;
}
static const struct backlight_ops ideapad_backlight_ops = {
.get_brightness = ideapad_backlight_get_brightness,
.update_status = ideapad_backlight_update_status,
};
static int ideapad_backlight_init(struct ideapad_private *priv)
{
struct backlight_device *blightdev;
struct backlight_properties props;
unsigned long max, now, power;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL_MAX, &max))
return -EIO;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL, &now))
return -EIO;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL_POWER, &power))
return -EIO;
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = max;
props.type = BACKLIGHT_PLATFORM;
blightdev = backlight_device_register("ideapad",
&priv->platform_device->dev,
priv,
&ideapad_backlight_ops,
&props);
if (IS_ERR(blightdev)) {
pr_err("Could not register backlight device\n");
return PTR_ERR(blightdev);
}
priv->blightdev = blightdev;
blightdev->props.brightness = now;
blightdev->props.power = power ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN;
backlight_update_status(blightdev);
return 0;
}
static void ideapad_backlight_exit(struct ideapad_private *priv)
{
if (priv->blightdev)
backlight_device_unregister(priv->blightdev);
priv->blightdev = NULL;
}
static void ideapad_backlight_notify_power(struct ideapad_private *priv)
{
unsigned long power;
struct backlight_device *blightdev = priv->blightdev;
if (!blightdev)
return;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL_POWER, &power))
return;
blightdev->props.power = power ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN;
}
static void ideapad_backlight_notify_brightness(struct ideapad_private *priv)
{
unsigned long now;
/* if we control brightness via acpi video driver */
if (priv->blightdev == NULL) {
read_ec_data(ideapad_handle, VPCCMD_R_BL, &now);
return;
}
backlight_force_update(priv->blightdev, BACKLIGHT_UPDATE_HOTKEY);
}
/*
* module init/exit
*/
static const struct acpi_device_id ideapad_device_ids[] = {
{ "VPC2004", 0},
{ "", 0},
};
MODULE_DEVICE_TABLE(acpi, ideapad_device_ids);
static int __devinit ideapad_acpi_add(struct acpi_device *adevice)
{
int ret, i;
unsigned long cfg;
struct ideapad_private *priv;
if (read_method_int(adevice->handle, "_CFG", (int *)&cfg))
return -ENODEV;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
dev_set_drvdata(&adevice->dev, priv);
ideapad_priv = priv;
ideapad_handle = adevice->handle;
priv->cfg = cfg;
ret = ideapad_platform_init(priv);
if (ret)
goto platform_failed;
ret = ideapad_debugfs_init(priv);
if (ret)
goto debugfs_failed;
ret = ideapad_input_init(priv);
if (ret)
goto input_failed;
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++) {
if (test_bit(ideapad_rfk_data[i].cfgbit, &cfg))
ideapad_register_rfkill(adevice, i);
else
priv->rfk[i] = NULL;
}
ideapad_sync_rfk_state(priv);
if (!acpi_video_backlight_support()) {
ret = ideapad_backlight_init(priv);
if (ret && ret != -ENODEV)
goto backlight_failed;
}
return 0;
backlight_failed:
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++)
ideapad_unregister_rfkill(adevice, i);
ideapad_input_exit(priv);
input_failed:
ideapad_debugfs_exit(priv);
debugfs_failed:
ideapad_platform_exit(priv);
platform_failed:
kfree(priv);
return ret;
}
static int __devexit ideapad_acpi_remove(struct acpi_device *adevice, int type)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
int i;
ideapad_backlight_exit(priv);
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++)
ideapad_unregister_rfkill(adevice, i);
ideapad_input_exit(priv);
ideapad_debugfs_exit(priv);
ideapad_platform_exit(priv);
dev_set_drvdata(&adevice->dev, NULL);
kfree(priv);
return 0;
}
static void ideapad_acpi_notify(struct acpi_device *adevice, u32 event)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
acpi_handle handle = adevice->handle;
unsigned long vpc1, vpc2, vpc_bit;
if (read_ec_data(handle, VPCCMD_R_VPC1, &vpc1))
return;
if (read_ec_data(handle, VPCCMD_R_VPC2, &vpc2))
return;
vpc1 = (vpc2 << 8) | vpc1;
for (vpc_bit = 0; vpc_bit < 16; vpc_bit++) {
if (test_bit(vpc_bit, &vpc1)) {
switch (vpc_bit) {
case 9:
ideapad_sync_rfk_state(priv);
break;
case 4:
ideapad_backlight_notify_brightness(priv);
break;
case 3:
ideapad_input_novokey(priv);
break;
case 2:
ideapad_backlight_notify_power(priv);
break;
default:
ideapad_input_report(priv, vpc_bit);
}
}
}
}
static struct acpi_driver ideapad_acpi_driver = {
.name = "ideapad_acpi",
.class = "IdeaPad",
.ids = ideapad_device_ids,
.ops.add = ideapad_acpi_add,
.ops.remove = ideapad_acpi_remove,
.ops.notify = ideapad_acpi_notify,
.owner = THIS_MODULE,
};
static int __init ideapad_acpi_module_init(void)
{
return acpi_bus_register_driver(&ideapad_acpi_driver);
}
static void __exit ideapad_acpi_module_exit(void)
{
acpi_bus_unregister_driver(&ideapad_acpi_driver);
}
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("IdeaPad ACPI Extras");
MODULE_LICENSE("GPL");
module_init(ideapad_acpi_module_init);
module_exit(ideapad_acpi_module_exit);
| gpl-2.0 |
superr/android_kernel_502_falcon | drivers/platform/x86/ideapad-laptop.c | 4598 | 19939 | /*
* ideapad-laptop.c - Lenovo IdeaPad ACPI Extras
*
* Copyright © 2010 Intel Corporation
* Copyright © 2010 David Woodhouse <dwmw2@infradead.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include <linux/rfkill.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#define IDEAPAD_RFKILL_DEV_NUM (3)
#define CFG_BT_BIT (16)
#define CFG_3G_BIT (17)
#define CFG_WIFI_BIT (18)
#define CFG_CAMERA_BIT (19)
enum {
VPCCMD_R_VPC1 = 0x10,
VPCCMD_R_BL_MAX,
VPCCMD_R_BL,
VPCCMD_W_BL,
VPCCMD_R_WIFI,
VPCCMD_W_WIFI,
VPCCMD_R_BT,
VPCCMD_W_BT,
VPCCMD_R_BL_POWER,
VPCCMD_R_NOVO,
VPCCMD_R_VPC2,
VPCCMD_R_TOUCHPAD,
VPCCMD_W_TOUCHPAD,
VPCCMD_R_CAMERA,
VPCCMD_W_CAMERA,
VPCCMD_R_3G,
VPCCMD_W_3G,
VPCCMD_R_ODD, /* 0x21 */
VPCCMD_R_RF = 0x23,
VPCCMD_W_RF,
VPCCMD_W_BL_POWER = 0x33,
};
struct ideapad_private {
struct rfkill *rfk[IDEAPAD_RFKILL_DEV_NUM];
struct platform_device *platform_device;
struct input_dev *inputdev;
struct backlight_device *blightdev;
struct dentry *debug;
unsigned long cfg;
};
static acpi_handle ideapad_handle;
static struct ideapad_private *ideapad_priv;
static bool no_bt_rfkill;
module_param(no_bt_rfkill, bool, 0444);
MODULE_PARM_DESC(no_bt_rfkill, "No rfkill for bluetooth.");
/*
* ACPI Helpers
*/
#define IDEAPAD_EC_TIMEOUT (100) /* in ms */
static int read_method_int(acpi_handle handle, const char *method, int *val)
{
acpi_status status;
unsigned long long result;
status = acpi_evaluate_integer(handle, (char *)method, NULL, &result);
if (ACPI_FAILURE(status)) {
*val = -1;
return -1;
} else {
*val = result;
return 0;
}
}
static int method_vpcr(acpi_handle handle, int cmd, int *ret)
{
acpi_status status;
unsigned long long result;
struct acpi_object_list params;
union acpi_object in_obj;
params.count = 1;
params.pointer = &in_obj;
in_obj.type = ACPI_TYPE_INTEGER;
in_obj.integer.value = cmd;
status = acpi_evaluate_integer(handle, "VPCR", ¶ms, &result);
if (ACPI_FAILURE(status)) {
*ret = -1;
return -1;
} else {
*ret = result;
return 0;
}
}
static int method_vpcw(acpi_handle handle, int cmd, int data)
{
struct acpi_object_list params;
union acpi_object in_obj[2];
acpi_status status;
params.count = 2;
params.pointer = in_obj;
in_obj[0].type = ACPI_TYPE_INTEGER;
in_obj[0].integer.value = cmd;
in_obj[1].type = ACPI_TYPE_INTEGER;
in_obj[1].integer.value = data;
status = acpi_evaluate_object(handle, "VPCW", ¶ms, NULL);
if (status != AE_OK)
return -1;
return 0;
}
static int read_ec_data(acpi_handle handle, int cmd, unsigned long *data)
{
int val;
unsigned long int end_jiffies;
if (method_vpcw(handle, 1, cmd))
return -1;
for (end_jiffies = jiffies+(HZ)*IDEAPAD_EC_TIMEOUT/1000+1;
time_before(jiffies, end_jiffies);) {
schedule();
if (method_vpcr(handle, 1, &val))
return -1;
if (val == 0) {
if (method_vpcr(handle, 0, &val))
return -1;
*data = val;
return 0;
}
}
pr_err("timeout in read_ec_cmd\n");
return -1;
}
static int write_ec_cmd(acpi_handle handle, int cmd, unsigned long data)
{
int val;
unsigned long int end_jiffies;
if (method_vpcw(handle, 0, data))
return -1;
if (method_vpcw(handle, 1, cmd))
return -1;
for (end_jiffies = jiffies+(HZ)*IDEAPAD_EC_TIMEOUT/1000+1;
time_before(jiffies, end_jiffies);) {
schedule();
if (method_vpcr(handle, 1, &val))
return -1;
if (val == 0)
return 0;
}
pr_err("timeout in write_ec_cmd\n");
return -1;
}
/*
* debugfs
*/
#define DEBUGFS_EVENT_LEN (4096)
static int debugfs_status_show(struct seq_file *s, void *data)
{
unsigned long value;
if (!read_ec_data(ideapad_handle, VPCCMD_R_BL_MAX, &value))
seq_printf(s, "Backlight max:\t%lu\n", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_BL, &value))
seq_printf(s, "Backlight now:\t%lu\n", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_BL_POWER, &value))
seq_printf(s, "BL power value:\t%s\n", value ? "On" : "Off");
seq_printf(s, "=====================\n");
if (!read_ec_data(ideapad_handle, VPCCMD_R_RF, &value))
seq_printf(s, "Radio status:\t%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_WIFI, &value))
seq_printf(s, "Wifi status:\t%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_BT, &value))
seq_printf(s, "BT status:\t%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_3G, &value))
seq_printf(s, "3G status:\t%s(%lu)\n",
value ? "On" : "Off", value);
seq_printf(s, "=====================\n");
if (!read_ec_data(ideapad_handle, VPCCMD_R_TOUCHPAD, &value))
seq_printf(s, "Touchpad status:%s(%lu)\n",
value ? "On" : "Off", value);
if (!read_ec_data(ideapad_handle, VPCCMD_R_CAMERA, &value))
seq_printf(s, "Camera status:\t%s(%lu)\n",
value ? "On" : "Off", value);
return 0;
}
static int debugfs_status_open(struct inode *inode, struct file *file)
{
return single_open(file, debugfs_status_show, NULL);
}
static const struct file_operations debugfs_status_fops = {
.owner = THIS_MODULE,
.open = debugfs_status_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int debugfs_cfg_show(struct seq_file *s, void *data)
{
if (!ideapad_priv) {
seq_printf(s, "cfg: N/A\n");
} else {
seq_printf(s, "cfg: 0x%.8lX\n\nCapability: ",
ideapad_priv->cfg);
if (test_bit(CFG_BT_BIT, &ideapad_priv->cfg))
seq_printf(s, "Bluetooth ");
if (test_bit(CFG_3G_BIT, &ideapad_priv->cfg))
seq_printf(s, "3G ");
if (test_bit(CFG_WIFI_BIT, &ideapad_priv->cfg))
seq_printf(s, "Wireless ");
if (test_bit(CFG_CAMERA_BIT, &ideapad_priv->cfg))
seq_printf(s, "Camera ");
seq_printf(s, "\nGraphic: ");
switch ((ideapad_priv->cfg)&0x700) {
case 0x100:
seq_printf(s, "Intel");
break;
case 0x200:
seq_printf(s, "ATI");
break;
case 0x300:
seq_printf(s, "Nvidia");
break;
case 0x400:
seq_printf(s, "Intel and ATI");
break;
case 0x500:
seq_printf(s, "Intel and Nvidia");
break;
}
seq_printf(s, "\n");
}
return 0;
}
static int debugfs_cfg_open(struct inode *inode, struct file *file)
{
return single_open(file, debugfs_cfg_show, NULL);
}
static const struct file_operations debugfs_cfg_fops = {
.owner = THIS_MODULE,
.open = debugfs_cfg_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __devinit ideapad_debugfs_init(struct ideapad_private *priv)
{
struct dentry *node;
priv->debug = debugfs_create_dir("ideapad", NULL);
if (priv->debug == NULL) {
pr_err("failed to create debugfs directory");
goto errout;
}
node = debugfs_create_file("cfg", S_IRUGO, priv->debug, NULL,
&debugfs_cfg_fops);
if (!node) {
pr_err("failed to create cfg in debugfs");
goto errout;
}
node = debugfs_create_file("status", S_IRUGO, priv->debug, NULL,
&debugfs_status_fops);
if (!node) {
pr_err("failed to create event in debugfs");
goto errout;
}
return 0;
errout:
return -ENOMEM;
}
static void ideapad_debugfs_exit(struct ideapad_private *priv)
{
debugfs_remove_recursive(priv->debug);
priv->debug = NULL;
}
/*
* sysfs
*/
static ssize_t show_ideapad_cam(struct device *dev,
struct device_attribute *attr,
char *buf)
{
unsigned long result;
if (read_ec_data(ideapad_handle, VPCCMD_R_CAMERA, &result))
return sprintf(buf, "-1\n");
return sprintf(buf, "%lu\n", result);
}
static ssize_t store_ideapad_cam(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int ret, state;
if (!count)
return 0;
if (sscanf(buf, "%i", &state) != 1)
return -EINVAL;
ret = write_ec_cmd(ideapad_handle, VPCCMD_W_CAMERA, state);
if (ret < 0)
return ret;
return count;
}
static DEVICE_ATTR(camera_power, 0644, show_ideapad_cam, store_ideapad_cam);
static struct attribute *ideapad_attributes[] = {
&dev_attr_camera_power.attr,
NULL
};
static umode_t ideapad_is_visible(struct kobject *kobj,
struct attribute *attr,
int idx)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct ideapad_private *priv = dev_get_drvdata(dev);
bool supported;
if (attr == &dev_attr_camera_power.attr)
supported = test_bit(CFG_CAMERA_BIT, &(priv->cfg));
else
supported = true;
return supported ? attr->mode : 0;
}
static struct attribute_group ideapad_attribute_group = {
.is_visible = ideapad_is_visible,
.attrs = ideapad_attributes
};
/*
* Rfkill
*/
struct ideapad_rfk_data {
char *name;
int cfgbit;
int opcode;
int type;
};
const struct ideapad_rfk_data ideapad_rfk_data[] = {
{ "ideapad_wlan", CFG_WIFI_BIT, VPCCMD_W_WIFI, RFKILL_TYPE_WLAN },
{ "ideapad_bluetooth", CFG_BT_BIT, VPCCMD_W_BT, RFKILL_TYPE_BLUETOOTH },
{ "ideapad_3g", CFG_3G_BIT, VPCCMD_W_3G, RFKILL_TYPE_WWAN },
};
static int ideapad_rfk_set(void *data, bool blocked)
{
unsigned long opcode = (unsigned long)data;
return write_ec_cmd(ideapad_handle, opcode, !blocked);
}
static struct rfkill_ops ideapad_rfk_ops = {
.set_block = ideapad_rfk_set,
};
static void ideapad_sync_rfk_state(struct ideapad_private *priv)
{
unsigned long hw_blocked;
int i;
if (read_ec_data(ideapad_handle, VPCCMD_R_RF, &hw_blocked))
return;
hw_blocked = !hw_blocked;
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++)
if (priv->rfk[i])
rfkill_set_hw_state(priv->rfk[i], hw_blocked);
}
static int __devinit ideapad_register_rfkill(struct acpi_device *adevice,
int dev)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
int ret;
unsigned long sw_blocked;
if (no_bt_rfkill &&
(ideapad_rfk_data[dev].type == RFKILL_TYPE_BLUETOOTH)) {
/* Force to enable bluetooth when no_bt_rfkill=1 */
write_ec_cmd(ideapad_handle,
ideapad_rfk_data[dev].opcode, 1);
return 0;
}
priv->rfk[dev] = rfkill_alloc(ideapad_rfk_data[dev].name, &adevice->dev,
ideapad_rfk_data[dev].type, &ideapad_rfk_ops,
(void *)(long)dev);
if (!priv->rfk[dev])
return -ENOMEM;
if (read_ec_data(ideapad_handle, ideapad_rfk_data[dev].opcode-1,
&sw_blocked)) {
rfkill_init_sw_state(priv->rfk[dev], 0);
} else {
sw_blocked = !sw_blocked;
rfkill_init_sw_state(priv->rfk[dev], sw_blocked);
}
ret = rfkill_register(priv->rfk[dev]);
if (ret) {
rfkill_destroy(priv->rfk[dev]);
return ret;
}
return 0;
}
static void ideapad_unregister_rfkill(struct acpi_device *adevice, int dev)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
if (!priv->rfk[dev])
return;
rfkill_unregister(priv->rfk[dev]);
rfkill_destroy(priv->rfk[dev]);
}
/*
* Platform device
*/
static int __devinit ideapad_platform_init(struct ideapad_private *priv)
{
int result;
priv->platform_device = platform_device_alloc("ideapad", -1);
if (!priv->platform_device)
return -ENOMEM;
platform_set_drvdata(priv->platform_device, priv);
result = platform_device_add(priv->platform_device);
if (result)
goto fail_platform_device;
result = sysfs_create_group(&priv->platform_device->dev.kobj,
&ideapad_attribute_group);
if (result)
goto fail_sysfs;
return 0;
fail_sysfs:
platform_device_del(priv->platform_device);
fail_platform_device:
platform_device_put(priv->platform_device);
return result;
}
static void ideapad_platform_exit(struct ideapad_private *priv)
{
sysfs_remove_group(&priv->platform_device->dev.kobj,
&ideapad_attribute_group);
platform_device_unregister(priv->platform_device);
}
/*
* input device
*/
static const struct key_entry ideapad_keymap[] = {
{ KE_KEY, 6, { KEY_SWITCHVIDEOMODE } },
{ KE_KEY, 13, { KEY_WLAN } },
{ KE_KEY, 16, { KEY_PROG1 } },
{ KE_KEY, 17, { KEY_PROG2 } },
{ KE_END, 0 },
};
static int __devinit ideapad_input_init(struct ideapad_private *priv)
{
struct input_dev *inputdev;
int error;
inputdev = input_allocate_device();
if (!inputdev) {
pr_info("Unable to allocate input device\n");
return -ENOMEM;
}
inputdev->name = "Ideapad extra buttons";
inputdev->phys = "ideapad/input0";
inputdev->id.bustype = BUS_HOST;
inputdev->dev.parent = &priv->platform_device->dev;
error = sparse_keymap_setup(inputdev, ideapad_keymap, NULL);
if (error) {
pr_err("Unable to setup input device keymap\n");
goto err_free_dev;
}
error = input_register_device(inputdev);
if (error) {
pr_err("Unable to register input device\n");
goto err_free_keymap;
}
priv->inputdev = inputdev;
return 0;
err_free_keymap:
sparse_keymap_free(inputdev);
err_free_dev:
input_free_device(inputdev);
return error;
}
static void ideapad_input_exit(struct ideapad_private *priv)
{
sparse_keymap_free(priv->inputdev);
input_unregister_device(priv->inputdev);
priv->inputdev = NULL;
}
static void ideapad_input_report(struct ideapad_private *priv,
unsigned long scancode)
{
sparse_keymap_report_event(priv->inputdev, scancode, 1, true);
}
static void ideapad_input_novokey(struct ideapad_private *priv)
{
unsigned long long_pressed;
if (read_ec_data(ideapad_handle, VPCCMD_R_NOVO, &long_pressed))
return;
if (long_pressed)
ideapad_input_report(priv, 17);
else
ideapad_input_report(priv, 16);
}
/*
* backlight
*/
static int ideapad_backlight_get_brightness(struct backlight_device *blightdev)
{
unsigned long now;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL, &now))
return -EIO;
return now;
}
static int ideapad_backlight_update_status(struct backlight_device *blightdev)
{
if (write_ec_cmd(ideapad_handle, VPCCMD_W_BL,
blightdev->props.brightness))
return -EIO;
if (write_ec_cmd(ideapad_handle, VPCCMD_W_BL_POWER,
blightdev->props.power == FB_BLANK_POWERDOWN ? 0 : 1))
return -EIO;
return 0;
}
static const struct backlight_ops ideapad_backlight_ops = {
.get_brightness = ideapad_backlight_get_brightness,
.update_status = ideapad_backlight_update_status,
};
static int ideapad_backlight_init(struct ideapad_private *priv)
{
struct backlight_device *blightdev;
struct backlight_properties props;
unsigned long max, now, power;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL_MAX, &max))
return -EIO;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL, &now))
return -EIO;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL_POWER, &power))
return -EIO;
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = max;
props.type = BACKLIGHT_PLATFORM;
blightdev = backlight_device_register("ideapad",
&priv->platform_device->dev,
priv,
&ideapad_backlight_ops,
&props);
if (IS_ERR(blightdev)) {
pr_err("Could not register backlight device\n");
return PTR_ERR(blightdev);
}
priv->blightdev = blightdev;
blightdev->props.brightness = now;
blightdev->props.power = power ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN;
backlight_update_status(blightdev);
return 0;
}
static void ideapad_backlight_exit(struct ideapad_private *priv)
{
if (priv->blightdev)
backlight_device_unregister(priv->blightdev);
priv->blightdev = NULL;
}
static void ideapad_backlight_notify_power(struct ideapad_private *priv)
{
unsigned long power;
struct backlight_device *blightdev = priv->blightdev;
if (!blightdev)
return;
if (read_ec_data(ideapad_handle, VPCCMD_R_BL_POWER, &power))
return;
blightdev->props.power = power ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN;
}
static void ideapad_backlight_notify_brightness(struct ideapad_private *priv)
{
unsigned long now;
/* if we control brightness via acpi video driver */
if (priv->blightdev == NULL) {
read_ec_data(ideapad_handle, VPCCMD_R_BL, &now);
return;
}
backlight_force_update(priv->blightdev, BACKLIGHT_UPDATE_HOTKEY);
}
/*
* module init/exit
*/
static const struct acpi_device_id ideapad_device_ids[] = {
{ "VPC2004", 0},
{ "", 0},
};
MODULE_DEVICE_TABLE(acpi, ideapad_device_ids);
static int __devinit ideapad_acpi_add(struct acpi_device *adevice)
{
int ret, i;
unsigned long cfg;
struct ideapad_private *priv;
if (read_method_int(adevice->handle, "_CFG", (int *)&cfg))
return -ENODEV;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
dev_set_drvdata(&adevice->dev, priv);
ideapad_priv = priv;
ideapad_handle = adevice->handle;
priv->cfg = cfg;
ret = ideapad_platform_init(priv);
if (ret)
goto platform_failed;
ret = ideapad_debugfs_init(priv);
if (ret)
goto debugfs_failed;
ret = ideapad_input_init(priv);
if (ret)
goto input_failed;
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++) {
if (test_bit(ideapad_rfk_data[i].cfgbit, &cfg))
ideapad_register_rfkill(adevice, i);
else
priv->rfk[i] = NULL;
}
ideapad_sync_rfk_state(priv);
if (!acpi_video_backlight_support()) {
ret = ideapad_backlight_init(priv);
if (ret && ret != -ENODEV)
goto backlight_failed;
}
return 0;
backlight_failed:
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++)
ideapad_unregister_rfkill(adevice, i);
ideapad_input_exit(priv);
input_failed:
ideapad_debugfs_exit(priv);
debugfs_failed:
ideapad_platform_exit(priv);
platform_failed:
kfree(priv);
return ret;
}
static int __devexit ideapad_acpi_remove(struct acpi_device *adevice, int type)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
int i;
ideapad_backlight_exit(priv);
for (i = 0; i < IDEAPAD_RFKILL_DEV_NUM; i++)
ideapad_unregister_rfkill(adevice, i);
ideapad_input_exit(priv);
ideapad_debugfs_exit(priv);
ideapad_platform_exit(priv);
dev_set_drvdata(&adevice->dev, NULL);
kfree(priv);
return 0;
}
static void ideapad_acpi_notify(struct acpi_device *adevice, u32 event)
{
struct ideapad_private *priv = dev_get_drvdata(&adevice->dev);
acpi_handle handle = adevice->handle;
unsigned long vpc1, vpc2, vpc_bit;
if (read_ec_data(handle, VPCCMD_R_VPC1, &vpc1))
return;
if (read_ec_data(handle, VPCCMD_R_VPC2, &vpc2))
return;
vpc1 = (vpc2 << 8) | vpc1;
for (vpc_bit = 0; vpc_bit < 16; vpc_bit++) {
if (test_bit(vpc_bit, &vpc1)) {
switch (vpc_bit) {
case 9:
ideapad_sync_rfk_state(priv);
break;
case 4:
ideapad_backlight_notify_brightness(priv);
break;
case 3:
ideapad_input_novokey(priv);
break;
case 2:
ideapad_backlight_notify_power(priv);
break;
default:
ideapad_input_report(priv, vpc_bit);
}
}
}
}
static struct acpi_driver ideapad_acpi_driver = {
.name = "ideapad_acpi",
.class = "IdeaPad",
.ids = ideapad_device_ids,
.ops.add = ideapad_acpi_add,
.ops.remove = ideapad_acpi_remove,
.ops.notify = ideapad_acpi_notify,
.owner = THIS_MODULE,
};
static int __init ideapad_acpi_module_init(void)
{
return acpi_bus_register_driver(&ideapad_acpi_driver);
}
static void __exit ideapad_acpi_module_exit(void)
{
acpi_bus_unregister_driver(&ideapad_acpi_driver);
}
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("IdeaPad ACPI Extras");
MODULE_LICENSE("GPL");
module_init(ideapad_acpi_module_init);
module_exit(ideapad_acpi_module_exit);
| gpl-2.0 |
cile381/kernel_m7_4.4.3 | drivers/char/ipmi/ipmi_watchdog.c | 4854 | 35627 | /*
* ipmi_watchdog.c
*
* A watchdog timer based upon the IPMI interface.
*
* Author: MontaVista Software, Inc.
* Corey Minyard <minyard@mvista.com>
* source@mvista.com
*
* Copyright 2002 MontaVista Software Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/ipmi.h>
#include <linux/ipmi_smi.h>
#include <linux/mutex.h>
#include <linux/watchdog.h>
#include <linux/miscdevice.h>
#include <linux/init.h>
#include <linux/completion.h>
#include <linux/kdebug.h>
#include <linux/rwsem.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <linux/notifier.h>
#include <linux/nmi.h>
#include <linux/reboot.h>
#include <linux/wait.h>
#include <linux/poll.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#ifdef CONFIG_X86
/*
* This is ugly, but I've determined that x86 is the only architecture
* that can reasonably support the IPMI NMI watchdog timeout at this
* time. If another architecture adds this capability somehow, it
* will have to be a somewhat different mechanism and I have no idea
* how it will work. So in the unlikely event that another
* architecture supports this, we can figure out a good generic
* mechanism for it at that time.
*/
#include <asm/kdebug.h>
#include <asm/nmi.h>
#define HAVE_DIE_NMI
#endif
#define PFX "IPMI Watchdog: "
/*
* The IPMI command/response information for the watchdog timer.
*/
/* values for byte 1 of the set command, byte 2 of the get response. */
#define WDOG_DONT_LOG (1 << 7)
#define WDOG_DONT_STOP_ON_SET (1 << 6)
#define WDOG_SET_TIMER_USE(byte, use) \
byte = ((byte) & 0xf8) | ((use) & 0x7)
#define WDOG_GET_TIMER_USE(byte) ((byte) & 0x7)
#define WDOG_TIMER_USE_BIOS_FRB2 1
#define WDOG_TIMER_USE_BIOS_POST 2
#define WDOG_TIMER_USE_OS_LOAD 3
#define WDOG_TIMER_USE_SMS_OS 4
#define WDOG_TIMER_USE_OEM 5
/* values for byte 2 of the set command, byte 3 of the get response. */
#define WDOG_SET_PRETIMEOUT_ACT(byte, use) \
byte = ((byte) & 0x8f) | (((use) & 0x7) << 4)
#define WDOG_GET_PRETIMEOUT_ACT(byte) (((byte) >> 4) & 0x7)
#define WDOG_PRETIMEOUT_NONE 0
#define WDOG_PRETIMEOUT_SMI 1
#define WDOG_PRETIMEOUT_NMI 2
#define WDOG_PRETIMEOUT_MSG_INT 3
/* Operations that can be performed on a pretimout. */
#define WDOG_PREOP_NONE 0
#define WDOG_PREOP_PANIC 1
/* Cause data to be available to read. Doesn't work in NMI mode. */
#define WDOG_PREOP_GIVE_DATA 2
/* Actions to perform on a full timeout. */
#define WDOG_SET_TIMEOUT_ACT(byte, use) \
byte = ((byte) & 0xf8) | ((use) & 0x7)
#define WDOG_GET_TIMEOUT_ACT(byte) ((byte) & 0x7)
#define WDOG_TIMEOUT_NONE 0
#define WDOG_TIMEOUT_RESET 1
#define WDOG_TIMEOUT_POWER_DOWN 2
#define WDOG_TIMEOUT_POWER_CYCLE 3
/*
* Byte 3 of the get command, byte 4 of the get response is the
* pre-timeout in seconds.
*/
/* Bits for setting byte 4 of the set command, byte 5 of the get response. */
#define WDOG_EXPIRE_CLEAR_BIOS_FRB2 (1 << 1)
#define WDOG_EXPIRE_CLEAR_BIOS_POST (1 << 2)
#define WDOG_EXPIRE_CLEAR_OS_LOAD (1 << 3)
#define WDOG_EXPIRE_CLEAR_SMS_OS (1 << 4)
#define WDOG_EXPIRE_CLEAR_OEM (1 << 5)
/*
* Setting/getting the watchdog timer value. This is for bytes 5 and
* 6 (the timeout time) of the set command, and bytes 6 and 7 (the
* timeout time) and 8 and 9 (the current countdown value) of the
* response. The timeout value is given in seconds (in the command it
* is 100ms intervals).
*/
#define WDOG_SET_TIMEOUT(byte1, byte2, val) \
(byte1) = (((val) * 10) & 0xff), (byte2) = (((val) * 10) >> 8)
#define WDOG_GET_TIMEOUT(byte1, byte2) \
(((byte1) | ((byte2) << 8)) / 10)
#define IPMI_WDOG_RESET_TIMER 0x22
#define IPMI_WDOG_SET_TIMER 0x24
#define IPMI_WDOG_GET_TIMER 0x25
#define IPMI_WDOG_TIMER_NOT_INIT_RESP 0x80
/* These are here until the real ones get into the watchdog.h interface. */
#ifndef WDIOC_GETTIMEOUT
#define WDIOC_GETTIMEOUT _IOW(WATCHDOG_IOCTL_BASE, 20, int)
#endif
#ifndef WDIOC_SET_PRETIMEOUT
#define WDIOC_SET_PRETIMEOUT _IOW(WATCHDOG_IOCTL_BASE, 21, int)
#endif
#ifndef WDIOC_GET_PRETIMEOUT
#define WDIOC_GET_PRETIMEOUT _IOW(WATCHDOG_IOCTL_BASE, 22, int)
#endif
static DEFINE_MUTEX(ipmi_watchdog_mutex);
static bool nowayout = WATCHDOG_NOWAYOUT;
static ipmi_user_t watchdog_user;
static int watchdog_ifnum;
/* Default the timeout to 10 seconds. */
static int timeout = 10;
/* The pre-timeout is disabled by default. */
static int pretimeout;
/* Default action is to reset the board on a timeout. */
static unsigned char action_val = WDOG_TIMEOUT_RESET;
static char action[16] = "reset";
static unsigned char preaction_val = WDOG_PRETIMEOUT_NONE;
static char preaction[16] = "pre_none";
static unsigned char preop_val = WDOG_PREOP_NONE;
static char preop[16] = "preop_none";
static DEFINE_SPINLOCK(ipmi_read_lock);
static char data_to_read;
static DECLARE_WAIT_QUEUE_HEAD(read_q);
static struct fasync_struct *fasync_q;
static char pretimeout_since_last_heartbeat;
static char expect_close;
static int ifnum_to_use = -1;
/* Parameters to ipmi_set_timeout */
#define IPMI_SET_TIMEOUT_NO_HB 0
#define IPMI_SET_TIMEOUT_HB_IF_NECESSARY 1
#define IPMI_SET_TIMEOUT_FORCE_HB 2
static int ipmi_set_timeout(int do_heartbeat);
static void ipmi_register_watchdog(int ipmi_intf);
static void ipmi_unregister_watchdog(int ipmi_intf);
/*
* If true, the driver will start running as soon as it is configured
* and ready.
*/
static int start_now;
static int set_param_timeout(const char *val, const struct kernel_param *kp)
{
char *endp;
int l;
int rv = 0;
if (!val)
return -EINVAL;
l = simple_strtoul(val, &endp, 0);
if (endp == val)
return -EINVAL;
*((int *)kp->arg) = l;
if (watchdog_user)
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
return rv;
}
static struct kernel_param_ops param_ops_timeout = {
.set = set_param_timeout,
.get = param_get_int,
};
#define param_check_timeout param_check_int
typedef int (*action_fn)(const char *intval, char *outval);
static int action_op(const char *inval, char *outval);
static int preaction_op(const char *inval, char *outval);
static int preop_op(const char *inval, char *outval);
static void check_parms(void);
static int set_param_str(const char *val, const struct kernel_param *kp)
{
action_fn fn = (action_fn) kp->arg;
int rv = 0;
char valcp[16];
char *s;
strncpy(valcp, val, 16);
valcp[15] = '\0';
s = strstrip(valcp);
rv = fn(s, NULL);
if (rv)
goto out;
check_parms();
if (watchdog_user)
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
out:
return rv;
}
static int get_param_str(char *buffer, const struct kernel_param *kp)
{
action_fn fn = (action_fn) kp->arg;
int rv;
rv = fn(NULL, buffer);
if (rv)
return rv;
return strlen(buffer);
}
static int set_param_wdog_ifnum(const char *val, const struct kernel_param *kp)
{
int rv = param_set_int(val, kp);
if (rv)
return rv;
if ((ifnum_to_use < 0) || (ifnum_to_use == watchdog_ifnum))
return 0;
ipmi_unregister_watchdog(watchdog_ifnum);
ipmi_register_watchdog(ifnum_to_use);
return 0;
}
static struct kernel_param_ops param_ops_wdog_ifnum = {
.set = set_param_wdog_ifnum,
.get = param_get_int,
};
#define param_check_wdog_ifnum param_check_int
static struct kernel_param_ops param_ops_str = {
.set = set_param_str,
.get = get_param_str,
};
module_param(ifnum_to_use, wdog_ifnum, 0644);
MODULE_PARM_DESC(ifnum_to_use, "The interface number to use for the watchdog "
"timer. Setting to -1 defaults to the first registered "
"interface");
module_param(timeout, timeout, 0644);
MODULE_PARM_DESC(timeout, "Timeout value in seconds.");
module_param(pretimeout, timeout, 0644);
MODULE_PARM_DESC(pretimeout, "Pretimeout value in seconds.");
module_param_cb(action, ¶m_ops_str, action_op, 0644);
MODULE_PARM_DESC(action, "Timeout action. One of: "
"reset, none, power_cycle, power_off.");
module_param_cb(preaction, ¶m_ops_str, preaction_op, 0644);
MODULE_PARM_DESC(preaction, "Pretimeout action. One of: "
"pre_none, pre_smi, pre_nmi, pre_int.");
module_param_cb(preop, ¶m_ops_str, preop_op, 0644);
MODULE_PARM_DESC(preop, "Pretimeout driver operation. One of: "
"preop_none, preop_panic, preop_give_data.");
module_param(start_now, int, 0444);
MODULE_PARM_DESC(start_now, "Set to 1 to start the watchdog as"
"soon as the driver is loaded.");
module_param(nowayout, bool, 0644);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started "
"(default=CONFIG_WATCHDOG_NOWAYOUT)");
/* Default state of the timer. */
static unsigned char ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
/* If shutting down via IPMI, we ignore the heartbeat. */
static int ipmi_ignore_heartbeat;
/* Is someone using the watchdog? Only one user is allowed. */
static unsigned long ipmi_wdog_open;
/*
* If set to 1, the heartbeat command will set the state to reset and
* start the timer. The timer doesn't normally run when the driver is
* first opened until the heartbeat is set the first time, this
* variable is used to accomplish this.
*/
static int ipmi_start_timer_on_heartbeat;
/* IPMI version of the BMC. */
static unsigned char ipmi_version_major;
static unsigned char ipmi_version_minor;
/* If a pretimeout occurs, this is used to allow only one panic to happen. */
static atomic_t preop_panic_excl = ATOMIC_INIT(-1);
#ifdef HAVE_DIE_NMI
static int testing_nmi;
static int nmi_handler_registered;
#endif
static int ipmi_heartbeat(void);
/*
* We use a mutex to make sure that only one thing can send a set
* timeout at one time, because we only have one copy of the data.
* The mutex is claimed when the set_timeout is sent and freed
* when both messages are free.
*/
static atomic_t set_timeout_tofree = ATOMIC_INIT(0);
static DEFINE_MUTEX(set_timeout_lock);
static DECLARE_COMPLETION(set_timeout_wait);
static void set_timeout_free_smi(struct ipmi_smi_msg *msg)
{
if (atomic_dec_and_test(&set_timeout_tofree))
complete(&set_timeout_wait);
}
static void set_timeout_free_recv(struct ipmi_recv_msg *msg)
{
if (atomic_dec_and_test(&set_timeout_tofree))
complete(&set_timeout_wait);
}
static struct ipmi_smi_msg set_timeout_smi_msg = {
.done = set_timeout_free_smi
};
static struct ipmi_recv_msg set_timeout_recv_msg = {
.done = set_timeout_free_recv
};
static int i_ipmi_set_timeout(struct ipmi_smi_msg *smi_msg,
struct ipmi_recv_msg *recv_msg,
int *send_heartbeat_now)
{
struct kernel_ipmi_msg msg;
unsigned char data[6];
int rv;
struct ipmi_system_interface_addr addr;
int hbnow = 0;
/* These can be cleared as we are setting the timeout. */
pretimeout_since_last_heartbeat = 0;
data[0] = 0;
WDOG_SET_TIMER_USE(data[0], WDOG_TIMER_USE_SMS_OS);
if ((ipmi_version_major > 1)
|| ((ipmi_version_major == 1) && (ipmi_version_minor >= 5))) {
/* This is an IPMI 1.5-only feature. */
data[0] |= WDOG_DONT_STOP_ON_SET;
} else if (ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
/*
* In ipmi 1.0, setting the timer stops the watchdog, we
* need to start it back up again.
*/
hbnow = 1;
}
data[1] = 0;
WDOG_SET_TIMEOUT_ACT(data[1], ipmi_watchdog_state);
if ((pretimeout > 0) && (ipmi_watchdog_state != WDOG_TIMEOUT_NONE)) {
WDOG_SET_PRETIMEOUT_ACT(data[1], preaction_val);
data[2] = pretimeout;
} else {
WDOG_SET_PRETIMEOUT_ACT(data[1], WDOG_PRETIMEOUT_NONE);
data[2] = 0; /* No pretimeout. */
}
data[3] = 0;
WDOG_SET_TIMEOUT(data[4], data[5], timeout);
addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
addr.channel = IPMI_BMC_CHANNEL;
addr.lun = 0;
msg.netfn = 0x06;
msg.cmd = IPMI_WDOG_SET_TIMER;
msg.data = data;
msg.data_len = sizeof(data);
rv = ipmi_request_supply_msgs(watchdog_user,
(struct ipmi_addr *) &addr,
0,
&msg,
NULL,
smi_msg,
recv_msg,
1);
if (rv) {
printk(KERN_WARNING PFX "set timeout error: %d\n",
rv);
}
if (send_heartbeat_now)
*send_heartbeat_now = hbnow;
return rv;
}
static int ipmi_set_timeout(int do_heartbeat)
{
int send_heartbeat_now;
int rv;
/* We can only send one of these at a time. */
mutex_lock(&set_timeout_lock);
atomic_set(&set_timeout_tofree, 2);
rv = i_ipmi_set_timeout(&set_timeout_smi_msg,
&set_timeout_recv_msg,
&send_heartbeat_now);
if (rv) {
mutex_unlock(&set_timeout_lock);
goto out;
}
wait_for_completion(&set_timeout_wait);
mutex_unlock(&set_timeout_lock);
if ((do_heartbeat == IPMI_SET_TIMEOUT_FORCE_HB)
|| ((send_heartbeat_now)
&& (do_heartbeat == IPMI_SET_TIMEOUT_HB_IF_NECESSARY)))
rv = ipmi_heartbeat();
out:
return rv;
}
static atomic_t panic_done_count = ATOMIC_INIT(0);
static void panic_smi_free(struct ipmi_smi_msg *msg)
{
atomic_dec(&panic_done_count);
}
static void panic_recv_free(struct ipmi_recv_msg *msg)
{
atomic_dec(&panic_done_count);
}
static struct ipmi_smi_msg panic_halt_heartbeat_smi_msg = {
.done = panic_smi_free
};
static struct ipmi_recv_msg panic_halt_heartbeat_recv_msg = {
.done = panic_recv_free
};
static void panic_halt_ipmi_heartbeat(void)
{
struct kernel_ipmi_msg msg;
struct ipmi_system_interface_addr addr;
int rv;
/*
* Don't reset the timer if we have the timer turned off, that
* re-enables the watchdog.
*/
if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
return;
addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
addr.channel = IPMI_BMC_CHANNEL;
addr.lun = 0;
msg.netfn = 0x06;
msg.cmd = IPMI_WDOG_RESET_TIMER;
msg.data = NULL;
msg.data_len = 0;
atomic_add(2, &panic_done_count);
rv = ipmi_request_supply_msgs(watchdog_user,
(struct ipmi_addr *) &addr,
0,
&msg,
NULL,
&panic_halt_heartbeat_smi_msg,
&panic_halt_heartbeat_recv_msg,
1);
if (rv)
atomic_sub(2, &panic_done_count);
}
static struct ipmi_smi_msg panic_halt_smi_msg = {
.done = panic_smi_free
};
static struct ipmi_recv_msg panic_halt_recv_msg = {
.done = panic_recv_free
};
/*
* Special call, doesn't claim any locks. This is only to be called
* at panic or halt time, in run-to-completion mode, when the caller
* is the only CPU and the only thing that will be going is these IPMI
* calls.
*/
static void panic_halt_ipmi_set_timeout(void)
{
int send_heartbeat_now;
int rv;
/* Wait for the messages to be free. */
while (atomic_read(&panic_done_count) != 0)
ipmi_poll_interface(watchdog_user);
atomic_add(2, &panic_done_count);
rv = i_ipmi_set_timeout(&panic_halt_smi_msg,
&panic_halt_recv_msg,
&send_heartbeat_now);
if (rv) {
atomic_sub(2, &panic_done_count);
printk(KERN_WARNING PFX
"Unable to extend the watchdog timeout.");
} else {
if (send_heartbeat_now)
panic_halt_ipmi_heartbeat();
}
while (atomic_read(&panic_done_count) != 0)
ipmi_poll_interface(watchdog_user);
}
/*
* We use a mutex to make sure that only one thing can send a
* heartbeat at one time, because we only have one copy of the data.
* The semaphore is claimed when the set_timeout is sent and freed
* when both messages are free.
*/
static atomic_t heartbeat_tofree = ATOMIC_INIT(0);
static DEFINE_MUTEX(heartbeat_lock);
static DECLARE_COMPLETION(heartbeat_wait);
static void heartbeat_free_smi(struct ipmi_smi_msg *msg)
{
if (atomic_dec_and_test(&heartbeat_tofree))
complete(&heartbeat_wait);
}
static void heartbeat_free_recv(struct ipmi_recv_msg *msg)
{
if (atomic_dec_and_test(&heartbeat_tofree))
complete(&heartbeat_wait);
}
static struct ipmi_smi_msg heartbeat_smi_msg = {
.done = heartbeat_free_smi
};
static struct ipmi_recv_msg heartbeat_recv_msg = {
.done = heartbeat_free_recv
};
static int ipmi_heartbeat(void)
{
struct kernel_ipmi_msg msg;
int rv;
struct ipmi_system_interface_addr addr;
int timeout_retries = 0;
if (ipmi_ignore_heartbeat)
return 0;
if (ipmi_start_timer_on_heartbeat) {
ipmi_start_timer_on_heartbeat = 0;
ipmi_watchdog_state = action_val;
return ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
} else if (pretimeout_since_last_heartbeat) {
/*
* A pretimeout occurred, make sure we set the timeout.
* We don't want to set the action, though, we want to
* leave that alone (thus it can't be combined with the
* above operation.
*/
return ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
}
mutex_lock(&heartbeat_lock);
restart:
atomic_set(&heartbeat_tofree, 2);
/*
* Don't reset the timer if we have the timer turned off, that
* re-enables the watchdog.
*/
if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE) {
mutex_unlock(&heartbeat_lock);
return 0;
}
addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
addr.channel = IPMI_BMC_CHANNEL;
addr.lun = 0;
msg.netfn = 0x06;
msg.cmd = IPMI_WDOG_RESET_TIMER;
msg.data = NULL;
msg.data_len = 0;
rv = ipmi_request_supply_msgs(watchdog_user,
(struct ipmi_addr *) &addr,
0,
&msg,
NULL,
&heartbeat_smi_msg,
&heartbeat_recv_msg,
1);
if (rv) {
mutex_unlock(&heartbeat_lock);
printk(KERN_WARNING PFX "heartbeat failure: %d\n",
rv);
return rv;
}
/* Wait for the heartbeat to be sent. */
wait_for_completion(&heartbeat_wait);
if (heartbeat_recv_msg.msg.data[0] == IPMI_WDOG_TIMER_NOT_INIT_RESP) {
timeout_retries++;
if (timeout_retries > 3) {
printk(KERN_ERR PFX ": Unable to restore the IPMI"
" watchdog's settings, giving up.\n");
rv = -EIO;
goto out_unlock;
}
/*
* The timer was not initialized, that means the BMC was
* probably reset and lost the watchdog information. Attempt
* to restore the timer's info. Note that we still hold
* the heartbeat lock, to keep a heartbeat from happening
* in this process, so must say no heartbeat to avoid a
* deadlock on this mutex.
*/
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
if (rv) {
printk(KERN_ERR PFX ": Unable to send the command to"
" set the watchdog's settings, giving up.\n");
goto out_unlock;
}
/* We might need a new heartbeat, so do it now */
goto restart;
} else if (heartbeat_recv_msg.msg.data[0] != 0) {
/*
* Got an error in the heartbeat response. It was already
* reported in ipmi_wdog_msg_handler, but we should return
* an error here.
*/
rv = -EINVAL;
}
out_unlock:
mutex_unlock(&heartbeat_lock);
return rv;
}
static struct watchdog_info ident = {
.options = 0, /* WDIOF_SETTIMEOUT, */
.firmware_version = 1,
.identity = "IPMI"
};
static int ipmi_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
int i;
int val;
switch (cmd) {
case WDIOC_GETSUPPORT:
i = copy_to_user(argp, &ident, sizeof(ident));
return i ? -EFAULT : 0;
case WDIOC_SETTIMEOUT:
i = copy_from_user(&val, argp, sizeof(int));
if (i)
return -EFAULT;
timeout = val;
return ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
case WDIOC_GETTIMEOUT:
i = copy_to_user(argp, &timeout, sizeof(timeout));
if (i)
return -EFAULT;
return 0;
case WDIOC_SET_PRETIMEOUT:
case WDIOC_SETPRETIMEOUT:
i = copy_from_user(&val, argp, sizeof(int));
if (i)
return -EFAULT;
pretimeout = val;
return ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
case WDIOC_GET_PRETIMEOUT:
case WDIOC_GETPRETIMEOUT:
i = copy_to_user(argp, &pretimeout, sizeof(pretimeout));
if (i)
return -EFAULT;
return 0;
case WDIOC_KEEPALIVE:
return ipmi_heartbeat();
case WDIOC_SETOPTIONS:
i = copy_from_user(&val, argp, sizeof(int));
if (i)
return -EFAULT;
if (val & WDIOS_DISABLECARD) {
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
ipmi_start_timer_on_heartbeat = 0;
}
if (val & WDIOS_ENABLECARD) {
ipmi_watchdog_state = action_val;
ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
}
return 0;
case WDIOC_GETSTATUS:
val = 0;
i = copy_to_user(argp, &val, sizeof(val));
if (i)
return -EFAULT;
return 0;
default:
return -ENOIOCTLCMD;
}
}
static long ipmi_unlocked_ioctl(struct file *file,
unsigned int cmd,
unsigned long arg)
{
int ret;
mutex_lock(&ipmi_watchdog_mutex);
ret = ipmi_ioctl(file, cmd, arg);
mutex_unlock(&ipmi_watchdog_mutex);
return ret;
}
static ssize_t ipmi_write(struct file *file,
const char __user *buf,
size_t len,
loff_t *ppos)
{
int rv;
if (len) {
if (!nowayout) {
size_t i;
/* In case it was set long ago */
expect_close = 0;
for (i = 0; i != len; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V')
expect_close = 42;
}
}
rv = ipmi_heartbeat();
if (rv)
return rv;
}
return len;
}
static ssize_t ipmi_read(struct file *file,
char __user *buf,
size_t count,
loff_t *ppos)
{
int rv = 0;
wait_queue_t wait;
if (count <= 0)
return 0;
/*
* Reading returns if the pretimeout has gone off, and it only does
* it once per pretimeout.
*/
spin_lock(&ipmi_read_lock);
if (!data_to_read) {
if (file->f_flags & O_NONBLOCK) {
rv = -EAGAIN;
goto out;
}
init_waitqueue_entry(&wait, current);
add_wait_queue(&read_q, &wait);
while (!data_to_read) {
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock(&ipmi_read_lock);
schedule();
spin_lock(&ipmi_read_lock);
}
remove_wait_queue(&read_q, &wait);
if (signal_pending(current)) {
rv = -ERESTARTSYS;
goto out;
}
}
data_to_read = 0;
out:
spin_unlock(&ipmi_read_lock);
if (rv == 0) {
if (copy_to_user(buf, &data_to_read, 1))
rv = -EFAULT;
else
rv = 1;
}
return rv;
}
static int ipmi_open(struct inode *ino, struct file *filep)
{
switch (iminor(ino)) {
case WATCHDOG_MINOR:
if (test_and_set_bit(0, &ipmi_wdog_open))
return -EBUSY;
/*
* Don't start the timer now, let it start on the
* first heartbeat.
*/
ipmi_start_timer_on_heartbeat = 1;
return nonseekable_open(ino, filep);
default:
return (-ENODEV);
}
}
static unsigned int ipmi_poll(struct file *file, poll_table *wait)
{
unsigned int mask = 0;
poll_wait(file, &read_q, wait);
spin_lock(&ipmi_read_lock);
if (data_to_read)
mask |= (POLLIN | POLLRDNORM);
spin_unlock(&ipmi_read_lock);
return mask;
}
static int ipmi_fasync(int fd, struct file *file, int on)
{
int result;
result = fasync_helper(fd, file, on, &fasync_q);
return (result);
}
static int ipmi_close(struct inode *ino, struct file *filep)
{
if (iminor(ino) == WATCHDOG_MINOR) {
if (expect_close == 42) {
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
} else {
printk(KERN_CRIT PFX
"Unexpected close, not stopping watchdog!\n");
ipmi_heartbeat();
}
clear_bit(0, &ipmi_wdog_open);
}
expect_close = 0;
return 0;
}
static const struct file_operations ipmi_wdog_fops = {
.owner = THIS_MODULE,
.read = ipmi_read,
.poll = ipmi_poll,
.write = ipmi_write,
.unlocked_ioctl = ipmi_unlocked_ioctl,
.open = ipmi_open,
.release = ipmi_close,
.fasync = ipmi_fasync,
.llseek = no_llseek,
};
static struct miscdevice ipmi_wdog_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &ipmi_wdog_fops
};
static void ipmi_wdog_msg_handler(struct ipmi_recv_msg *msg,
void *handler_data)
{
if (msg->msg.cmd == IPMI_WDOG_RESET_TIMER &&
msg->msg.data[0] == IPMI_WDOG_TIMER_NOT_INIT_RESP)
printk(KERN_INFO PFX "response: The IPMI controller appears"
" to have been reset, will attempt to reinitialize"
" the watchdog timer\n");
else if (msg->msg.data[0] != 0)
printk(KERN_ERR PFX "response: Error %x on cmd %x\n",
msg->msg.data[0],
msg->msg.cmd);
ipmi_free_recv_msg(msg);
}
static void ipmi_wdog_pretimeout_handler(void *handler_data)
{
if (preaction_val != WDOG_PRETIMEOUT_NONE) {
if (preop_val == WDOG_PREOP_PANIC) {
if (atomic_inc_and_test(&preop_panic_excl))
panic("Watchdog pre-timeout");
} else if (preop_val == WDOG_PREOP_GIVE_DATA) {
spin_lock(&ipmi_read_lock);
data_to_read = 1;
wake_up_interruptible(&read_q);
kill_fasync(&fasync_q, SIGIO, POLL_IN);
spin_unlock(&ipmi_read_lock);
}
}
/*
* On some machines, the heartbeat will give an error and not
* work unless we re-enable the timer. So do so.
*/
pretimeout_since_last_heartbeat = 1;
}
static struct ipmi_user_hndl ipmi_hndlrs = {
.ipmi_recv_hndl = ipmi_wdog_msg_handler,
.ipmi_watchdog_pretimeout = ipmi_wdog_pretimeout_handler
};
static void ipmi_register_watchdog(int ipmi_intf)
{
int rv = -EBUSY;
if (watchdog_user)
goto out;
if ((ifnum_to_use >= 0) && (ifnum_to_use != ipmi_intf))
goto out;
watchdog_ifnum = ipmi_intf;
rv = ipmi_create_user(ipmi_intf, &ipmi_hndlrs, NULL, &watchdog_user);
if (rv < 0) {
printk(KERN_CRIT PFX "Unable to register with ipmi\n");
goto out;
}
ipmi_get_version(watchdog_user,
&ipmi_version_major,
&ipmi_version_minor);
rv = misc_register(&ipmi_wdog_miscdev);
if (rv < 0) {
ipmi_destroy_user(watchdog_user);
watchdog_user = NULL;
printk(KERN_CRIT PFX "Unable to register misc device\n");
}
#ifdef HAVE_DIE_NMI
if (nmi_handler_registered) {
int old_pretimeout = pretimeout;
int old_timeout = timeout;
int old_preop_val = preop_val;
/*
* Set the pretimeout to go off in a second and give
* ourselves plenty of time to stop the timer.
*/
ipmi_watchdog_state = WDOG_TIMEOUT_RESET;
preop_val = WDOG_PREOP_NONE; /* Make sure nothing happens */
pretimeout = 99;
timeout = 100;
testing_nmi = 1;
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
if (rv) {
printk(KERN_WARNING PFX "Error starting timer to"
" test NMI: 0x%x. The NMI pretimeout will"
" likely not work\n", rv);
rv = 0;
goto out_restore;
}
msleep(1500);
if (testing_nmi != 2) {
printk(KERN_WARNING PFX "IPMI NMI didn't seem to"
" occur. The NMI pretimeout will"
" likely not work\n");
}
out_restore:
testing_nmi = 0;
preop_val = old_preop_val;
pretimeout = old_pretimeout;
timeout = old_timeout;
}
#endif
out:
if ((start_now) && (rv == 0)) {
/* Run from startup, so start the timer now. */
start_now = 0; /* Disable this function after first startup. */
ipmi_watchdog_state = action_val;
ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
printk(KERN_INFO PFX "Starting now!\n");
} else {
/* Stop the timer now. */
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
}
}
static void ipmi_unregister_watchdog(int ipmi_intf)
{
int rv;
if (!watchdog_user)
goto out;
if (watchdog_ifnum != ipmi_intf)
goto out;
/* Make sure no one can call us any more. */
misc_deregister(&ipmi_wdog_miscdev);
/*
* Wait to make sure the message makes it out. The lower layer has
* pointers to our buffers, we want to make sure they are done before
* we release our memory.
*/
while (atomic_read(&set_timeout_tofree))
schedule_timeout_uninterruptible(1);
/* Disconnect from IPMI. */
rv = ipmi_destroy_user(watchdog_user);
if (rv) {
printk(KERN_WARNING PFX "error unlinking from IPMI: %d\n",
rv);
}
watchdog_user = NULL;
out:
return;
}
#ifdef HAVE_DIE_NMI
static int
ipmi_nmi(unsigned int val, struct pt_regs *regs)
{
/*
* If we get here, it's an NMI that's not a memory or I/O
* error. We can't truly tell if it's from IPMI or not
* without sending a message, and sending a message is almost
* impossible because of locking.
*/
if (testing_nmi) {
testing_nmi = 2;
return NMI_HANDLED;
}
/* If we are not expecting a timeout, ignore it. */
if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
return NMI_DONE;
if (preaction_val != WDOG_PRETIMEOUT_NMI)
return NMI_DONE;
/*
* If no one else handled the NMI, we assume it was the IPMI
* watchdog.
*/
if (preop_val == WDOG_PREOP_PANIC) {
/* On some machines, the heartbeat will give
an error and not work unless we re-enable
the timer. So do so. */
pretimeout_since_last_heartbeat = 1;
if (atomic_inc_and_test(&preop_panic_excl))
panic(PFX "pre-timeout");
}
return NMI_HANDLED;
}
#endif
static int wdog_reboot_handler(struct notifier_block *this,
unsigned long code,
void *unused)
{
static int reboot_event_handled;
if ((watchdog_user) && (!reboot_event_handled)) {
/* Make sure we only do this once. */
reboot_event_handled = 1;
if (code == SYS_POWER_OFF || code == SYS_HALT) {
/* Disable the WDT if we are shutting down. */
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
} else if (ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
/* Set a long timer to let the reboot happens, but
reboot if it hangs, but only if the watchdog
timer was already running. */
timeout = 120;
pretimeout = 0;
ipmi_watchdog_state = WDOG_TIMEOUT_RESET;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
}
}
return NOTIFY_OK;
}
static struct notifier_block wdog_reboot_notifier = {
.notifier_call = wdog_reboot_handler,
.next = NULL,
.priority = 0
};
static int wdog_panic_handler(struct notifier_block *this,
unsigned long event,
void *unused)
{
static int panic_event_handled;
/* On a panic, if we have a panic timeout, make sure to extend
the watchdog timer to a reasonable value to complete the
panic, if the watchdog timer is running. Plus the
pretimeout is meaningless at panic time. */
if (watchdog_user && !panic_event_handled &&
ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
/* Make sure we do this only once. */
panic_event_handled = 1;
timeout = 255;
pretimeout = 0;
panic_halt_ipmi_set_timeout();
}
return NOTIFY_OK;
}
static struct notifier_block wdog_panic_notifier = {
.notifier_call = wdog_panic_handler,
.next = NULL,
.priority = 150 /* priority: INT_MAX >= x >= 0 */
};
static void ipmi_new_smi(int if_num, struct device *device)
{
ipmi_register_watchdog(if_num);
}
static void ipmi_smi_gone(int if_num)
{
ipmi_unregister_watchdog(if_num);
}
static struct ipmi_smi_watcher smi_watcher = {
.owner = THIS_MODULE,
.new_smi = ipmi_new_smi,
.smi_gone = ipmi_smi_gone
};
static int action_op(const char *inval, char *outval)
{
if (outval)
strcpy(outval, action);
if (!inval)
return 0;
if (strcmp(inval, "reset") == 0)
action_val = WDOG_TIMEOUT_RESET;
else if (strcmp(inval, "none") == 0)
action_val = WDOG_TIMEOUT_NONE;
else if (strcmp(inval, "power_cycle") == 0)
action_val = WDOG_TIMEOUT_POWER_CYCLE;
else if (strcmp(inval, "power_off") == 0)
action_val = WDOG_TIMEOUT_POWER_DOWN;
else
return -EINVAL;
strcpy(action, inval);
return 0;
}
static int preaction_op(const char *inval, char *outval)
{
if (outval)
strcpy(outval, preaction);
if (!inval)
return 0;
if (strcmp(inval, "pre_none") == 0)
preaction_val = WDOG_PRETIMEOUT_NONE;
else if (strcmp(inval, "pre_smi") == 0)
preaction_val = WDOG_PRETIMEOUT_SMI;
#ifdef HAVE_DIE_NMI
else if (strcmp(inval, "pre_nmi") == 0)
preaction_val = WDOG_PRETIMEOUT_NMI;
#endif
else if (strcmp(inval, "pre_int") == 0)
preaction_val = WDOG_PRETIMEOUT_MSG_INT;
else
return -EINVAL;
strcpy(preaction, inval);
return 0;
}
static int preop_op(const char *inval, char *outval)
{
if (outval)
strcpy(outval, preop);
if (!inval)
return 0;
if (strcmp(inval, "preop_none") == 0)
preop_val = WDOG_PREOP_NONE;
else if (strcmp(inval, "preop_panic") == 0)
preop_val = WDOG_PREOP_PANIC;
else if (strcmp(inval, "preop_give_data") == 0)
preop_val = WDOG_PREOP_GIVE_DATA;
else
return -EINVAL;
strcpy(preop, inval);
return 0;
}
static void check_parms(void)
{
#ifdef HAVE_DIE_NMI
int do_nmi = 0;
int rv;
if (preaction_val == WDOG_PRETIMEOUT_NMI) {
do_nmi = 1;
if (preop_val == WDOG_PREOP_GIVE_DATA) {
printk(KERN_WARNING PFX "Pretimeout op is to give data"
" but NMI pretimeout is enabled, setting"
" pretimeout op to none\n");
preop_op("preop_none", NULL);
do_nmi = 0;
}
}
if (do_nmi && !nmi_handler_registered) {
rv = register_nmi_handler(NMI_UNKNOWN, ipmi_nmi, 0,
"ipmi");
if (rv) {
printk(KERN_WARNING PFX
"Can't register nmi handler\n");
return;
} else
nmi_handler_registered = 1;
} else if (!do_nmi && nmi_handler_registered) {
unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
nmi_handler_registered = 0;
}
#endif
}
static int __init ipmi_wdog_init(void)
{
int rv;
if (action_op(action, NULL)) {
action_op("reset", NULL);
printk(KERN_INFO PFX "Unknown action '%s', defaulting to"
" reset\n", action);
}
if (preaction_op(preaction, NULL)) {
preaction_op("pre_none", NULL);
printk(KERN_INFO PFX "Unknown preaction '%s', defaulting to"
" none\n", preaction);
}
if (preop_op(preop, NULL)) {
preop_op("preop_none", NULL);
printk(KERN_INFO PFX "Unknown preop '%s', defaulting to"
" none\n", preop);
}
check_parms();
register_reboot_notifier(&wdog_reboot_notifier);
atomic_notifier_chain_register(&panic_notifier_list,
&wdog_panic_notifier);
rv = ipmi_smi_watcher_register(&smi_watcher);
if (rv) {
#ifdef HAVE_DIE_NMI
if (nmi_handler_registered)
unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
#endif
atomic_notifier_chain_unregister(&panic_notifier_list,
&wdog_panic_notifier);
unregister_reboot_notifier(&wdog_reboot_notifier);
printk(KERN_WARNING PFX "can't register smi watcher\n");
return rv;
}
printk(KERN_INFO PFX "driver initialized\n");
return 0;
}
static void __exit ipmi_wdog_exit(void)
{
ipmi_smi_watcher_unregister(&smi_watcher);
ipmi_unregister_watchdog(watchdog_ifnum);
#ifdef HAVE_DIE_NMI
if (nmi_handler_registered)
unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
#endif
atomic_notifier_chain_unregister(&panic_notifier_list,
&wdog_panic_notifier);
unregister_reboot_notifier(&wdog_reboot_notifier);
}
module_exit(ipmi_wdog_exit);
module_init(ipmi_wdog_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
MODULE_DESCRIPTION("watchdog timer based upon the IPMI interface.");
| gpl-2.0 |
cwyy/linux-3.4.69 | drivers/leds/leds-88pm860x.c | 4854 | 6359 | /*
* LED driver for Marvell 88PM860x
*
* Copyright (C) 2009 Marvell International Ltd.
* Haojian Zhuang <haojian.zhuang@marvell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/leds.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/mfd/88pm860x.h>
#include <linux/module.h>
#define LED_PWM_SHIFT (3)
#define LED_PWM_MASK (0x1F)
#define LED_CURRENT_MASK (0x07 << 5)
#define LED_BLINK_ON_MASK (0x07)
#define LED_BLINK_MASK (0x7F)
#define LED_BLINK_ON(x) ((x & 0x7) * 66 + 66)
#define LED_BLINK_ON_MIN LED_BLINK_ON(0)
#define LED_BLINK_ON_MAX LED_BLINK_ON(0x7)
#define LED_ON_CONTINUOUS (0x0F << 3)
#define LED_TO_ON(x) ((x - 66) / 66)
#define LED1_BLINK_EN (1 << 1)
#define LED2_BLINK_EN (1 << 2)
struct pm860x_led {
struct led_classdev cdev;
struct i2c_client *i2c;
struct work_struct work;
struct pm860x_chip *chip;
struct mutex lock;
char name[MFD_NAME_SIZE];
int port;
int iset;
unsigned char brightness;
unsigned char current_brightness;
int blink_data;
int blink_time;
int blink_on;
int blink_off;
};
/* return offset of color register */
static inline int __led_off(int port)
{
int ret = -EINVAL;
switch (port) {
case PM8606_LED1_RED:
case PM8606_LED1_GREEN:
case PM8606_LED1_BLUE:
ret = port - PM8606_LED1_RED + PM8606_RGB1B;
break;
case PM8606_LED2_RED:
case PM8606_LED2_GREEN:
case PM8606_LED2_BLUE:
ret = port - PM8606_LED2_RED + PM8606_RGB2B;
break;
}
return ret;
}
/* return offset of blink register */
static inline int __blink_off(int port)
{
int ret = -EINVAL;
switch (port) {
case PM8606_LED1_RED:
case PM8606_LED1_GREEN:
case PM8606_LED1_BLUE:
ret = PM8606_RGB1A;
break;
case PM8606_LED2_RED:
case PM8606_LED2_GREEN:
case PM8606_LED2_BLUE:
ret = PM8606_RGB2A;
break;
}
return ret;
}
static inline int __blink_ctl_mask(int port)
{
int ret = -EINVAL;
switch (port) {
case PM8606_LED1_RED:
case PM8606_LED1_GREEN:
case PM8606_LED1_BLUE:
ret = LED1_BLINK_EN;
break;
case PM8606_LED2_RED:
case PM8606_LED2_GREEN:
case PM8606_LED2_BLUE:
ret = LED2_BLINK_EN;
break;
}
return ret;
}
static int led_power_set(struct pm860x_chip *chip, int port, int on)
{
int ret = -EINVAL;
switch (port) {
case PM8606_LED1_RED:
case PM8606_LED1_GREEN:
case PM8606_LED1_BLUE:
ret = on ? pm8606_osc_enable(chip, RGB1_ENABLE) :
pm8606_osc_disable(chip, RGB1_ENABLE);
break;
case PM8606_LED2_RED:
case PM8606_LED2_GREEN:
case PM8606_LED2_BLUE:
ret = on ? pm8606_osc_enable(chip, RGB2_ENABLE) :
pm8606_osc_disable(chip, RGB2_ENABLE);
break;
}
return ret;
}
static void pm860x_led_work(struct work_struct *work)
{
struct pm860x_led *led;
struct pm860x_chip *chip;
unsigned char buf[3];
int mask, ret;
led = container_of(work, struct pm860x_led, work);
chip = led->chip;
mutex_lock(&led->lock);
if ((led->current_brightness == 0) && led->brightness) {
led_power_set(chip, led->port, 1);
if (led->iset) {
pm860x_set_bits(led->i2c, __led_off(led->port),
LED_CURRENT_MASK, led->iset);
}
pm860x_set_bits(led->i2c, __blink_off(led->port),
LED_BLINK_MASK, LED_ON_CONTINUOUS);
mask = __blink_ctl_mask(led->port);
pm860x_set_bits(led->i2c, PM8606_WLED3B, mask, mask);
}
pm860x_set_bits(led->i2c, __led_off(led->port), LED_PWM_MASK,
led->brightness);
if (led->brightness == 0) {
pm860x_bulk_read(led->i2c, __led_off(led->port), 3, buf);
ret = buf[0] & LED_PWM_MASK;
ret |= buf[1] & LED_PWM_MASK;
ret |= buf[2] & LED_PWM_MASK;
if (ret == 0) {
/* unset current since no led is lighting */
pm860x_set_bits(led->i2c, __led_off(led->port),
LED_CURRENT_MASK, 0);
mask = __blink_ctl_mask(led->port);
pm860x_set_bits(led->i2c, PM8606_WLED3B, mask, 0);
led_power_set(chip, led->port, 0);
}
}
led->current_brightness = led->brightness;
dev_dbg(chip->dev, "Update LED. (reg:%d, brightness:%d)\n",
__led_off(led->port), led->brightness);
mutex_unlock(&led->lock);
}
static void pm860x_led_set(struct led_classdev *cdev,
enum led_brightness value)
{
struct pm860x_led *data = container_of(cdev, struct pm860x_led, cdev);
data->brightness = value >> 3;
schedule_work(&data->work);
}
static int pm860x_led_probe(struct platform_device *pdev)
{
struct pm860x_chip *chip = dev_get_drvdata(pdev->dev.parent);
struct pm860x_led_pdata *pdata;
struct pm860x_led *data;
struct resource *res;
int ret;
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (res == NULL) {
dev_err(&pdev->dev, "No I/O resource!\n");
return -EINVAL;
}
pdata = pdev->dev.platform_data;
if (pdata == NULL) {
dev_err(&pdev->dev, "No platform data!\n");
return -EINVAL;
}
data = kzalloc(sizeof(struct pm860x_led), GFP_KERNEL);
if (data == NULL)
return -ENOMEM;
strncpy(data->name, res->name, MFD_NAME_SIZE - 1);
dev_set_drvdata(&pdev->dev, data);
data->chip = chip;
data->i2c = (chip->id == CHIP_PM8606) ? chip->client : chip->companion;
data->iset = pdata->iset;
data->port = pdata->flags;
if (data->port < 0) {
dev_err(&pdev->dev, "check device failed\n");
kfree(data);
return -EINVAL;
}
data->current_brightness = 0;
data->cdev.name = data->name;
data->cdev.brightness_set = pm860x_led_set;
mutex_init(&data->lock);
INIT_WORK(&data->work, pm860x_led_work);
ret = led_classdev_register(chip->dev, &data->cdev);
if (ret < 0) {
dev_err(&pdev->dev, "Failed to register LED: %d\n", ret);
goto out;
}
pm860x_led_set(&data->cdev, 0);
return 0;
out:
kfree(data);
return ret;
}
static int pm860x_led_remove(struct platform_device *pdev)
{
struct pm860x_led *data = platform_get_drvdata(pdev);
led_classdev_unregister(&data->cdev);
kfree(data);
return 0;
}
static struct platform_driver pm860x_led_driver = {
.driver = {
.name = "88pm860x-led",
.owner = THIS_MODULE,
},
.probe = pm860x_led_probe,
.remove = pm860x_led_remove,
};
module_platform_driver(pm860x_led_driver);
MODULE_DESCRIPTION("LED driver for Marvell PM860x");
MODULE_AUTHOR("Haojian Zhuang <haojian.zhuang@marvell.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:88pm860x-led");
| gpl-2.0 |
houst0nn/android_kernel_lge_g3 | drivers/s390/block/dasd_diag.c | 4854 | 18391 | /*
* File...........: linux/drivers/s390/block/dasd_diag.c
* Author(s)......: Holger Smolinski <Holger.Smolinski@de.ibm.com>
* Based on.......: linux/drivers/s390/block/mdisk.c
* ...............: by Hartmunt Penner <hpenner@de.ibm.com>
* Bugreports.to..: <Linux390@de.ibm.com>
* (C) IBM Corporation, IBM Deutschland Entwicklung GmbH, 1999,2000
*
*/
#define KMSG_COMPONENT "dasd"
#include <linux/kernel_stat.h>
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/hdreg.h>
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <asm/dasd.h>
#include <asm/debug.h>
#include <asm/ebcdic.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/vtoc.h>
#include <asm/diag.h>
#include "dasd_int.h"
#include "dasd_diag.h"
#define PRINTK_HEADER "dasd(diag):"
MODULE_LICENSE("GPL");
/* The maximum number of blocks per request (max_blocks) is dependent on the
* amount of storage that is available in the static I/O buffer for each
* device. Currently each device gets 2 pages. We want to fit two requests
* into the available memory so that we can immediately start the next if one
* finishes. */
#define DIAG_MAX_BLOCKS (((2 * PAGE_SIZE - sizeof(struct dasd_ccw_req) - \
sizeof(struct dasd_diag_req)) / \
sizeof(struct dasd_diag_bio)) / 2)
#define DIAG_MAX_RETRIES 32
#define DIAG_TIMEOUT 50
static struct dasd_discipline dasd_diag_discipline;
struct dasd_diag_private {
struct dasd_diag_characteristics rdc_data;
struct dasd_diag_rw_io iob;
struct dasd_diag_init_io iib;
blocknum_t pt_block;
struct ccw_dev_id dev_id;
};
struct dasd_diag_req {
unsigned int block_count;
struct dasd_diag_bio bio[0];
};
static const u8 DASD_DIAG_CMS1[] = { 0xc3, 0xd4, 0xe2, 0xf1 };/* EBCDIC CMS1 */
/* Perform DIAG250 call with block I/O parameter list iob (input and output)
* and function code cmd.
* In case of an exception return 3. Otherwise return result of bitwise OR of
* resulting condition code and DIAG return code. */
static inline int dia250(void *iob, int cmd)
{
register unsigned long reg2 asm ("2") = (unsigned long) iob;
typedef union {
struct dasd_diag_init_io init_io;
struct dasd_diag_rw_io rw_io;
} addr_type;
int rc;
rc = 3;
asm volatile(
" diag 2,%2,0x250\n"
"0: ipm %0\n"
" srl %0,28\n"
" or %0,3\n"
"1:\n"
EX_TABLE(0b,1b)
: "+d" (rc), "=m" (*(addr_type *) iob)
: "d" (cmd), "d" (reg2), "m" (*(addr_type *) iob)
: "3", "cc");
return rc;
}
/* Initialize block I/O to DIAG device using the specified blocksize and
* block offset. On success, return zero and set end_block to contain the
* number of blocks on the device minus the specified offset. Return non-zero
* otherwise. */
static inline int
mdsk_init_io(struct dasd_device *device, unsigned int blocksize,
blocknum_t offset, blocknum_t *end_block)
{
struct dasd_diag_private *private;
struct dasd_diag_init_io *iib;
int rc;
private = (struct dasd_diag_private *) device->private;
iib = &private->iib;
memset(iib, 0, sizeof (struct dasd_diag_init_io));
iib->dev_nr = private->dev_id.devno;
iib->block_size = blocksize;
iib->offset = offset;
iib->flaga = DASD_DIAG_FLAGA_DEFAULT;
rc = dia250(iib, INIT_BIO);
if ((rc & 3) == 0 && end_block)
*end_block = iib->end_block;
return rc;
}
/* Remove block I/O environment for device. Return zero on success, non-zero
* otherwise. */
static inline int
mdsk_term_io(struct dasd_device * device)
{
struct dasd_diag_private *private;
struct dasd_diag_init_io *iib;
int rc;
private = (struct dasd_diag_private *) device->private;
iib = &private->iib;
memset(iib, 0, sizeof (struct dasd_diag_init_io));
iib->dev_nr = private->dev_id.devno;
rc = dia250(iib, TERM_BIO);
return rc;
}
/* Error recovery for failed DIAG requests - try to reestablish the DIAG
* environment. */
static void
dasd_diag_erp(struct dasd_device *device)
{
int rc;
mdsk_term_io(device);
rc = mdsk_init_io(device, device->block->bp_block, 0, NULL);
if (rc == 4) {
if (!(test_and_set_bit(DASD_FLAG_DEVICE_RO, &device->flags)))
pr_warning("%s: The access mode of a DIAG device "
"changed to read-only\n",
dev_name(&device->cdev->dev));
rc = 0;
}
if (rc)
pr_warning("%s: DIAG ERP failed with "
"rc=%d\n", dev_name(&device->cdev->dev), rc);
}
/* Start a given request at the device. Return zero on success, non-zero
* otherwise. */
static int
dasd_start_diag(struct dasd_ccw_req * cqr)
{
struct dasd_device *device;
struct dasd_diag_private *private;
struct dasd_diag_req *dreq;
int rc;
device = cqr->startdev;
if (cqr->retries < 0) {
DBF_DEV_EVENT(DBF_ERR, device, "DIAG start_IO: request %p "
"- no retry left)", cqr);
cqr->status = DASD_CQR_ERROR;
return -EIO;
}
private = (struct dasd_diag_private *) device->private;
dreq = (struct dasd_diag_req *) cqr->data;
private->iob.dev_nr = private->dev_id.devno;
private->iob.key = 0;
private->iob.flags = DASD_DIAG_RWFLAG_ASYNC;
private->iob.block_count = dreq->block_count;
private->iob.interrupt_params = (addr_t) cqr;
private->iob.bio_list = dreq->bio;
private->iob.flaga = DASD_DIAG_FLAGA_DEFAULT;
cqr->startclk = get_clock();
cqr->starttime = jiffies;
cqr->retries--;
rc = dia250(&private->iob, RW_BIO);
switch (rc) {
case 0: /* Synchronous I/O finished successfully */
cqr->stopclk = get_clock();
cqr->status = DASD_CQR_SUCCESS;
/* Indicate to calling function that only a dasd_schedule_bh()
and no timer is needed */
rc = -EACCES;
break;
case 8: /* Asynchronous I/O was started */
cqr->status = DASD_CQR_IN_IO;
rc = 0;
break;
default: /* Error condition */
cqr->status = DASD_CQR_QUEUED;
DBF_DEV_EVENT(DBF_WARNING, device, "dia250 returned rc=%d", rc);
dasd_diag_erp(device);
rc = -EIO;
break;
}
cqr->intrc = rc;
return rc;
}
/* Terminate given request at the device. */
static int
dasd_diag_term_IO(struct dasd_ccw_req * cqr)
{
struct dasd_device *device;
device = cqr->startdev;
mdsk_term_io(device);
mdsk_init_io(device, device->block->bp_block, 0, NULL);
cqr->status = DASD_CQR_CLEAR_PENDING;
cqr->stopclk = get_clock();
dasd_schedule_device_bh(device);
return 0;
}
/* Handle external interruption. */
static void dasd_ext_handler(struct ext_code ext_code,
unsigned int param32, unsigned long param64)
{
struct dasd_ccw_req *cqr, *next;
struct dasd_device *device;
unsigned long long expires;
unsigned long flags;
addr_t ip;
int rc;
switch (ext_code.subcode >> 8) {
case DASD_DIAG_CODE_31BIT:
ip = (addr_t) param32;
break;
case DASD_DIAG_CODE_64BIT:
ip = (addr_t) param64;
break;
default:
return;
}
kstat_cpu(smp_processor_id()).irqs[EXTINT_DSD]++;
if (!ip) { /* no intparm: unsolicited interrupt */
DBF_EVENT(DBF_NOTICE, "%s", "caught unsolicited "
"interrupt");
return;
}
cqr = (struct dasd_ccw_req *) ip;
device = (struct dasd_device *) cqr->startdev;
if (strncmp(device->discipline->ebcname, (char *) &cqr->magic, 4)) {
DBF_DEV_EVENT(DBF_WARNING, device,
" magic number of dasd_ccw_req 0x%08X doesn't"
" match discipline 0x%08X",
cqr->magic, *(int *) (&device->discipline->name));
return;
}
/* get irq lock to modify request queue */
spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
/* Check for a pending clear operation */
if (cqr->status == DASD_CQR_CLEAR_PENDING) {
cqr->status = DASD_CQR_CLEARED;
dasd_device_clear_timer(device);
dasd_schedule_device_bh(device);
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
return;
}
cqr->stopclk = get_clock();
expires = 0;
if ((ext_code.subcode & 0xff) == 0) {
cqr->status = DASD_CQR_SUCCESS;
/* Start first request on queue if possible -> fast_io. */
if (!list_empty(&device->ccw_queue)) {
next = list_entry(device->ccw_queue.next,
struct dasd_ccw_req, devlist);
if (next->status == DASD_CQR_QUEUED) {
rc = dasd_start_diag(next);
if (rc == 0)
expires = next->expires;
}
}
} else {
cqr->status = DASD_CQR_QUEUED;
DBF_DEV_EVENT(DBF_DEBUG, device, "interrupt status for "
"request %p was %d (%d retries left)", cqr,
ext_code.subcode & 0xff, cqr->retries);
dasd_diag_erp(device);
}
if (expires != 0)
dasd_device_set_timer(device, expires);
else
dasd_device_clear_timer(device);
dasd_schedule_device_bh(device);
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
}
/* Check whether device can be controlled by DIAG discipline. Return zero on
* success, non-zero otherwise. */
static int
dasd_diag_check_device(struct dasd_device *device)
{
struct dasd_block *block;
struct dasd_diag_private *private;
struct dasd_diag_characteristics *rdc_data;
struct dasd_diag_bio bio;
struct vtoc_cms_label *label;
blocknum_t end_block;
unsigned int sb, bsize;
int rc;
private = (struct dasd_diag_private *) device->private;
if (private == NULL) {
private = kzalloc(sizeof(struct dasd_diag_private),GFP_KERNEL);
if (private == NULL) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Allocating memory for private DASD data "
"failed\n");
return -ENOMEM;
}
ccw_device_get_id(device->cdev, &private->dev_id);
device->private = (void *) private;
}
block = dasd_alloc_block();
if (IS_ERR(block)) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"could not allocate dasd block structure");
device->private = NULL;
kfree(private);
return PTR_ERR(block);
}
device->block = block;
block->base = device;
/* Read Device Characteristics */
rdc_data = (void *) &(private->rdc_data);
rdc_data->dev_nr = private->dev_id.devno;
rdc_data->rdc_len = sizeof (struct dasd_diag_characteristics);
rc = diag210((struct diag210 *) rdc_data);
if (rc) {
DBF_DEV_EVENT(DBF_WARNING, device, "failed to retrieve device "
"information (rc=%d)", rc);
rc = -EOPNOTSUPP;
goto out;
}
device->default_expires = DIAG_TIMEOUT;
/* Figure out position of label block */
switch (private->rdc_data.vdev_class) {
case DEV_CLASS_FBA:
private->pt_block = 1;
break;
case DEV_CLASS_ECKD:
private->pt_block = 2;
break;
default:
pr_warning("%s: Device type %d is not supported "
"in DIAG mode\n", dev_name(&device->cdev->dev),
private->rdc_data.vdev_class);
rc = -EOPNOTSUPP;
goto out;
}
DBF_DEV_EVENT(DBF_INFO, device,
"%04X: %04X on real %04X/%02X",
rdc_data->dev_nr,
rdc_data->vdev_type,
rdc_data->rdev_type, rdc_data->rdev_model);
/* terminate all outstanding operations */
mdsk_term_io(device);
/* figure out blocksize of device */
label = (struct vtoc_cms_label *) get_zeroed_page(GFP_KERNEL);
if (label == NULL) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"No memory to allocate initialization request");
rc = -ENOMEM;
goto out;
}
rc = 0;
end_block = 0;
/* try all sizes - needed for ECKD devices */
for (bsize = 512; bsize <= PAGE_SIZE; bsize <<= 1) {
mdsk_init_io(device, bsize, 0, &end_block);
memset(&bio, 0, sizeof (struct dasd_diag_bio));
bio.type = MDSK_READ_REQ;
bio.block_number = private->pt_block + 1;
bio.buffer = label;
memset(&private->iob, 0, sizeof (struct dasd_diag_rw_io));
private->iob.dev_nr = rdc_data->dev_nr;
private->iob.key = 0;
private->iob.flags = 0; /* do synchronous io */
private->iob.block_count = 1;
private->iob.interrupt_params = 0;
private->iob.bio_list = &bio;
private->iob.flaga = DASD_DIAG_FLAGA_DEFAULT;
rc = dia250(&private->iob, RW_BIO);
if (rc == 3) {
pr_warning("%s: A 64-bit DIAG call failed\n",
dev_name(&device->cdev->dev));
rc = -EOPNOTSUPP;
goto out_label;
}
mdsk_term_io(device);
if (rc == 0)
break;
}
if (bsize > PAGE_SIZE) {
pr_warning("%s: Accessing the DASD failed because of an "
"incorrect format (rc=%d)\n",
dev_name(&device->cdev->dev), rc);
rc = -EIO;
goto out_label;
}
/* check for label block */
if (memcmp(label->label_id, DASD_DIAG_CMS1,
sizeof(DASD_DIAG_CMS1)) == 0) {
/* get formatted blocksize from label block */
bsize = (unsigned int) label->block_size;
block->blocks = (unsigned long) label->block_count;
} else
block->blocks = end_block;
block->bp_block = bsize;
block->s2b_shift = 0; /* bits to shift 512 to get a block */
for (sb = 512; sb < bsize; sb = sb << 1)
block->s2b_shift++;
rc = mdsk_init_io(device, block->bp_block, 0, NULL);
if (rc && (rc != 4)) {
pr_warning("%s: DIAG initialization failed with rc=%d\n",
dev_name(&device->cdev->dev), rc);
rc = -EIO;
} else {
if (rc == 4)
set_bit(DASD_FLAG_DEVICE_RO, &device->flags);
pr_info("%s: New DASD with %ld byte/block, total size %ld "
"KB%s\n", dev_name(&device->cdev->dev),
(unsigned long) block->bp_block,
(unsigned long) (block->blocks <<
block->s2b_shift) >> 1,
(rc == 4) ? ", read-only device" : "");
rc = 0;
}
out_label:
free_page((long) label);
out:
if (rc) {
device->block = NULL;
dasd_free_block(block);
device->private = NULL;
kfree(private);
}
return rc;
}
/* Fill in virtual disk geometry for device. Return zero on success, non-zero
* otherwise. */
static int
dasd_diag_fill_geometry(struct dasd_block *block, struct hd_geometry *geo)
{
if (dasd_check_blocksize(block->bp_block) != 0)
return -EINVAL;
geo->cylinders = (block->blocks << block->s2b_shift) >> 10;
geo->heads = 16;
geo->sectors = 128 >> block->s2b_shift;
return 0;
}
static dasd_erp_fn_t
dasd_diag_erp_action(struct dasd_ccw_req * cqr)
{
return dasd_default_erp_action;
}
static dasd_erp_fn_t
dasd_diag_erp_postaction(struct dasd_ccw_req * cqr)
{
return dasd_default_erp_postaction;
}
/* Create DASD request from block device request. Return pointer to new
* request on success, ERR_PTR otherwise. */
static struct dasd_ccw_req *dasd_diag_build_cp(struct dasd_device *memdev,
struct dasd_block *block,
struct request *req)
{
struct dasd_ccw_req *cqr;
struct dasd_diag_req *dreq;
struct dasd_diag_bio *dbio;
struct req_iterator iter;
struct bio_vec *bv;
char *dst;
unsigned int count, datasize;
sector_t recid, first_rec, last_rec;
unsigned int blksize, off;
unsigned char rw_cmd;
if (rq_data_dir(req) == READ)
rw_cmd = MDSK_READ_REQ;
else if (rq_data_dir(req) == WRITE)
rw_cmd = MDSK_WRITE_REQ;
else
return ERR_PTR(-EINVAL);
blksize = block->bp_block;
/* Calculate record id of first and last block. */
first_rec = blk_rq_pos(req) >> block->s2b_shift;
last_rec =
(blk_rq_pos(req) + blk_rq_sectors(req) - 1) >> block->s2b_shift;
/* Check struct bio and count the number of blocks for the request. */
count = 0;
rq_for_each_segment(bv, req, iter) {
if (bv->bv_len & (blksize - 1))
/* Fba can only do full blocks. */
return ERR_PTR(-EINVAL);
count += bv->bv_len >> (block->s2b_shift + 9);
}
/* Paranoia. */
if (count != last_rec - first_rec + 1)
return ERR_PTR(-EINVAL);
/* Build the request */
datasize = sizeof(struct dasd_diag_req) +
count*sizeof(struct dasd_diag_bio);
cqr = dasd_smalloc_request(DASD_DIAG_MAGIC, 0, datasize, memdev);
if (IS_ERR(cqr))
return cqr;
dreq = (struct dasd_diag_req *) cqr->data;
dreq->block_count = count;
dbio = dreq->bio;
recid = first_rec;
rq_for_each_segment(bv, req, iter) {
dst = page_address(bv->bv_page) + bv->bv_offset;
for (off = 0; off < bv->bv_len; off += blksize) {
memset(dbio, 0, sizeof (struct dasd_diag_bio));
dbio->type = rw_cmd;
dbio->block_number = recid + 1;
dbio->buffer = dst;
dbio++;
dst += blksize;
recid++;
}
}
cqr->retries = DIAG_MAX_RETRIES;
cqr->buildclk = get_clock();
if (blk_noretry_request(req) ||
block->base->features & DASD_FEATURE_FAILFAST)
set_bit(DASD_CQR_FLAGS_FAILFAST, &cqr->flags);
cqr->startdev = memdev;
cqr->memdev = memdev;
cqr->block = block;
cqr->expires = memdev->default_expires * HZ;
cqr->status = DASD_CQR_FILLED;
return cqr;
}
/* Release DASD request. Return non-zero if request was successful, zero
* otherwise. */
static int
dasd_diag_free_cp(struct dasd_ccw_req *cqr, struct request *req)
{
int status;
status = cqr->status == DASD_CQR_DONE;
dasd_sfree_request(cqr, cqr->memdev);
return status;
}
static void dasd_diag_handle_terminated_request(struct dasd_ccw_req *cqr)
{
cqr->status = DASD_CQR_FILLED;
};
/* Fill in IOCTL data for device. */
static int
dasd_diag_fill_info(struct dasd_device * device,
struct dasd_information2_t * info)
{
struct dasd_diag_private *private;
private = (struct dasd_diag_private *) device->private;
info->label_block = (unsigned int) private->pt_block;
info->FBA_layout = 1;
info->format = DASD_FORMAT_LDL;
info->characteristics_size = sizeof (struct dasd_diag_characteristics);
memcpy(info->characteristics,
&((struct dasd_diag_private *) device->private)->rdc_data,
sizeof (struct dasd_diag_characteristics));
info->confdata_size = 0;
return 0;
}
static void
dasd_diag_dump_sense(struct dasd_device *device, struct dasd_ccw_req * req,
struct irb *stat)
{
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"dump sense not available for DIAG data");
}
static struct dasd_discipline dasd_diag_discipline = {
.owner = THIS_MODULE,
.name = "DIAG",
.ebcname = "DIAG",
.max_blocks = DIAG_MAX_BLOCKS,
.check_device = dasd_diag_check_device,
.verify_path = dasd_generic_verify_path,
.fill_geometry = dasd_diag_fill_geometry,
.start_IO = dasd_start_diag,
.term_IO = dasd_diag_term_IO,
.handle_terminated_request = dasd_diag_handle_terminated_request,
.erp_action = dasd_diag_erp_action,
.erp_postaction = dasd_diag_erp_postaction,
.build_cp = dasd_diag_build_cp,
.free_cp = dasd_diag_free_cp,
.dump_sense = dasd_diag_dump_sense,
.fill_info = dasd_diag_fill_info,
};
static int __init
dasd_diag_init(void)
{
if (!MACHINE_IS_VM) {
pr_info("Discipline %s cannot be used without z/VM\n",
dasd_diag_discipline.name);
return -ENODEV;
}
ASCEBC(dasd_diag_discipline.ebcname, 4);
service_subclass_irq_register();
register_external_interrupt(0x2603, dasd_ext_handler);
dasd_diag_discipline_pointer = &dasd_diag_discipline;
return 0;
}
static void __exit
dasd_diag_cleanup(void)
{
unregister_external_interrupt(0x2603, dasd_ext_handler);
service_subclass_irq_unregister();
dasd_diag_discipline_pointer = NULL;
}
module_init(dasd_diag_init);
module_exit(dasd_diag_cleanup);
| gpl-2.0 |
VilleEvitaCake/android_kernel_htc_msm8960 | fs/yaffs2/yaffs_verify.c | 7926 | 13283 | /*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2010 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <charles@aleph1.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include "yaffs_verify.h"
#include "yaffs_trace.h"
#include "yaffs_bitmap.h"
#include "yaffs_getblockinfo.h"
#include "yaffs_nand.h"
int yaffs_skip_verification(struct yaffs_dev *dev)
{
dev = dev;
return !(yaffs_trace_mask &
(YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
}
static int yaffs_skip_full_verification(struct yaffs_dev *dev)
{
dev = dev;
return !(yaffs_trace_mask & (YAFFS_TRACE_VERIFY_FULL));
}
static int yaffs_skip_nand_verification(struct yaffs_dev *dev)
{
dev = dev;
return !(yaffs_trace_mask & (YAFFS_TRACE_VERIFY_NAND));
}
static const char *block_state_name[] = {
"Unknown",
"Needs scanning",
"Scanning",
"Empty",
"Allocating",
"Full",
"Dirty",
"Checkpoint",
"Collecting",
"Dead"
};
void yaffs_verify_blk(struct yaffs_dev *dev, struct yaffs_block_info *bi, int n)
{
int actually_used;
int in_use;
if (yaffs_skip_verification(dev))
return;
/* Report illegal runtime states */
if (bi->block_state >= YAFFS_NUMBER_OF_BLOCK_STATES)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has undefined state %d",
n, bi->block_state);
switch (bi->block_state) {
case YAFFS_BLOCK_STATE_UNKNOWN:
case YAFFS_BLOCK_STATE_SCANNING:
case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has bad run-state %s",
n, block_state_name[bi->block_state]);
}
/* Check pages in use and soft deletions are legal */
actually_used = bi->pages_in_use - bi->soft_del_pages;
if (bi->pages_in_use < 0
|| bi->pages_in_use > dev->param.chunks_per_block
|| bi->soft_del_pages < 0
|| bi->soft_del_pages > dev->param.chunks_per_block
|| actually_used < 0 || actually_used > dev->param.chunks_per_block)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has illegal values pages_in_used %d soft_del_pages %d",
n, bi->pages_in_use, bi->soft_del_pages);
/* Check chunk bitmap legal */
in_use = yaffs_count_chunk_bits(dev, n);
if (in_use != bi->pages_in_use)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has inconsistent values pages_in_use %d counted chunk bits %d",
n, bi->pages_in_use, in_use);
}
void yaffs_verify_collected_blk(struct yaffs_dev *dev,
struct yaffs_block_info *bi, int n)
{
yaffs_verify_blk(dev, bi, n);
/* After collection the block should be in the erased state */
if (bi->block_state != YAFFS_BLOCK_STATE_COLLECTING &&
bi->block_state != YAFFS_BLOCK_STATE_EMPTY) {
yaffs_trace(YAFFS_TRACE_ERROR,
"Block %d is in state %d after gc, should be erased",
n, bi->block_state);
}
}
void yaffs_verify_blocks(struct yaffs_dev *dev)
{
int i;
int state_count[YAFFS_NUMBER_OF_BLOCK_STATES];
int illegal_states = 0;
if (yaffs_skip_verification(dev))
return;
memset(state_count, 0, sizeof(state_count));
for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
struct yaffs_block_info *bi = yaffs_get_block_info(dev, i);
yaffs_verify_blk(dev, bi, i);
if (bi->block_state < YAFFS_NUMBER_OF_BLOCK_STATES)
state_count[bi->block_state]++;
else
illegal_states++;
}
yaffs_trace(YAFFS_TRACE_VERIFY, "Block summary");
yaffs_trace(YAFFS_TRACE_VERIFY,
"%d blocks have illegal states",
illegal_states);
if (state_count[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Too many allocating blocks");
for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
yaffs_trace(YAFFS_TRACE_VERIFY,
"%s %d blocks",
block_state_name[i], state_count[i]);
if (dev->blocks_in_checkpt != state_count[YAFFS_BLOCK_STATE_CHECKPOINT])
yaffs_trace(YAFFS_TRACE_VERIFY,
"Checkpoint block count wrong dev %d count %d",
dev->blocks_in_checkpt,
state_count[YAFFS_BLOCK_STATE_CHECKPOINT]);
if (dev->n_erased_blocks != state_count[YAFFS_BLOCK_STATE_EMPTY])
yaffs_trace(YAFFS_TRACE_VERIFY,
"Erased block count wrong dev %d count %d",
dev->n_erased_blocks,
state_count[YAFFS_BLOCK_STATE_EMPTY]);
if (state_count[YAFFS_BLOCK_STATE_COLLECTING] > 1)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Too many collecting blocks %d (max is 1)",
state_count[YAFFS_BLOCK_STATE_COLLECTING]);
}
/*
* Verify the object header. oh must be valid, but obj and tags may be NULL in which
* case those tests will not be performed.
*/
void yaffs_verify_oh(struct yaffs_obj *obj, struct yaffs_obj_hdr *oh,
struct yaffs_ext_tags *tags, int parent_check)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
if (!(tags && obj && oh)) {
yaffs_trace(YAFFS_TRACE_VERIFY,
"Verifying object header tags %p obj %p oh %p",
tags, obj, oh);
return;
}
if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
oh->type > YAFFS_OBJECT_TYPE_MAX)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header type is illegal value 0x%x",
tags->obj_id, oh->type);
if (tags->obj_id != obj->obj_id)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header mismatch obj_id %d",
tags->obj_id, obj->obj_id);
/*
* Check that the object's parent ids match if parent_check requested.
*
* Tests do not apply to the root object.
*/
if (parent_check && tags->obj_id > 1 && !obj->parent)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header mismatch parent_id %d obj->parent is NULL",
tags->obj_id, oh->parent_obj_id);
if (parent_check && obj->parent &&
oh->parent_obj_id != obj->parent->obj_id &&
(oh->parent_obj_id != YAFFS_OBJECTID_UNLINKED ||
obj->parent->obj_id != YAFFS_OBJECTID_DELETED))
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header mismatch parent_id %d parent_obj_id %d",
tags->obj_id, oh->parent_obj_id,
obj->parent->obj_id);
if (tags->obj_id > 1 && oh->name[0] == 0) /* Null name */
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header name is NULL",
obj->obj_id);
if (tags->obj_id > 1 && ((u8) (oh->name[0])) == 0xff) /* Trashed name */
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header name is 0xFF",
obj->obj_id);
}
void yaffs_verify_file(struct yaffs_obj *obj)
{
int required_depth;
int actual_depth;
u32 last_chunk;
u32 x;
u32 i;
struct yaffs_dev *dev;
struct yaffs_ext_tags tags;
struct yaffs_tnode *tn;
u32 obj_id;
if (!obj)
return;
if (yaffs_skip_verification(obj->my_dev))
return;
dev = obj->my_dev;
obj_id = obj->obj_id;
/* Check file size is consistent with tnode depth */
last_chunk =
obj->variant.file_variant.file_size / dev->data_bytes_per_chunk + 1;
x = last_chunk >> YAFFS_TNODES_LEVEL0_BITS;
required_depth = 0;
while (x > 0) {
x >>= YAFFS_TNODES_INTERNAL_BITS;
required_depth++;
}
actual_depth = obj->variant.file_variant.top_level;
/* Check that the chunks in the tnode tree are all correct.
* We do this by scanning through the tnode tree and
* checking the tags for every chunk match.
*/
if (yaffs_skip_nand_verification(dev))
return;
for (i = 1; i <= last_chunk; i++) {
tn = yaffs_find_tnode_0(dev, &obj->variant.file_variant, i);
if (tn) {
u32 the_chunk = yaffs_get_group_base(dev, tn, i);
if (the_chunk > 0) {
yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
&tags);
if (tags.obj_id != obj_id || tags.chunk_id != i)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Object %d chunk_id %d NAND mismatch chunk %d tags (%d:%d)",
obj_id, i, the_chunk,
tags.obj_id, tags.chunk_id);
}
}
}
}
void yaffs_verify_link(struct yaffs_obj *obj)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
/* Verify sane equivalent object */
}
void yaffs_verify_symlink(struct yaffs_obj *obj)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
/* Verify symlink string */
}
void yaffs_verify_special(struct yaffs_obj *obj)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
}
void yaffs_verify_obj(struct yaffs_obj *obj)
{
struct yaffs_dev *dev;
u32 chunk_min;
u32 chunk_max;
u32 chunk_id_ok;
u32 chunk_in_range;
u32 chunk_wrongly_deleted;
u32 chunk_valid;
if (!obj)
return;
if (obj->being_created)
return;
dev = obj->my_dev;
if (yaffs_skip_verification(dev))
return;
/* Check sane object header chunk */
chunk_min = dev->internal_start_block * dev->param.chunks_per_block;
chunk_max =
(dev->internal_end_block + 1) * dev->param.chunks_per_block - 1;
chunk_in_range = (((unsigned)(obj->hdr_chunk)) >= chunk_min &&
((unsigned)(obj->hdr_chunk)) <= chunk_max);
chunk_id_ok = chunk_in_range || (obj->hdr_chunk == 0);
chunk_valid = chunk_in_range &&
yaffs_check_chunk_bit(dev,
obj->hdr_chunk / dev->param.chunks_per_block,
obj->hdr_chunk % dev->param.chunks_per_block);
chunk_wrongly_deleted = chunk_in_range && !chunk_valid;
if (!obj->fake && (!chunk_id_ok || chunk_wrongly_deleted))
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d has chunk_id %d %s %s",
obj->obj_id, obj->hdr_chunk,
chunk_id_ok ? "" : ",out of range",
chunk_wrongly_deleted ? ",marked as deleted" : "");
if (chunk_valid && !yaffs_skip_nand_verification(dev)) {
struct yaffs_ext_tags tags;
struct yaffs_obj_hdr *oh;
u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
oh = (struct yaffs_obj_hdr *)buffer;
yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, buffer, &tags);
yaffs_verify_oh(obj, oh, &tags, 1);
yaffs_release_temp_buffer(dev, buffer, __LINE__);
}
/* Verify it has a parent */
if (obj && !obj->fake && (!obj->parent || obj->parent->my_dev != dev)) {
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d has parent pointer %p which does not look like an object",
obj->obj_id, obj->parent);
}
/* Verify parent is a directory */
if (obj->parent
&& obj->parent->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d's parent is not a directory (type %d)",
obj->obj_id, obj->parent->variant_type);
}
switch (obj->variant_type) {
case YAFFS_OBJECT_TYPE_FILE:
yaffs_verify_file(obj);
break;
case YAFFS_OBJECT_TYPE_SYMLINK:
yaffs_verify_symlink(obj);
break;
case YAFFS_OBJECT_TYPE_DIRECTORY:
yaffs_verify_dir(obj);
break;
case YAFFS_OBJECT_TYPE_HARDLINK:
yaffs_verify_link(obj);
break;
case YAFFS_OBJECT_TYPE_SPECIAL:
yaffs_verify_special(obj);
break;
case YAFFS_OBJECT_TYPE_UNKNOWN:
default:
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d has illegaltype %d",
obj->obj_id, obj->variant_type);
break;
}
}
void yaffs_verify_objects(struct yaffs_dev *dev)
{
struct yaffs_obj *obj;
int i;
struct list_head *lh;
if (yaffs_skip_verification(dev))
return;
/* Iterate through the objects in each hash entry */
for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
list_for_each(lh, &dev->obj_bucket[i].list) {
if (lh) {
obj =
list_entry(lh, struct yaffs_obj, hash_link);
yaffs_verify_obj(obj);
}
}
}
}
void yaffs_verify_obj_in_dir(struct yaffs_obj *obj)
{
struct list_head *lh;
struct yaffs_obj *list_obj;
int count = 0;
if (!obj) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "No object to verify");
YBUG();
return;
}
if (yaffs_skip_verification(obj->my_dev))
return;
if (!obj->parent) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "Object does not have parent" );
YBUG();
return;
}
if (obj->parent->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "Parent is not directory");
YBUG();
}
/* Iterate through the objects in each hash entry */
list_for_each(lh, &obj->parent->variant.dir_variant.children) {
if (lh) {
list_obj = list_entry(lh, struct yaffs_obj, siblings);
yaffs_verify_obj(list_obj);
if (obj == list_obj)
count++;
}
}
if (count != 1) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Object in directory %d times",
count);
YBUG();
}
}
void yaffs_verify_dir(struct yaffs_obj *directory)
{
struct list_head *lh;
struct yaffs_obj *list_obj;
if (!directory) {
YBUG();
return;
}
if (yaffs_skip_full_verification(directory->my_dev))
return;
if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Directory has wrong type: %d",
directory->variant_type);
YBUG();
}
/* Iterate through the objects in each hash entry */
list_for_each(lh, &directory->variant.dir_variant.children) {
if (lh) {
list_obj = list_entry(lh, struct yaffs_obj, siblings);
if (list_obj->parent != directory) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Object in directory list has wrong parent %p",
list_obj->parent);
YBUG();
}
yaffs_verify_obj_in_dir(list_obj);
}
}
}
static int yaffs_free_verification_failures;
void yaffs_verify_free_chunks(struct yaffs_dev *dev)
{
int counted;
int difference;
if (yaffs_skip_verification(dev))
return;
counted = yaffs_count_free_chunks(dev);
difference = dev->n_free_chunks - counted;
if (difference) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Freechunks verification failure %d %d %d",
dev->n_free_chunks, counted, difference);
yaffs_free_verification_failures++;
}
}
int yaffs_verify_file_sane(struct yaffs_obj *in)
{
in = in;
return YAFFS_OK;
}
| gpl-2.0 |
Kenepo/roots_kk_lge_msm8974 | net/rxrpc/ar-transport.c | 10742 | 7236 | /* RxRPC point-to-point transport session management
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include "ar-internal.h"
static void rxrpc_transport_reaper(struct work_struct *work);
static LIST_HEAD(rxrpc_transports);
static DEFINE_RWLOCK(rxrpc_transport_lock);
static unsigned long rxrpc_transport_timeout = 3600 * 24;
static DECLARE_DELAYED_WORK(rxrpc_transport_reap, rxrpc_transport_reaper);
/*
* allocate a new transport session manager
*/
static struct rxrpc_transport *rxrpc_alloc_transport(struct rxrpc_local *local,
struct rxrpc_peer *peer,
gfp_t gfp)
{
struct rxrpc_transport *trans;
_enter("");
trans = kzalloc(sizeof(struct rxrpc_transport), gfp);
if (trans) {
trans->local = local;
trans->peer = peer;
INIT_LIST_HEAD(&trans->link);
trans->bundles = RB_ROOT;
trans->client_conns = RB_ROOT;
trans->server_conns = RB_ROOT;
skb_queue_head_init(&trans->error_queue);
spin_lock_init(&trans->client_lock);
rwlock_init(&trans->conn_lock);
atomic_set(&trans->usage, 1);
trans->debug_id = atomic_inc_return(&rxrpc_debug_id);
if (peer->srx.transport.family == AF_INET) {
switch (peer->srx.transport_type) {
case SOCK_DGRAM:
INIT_WORK(&trans->error_handler,
rxrpc_UDP_error_handler);
break;
default:
BUG();
break;
}
} else {
BUG();
}
}
_leave(" = %p", trans);
return trans;
}
/*
* obtain a transport session for the nominated endpoints
*/
struct rxrpc_transport *rxrpc_get_transport(struct rxrpc_local *local,
struct rxrpc_peer *peer,
gfp_t gfp)
{
struct rxrpc_transport *trans, *candidate;
const char *new = "old";
int usage;
_enter("{%pI4+%hu},{%pI4+%hu},",
&local->srx.transport.sin.sin_addr,
ntohs(local->srx.transport.sin.sin_port),
&peer->srx.transport.sin.sin_addr,
ntohs(peer->srx.transport.sin.sin_port));
/* search the transport list first */
read_lock_bh(&rxrpc_transport_lock);
list_for_each_entry(trans, &rxrpc_transports, link) {
if (trans->local == local && trans->peer == peer)
goto found_extant_transport;
}
read_unlock_bh(&rxrpc_transport_lock);
/* not yet present - create a candidate for a new record and then
* redo the search */
candidate = rxrpc_alloc_transport(local, peer, gfp);
if (!candidate) {
_leave(" = -ENOMEM");
return ERR_PTR(-ENOMEM);
}
write_lock_bh(&rxrpc_transport_lock);
list_for_each_entry(trans, &rxrpc_transports, link) {
if (trans->local == local && trans->peer == peer)
goto found_extant_second;
}
/* we can now add the new candidate to the list */
trans = candidate;
candidate = NULL;
usage = atomic_read(&trans->usage);
rxrpc_get_local(trans->local);
atomic_inc(&trans->peer->usage);
list_add_tail(&trans->link, &rxrpc_transports);
write_unlock_bh(&rxrpc_transport_lock);
new = "new";
success:
_net("TRANSPORT %s %d local %d -> peer %d",
new,
trans->debug_id,
trans->local->debug_id,
trans->peer->debug_id);
_leave(" = %p {u=%d}", trans, usage);
return trans;
/* we found the transport in the list immediately */
found_extant_transport:
usage = atomic_inc_return(&trans->usage);
read_unlock_bh(&rxrpc_transport_lock);
goto success;
/* we found the transport on the second time through the list */
found_extant_second:
usage = atomic_inc_return(&trans->usage);
write_unlock_bh(&rxrpc_transport_lock);
kfree(candidate);
goto success;
}
/*
* find the transport connecting two endpoints
*/
struct rxrpc_transport *rxrpc_find_transport(struct rxrpc_local *local,
struct rxrpc_peer *peer)
{
struct rxrpc_transport *trans;
_enter("{%pI4+%hu},{%pI4+%hu},",
&local->srx.transport.sin.sin_addr,
ntohs(local->srx.transport.sin.sin_port),
&peer->srx.transport.sin.sin_addr,
ntohs(peer->srx.transport.sin.sin_port));
/* search the transport list */
read_lock_bh(&rxrpc_transport_lock);
list_for_each_entry(trans, &rxrpc_transports, link) {
if (trans->local == local && trans->peer == peer)
goto found_extant_transport;
}
read_unlock_bh(&rxrpc_transport_lock);
_leave(" = NULL");
return NULL;
found_extant_transport:
atomic_inc(&trans->usage);
read_unlock_bh(&rxrpc_transport_lock);
_leave(" = %p", trans);
return trans;
}
/*
* release a transport session
*/
void rxrpc_put_transport(struct rxrpc_transport *trans)
{
_enter("%p{u=%d}", trans, atomic_read(&trans->usage));
ASSERTCMP(atomic_read(&trans->usage), >, 0);
trans->put_time = get_seconds();
if (unlikely(atomic_dec_and_test(&trans->usage))) {
_debug("zombie");
/* let the reaper determine the timeout to avoid a race with
* overextending the timeout if the reaper is running at the
* same time */
rxrpc_queue_delayed_work(&rxrpc_transport_reap, 0);
}
_leave("");
}
/*
* clean up a transport session
*/
static void rxrpc_cleanup_transport(struct rxrpc_transport *trans)
{
_net("DESTROY TRANS %d", trans->debug_id);
rxrpc_purge_queue(&trans->error_queue);
rxrpc_put_local(trans->local);
rxrpc_put_peer(trans->peer);
kfree(trans);
}
/*
* reap dead transports that have passed their expiry date
*/
static void rxrpc_transport_reaper(struct work_struct *work)
{
struct rxrpc_transport *trans, *_p;
unsigned long now, earliest, reap_time;
LIST_HEAD(graveyard);
_enter("");
now = get_seconds();
earliest = ULONG_MAX;
/* extract all the transports that have been dead too long */
write_lock_bh(&rxrpc_transport_lock);
list_for_each_entry_safe(trans, _p, &rxrpc_transports, link) {
_debug("reap TRANS %d { u=%d t=%ld }",
trans->debug_id, atomic_read(&trans->usage),
(long) now - (long) trans->put_time);
if (likely(atomic_read(&trans->usage) > 0))
continue;
reap_time = trans->put_time + rxrpc_transport_timeout;
if (reap_time <= now)
list_move_tail(&trans->link, &graveyard);
else if (reap_time < earliest)
earliest = reap_time;
}
write_unlock_bh(&rxrpc_transport_lock);
if (earliest != ULONG_MAX) {
_debug("reschedule reaper %ld", (long) earliest - now);
ASSERTCMP(earliest, >, now);
rxrpc_queue_delayed_work(&rxrpc_transport_reap,
(earliest - now) * HZ);
}
/* then destroy all those pulled out */
while (!list_empty(&graveyard)) {
trans = list_entry(graveyard.next, struct rxrpc_transport,
link);
list_del_init(&trans->link);
ASSERTCMP(atomic_read(&trans->usage), ==, 0);
rxrpc_cleanup_transport(trans);
}
_leave("");
}
/*
* preemptively destroy all the transport session records rather than waiting
* for them to time out
*/
void __exit rxrpc_destroy_all_transports(void)
{
_enter("");
rxrpc_transport_timeout = 0;
cancel_delayed_work(&rxrpc_transport_reap);
rxrpc_queue_delayed_work(&rxrpc_transport_reap, 0);
_leave("");
}
| gpl-2.0 |
KatsuraKKKK/linux | drivers/media/pci/zoran/videocodec.c | 12790 | 9286 | /*
* VIDEO MOTION CODECs internal API for video devices
*
* Interface for MJPEG (and maybe later MPEG/WAVELETS) codec's
* bound to a master device.
*
* (c) 2002 Wolfgang Scherr <scherr@net4you.at>
*
* $Id: videocodec.c,v 1.1.2.8 2003/03/29 07:16:04 rbultje Exp $
*
* ------------------------------------------------------------------------
*
* 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 VIDEOCODEC_VERSION "v0.2"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/slab.h>
// kernel config is here (procfs flag)
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
#endif
#include "videocodec.h"
static int debug;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0-4)");
#define dprintk(num, format, args...) \
do { \
if (debug >= num) \
printk(format, ##args); \
} while (0)
struct attached_list {
struct videocodec *codec;
struct attached_list *next;
};
struct codec_list {
const struct videocodec *codec;
int attached;
struct attached_list *list;
struct codec_list *next;
};
static struct codec_list *codeclist_top = NULL;
/* ================================================= */
/* function prototypes of the master/slave interface */
/* ================================================= */
struct videocodec *
videocodec_attach (struct videocodec_master *master)
{
struct codec_list *h = codeclist_top;
struct attached_list *a, *ptr;
struct videocodec *codec;
int res;
if (!master) {
dprintk(1, KERN_ERR "videocodec_attach: no data\n");
return NULL;
}
dprintk(2,
"videocodec_attach: '%s', flags %lx, magic %lx\n",
master->name, master->flags, master->magic);
if (!h) {
dprintk(1,
KERN_ERR
"videocodec_attach: no device available\n");
return NULL;
}
while (h) {
// attach only if the slave has at least the flags
// expected by the master
if ((master->flags & h->codec->flags) == master->flags) {
dprintk(4, "videocodec_attach: try '%s'\n",
h->codec->name);
if (!try_module_get(h->codec->owner))
return NULL;
codec = kmemdup(h->codec, sizeof(struct videocodec),
GFP_KERNEL);
if (!codec) {
dprintk(1,
KERN_ERR
"videocodec_attach: no mem\n");
goto out_module_put;
}
snprintf(codec->name, sizeof(codec->name),
"%s[%d]", codec->name, h->attached);
codec->master_data = master;
res = codec->setup(codec);
if (res == 0) {
dprintk(3, "videocodec_attach '%s'\n",
codec->name);
ptr = kzalloc(sizeof(struct attached_list), GFP_KERNEL);
if (!ptr) {
dprintk(1,
KERN_ERR
"videocodec_attach: no memory\n");
goto out_kfree;
}
ptr->codec = codec;
a = h->list;
if (!a) {
h->list = ptr;
dprintk(4,
"videocodec: first element\n");
} else {
while (a->next)
a = a->next; // find end
a->next = ptr;
dprintk(4,
"videocodec: in after '%s'\n",
h->codec->name);
}
h->attached += 1;
return codec;
} else {
kfree(codec);
}
}
h = h->next;
}
dprintk(1, KERN_ERR "videocodec_attach: no codec found!\n");
return NULL;
out_module_put:
module_put(h->codec->owner);
out_kfree:
kfree(codec);
return NULL;
}
int
videocodec_detach (struct videocodec *codec)
{
struct codec_list *h = codeclist_top;
struct attached_list *a, *prev;
int res;
if (!codec) {
dprintk(1, KERN_ERR "videocodec_detach: no data\n");
return -EINVAL;
}
dprintk(2,
"videocodec_detach: '%s', type: %x, flags %lx, magic %lx\n",
codec->name, codec->type, codec->flags, codec->magic);
if (!h) {
dprintk(1,
KERN_ERR "videocodec_detach: no device left...\n");
return -ENXIO;
}
while (h) {
a = h->list;
prev = NULL;
while (a) {
if (codec == a->codec) {
res = a->codec->unset(a->codec);
if (res >= 0) {
dprintk(3,
"videocodec_detach: '%s'\n",
a->codec->name);
a->codec->master_data = NULL;
} else {
dprintk(1,
KERN_ERR
"videocodec_detach: '%s'\n",
a->codec->name);
a->codec->master_data = NULL;
}
if (prev == NULL) {
h->list = a->next;
dprintk(4,
"videocodec: delete first\n");
} else {
prev->next = a->next;
dprintk(4,
"videocodec: delete middle\n");
}
module_put(a->codec->owner);
kfree(a->codec);
kfree(a);
h->attached -= 1;
return 0;
}
prev = a;
a = a->next;
}
h = h->next;
}
dprintk(1, KERN_ERR "videocodec_detach: given codec not found!\n");
return -EINVAL;
}
int
videocodec_register (const struct videocodec *codec)
{
struct codec_list *ptr, *h = codeclist_top;
if (!codec) {
dprintk(1, KERN_ERR "videocodec_register: no data!\n");
return -EINVAL;
}
dprintk(2,
"videocodec: register '%s', type: %x, flags %lx, magic %lx\n",
codec->name, codec->type, codec->flags, codec->magic);
ptr = kzalloc(sizeof(struct codec_list), GFP_KERNEL);
if (!ptr) {
dprintk(1, KERN_ERR "videocodec_register: no memory\n");
return -ENOMEM;
}
ptr->codec = codec;
if (!h) {
codeclist_top = ptr;
dprintk(4, "videocodec: hooked in as first element\n");
} else {
while (h->next)
h = h->next; // find the end
h->next = ptr;
dprintk(4, "videocodec: hooked in after '%s'\n",
h->codec->name);
}
return 0;
}
int
videocodec_unregister (const struct videocodec *codec)
{
struct codec_list *prev = NULL, *h = codeclist_top;
if (!codec) {
dprintk(1, KERN_ERR "videocodec_unregister: no data!\n");
return -EINVAL;
}
dprintk(2,
"videocodec: unregister '%s', type: %x, flags %lx, magic %lx\n",
codec->name, codec->type, codec->flags, codec->magic);
if (!h) {
dprintk(1,
KERN_ERR
"videocodec_unregister: no device left...\n");
return -ENXIO;
}
while (h) {
if (codec == h->codec) {
if (h->attached) {
dprintk(1,
KERN_ERR
"videocodec: '%s' is used\n",
h->codec->name);
return -EBUSY;
}
dprintk(3, "videocodec: unregister '%s' is ok.\n",
h->codec->name);
if (prev == NULL) {
codeclist_top = h->next;
dprintk(4,
"videocodec: delete first element\n");
} else {
prev->next = h->next;
dprintk(4,
"videocodec: delete middle element\n");
}
kfree(h);
return 0;
}
prev = h;
h = h->next;
}
dprintk(1,
KERN_ERR
"videocodec_unregister: given codec not found!\n");
return -EINVAL;
}
#ifdef CONFIG_PROC_FS
static int proc_videocodecs_show(struct seq_file *m, void *v)
{
struct codec_list *h = codeclist_top;
struct attached_list *a;
seq_printf(m, "<S>lave or attached <M>aster name type flags magic ");
seq_printf(m, "(connected as)\n");
h = codeclist_top;
while (h) {
seq_printf(m, "S %32s %04x %08lx %08lx (TEMPLATE)\n",
h->codec->name, h->codec->type,
h->codec->flags, h->codec->magic);
a = h->list;
while (a) {
seq_printf(m, "M %32s %04x %08lx %08lx (%s)\n",
a->codec->master_data->name,
a->codec->master_data->type,
a->codec->master_data->flags,
a->codec->master_data->magic,
a->codec->name);
a = a->next;
}
h = h->next;
}
return 0;
}
static int proc_videocodecs_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_videocodecs_show, NULL);
}
static const struct file_operations videocodecs_proc_fops = {
.owner = THIS_MODULE,
.open = proc_videocodecs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
/* ===================== */
/* hook in driver module */
/* ===================== */
static int __init
videocodec_init (void)
{
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *videocodec_proc_entry;
#endif
printk(KERN_INFO "Linux video codec intermediate layer: %s\n",
VIDEOCODEC_VERSION);
#ifdef CONFIG_PROC_FS
videocodec_proc_entry = proc_create("videocodecs", 0, NULL, &videocodecs_proc_fops);
if (!videocodec_proc_entry) {
dprintk(1, KERN_ERR "videocodec: can't init procfs.\n");
}
#endif
return 0;
}
static void __exit
videocodec_exit (void)
{
#ifdef CONFIG_PROC_FS
remove_proc_entry("videocodecs", NULL);
#endif
}
EXPORT_SYMBOL(videocodec_attach);
EXPORT_SYMBOL(videocodec_detach);
EXPORT_SYMBOL(videocodec_register);
EXPORT_SYMBOL(videocodec_unregister);
module_init(videocodec_init);
module_exit(videocodec_exit);
MODULE_AUTHOR("Wolfgang Scherr <scherr@net4you.at>");
MODULE_DESCRIPTION("Intermediate API module for video codecs "
VIDEOCODEC_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
xplodwild/android_kernel_asus_tf300t | arch/sparc/kernel/pci_sun4v.c | 759 | 24287 | /* pci_sun4v.c: SUN4V specific PCI controller support.
*
* Copyright (C) 2006, 2007, 2008 David S. Miller (davem@davemloft.net)
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/percpu.h>
#include <linux/irq.h>
#include <linux/msi.h>
#include <linux/log2.h>
#include <linux/of_device.h>
#include <asm/iommu.h>
#include <asm/irq.h>
#include <asm/hypervisor.h>
#include <asm/prom.h>
#include "pci_impl.h"
#include "iommu_common.h"
#include "pci_sun4v.h"
#define DRIVER_NAME "pci_sun4v"
#define PFX DRIVER_NAME ": "
static unsigned long vpci_major = 1;
static unsigned long vpci_minor = 1;
#define PGLIST_NENTS (PAGE_SIZE / sizeof(u64))
struct iommu_batch {
struct device *dev; /* Device mapping is for. */
unsigned long prot; /* IOMMU page protections */
unsigned long entry; /* Index into IOTSB. */
u64 *pglist; /* List of physical pages */
unsigned long npages; /* Number of pages in list. */
};
static DEFINE_PER_CPU(struct iommu_batch, iommu_batch);
static int iommu_batch_initialized;
/* Interrupts must be disabled. */
static inline void iommu_batch_start(struct device *dev, unsigned long prot, unsigned long entry)
{
struct iommu_batch *p = &__get_cpu_var(iommu_batch);
p->dev = dev;
p->prot = prot;
p->entry = entry;
p->npages = 0;
}
/* Interrupts must be disabled. */
static long iommu_batch_flush(struct iommu_batch *p)
{
struct pci_pbm_info *pbm = p->dev->archdata.host_controller;
unsigned long devhandle = pbm->devhandle;
unsigned long prot = p->prot;
unsigned long entry = p->entry;
u64 *pglist = p->pglist;
unsigned long npages = p->npages;
while (npages != 0) {
long num;
num = pci_sun4v_iommu_map(devhandle, HV_PCI_TSBID(0, entry),
npages, prot, __pa(pglist));
if (unlikely(num < 0)) {
if (printk_ratelimit())
printk("iommu_batch_flush: IOMMU map of "
"[%08lx:%08llx:%lx:%lx:%lx] failed with "
"status %ld\n",
devhandle, HV_PCI_TSBID(0, entry),
npages, prot, __pa(pglist), num);
return -1;
}
entry += num;
npages -= num;
pglist += num;
}
p->entry = entry;
p->npages = 0;
return 0;
}
static inline void iommu_batch_new_entry(unsigned long entry)
{
struct iommu_batch *p = &__get_cpu_var(iommu_batch);
if (p->entry + p->npages == entry)
return;
if (p->entry != ~0UL)
iommu_batch_flush(p);
p->entry = entry;
}
/* Interrupts must be disabled. */
static inline long iommu_batch_add(u64 phys_page)
{
struct iommu_batch *p = &__get_cpu_var(iommu_batch);
BUG_ON(p->npages >= PGLIST_NENTS);
p->pglist[p->npages++] = phys_page;
if (p->npages == PGLIST_NENTS)
return iommu_batch_flush(p);
return 0;
}
/* Interrupts must be disabled. */
static inline long iommu_batch_end(void)
{
struct iommu_batch *p = &__get_cpu_var(iommu_batch);
BUG_ON(p->npages >= PGLIST_NENTS);
return iommu_batch_flush(p);
}
static void *dma_4v_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_addrp, gfp_t gfp)
{
unsigned long flags, order, first_page, npages, n;
struct iommu *iommu;
struct page *page;
void *ret;
long entry;
int nid;
size = IO_PAGE_ALIGN(size);
order = get_order(size);
if (unlikely(order >= MAX_ORDER))
return NULL;
npages = size >> IO_PAGE_SHIFT;
nid = dev->archdata.numa_node;
page = alloc_pages_node(nid, gfp, order);
if (unlikely(!page))
return NULL;
first_page = (unsigned long) page_address(page);
memset((char *)first_page, 0, PAGE_SIZE << order);
iommu = dev->archdata.iommu;
spin_lock_irqsave(&iommu->lock, flags);
entry = iommu_range_alloc(dev, iommu, npages, NULL);
spin_unlock_irqrestore(&iommu->lock, flags);
if (unlikely(entry == DMA_ERROR_CODE))
goto range_alloc_fail;
*dma_addrp = (iommu->page_table_map_base +
(entry << IO_PAGE_SHIFT));
ret = (void *) first_page;
first_page = __pa(first_page);
local_irq_save(flags);
iommu_batch_start(dev,
(HV_PCI_MAP_ATTR_READ |
HV_PCI_MAP_ATTR_WRITE),
entry);
for (n = 0; n < npages; n++) {
long err = iommu_batch_add(first_page + (n * PAGE_SIZE));
if (unlikely(err < 0L))
goto iommu_map_fail;
}
if (unlikely(iommu_batch_end() < 0L))
goto iommu_map_fail;
local_irq_restore(flags);
return ret;
iommu_map_fail:
/* Interrupts are disabled. */
spin_lock(&iommu->lock);
iommu_range_free(iommu, *dma_addrp, npages);
spin_unlock_irqrestore(&iommu->lock, flags);
range_alloc_fail:
free_pages(first_page, order);
return NULL;
}
static void dma_4v_free_coherent(struct device *dev, size_t size, void *cpu,
dma_addr_t dvma)
{
struct pci_pbm_info *pbm;
struct iommu *iommu;
unsigned long flags, order, npages, entry;
u32 devhandle;
npages = IO_PAGE_ALIGN(size) >> IO_PAGE_SHIFT;
iommu = dev->archdata.iommu;
pbm = dev->archdata.host_controller;
devhandle = pbm->devhandle;
entry = ((dvma - iommu->page_table_map_base) >> IO_PAGE_SHIFT);
spin_lock_irqsave(&iommu->lock, flags);
iommu_range_free(iommu, dvma, npages);
do {
unsigned long num;
num = pci_sun4v_iommu_demap(devhandle, HV_PCI_TSBID(0, entry),
npages);
entry += num;
npages -= num;
} while (npages != 0);
spin_unlock_irqrestore(&iommu->lock, flags);
order = get_order(size);
if (order < 10)
free_pages((unsigned long)cpu, order);
}
static dma_addr_t dma_4v_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t sz,
enum dma_data_direction direction,
struct dma_attrs *attrs)
{
struct iommu *iommu;
unsigned long flags, npages, oaddr;
unsigned long i, base_paddr;
u32 bus_addr, ret;
unsigned long prot;
long entry;
iommu = dev->archdata.iommu;
if (unlikely(direction == DMA_NONE))
goto bad;
oaddr = (unsigned long)(page_address(page) + offset);
npages = IO_PAGE_ALIGN(oaddr + sz) - (oaddr & IO_PAGE_MASK);
npages >>= IO_PAGE_SHIFT;
spin_lock_irqsave(&iommu->lock, flags);
entry = iommu_range_alloc(dev, iommu, npages, NULL);
spin_unlock_irqrestore(&iommu->lock, flags);
if (unlikely(entry == DMA_ERROR_CODE))
goto bad;
bus_addr = (iommu->page_table_map_base +
(entry << IO_PAGE_SHIFT));
ret = bus_addr | (oaddr & ~IO_PAGE_MASK);
base_paddr = __pa(oaddr & IO_PAGE_MASK);
prot = HV_PCI_MAP_ATTR_READ;
if (direction != DMA_TO_DEVICE)
prot |= HV_PCI_MAP_ATTR_WRITE;
local_irq_save(flags);
iommu_batch_start(dev, prot, entry);
for (i = 0; i < npages; i++, base_paddr += IO_PAGE_SIZE) {
long err = iommu_batch_add(base_paddr);
if (unlikely(err < 0L))
goto iommu_map_fail;
}
if (unlikely(iommu_batch_end() < 0L))
goto iommu_map_fail;
local_irq_restore(flags);
return ret;
bad:
if (printk_ratelimit())
WARN_ON(1);
return DMA_ERROR_CODE;
iommu_map_fail:
/* Interrupts are disabled. */
spin_lock(&iommu->lock);
iommu_range_free(iommu, bus_addr, npages);
spin_unlock_irqrestore(&iommu->lock, flags);
return DMA_ERROR_CODE;
}
static void dma_4v_unmap_page(struct device *dev, dma_addr_t bus_addr,
size_t sz, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
struct pci_pbm_info *pbm;
struct iommu *iommu;
unsigned long flags, npages;
long entry;
u32 devhandle;
if (unlikely(direction == DMA_NONE)) {
if (printk_ratelimit())
WARN_ON(1);
return;
}
iommu = dev->archdata.iommu;
pbm = dev->archdata.host_controller;
devhandle = pbm->devhandle;
npages = IO_PAGE_ALIGN(bus_addr + sz) - (bus_addr & IO_PAGE_MASK);
npages >>= IO_PAGE_SHIFT;
bus_addr &= IO_PAGE_MASK;
spin_lock_irqsave(&iommu->lock, flags);
iommu_range_free(iommu, bus_addr, npages);
entry = (bus_addr - iommu->page_table_map_base) >> IO_PAGE_SHIFT;
do {
unsigned long num;
num = pci_sun4v_iommu_demap(devhandle, HV_PCI_TSBID(0, entry),
npages);
entry += num;
npages -= num;
} while (npages != 0);
spin_unlock_irqrestore(&iommu->lock, flags);
}
static int dma_4v_map_sg(struct device *dev, struct scatterlist *sglist,
int nelems, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
struct scatterlist *s, *outs, *segstart;
unsigned long flags, handle, prot;
dma_addr_t dma_next = 0, dma_addr;
unsigned int max_seg_size;
unsigned long seg_boundary_size;
int outcount, incount, i;
struct iommu *iommu;
unsigned long base_shift;
long err;
BUG_ON(direction == DMA_NONE);
iommu = dev->archdata.iommu;
if (nelems == 0 || !iommu)
return 0;
prot = HV_PCI_MAP_ATTR_READ;
if (direction != DMA_TO_DEVICE)
prot |= HV_PCI_MAP_ATTR_WRITE;
outs = s = segstart = &sglist[0];
outcount = 1;
incount = nelems;
handle = 0;
/* Init first segment length for backout at failure */
outs->dma_length = 0;
spin_lock_irqsave(&iommu->lock, flags);
iommu_batch_start(dev, prot, ~0UL);
max_seg_size = dma_get_max_seg_size(dev);
seg_boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
IO_PAGE_SIZE) >> IO_PAGE_SHIFT;
base_shift = iommu->page_table_map_base >> IO_PAGE_SHIFT;
for_each_sg(sglist, s, nelems, i) {
unsigned long paddr, npages, entry, out_entry = 0, slen;
slen = s->length;
/* Sanity check */
if (slen == 0) {
dma_next = 0;
continue;
}
/* Allocate iommu entries for that segment */
paddr = (unsigned long) SG_ENT_PHYS_ADDRESS(s);
npages = iommu_num_pages(paddr, slen, IO_PAGE_SIZE);
entry = iommu_range_alloc(dev, iommu, npages, &handle);
/* Handle failure */
if (unlikely(entry == DMA_ERROR_CODE)) {
if (printk_ratelimit())
printk(KERN_INFO "iommu_alloc failed, iommu %p paddr %lx"
" npages %lx\n", iommu, paddr, npages);
goto iommu_map_failed;
}
iommu_batch_new_entry(entry);
/* Convert entry to a dma_addr_t */
dma_addr = iommu->page_table_map_base +
(entry << IO_PAGE_SHIFT);
dma_addr |= (s->offset & ~IO_PAGE_MASK);
/* Insert into HW table */
paddr &= IO_PAGE_MASK;
while (npages--) {
err = iommu_batch_add(paddr);
if (unlikely(err < 0L))
goto iommu_map_failed;
paddr += IO_PAGE_SIZE;
}
/* If we are in an open segment, try merging */
if (segstart != s) {
/* We cannot merge if:
* - allocated dma_addr isn't contiguous to previous allocation
*/
if ((dma_addr != dma_next) ||
(outs->dma_length + s->length > max_seg_size) ||
(is_span_boundary(out_entry, base_shift,
seg_boundary_size, outs, s))) {
/* Can't merge: create a new segment */
segstart = s;
outcount++;
outs = sg_next(outs);
} else {
outs->dma_length += s->length;
}
}
if (segstart == s) {
/* This is a new segment, fill entries */
outs->dma_address = dma_addr;
outs->dma_length = slen;
out_entry = entry;
}
/* Calculate next page pointer for contiguous check */
dma_next = dma_addr + slen;
}
err = iommu_batch_end();
if (unlikely(err < 0L))
goto iommu_map_failed;
spin_unlock_irqrestore(&iommu->lock, flags);
if (outcount < incount) {
outs = sg_next(outs);
outs->dma_address = DMA_ERROR_CODE;
outs->dma_length = 0;
}
return outcount;
iommu_map_failed:
for_each_sg(sglist, s, nelems, i) {
if (s->dma_length != 0) {
unsigned long vaddr, npages;
vaddr = s->dma_address & IO_PAGE_MASK;
npages = iommu_num_pages(s->dma_address, s->dma_length,
IO_PAGE_SIZE);
iommu_range_free(iommu, vaddr, npages);
/* XXX demap? XXX */
s->dma_address = DMA_ERROR_CODE;
s->dma_length = 0;
}
if (s == outs)
break;
}
spin_unlock_irqrestore(&iommu->lock, flags);
return 0;
}
static void dma_4v_unmap_sg(struct device *dev, struct scatterlist *sglist,
int nelems, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
struct pci_pbm_info *pbm;
struct scatterlist *sg;
struct iommu *iommu;
unsigned long flags;
u32 devhandle;
BUG_ON(direction == DMA_NONE);
iommu = dev->archdata.iommu;
pbm = dev->archdata.host_controller;
devhandle = pbm->devhandle;
spin_lock_irqsave(&iommu->lock, flags);
sg = sglist;
while (nelems--) {
dma_addr_t dma_handle = sg->dma_address;
unsigned int len = sg->dma_length;
unsigned long npages, entry;
if (!len)
break;
npages = iommu_num_pages(dma_handle, len, IO_PAGE_SIZE);
iommu_range_free(iommu, dma_handle, npages);
entry = ((dma_handle - iommu->page_table_map_base) >> IO_PAGE_SHIFT);
while (npages) {
unsigned long num;
num = pci_sun4v_iommu_demap(devhandle, HV_PCI_TSBID(0, entry),
npages);
entry += num;
npages -= num;
}
sg = sg_next(sg);
}
spin_unlock_irqrestore(&iommu->lock, flags);
}
static struct dma_map_ops sun4v_dma_ops = {
.alloc_coherent = dma_4v_alloc_coherent,
.free_coherent = dma_4v_free_coherent,
.map_page = dma_4v_map_page,
.unmap_page = dma_4v_unmap_page,
.map_sg = dma_4v_map_sg,
.unmap_sg = dma_4v_unmap_sg,
};
static void __devinit pci_sun4v_scan_bus(struct pci_pbm_info *pbm,
struct device *parent)
{
struct property *prop;
struct device_node *dp;
dp = pbm->op->dev.of_node;
prop = of_find_property(dp, "66mhz-capable", NULL);
pbm->is_66mhz_capable = (prop != NULL);
pbm->pci_bus = pci_scan_one_pbm(pbm, parent);
/* XXX register error interrupt handlers XXX */
}
static unsigned long __devinit probe_existing_entries(struct pci_pbm_info *pbm,
struct iommu *iommu)
{
struct iommu_arena *arena = &iommu->arena;
unsigned long i, cnt = 0;
u32 devhandle;
devhandle = pbm->devhandle;
for (i = 0; i < arena->limit; i++) {
unsigned long ret, io_attrs, ra;
ret = pci_sun4v_iommu_getmap(devhandle,
HV_PCI_TSBID(0, i),
&io_attrs, &ra);
if (ret == HV_EOK) {
if (page_in_phys_avail(ra)) {
pci_sun4v_iommu_demap(devhandle,
HV_PCI_TSBID(0, i), 1);
} else {
cnt++;
__set_bit(i, arena->map);
}
}
}
return cnt;
}
static int __devinit pci_sun4v_iommu_init(struct pci_pbm_info *pbm)
{
static const u32 vdma_default[] = { 0x80000000, 0x80000000 };
struct iommu *iommu = pbm->iommu;
unsigned long num_tsb_entries, sz;
u32 dma_mask, dma_offset;
const u32 *vdma;
vdma = of_get_property(pbm->op->dev.of_node, "virtual-dma", NULL);
if (!vdma)
vdma = vdma_default;
if ((vdma[0] | vdma[1]) & ~IO_PAGE_MASK) {
printk(KERN_ERR PFX "Strange virtual-dma[%08x:%08x].\n",
vdma[0], vdma[1]);
return -EINVAL;
};
dma_mask = (roundup_pow_of_two(vdma[1]) - 1UL);
num_tsb_entries = vdma[1] / IO_PAGE_SIZE;
dma_offset = vdma[0];
/* Setup initial software IOMMU state. */
spin_lock_init(&iommu->lock);
iommu->ctx_lowest_free = 1;
iommu->page_table_map_base = dma_offset;
iommu->dma_addr_mask = dma_mask;
/* Allocate and initialize the free area map. */
sz = (num_tsb_entries + 7) / 8;
sz = (sz + 7UL) & ~7UL;
iommu->arena.map = kzalloc(sz, GFP_KERNEL);
if (!iommu->arena.map) {
printk(KERN_ERR PFX "Error, kmalloc(arena.map) failed.\n");
return -ENOMEM;
}
iommu->arena.limit = num_tsb_entries;
sz = probe_existing_entries(pbm, iommu);
if (sz)
printk("%s: Imported %lu TSB entries from OBP\n",
pbm->name, sz);
return 0;
}
#ifdef CONFIG_PCI_MSI
struct pci_sun4v_msiq_entry {
u64 version_type;
#define MSIQ_VERSION_MASK 0xffffffff00000000UL
#define MSIQ_VERSION_SHIFT 32
#define MSIQ_TYPE_MASK 0x00000000000000ffUL
#define MSIQ_TYPE_SHIFT 0
#define MSIQ_TYPE_NONE 0x00
#define MSIQ_TYPE_MSG 0x01
#define MSIQ_TYPE_MSI32 0x02
#define MSIQ_TYPE_MSI64 0x03
#define MSIQ_TYPE_INTX 0x08
#define MSIQ_TYPE_NONE2 0xff
u64 intx_sysino;
u64 reserved1;
u64 stick;
u64 req_id; /* bus/device/func */
#define MSIQ_REQID_BUS_MASK 0xff00UL
#define MSIQ_REQID_BUS_SHIFT 8
#define MSIQ_REQID_DEVICE_MASK 0x00f8UL
#define MSIQ_REQID_DEVICE_SHIFT 3
#define MSIQ_REQID_FUNC_MASK 0x0007UL
#define MSIQ_REQID_FUNC_SHIFT 0
u64 msi_address;
/* The format of this value is message type dependent.
* For MSI bits 15:0 are the data from the MSI packet.
* For MSI-X bits 31:0 are the data from the MSI packet.
* For MSG, the message code and message routing code where:
* bits 39:32 is the bus/device/fn of the msg target-id
* bits 18:16 is the message routing code
* bits 7:0 is the message code
* For INTx the low order 2-bits are:
* 00 - INTA
* 01 - INTB
* 10 - INTC
* 11 - INTD
*/
u64 msi_data;
u64 reserved2;
};
static int pci_sun4v_get_head(struct pci_pbm_info *pbm, unsigned long msiqid,
unsigned long *head)
{
unsigned long err, limit;
err = pci_sun4v_msiq_gethead(pbm->devhandle, msiqid, head);
if (unlikely(err))
return -ENXIO;
limit = pbm->msiq_ent_count * sizeof(struct pci_sun4v_msiq_entry);
if (unlikely(*head >= limit))
return -EFBIG;
return 0;
}
static int pci_sun4v_dequeue_msi(struct pci_pbm_info *pbm,
unsigned long msiqid, unsigned long *head,
unsigned long *msi)
{
struct pci_sun4v_msiq_entry *ep;
unsigned long err, type;
/* Note: void pointer arithmetic, 'head' is a byte offset */
ep = (pbm->msi_queues + ((msiqid - pbm->msiq_first) *
(pbm->msiq_ent_count *
sizeof(struct pci_sun4v_msiq_entry))) +
*head);
if ((ep->version_type & MSIQ_TYPE_MASK) == 0)
return 0;
type = (ep->version_type & MSIQ_TYPE_MASK) >> MSIQ_TYPE_SHIFT;
if (unlikely(type != MSIQ_TYPE_MSI32 &&
type != MSIQ_TYPE_MSI64))
return -EINVAL;
*msi = ep->msi_data;
err = pci_sun4v_msi_setstate(pbm->devhandle,
ep->msi_data /* msi_num */,
HV_MSISTATE_IDLE);
if (unlikely(err))
return -ENXIO;
/* Clear the entry. */
ep->version_type &= ~MSIQ_TYPE_MASK;
(*head) += sizeof(struct pci_sun4v_msiq_entry);
if (*head >=
(pbm->msiq_ent_count * sizeof(struct pci_sun4v_msiq_entry)))
*head = 0;
return 1;
}
static int pci_sun4v_set_head(struct pci_pbm_info *pbm, unsigned long msiqid,
unsigned long head)
{
unsigned long err;
err = pci_sun4v_msiq_sethead(pbm->devhandle, msiqid, head);
if (unlikely(err))
return -EINVAL;
return 0;
}
static int pci_sun4v_msi_setup(struct pci_pbm_info *pbm, unsigned long msiqid,
unsigned long msi, int is_msi64)
{
if (pci_sun4v_msi_setmsiq(pbm->devhandle, msi, msiqid,
(is_msi64 ?
HV_MSITYPE_MSI64 : HV_MSITYPE_MSI32)))
return -ENXIO;
if (pci_sun4v_msi_setstate(pbm->devhandle, msi, HV_MSISTATE_IDLE))
return -ENXIO;
if (pci_sun4v_msi_setvalid(pbm->devhandle, msi, HV_MSIVALID_VALID))
return -ENXIO;
return 0;
}
static int pci_sun4v_msi_teardown(struct pci_pbm_info *pbm, unsigned long msi)
{
unsigned long err, msiqid;
err = pci_sun4v_msi_getmsiq(pbm->devhandle, msi, &msiqid);
if (err)
return -ENXIO;
pci_sun4v_msi_setvalid(pbm->devhandle, msi, HV_MSIVALID_INVALID);
return 0;
}
static int pci_sun4v_msiq_alloc(struct pci_pbm_info *pbm)
{
unsigned long q_size, alloc_size, pages, order;
int i;
q_size = pbm->msiq_ent_count * sizeof(struct pci_sun4v_msiq_entry);
alloc_size = (pbm->msiq_num * q_size);
order = get_order(alloc_size);
pages = __get_free_pages(GFP_KERNEL | __GFP_COMP, order);
if (pages == 0UL) {
printk(KERN_ERR "MSI: Cannot allocate MSI queues (o=%lu).\n",
order);
return -ENOMEM;
}
memset((char *)pages, 0, PAGE_SIZE << order);
pbm->msi_queues = (void *) pages;
for (i = 0; i < pbm->msiq_num; i++) {
unsigned long err, base = __pa(pages + (i * q_size));
unsigned long ret1, ret2;
err = pci_sun4v_msiq_conf(pbm->devhandle,
pbm->msiq_first + i,
base, pbm->msiq_ent_count);
if (err) {
printk(KERN_ERR "MSI: msiq register fails (err=%lu)\n",
err);
goto h_error;
}
err = pci_sun4v_msiq_info(pbm->devhandle,
pbm->msiq_first + i,
&ret1, &ret2);
if (err) {
printk(KERN_ERR "MSI: Cannot read msiq (err=%lu)\n",
err);
goto h_error;
}
if (ret1 != base || ret2 != pbm->msiq_ent_count) {
printk(KERN_ERR "MSI: Bogus qconf "
"expected[%lx:%x] got[%lx:%lx]\n",
base, pbm->msiq_ent_count,
ret1, ret2);
goto h_error;
}
}
return 0;
h_error:
free_pages(pages, order);
return -EINVAL;
}
static void pci_sun4v_msiq_free(struct pci_pbm_info *pbm)
{
unsigned long q_size, alloc_size, pages, order;
int i;
for (i = 0; i < pbm->msiq_num; i++) {
unsigned long msiqid = pbm->msiq_first + i;
(void) pci_sun4v_msiq_conf(pbm->devhandle, msiqid, 0UL, 0);
}
q_size = pbm->msiq_ent_count * sizeof(struct pci_sun4v_msiq_entry);
alloc_size = (pbm->msiq_num * q_size);
order = get_order(alloc_size);
pages = (unsigned long) pbm->msi_queues;
free_pages(pages, order);
pbm->msi_queues = NULL;
}
static int pci_sun4v_msiq_build_irq(struct pci_pbm_info *pbm,
unsigned long msiqid,
unsigned long devino)
{
unsigned int irq = sun4v_build_irq(pbm->devhandle, devino);
if (!irq)
return -ENOMEM;
if (pci_sun4v_msiq_setstate(pbm->devhandle, msiqid, HV_MSIQSTATE_IDLE))
return -EINVAL;
if (pci_sun4v_msiq_setvalid(pbm->devhandle, msiqid, HV_MSIQ_VALID))
return -EINVAL;
return irq;
}
static const struct sparc64_msiq_ops pci_sun4v_msiq_ops = {
.get_head = pci_sun4v_get_head,
.dequeue_msi = pci_sun4v_dequeue_msi,
.set_head = pci_sun4v_set_head,
.msi_setup = pci_sun4v_msi_setup,
.msi_teardown = pci_sun4v_msi_teardown,
.msiq_alloc = pci_sun4v_msiq_alloc,
.msiq_free = pci_sun4v_msiq_free,
.msiq_build_irq = pci_sun4v_msiq_build_irq,
};
static void pci_sun4v_msi_init(struct pci_pbm_info *pbm)
{
sparc64_pbm_msi_init(pbm, &pci_sun4v_msiq_ops);
}
#else /* CONFIG_PCI_MSI */
static void pci_sun4v_msi_init(struct pci_pbm_info *pbm)
{
}
#endif /* !(CONFIG_PCI_MSI) */
static int __devinit pci_sun4v_pbm_init(struct pci_pbm_info *pbm,
struct platform_device *op, u32 devhandle)
{
struct device_node *dp = op->dev.of_node;
int err;
pbm->numa_node = of_node_to_nid(dp);
pbm->pci_ops = &sun4v_pci_ops;
pbm->config_space_reg_bits = 12;
pbm->index = pci_num_pbms++;
pbm->op = op;
pbm->devhandle = devhandle;
pbm->name = dp->full_name;
printk("%s: SUN4V PCI Bus Module\n", pbm->name);
printk("%s: On NUMA node %d\n", pbm->name, pbm->numa_node);
pci_determine_mem_io_space(pbm);
pci_get_pbm_props(pbm);
err = pci_sun4v_iommu_init(pbm);
if (err)
return err;
pci_sun4v_msi_init(pbm);
pci_sun4v_scan_bus(pbm, &op->dev);
pbm->next = pci_pbm_root;
pci_pbm_root = pbm;
return 0;
}
static int __devinit pci_sun4v_probe(struct platform_device *op)
{
const struct linux_prom64_registers *regs;
static int hvapi_negotiated = 0;
struct pci_pbm_info *pbm;
struct device_node *dp;
struct iommu *iommu;
u32 devhandle;
int i, err;
dp = op->dev.of_node;
if (!hvapi_negotiated++) {
err = sun4v_hvapi_register(HV_GRP_PCI,
vpci_major,
&vpci_minor);
if (err) {
printk(KERN_ERR PFX "Could not register hvapi, "
"err=%d\n", err);
return err;
}
printk(KERN_INFO PFX "Registered hvapi major[%lu] minor[%lu]\n",
vpci_major, vpci_minor);
dma_ops = &sun4v_dma_ops;
}
regs = of_get_property(dp, "reg", NULL);
err = -ENODEV;
if (!regs) {
printk(KERN_ERR PFX "Could not find config registers\n");
goto out_err;
}
devhandle = (regs->phys_addr >> 32UL) & 0x0fffffff;
err = -ENOMEM;
if (!iommu_batch_initialized) {
for_each_possible_cpu(i) {
unsigned long page = get_zeroed_page(GFP_KERNEL);
if (!page)
goto out_err;
per_cpu(iommu_batch, i).pglist = (u64 *) page;
}
iommu_batch_initialized = 1;
}
pbm = kzalloc(sizeof(*pbm), GFP_KERNEL);
if (!pbm) {
printk(KERN_ERR PFX "Could not allocate pci_pbm_info\n");
goto out_err;
}
iommu = kzalloc(sizeof(struct iommu), GFP_KERNEL);
if (!iommu) {
printk(KERN_ERR PFX "Could not allocate pbm iommu\n");
goto out_free_controller;
}
pbm->iommu = iommu;
err = pci_sun4v_pbm_init(pbm, op, devhandle);
if (err)
goto out_free_iommu;
dev_set_drvdata(&op->dev, pbm);
return 0;
out_free_iommu:
kfree(pbm->iommu);
out_free_controller:
kfree(pbm);
out_err:
return err;
}
static const struct of_device_id pci_sun4v_match[] = {
{
.name = "pci",
.compatible = "SUNW,sun4v-pci",
},
{},
};
static struct platform_driver pci_sun4v_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.of_match_table = pci_sun4v_match,
},
.probe = pci_sun4v_probe,
};
static int __init pci_sun4v_init(void)
{
return platform_driver_register(&pci_sun4v_driver);
}
subsys_initcall(pci_sun4v_init);
| gpl-2.0 |
satgass/android_kernel_hisense_msm8916 | drivers/firmware/efi/efi.c | 759 | 9220 | /*
* efi.c - EFI subsystem
*
* Copyright (C) 2001,2003,2004 Dell <Matt_Domsch@dell.com>
* Copyright (C) 2004 Intel Corporation <matthew.e.tolentino@intel.com>
* Copyright (C) 2013 Tom Gundersen <teg@jklm.no>
*
* This code registers /sys/firmware/efi{,/efivars} when EFI is supported,
* allowing the efivarfs to be mounted or the efivars module to be loaded.
* The existance of /sys/firmware/efi may also be used by userspace to
* determine that the system supports EFI.
*
* This file is released under the GPLv2.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kobject.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/efi.h>
#include <linux/of.h>
#include <linux/of_fdt.h>
#include <linux/io.h>
struct efi __read_mostly efi = {
.mps = EFI_INVALID_TABLE_ADDR,
.acpi = EFI_INVALID_TABLE_ADDR,
.acpi20 = EFI_INVALID_TABLE_ADDR,
.smbios = EFI_INVALID_TABLE_ADDR,
.sal_systab = EFI_INVALID_TABLE_ADDR,
.boot_info = EFI_INVALID_TABLE_ADDR,
.hcdp = EFI_INVALID_TABLE_ADDR,
.uga = EFI_INVALID_TABLE_ADDR,
.uv_systab = EFI_INVALID_TABLE_ADDR,
};
EXPORT_SYMBOL(efi);
static struct kobject *efi_kobj;
static struct kobject *efivars_kobj;
/*
* Let's not leave out systab information that snuck into
* the efivars driver
*/
static ssize_t systab_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
char *str = buf;
if (!kobj || !buf)
return -EINVAL;
if (efi.mps != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "MPS=0x%lx\n", efi.mps);
if (efi.acpi20 != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "ACPI20=0x%lx\n", efi.acpi20);
if (efi.acpi != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "ACPI=0x%lx\n", efi.acpi);
if (efi.smbios != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "SMBIOS=0x%lx\n", efi.smbios);
if (efi.hcdp != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "HCDP=0x%lx\n", efi.hcdp);
if (efi.boot_info != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "BOOTINFO=0x%lx\n", efi.boot_info);
if (efi.uga != EFI_INVALID_TABLE_ADDR)
str += sprintf(str, "UGA=0x%lx\n", efi.uga);
return str - buf;
}
static struct kobj_attribute efi_attr_systab =
__ATTR(systab, 0400, systab_show, NULL);
static struct attribute *efi_subsys_attrs[] = {
&efi_attr_systab.attr,
NULL, /* maybe more in the future? */
};
static struct attribute_group efi_subsys_attr_group = {
.attrs = efi_subsys_attrs,
};
static struct efivars generic_efivars;
static struct efivar_operations generic_ops;
static int generic_ops_register(void)
{
generic_ops.get_variable = efi.get_variable;
generic_ops.set_variable = efi.set_variable;
generic_ops.get_next_variable = efi.get_next_variable;
generic_ops.query_variable_store = efi_query_variable_store;
return efivars_register(&generic_efivars, &generic_ops, efi_kobj);
}
static void generic_ops_unregister(void)
{
efivars_unregister(&generic_efivars);
}
/*
* We register the efi subsystem with the firmware subsystem and the
* efivars subsystem with the efi subsystem, if the system was booted with
* EFI.
*/
static int __init efisubsys_init(void)
{
int error;
if (!efi_enabled(EFI_BOOT))
return 0;
/* We register the efi directory at /sys/firmware/efi */
efi_kobj = kobject_create_and_add("efi", firmware_kobj);
if (!efi_kobj) {
pr_err("efi: Firmware registration failed.\n");
return -ENOMEM;
}
error = generic_ops_register();
if (error)
goto err_put;
error = sysfs_create_group(efi_kobj, &efi_subsys_attr_group);
if (error) {
pr_err("efi: Sysfs attribute export failed with error %d.\n",
error);
goto err_unregister;
}
/* and the standard mountpoint for efivarfs */
efivars_kobj = kobject_create_and_add("efivars", efi_kobj);
if (!efivars_kobj) {
pr_err("efivars: Subsystem registration failed.\n");
error = -ENOMEM;
goto err_remove_group;
}
return 0;
err_remove_group:
sysfs_remove_group(efi_kobj, &efi_subsys_attr_group);
err_unregister:
generic_ops_unregister();
err_put:
kobject_put(efi_kobj);
return error;
}
subsys_initcall(efisubsys_init);
/*
* We can't ioremap data in EFI boot services RAM, because we've already mapped
* it as RAM. So, look it up in the existing EFI memory map instead. Only
* callable after efi_enter_virtual_mode and before efi_free_boot_services.
*/
void __iomem *efi_lookup_mapped_addr(u64 phys_addr)
{
struct efi_memory_map *map;
void *p;
map = efi.memmap;
if (!map)
return NULL;
if (WARN_ON(!map->map))
return NULL;
for (p = map->map; p < map->map_end; p += map->desc_size) {
efi_memory_desc_t *md = p;
u64 size = md->num_pages << EFI_PAGE_SHIFT;
u64 end = md->phys_addr + size;
if (!(md->attribute & EFI_MEMORY_RUNTIME) &&
md->type != EFI_BOOT_SERVICES_CODE &&
md->type != EFI_BOOT_SERVICES_DATA)
continue;
if (!md->virt_addr)
continue;
if (phys_addr >= md->phys_addr && phys_addr < end) {
phys_addr += md->virt_addr - md->phys_addr;
return (__force void __iomem *)(unsigned long)phys_addr;
}
}
return NULL;
}
static __initdata efi_config_table_type_t common_tables[] = {
{ACPI_20_TABLE_GUID, "ACPI 2.0", &efi.acpi20},
{ACPI_TABLE_GUID, "ACPI", &efi.acpi},
{HCDP_TABLE_GUID, "HCDP", &efi.hcdp},
{MPS_TABLE_GUID, "MPS", &efi.mps},
{SAL_SYSTEM_TABLE_GUID, "SALsystab", &efi.sal_systab},
{SMBIOS_TABLE_GUID, "SMBIOS", &efi.smbios},
{UGA_IO_PROTOCOL_GUID, "UGA", &efi.uga},
{NULL_GUID, NULL, 0},
};
static __init int match_config_table(efi_guid_t *guid,
unsigned long table,
efi_config_table_type_t *table_types)
{
u8 str[EFI_VARIABLE_GUID_LEN + 1];
int i;
if (table_types) {
efi_guid_unparse(guid, str);
for (i = 0; efi_guidcmp(table_types[i].guid, NULL_GUID); i++) {
efi_guid_unparse(&table_types[i].guid, str);
if (!efi_guidcmp(*guid, table_types[i].guid)) {
*(table_types[i].ptr) = table;
pr_cont(" %s=0x%lx ",
table_types[i].name, table);
return 1;
}
}
}
return 0;
}
int __init efi_config_init(efi_config_table_type_t *arch_tables)
{
void *config_tables, *tablep;
int i, sz;
if (efi_enabled(EFI_64BIT))
sz = sizeof(efi_config_table_64_t);
else
sz = sizeof(efi_config_table_32_t);
/*
* Let's see what config tables the firmware passed to us.
*/
config_tables = early_memremap(efi.systab->tables,
efi.systab->nr_tables * sz);
if (config_tables == NULL) {
pr_err("Could not map Configuration table!\n");
return -ENOMEM;
}
tablep = config_tables;
pr_info("");
for (i = 0; i < efi.systab->nr_tables; i++) {
efi_guid_t guid;
unsigned long table;
if (efi_enabled(EFI_64BIT)) {
u64 table64;
guid = ((efi_config_table_64_t *)tablep)->guid;
table64 = ((efi_config_table_64_t *)tablep)->table;
table = table64;
#ifndef CONFIG_64BIT
if (table64 >> 32) {
pr_cont("\n");
pr_err("Table located above 4GB, disabling EFI.\n");
early_iounmap(config_tables,
efi.systab->nr_tables * sz);
return -EINVAL;
}
#endif
} else {
guid = ((efi_config_table_32_t *)tablep)->guid;
table = ((efi_config_table_32_t *)tablep)->table;
}
if (!match_config_table(&guid, table, common_tables))
match_config_table(&guid, table, arch_tables);
tablep += sz;
}
pr_cont("\n");
early_iounmap(config_tables, efi.systab->nr_tables * sz);
return 0;
}
#ifdef CONFIG_EFI_PARAMS_FROM_FDT
#define UEFI_PARAM(name, prop, field) \
{ \
{ name }, \
{ prop }, \
offsetof(struct efi_fdt_params, field), \
FIELD_SIZEOF(struct efi_fdt_params, field) \
}
static __initdata struct {
const char name[32];
const char propname[32];
int offset;
int size;
} dt_params[] = {
UEFI_PARAM("System Table", "linux,uefi-system-table", system_table),
UEFI_PARAM("MemMap Address", "linux,uefi-mmap-start", mmap),
UEFI_PARAM("MemMap Size", "linux,uefi-mmap-size", mmap_size),
UEFI_PARAM("MemMap Desc. Size", "linux,uefi-mmap-desc-size", desc_size),
UEFI_PARAM("MemMap Desc. Version", "linux,uefi-mmap-desc-ver", desc_ver)
};
struct param_info {
int verbose;
void *params;
};
static int __init fdt_find_uefi_params(unsigned long node, const char *uname,
int depth, void *data)
{
struct param_info *info = data;
void *prop, *dest;
unsigned long len;
u64 val;
int i;
if (depth != 1 ||
(strcmp(uname, "chosen") != 0 && strcmp(uname, "chosen@0") != 0))
return 0;
pr_info("Getting parameters from FDT:\n");
for (i = 0; i < ARRAY_SIZE(dt_params); i++) {
prop = of_get_flat_dt_prop(node, dt_params[i].propname, &len);
if (!prop) {
pr_err("Can't find %s in device tree!\n",
dt_params[i].name);
return 0;
}
dest = info->params + dt_params[i].offset;
val = of_read_number(prop, len / sizeof(u32));
if (dt_params[i].size == sizeof(u32))
*(u32 *)dest = val;
else
*(u64 *)dest = val;
if (info->verbose)
pr_info(" %s: 0x%0*llx\n", dt_params[i].name,
dt_params[i].size * 2, val);
}
return 1;
}
int __init efi_get_fdt_params(struct efi_fdt_params *params, int verbose)
{
struct param_info info;
info.verbose = verbose;
info.params = params;
return of_scan_flat_dt(fdt_find_uefi_params, &info);
}
#endif /* CONFIG_EFI_PARAMS_FROM_FDT */
| gpl-2.0 |
NooNameR/qsd8x50-bravo- | arch/arm/mach-msm/msm_dcvs_scm.c | 759 | 3719 | /* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/memory_alloc.h>
#include <mach/memory.h>
#include <mach/scm.h>
#include <mach/msm_dcvs_scm.h>
#define DCVS_CMD_CREATE_GROUP 1
#define DCVS_CMD_REGISTER_CORE 2
#define DCVS_CMD_SET_ALGO_PARAM 3
#define DCVS_CMD_EVENT 4
#define DCVS_CMD_INIT 5
struct scm_register_core {
uint32_t core_id;
uint32_t group_id;
phys_addr_t core_param_phy;
phys_addr_t freq_phy;
};
struct scm_algo {
uint32_t core_id;
phys_addr_t algo_phy;
};
struct scm_init {
uint32_t phy;
uint32_t size;
};
int msm_dcvs_scm_init(size_t size)
{
int ret = 0;
struct scm_init init;
uint32_t p = 0;
/* Allocate word aligned non-cacheable memory */
p = allocate_contiguous_ebi_nomap(size, 4);
if (!p)
return -ENOMEM;
init.phy = p;
init.size = size;
ret = scm_call(SCM_SVC_DCVS, DCVS_CMD_INIT,
&init, sizeof(init), NULL, 0);
/* Not freed if the initialization succeeds */
if (ret)
free_contiguous_memory_by_paddr(p);
return ret;
}
EXPORT_SYMBOL(msm_dcvs_scm_init);
int msm_dcvs_scm_create_group(uint32_t id)
{
int ret = 0;
ret = scm_call(SCM_SVC_DCVS, DCVS_CMD_CREATE_GROUP,
&id, sizeof(uint32_t), NULL, 0);
return ret;
}
EXPORT_SYMBOL(msm_dcvs_scm_create_group);
int msm_dcvs_scm_register_core(uint32_t core_id, uint32_t group_id,
struct msm_dcvs_core_param *param,
struct msm_dcvs_freq_entry *freq)
{
int ret = 0;
struct scm_register_core reg_data;
struct msm_dcvs_core_param *p = NULL;
struct msm_dcvs_freq_entry *f = NULL;
p = kzalloc(PAGE_ALIGN(sizeof(struct msm_dcvs_core_param)), GFP_KERNEL);
if (!p)
return -ENOMEM;
f = kzalloc(PAGE_ALIGN(sizeof(struct msm_dcvs_freq_entry) *
param->num_freq), GFP_KERNEL);
if (!f) {
kfree(p);
return -ENOMEM;
}
memcpy(p, param, sizeof(struct msm_dcvs_core_param));
memcpy(f, freq, sizeof(struct msm_dcvs_freq_entry) * param->num_freq);
reg_data.core_id = core_id;
reg_data.group_id = group_id;
reg_data.core_param_phy = virt_to_phys(p);
reg_data.freq_phy = virt_to_phys(f);
ret = scm_call(SCM_SVC_DCVS, DCVS_CMD_REGISTER_CORE,
®_data, sizeof(reg_data), NULL, 0);
kfree(f);
kfree(p);
return ret;
}
EXPORT_SYMBOL(msm_dcvs_scm_register_core);
int msm_dcvs_scm_set_algo_params(uint32_t core_id,
struct msm_dcvs_algo_param *param)
{
int ret = 0;
struct scm_algo algo;
struct msm_dcvs_algo_param *p = NULL;
p = kzalloc(PAGE_ALIGN(sizeof(struct msm_dcvs_algo_param)), GFP_KERNEL);
if (!p)
return -ENOMEM;
memcpy(p, param, sizeof(struct msm_dcvs_algo_param));
algo.core_id = core_id;
algo.algo_phy = virt_to_phys(p);
ret = scm_call(SCM_SVC_DCVS, DCVS_CMD_SET_ALGO_PARAM,
&algo, sizeof(algo), NULL, 0);
kfree(p);
return ret;
}
EXPORT_SYMBOL(msm_dcvs_scm_set_algo_params);
int msm_dcvs_scm_event(uint32_t core_id,
enum msm_dcvs_scm_event event_id,
uint32_t param0, uint32_t param1,
uint32_t *ret0, uint32_t *ret1)
{
int ret = -EINVAL;
if (!ret0 || !ret1)
return ret;
ret = scm_call_atomic4_3(SCM_SVC_DCVS, DCVS_CMD_EVENT,
core_id, event_id, param0, param1, ret0, ret1);
return ret;
}
EXPORT_SYMBOL(msm_dcvs_scm_event);
| gpl-2.0 |
ioz9/GT-N7000-2.35.y-samsung-update1 | fs/jffs2/background.c | 759 | 4401 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2001-2007 Red Hat, Inc.
*
* Created by David Woodhouse <dwmw2@infradead.org>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*/
#include <linux/kernel.h>
#include <linux/jffs2.h>
#include <linux/mtd/mtd.h>
#include <linux/completion.h>
#include <linux/sched.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include "nodelist.h"
static int jffs2_garbage_collect_thread(void *);
void jffs2_garbage_collect_trigger(struct jffs2_sb_info *c)
{
assert_spin_locked(&c->erase_completion_lock);
if (c->gc_task && jffs2_thread_should_wake(c))
send_sig(SIGHUP, c->gc_task, 1);
}
/* This must only ever be called when no GC thread is currently running */
int jffs2_start_garbage_collect_thread(struct jffs2_sb_info *c)
{
struct task_struct *tsk;
int ret = 0;
BUG_ON(c->gc_task);
init_completion(&c->gc_thread_start);
init_completion(&c->gc_thread_exit);
tsk = kthread_run(jffs2_garbage_collect_thread, c, "jffs2_gcd_mtd%d", c->mtd->index);
if (IS_ERR(tsk)) {
printk(KERN_WARNING "fork failed for JFFS2 garbage collect thread: %ld\n", -PTR_ERR(tsk));
complete(&c->gc_thread_exit);
ret = PTR_ERR(tsk);
} else {
/* Wait for it... */
D1(printk(KERN_DEBUG "JFFS2: Garbage collect thread is pid %d\n", tsk->pid));
wait_for_completion(&c->gc_thread_start);
ret = tsk->pid;
}
return ret;
}
void jffs2_stop_garbage_collect_thread(struct jffs2_sb_info *c)
{
int wait = 0;
spin_lock(&c->erase_completion_lock);
if (c->gc_task) {
D1(printk(KERN_DEBUG "jffs2: Killing GC task %d\n", c->gc_task->pid));
send_sig(SIGKILL, c->gc_task, 1);
wait = 1;
}
spin_unlock(&c->erase_completion_lock);
if (wait)
wait_for_completion(&c->gc_thread_exit);
}
static int jffs2_garbage_collect_thread(void *_c)
{
struct jffs2_sb_info *c = _c;
allow_signal(SIGKILL);
allow_signal(SIGSTOP);
allow_signal(SIGCONT);
c->gc_task = current;
complete(&c->gc_thread_start);
set_user_nice(current, 10);
set_freezable();
for (;;) {
allow_signal(SIGHUP);
again:
spin_lock(&c->erase_completion_lock);
if (!jffs2_thread_should_wake(c)) {
set_current_state (TASK_INTERRUPTIBLE);
spin_unlock(&c->erase_completion_lock);
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread sleeping...\n"));
schedule();
} else
spin_unlock(&c->erase_completion_lock);
/* Problem - immediately after bootup, the GCD spends a lot
* of time in places like jffs2_kill_fragtree(); so much so
* that userspace processes (like gdm and X) are starved
* despite plenty of cond_resched()s and renicing. Yield()
* doesn't help, either (presumably because userspace and GCD
* are generally competing for a higher latency resource -
* disk).
* This forces the GCD to slow the hell down. Pulling an
* inode in with read_inode() is much preferable to having
* the GC thread get there first. */
schedule_timeout_interruptible(msecs_to_jiffies(50));
if (kthread_should_stop()) {
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread(): kthread_stop() called.\n"));
goto die;
}
/* Put_super will send a SIGKILL and then wait on the sem.
*/
while (signal_pending(current) || freezing(current)) {
siginfo_t info;
unsigned long signr;
if (try_to_freeze())
goto again;
signr = dequeue_signal_lock(current, ¤t->blocked, &info);
switch(signr) {
case SIGSTOP:
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread(): SIGSTOP received.\n"));
set_current_state(TASK_STOPPED);
schedule();
break;
case SIGKILL:
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread(): SIGKILL received.\n"));
goto die;
case SIGHUP:
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread(): SIGHUP received.\n"));
break;
default:
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread(): signal %ld received\n", signr));
}
}
/* We don't want SIGHUP to interrupt us. STOP and KILL are OK though. */
disallow_signal(SIGHUP);
D1(printk(KERN_DEBUG "jffs2_garbage_collect_thread(): pass\n"));
if (jffs2_garbage_collect_pass(c) == -ENOSPC) {
printk(KERN_NOTICE "No space for garbage collection. Aborting GC thread\n");
goto die;
}
}
die:
spin_lock(&c->erase_completion_lock);
c->gc_task = NULL;
spin_unlock(&c->erase_completion_lock);
complete_and_exit(&c->gc_thread_exit, 0);
}
| gpl-2.0 |
kornyone/htc-kernel-doubleshot_old | drivers/net/usb/kaweth.c | 759 | 38497 | /****************************************************************
*
* kaweth.c - driver for KL5KUSB101 based USB->Ethernet
*
* (c) 2000 Interlan Communications
* (c) 2000 Stephane Alnet
* (C) 2001 Brad Hards
* (C) 2002 Oliver Neukum
*
* Original author: The Zapman <zapman@interlan.net>
* Inspired by, and much credit goes to Michael Rothwell
* <rothwell@interlan.net> for the test equipment, help, and patience
* Based off of (and with thanks to) Petko Manolov's pegaus.c driver.
* Also many thanks to Joel Silverman and Ed Surprenant at Kawasaki
* for providing the firmware and driver resources.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
****************************************************************/
/* TODO:
* Develop test procedures for USB net interfaces
* Run test procedures
* Fix bugs from previous two steps
* Snoop other OSs for any tricks we're not doing
* Reduce arbitrary timeouts
* Smart multicast support
* Temporary MAC change support
* Tunable SOFs parameter - ioctl()?
* Ethernet stats collection
* Code formatting improvements
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/usb.h>
#include <linux/types.h>
#include <linux/ethtool.h>
#include <linux/dma-mapping.h>
#include <linux/wait.h>
#include <linux/firmware.h>
#include <asm/uaccess.h>
#include <asm/byteorder.h>
#undef DEBUG
#define KAWETH_MTU 1514
#define KAWETH_BUF_SIZE 1664
#define KAWETH_TX_TIMEOUT (5 * HZ)
#define KAWETH_SCRATCH_SIZE 32
#define KAWETH_FIRMWARE_BUF_SIZE 4096
#define KAWETH_CONTROL_TIMEOUT (30000)
#define KAWETH_STATUS_BROKEN 0x0000001
#define KAWETH_STATUS_CLOSING 0x0000002
#define KAWETH_STATUS_SUSPENDING 0x0000004
#define KAWETH_STATUS_BLOCKED (KAWETH_STATUS_CLOSING | KAWETH_STATUS_SUSPENDING)
#define KAWETH_PACKET_FILTER_PROMISCUOUS 0x01
#define KAWETH_PACKET_FILTER_ALL_MULTICAST 0x02
#define KAWETH_PACKET_FILTER_DIRECTED 0x04
#define KAWETH_PACKET_FILTER_BROADCAST 0x08
#define KAWETH_PACKET_FILTER_MULTICAST 0x10
/* Table 7 */
#define KAWETH_COMMAND_GET_ETHERNET_DESC 0x00
#define KAWETH_COMMAND_MULTICAST_FILTERS 0x01
#define KAWETH_COMMAND_SET_PACKET_FILTER 0x02
#define KAWETH_COMMAND_STATISTICS 0x03
#define KAWETH_COMMAND_SET_TEMP_MAC 0x06
#define KAWETH_COMMAND_GET_TEMP_MAC 0x07
#define KAWETH_COMMAND_SET_URB_SIZE 0x08
#define KAWETH_COMMAND_SET_SOFS_WAIT 0x09
#define KAWETH_COMMAND_SCAN 0xFF
#define KAWETH_SOFS_TO_WAIT 0x05
#define INTBUFFERSIZE 4
#define STATE_OFFSET 0
#define STATE_MASK 0x40
#define STATE_SHIFT 5
#define IS_BLOCKED(s) (s & KAWETH_STATUS_BLOCKED)
MODULE_AUTHOR("Michael Zappe <zapman@interlan.net>, Stephane Alnet <stephane@u-picardie.fr>, Brad Hards <bhards@bigpond.net.au> and Oliver Neukum <oliver@neukum.org>");
MODULE_DESCRIPTION("KL5USB101 USB Ethernet driver");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("kaweth/new_code.bin");
MODULE_FIRMWARE("kaweth/new_code_fix.bin");
MODULE_FIRMWARE("kaweth/trigger_code.bin");
MODULE_FIRMWARE("kaweth/trigger_code_fix.bin");
static const char driver_name[] = "kaweth";
static int kaweth_probe(
struct usb_interface *intf,
const struct usb_device_id *id /* from id_table */
);
static void kaweth_disconnect(struct usb_interface *intf);
static int kaweth_internal_control_msg(struct usb_device *usb_dev,
unsigned int pipe,
struct usb_ctrlrequest *cmd, void *data,
int len, int timeout);
static int kaweth_suspend(struct usb_interface *intf, pm_message_t message);
static int kaweth_resume(struct usb_interface *intf);
/****************************************************************
* usb_device_id
****************************************************************/
static struct usb_device_id usb_klsi_table[] = {
{ USB_DEVICE(0x03e8, 0x0008) }, /* AOX Endpoints USB Ethernet */
{ USB_DEVICE(0x04bb, 0x0901) }, /* I-O DATA USB-ET/T */
{ USB_DEVICE(0x0506, 0x03e8) }, /* 3Com 3C19250 */
{ USB_DEVICE(0x0506, 0x11f8) }, /* 3Com 3C460 */
{ USB_DEVICE(0x0557, 0x2002) }, /* ATEN USB Ethernet */
{ USB_DEVICE(0x0557, 0x4000) }, /* D-Link DSB-650C */
{ USB_DEVICE(0x0565, 0x0002) }, /* Peracom Enet */
{ USB_DEVICE(0x0565, 0x0003) }, /* Optus@Home UEP1045A */
{ USB_DEVICE(0x0565, 0x0005) }, /* Peracom Enet2 */
{ USB_DEVICE(0x05e9, 0x0008) }, /* KLSI KL5KUSB101B */
{ USB_DEVICE(0x05e9, 0x0009) }, /* KLSI KL5KUSB101B (Board change) */
{ USB_DEVICE(0x066b, 0x2202) }, /* Linksys USB10T */
{ USB_DEVICE(0x06e1, 0x0008) }, /* ADS USB-10BT */
{ USB_DEVICE(0x06e1, 0x0009) }, /* ADS USB-10BT */
{ USB_DEVICE(0x0707, 0x0100) }, /* SMC 2202USB */
{ USB_DEVICE(0x07aa, 0x0001) }, /* Correga K.K. */
{ USB_DEVICE(0x07b8, 0x4000) }, /* D-Link DU-E10 */
{ USB_DEVICE(0x07c9, 0xb010) }, /* Allied Telesyn AT-USB10 USB Ethernet Adapter */
{ USB_DEVICE(0x0846, 0x1001) }, /* NetGear EA-101 */
{ USB_DEVICE(0x0846, 0x1002) }, /* NetGear EA-101 */
{ USB_DEVICE(0x085a, 0x0008) }, /* PortGear Ethernet Adapter */
{ USB_DEVICE(0x085a, 0x0009) }, /* PortGear Ethernet Adapter */
{ USB_DEVICE(0x087d, 0x5704) }, /* Jaton USB Ethernet Device Adapter */
{ USB_DEVICE(0x0951, 0x0008) }, /* Kingston Technology USB Ethernet Adapter */
{ USB_DEVICE(0x095a, 0x3003) }, /* Portsmith Express Ethernet Adapter */
{ USB_DEVICE(0x10bd, 0x1427) }, /* ASANTE USB To Ethernet Adapter */
{ USB_DEVICE(0x1342, 0x0204) }, /* Mobility USB-Ethernet Adapter */
{ USB_DEVICE(0x13d2, 0x0400) }, /* Shark Pocket Adapter */
{ USB_DEVICE(0x1485, 0x0001) }, /* Silicom U2E */
{ USB_DEVICE(0x1485, 0x0002) }, /* Psion Dacom Gold Port Ethernet */
{ USB_DEVICE(0x1645, 0x0005) }, /* Entrega E45 */
{ USB_DEVICE(0x1645, 0x0008) }, /* Entrega USB Ethernet Adapter */
{ USB_DEVICE(0x1645, 0x8005) }, /* PortGear Ethernet Adapter */
{ USB_DEVICE(0x1668, 0x0323) }, /* Actiontec USB Ethernet */
{ USB_DEVICE(0x2001, 0x4000) }, /* D-link DSB-650C */
{} /* Null terminator */
};
MODULE_DEVICE_TABLE (usb, usb_klsi_table);
/****************************************************************
* kaweth_driver
****************************************************************/
static struct usb_driver kaweth_driver = {
.name = driver_name,
.probe = kaweth_probe,
.disconnect = kaweth_disconnect,
.suspend = kaweth_suspend,
.resume = kaweth_resume,
.id_table = usb_klsi_table,
.supports_autosuspend = 1,
};
typedef __u8 eth_addr_t[6];
/****************************************************************
* usb_eth_dev
****************************************************************/
struct usb_eth_dev {
char *name;
__u16 vendor;
__u16 device;
void *pdata;
};
/****************************************************************
* kaweth_ethernet_configuration
* Refer Table 8
****************************************************************/
struct kaweth_ethernet_configuration
{
__u8 size;
__u8 reserved1;
__u8 reserved2;
eth_addr_t hw_addr;
__u32 statistics_mask;
__le16 segment_size;
__u16 max_multicast_filters;
__u8 reserved3;
} __attribute__ ((packed));
/****************************************************************
* kaweth_device
****************************************************************/
struct kaweth_device
{
spinlock_t device_lock;
__u32 status;
int end;
int suspend_lowmem_rx;
int suspend_lowmem_ctrl;
int linkstate;
int opened;
struct delayed_work lowmem_work;
struct usb_device *dev;
struct usb_interface *intf;
struct net_device *net;
wait_queue_head_t term_wait;
struct urb *rx_urb;
struct urb *tx_urb;
struct urb *irq_urb;
dma_addr_t intbufferhandle;
__u8 *intbuffer;
dma_addr_t rxbufferhandle;
__u8 *rx_buf;
struct sk_buff *tx_skb;
__u8 *firmware_buf;
__u8 scratch[KAWETH_SCRATCH_SIZE];
__u16 packet_filter_bitmap;
struct kaweth_ethernet_configuration configuration;
struct net_device_stats stats;
};
/****************************************************************
* kaweth_control
****************************************************************/
static int kaweth_control(struct kaweth_device *kaweth,
unsigned int pipe,
__u8 request,
__u8 requesttype,
__u16 value,
__u16 index,
void *data,
__u16 size,
int timeout)
{
struct usb_ctrlrequest *dr;
int retval;
dbg("kaweth_control()");
if(in_interrupt()) {
dbg("in_interrupt()");
return -EBUSY;
}
dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_ATOMIC);
if (!dr) {
dbg("kmalloc() failed");
return -ENOMEM;
}
dr->bRequestType = requesttype;
dr->bRequest = request;
dr->wValue = cpu_to_le16(value);
dr->wIndex = cpu_to_le16(index);
dr->wLength = cpu_to_le16(size);
retval = kaweth_internal_control_msg(kaweth->dev,
pipe,
dr,
data,
size,
timeout);
kfree(dr);
return retval;
}
/****************************************************************
* kaweth_read_configuration
****************************************************************/
static int kaweth_read_configuration(struct kaweth_device *kaweth)
{
int retval;
dbg("Reading kaweth configuration");
retval = kaweth_control(kaweth,
usb_rcvctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_GET_ETHERNET_DESC,
USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
0,
0,
(void *)&kaweth->configuration,
sizeof(kaweth->configuration),
KAWETH_CONTROL_TIMEOUT);
return retval;
}
/****************************************************************
* kaweth_set_urb_size
****************************************************************/
static int kaweth_set_urb_size(struct kaweth_device *kaweth, __u16 urb_size)
{
int retval;
dbg("Setting URB size to %d", (unsigned)urb_size);
retval = kaweth_control(kaweth,
usb_sndctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_SET_URB_SIZE,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
urb_size,
0,
(void *)&kaweth->scratch,
0,
KAWETH_CONTROL_TIMEOUT);
return retval;
}
/****************************************************************
* kaweth_set_sofs_wait
****************************************************************/
static int kaweth_set_sofs_wait(struct kaweth_device *kaweth, __u16 sofs_wait)
{
int retval;
dbg("Set SOFS wait to %d", (unsigned)sofs_wait);
retval = kaweth_control(kaweth,
usb_sndctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_SET_SOFS_WAIT,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
sofs_wait,
0,
(void *)&kaweth->scratch,
0,
KAWETH_CONTROL_TIMEOUT);
return retval;
}
/****************************************************************
* kaweth_set_receive_filter
****************************************************************/
static int kaweth_set_receive_filter(struct kaweth_device *kaweth,
__u16 receive_filter)
{
int retval;
dbg("Set receive filter to %d", (unsigned)receive_filter);
retval = kaweth_control(kaweth,
usb_sndctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_SET_PACKET_FILTER,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
receive_filter,
0,
(void *)&kaweth->scratch,
0,
KAWETH_CONTROL_TIMEOUT);
return retval;
}
/****************************************************************
* kaweth_download_firmware
****************************************************************/
static int kaweth_download_firmware(struct kaweth_device *kaweth,
const char *fwname,
__u8 interrupt,
__u8 type)
{
const struct firmware *fw;
int data_len;
int ret;
ret = request_firmware(&fw, fwname, &kaweth->dev->dev);
if (ret) {
err("Firmware request failed\n");
return ret;
}
if (fw->size > KAWETH_FIRMWARE_BUF_SIZE) {
err("Firmware too big: %zu", fw->size);
return -ENOSPC;
}
data_len = fw->size;
memcpy(kaweth->firmware_buf, fw->data, fw->size);
release_firmware(fw);
kaweth->firmware_buf[2] = (data_len & 0xFF) - 7;
kaweth->firmware_buf[3] = data_len >> 8;
kaweth->firmware_buf[4] = type;
kaweth->firmware_buf[5] = interrupt;
dbg("High: %i, Low:%i", kaweth->firmware_buf[3],
kaweth->firmware_buf[2]);
dbg("Downloading firmware at %p to kaweth device at %p",
fw->data, kaweth);
dbg("Firmware length: %d", data_len);
return kaweth_control(kaweth,
usb_sndctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_SCAN,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
0,
0,
(void *)kaweth->firmware_buf,
data_len,
KAWETH_CONTROL_TIMEOUT);
}
/****************************************************************
* kaweth_trigger_firmware
****************************************************************/
static int kaweth_trigger_firmware(struct kaweth_device *kaweth,
__u8 interrupt)
{
kaweth->firmware_buf[0] = 0xB6;
kaweth->firmware_buf[1] = 0xC3;
kaweth->firmware_buf[2] = 0x01;
kaweth->firmware_buf[3] = 0x00;
kaweth->firmware_buf[4] = 0x06;
kaweth->firmware_buf[5] = interrupt;
kaweth->firmware_buf[6] = 0x00;
kaweth->firmware_buf[7] = 0x00;
dbg("Triggering firmware");
return kaweth_control(kaweth,
usb_sndctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_SCAN,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
0,
0,
(void *)kaweth->firmware_buf,
8,
KAWETH_CONTROL_TIMEOUT);
}
/****************************************************************
* kaweth_reset
****************************************************************/
static int kaweth_reset(struct kaweth_device *kaweth)
{
int result;
dbg("kaweth_reset(%p)", kaweth);
result = usb_reset_configuration(kaweth->dev);
mdelay(10);
dbg("kaweth_reset() returns %d.",result);
return result;
}
static void kaweth_usb_receive(struct urb *);
static int kaweth_resubmit_rx_urb(struct kaweth_device *, gfp_t);
/****************************************************************
int_callback
*****************************************************************/
static void kaweth_resubmit_int_urb(struct kaweth_device *kaweth, gfp_t mf)
{
int status;
status = usb_submit_urb (kaweth->irq_urb, mf);
if (unlikely(status == -ENOMEM)) {
kaweth->suspend_lowmem_ctrl = 1;
schedule_delayed_work(&kaweth->lowmem_work, HZ/4);
} else {
kaweth->suspend_lowmem_ctrl = 0;
}
if (status)
err ("can't resubmit intr, %s-%s, status %d",
kaweth->dev->bus->bus_name,
kaweth->dev->devpath, status);
}
static void int_callback(struct urb *u)
{
struct kaweth_device *kaweth = u->context;
int act_state;
int status = u->status;
switch (status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
goto resubmit;
}
/* we check the link state to report changes */
if (kaweth->linkstate != (act_state = ( kaweth->intbuffer[STATE_OFFSET] | STATE_MASK) >> STATE_SHIFT)) {
if (act_state)
netif_carrier_on(kaweth->net);
else
netif_carrier_off(kaweth->net);
kaweth->linkstate = act_state;
}
resubmit:
kaweth_resubmit_int_urb(kaweth, GFP_ATOMIC);
}
static void kaweth_resubmit_tl(struct work_struct *work)
{
struct kaweth_device *kaweth =
container_of(work, struct kaweth_device, lowmem_work.work);
if (IS_BLOCKED(kaweth->status))
return;
if (kaweth->suspend_lowmem_rx)
kaweth_resubmit_rx_urb(kaweth, GFP_NOIO);
if (kaweth->suspend_lowmem_ctrl)
kaweth_resubmit_int_urb(kaweth, GFP_NOIO);
}
/****************************************************************
* kaweth_resubmit_rx_urb
****************************************************************/
static int kaweth_resubmit_rx_urb(struct kaweth_device *kaweth,
gfp_t mem_flags)
{
int result;
usb_fill_bulk_urb(kaweth->rx_urb,
kaweth->dev,
usb_rcvbulkpipe(kaweth->dev, 1),
kaweth->rx_buf,
KAWETH_BUF_SIZE,
kaweth_usb_receive,
kaweth);
kaweth->rx_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
kaweth->rx_urb->transfer_dma = kaweth->rxbufferhandle;
if((result = usb_submit_urb(kaweth->rx_urb, mem_flags))) {
if (result == -ENOMEM) {
kaweth->suspend_lowmem_rx = 1;
schedule_delayed_work(&kaweth->lowmem_work, HZ/4);
}
err("resubmitting rx_urb %d failed", result);
} else {
kaweth->suspend_lowmem_rx = 0;
}
return result;
}
static void kaweth_async_set_rx_mode(struct kaweth_device *kaweth);
/****************************************************************
* kaweth_usb_receive
****************************************************************/
static void kaweth_usb_receive(struct urb *urb)
{
struct kaweth_device *kaweth = urb->context;
struct net_device *net = kaweth->net;
int status = urb->status;
int count = urb->actual_length;
int count2 = urb->transfer_buffer_length;
__u16 pkt_len = le16_to_cpup((__le16 *)kaweth->rx_buf);
struct sk_buff *skb;
if (unlikely(status == -EPIPE)) {
kaweth->stats.rx_errors++;
kaweth->end = 1;
wake_up(&kaweth->term_wait);
dbg("Status was -EPIPE.");
return;
}
if (unlikely(status == -ECONNRESET || status == -ESHUTDOWN)) {
/* we are killed - set a flag and wake the disconnect handler */
kaweth->end = 1;
wake_up(&kaweth->term_wait);
dbg("Status was -ECONNRESET or -ESHUTDOWN.");
return;
}
if (unlikely(status == -EPROTO || status == -ETIME ||
status == -EILSEQ)) {
kaweth->stats.rx_errors++;
dbg("Status was -EPROTO, -ETIME, or -EILSEQ.");
return;
}
if (unlikely(status == -EOVERFLOW)) {
kaweth->stats.rx_errors++;
dbg("Status was -EOVERFLOW.");
}
spin_lock(&kaweth->device_lock);
if (IS_BLOCKED(kaweth->status)) {
spin_unlock(&kaweth->device_lock);
return;
}
spin_unlock(&kaweth->device_lock);
if(status && status != -EREMOTEIO && count != 1) {
err("%s RX status: %d count: %d packet_len: %d",
net->name,
status,
count,
(int)pkt_len);
kaweth_resubmit_rx_urb(kaweth, GFP_ATOMIC);
return;
}
if(kaweth->net && (count > 2)) {
if(pkt_len > (count - 2)) {
err("Packet length too long for USB frame (pkt_len: %x, count: %x)",pkt_len, count);
err("Packet len & 2047: %x", pkt_len & 2047);
err("Count 2: %x", count2);
kaweth_resubmit_rx_urb(kaweth, GFP_ATOMIC);
return;
}
if(!(skb = dev_alloc_skb(pkt_len+2))) {
kaweth_resubmit_rx_urb(kaweth, GFP_ATOMIC);
return;
}
skb_reserve(skb, 2); /* Align IP on 16 byte boundaries */
skb_copy_to_linear_data(skb, kaweth->rx_buf + 2, pkt_len);
skb_put(skb, pkt_len);
skb->protocol = eth_type_trans(skb, net);
netif_rx(skb);
kaweth->stats.rx_packets++;
kaweth->stats.rx_bytes += pkt_len;
}
kaweth_resubmit_rx_urb(kaweth, GFP_ATOMIC);
}
/****************************************************************
* kaweth_open
****************************************************************/
static int kaweth_open(struct net_device *net)
{
struct kaweth_device *kaweth = netdev_priv(net);
int res;
dbg("Opening network device.");
res = usb_autopm_get_interface(kaweth->intf);
if (res) {
err("Interface cannot be resumed.");
return -EIO;
}
res = kaweth_resubmit_rx_urb(kaweth, GFP_KERNEL);
if (res)
goto err_out;
usb_fill_int_urb(
kaweth->irq_urb,
kaweth->dev,
usb_rcvintpipe(kaweth->dev, 3),
kaweth->intbuffer,
INTBUFFERSIZE,
int_callback,
kaweth,
250); /* overriding the descriptor */
kaweth->irq_urb->transfer_dma = kaweth->intbufferhandle;
kaweth->irq_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
res = usb_submit_urb(kaweth->irq_urb, GFP_KERNEL);
if (res) {
usb_kill_urb(kaweth->rx_urb);
goto err_out;
}
kaweth->opened = 1;
netif_start_queue(net);
kaweth_async_set_rx_mode(kaweth);
return 0;
err_out:
usb_autopm_put_interface(kaweth->intf);
return -EIO;
}
/****************************************************************
* kaweth_kill_urbs
****************************************************************/
static void kaweth_kill_urbs(struct kaweth_device *kaweth)
{
usb_kill_urb(kaweth->irq_urb);
usb_kill_urb(kaweth->rx_urb);
usb_kill_urb(kaweth->tx_urb);
cancel_delayed_work_sync(&kaweth->lowmem_work);
/* a scheduled work may have resubmitted,
we hit them again */
usb_kill_urb(kaweth->irq_urb);
usb_kill_urb(kaweth->rx_urb);
}
/****************************************************************
* kaweth_close
****************************************************************/
static int kaweth_close(struct net_device *net)
{
struct kaweth_device *kaweth = netdev_priv(net);
netif_stop_queue(net);
kaweth->opened = 0;
kaweth->status |= KAWETH_STATUS_CLOSING;
kaweth_kill_urbs(kaweth);
kaweth->status &= ~KAWETH_STATUS_CLOSING;
usb_autopm_put_interface(kaweth->intf);
return 0;
}
static void kaweth_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct kaweth_device *kaweth = netdev_priv(dev);
strlcpy(info->driver, driver_name, sizeof(info->driver));
usb_make_path(kaweth->dev, info->bus_info, sizeof (info->bus_info));
}
static u32 kaweth_get_link(struct net_device *dev)
{
struct kaweth_device *kaweth = netdev_priv(dev);
return kaweth->linkstate;
}
static const struct ethtool_ops ops = {
.get_drvinfo = kaweth_get_drvinfo,
.get_link = kaweth_get_link
};
/****************************************************************
* kaweth_usb_transmit_complete
****************************************************************/
static void kaweth_usb_transmit_complete(struct urb *urb)
{
struct kaweth_device *kaweth = urb->context;
struct sk_buff *skb = kaweth->tx_skb;
int status = urb->status;
if (unlikely(status != 0))
if (status != -ENOENT)
dbg("%s: TX status %d.", kaweth->net->name, status);
netif_wake_queue(kaweth->net);
dev_kfree_skb_irq(skb);
}
/****************************************************************
* kaweth_start_xmit
****************************************************************/
static netdev_tx_t kaweth_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct kaweth_device *kaweth = netdev_priv(net);
__le16 *private_header;
int res;
spin_lock_irq(&kaweth->device_lock);
kaweth_async_set_rx_mode(kaweth);
netif_stop_queue(net);
if (IS_BLOCKED(kaweth->status)) {
goto skip;
}
/* We now decide whether we can put our special header into the sk_buff */
if (skb_cloned(skb) || skb_headroom(skb) < 2) {
/* no such luck - we make our own */
struct sk_buff *copied_skb;
copied_skb = skb_copy_expand(skb, 2, 0, GFP_ATOMIC);
dev_kfree_skb_irq(skb);
skb = copied_skb;
if (!copied_skb) {
kaweth->stats.tx_errors++;
netif_start_queue(net);
spin_unlock_irq(&kaweth->device_lock);
return NETDEV_TX_OK;
}
}
private_header = (__le16 *)__skb_push(skb, 2);
*private_header = cpu_to_le16(skb->len-2);
kaweth->tx_skb = skb;
usb_fill_bulk_urb(kaweth->tx_urb,
kaweth->dev,
usb_sndbulkpipe(kaweth->dev, 2),
private_header,
skb->len,
kaweth_usb_transmit_complete,
kaweth);
kaweth->end = 0;
if((res = usb_submit_urb(kaweth->tx_urb, GFP_ATOMIC)))
{
dev_warn(&net->dev, "kaweth failed tx_urb %d\n", res);
skip:
kaweth->stats.tx_errors++;
netif_start_queue(net);
dev_kfree_skb_irq(skb);
}
else
{
kaweth->stats.tx_packets++;
kaweth->stats.tx_bytes += skb->len;
}
spin_unlock_irq(&kaweth->device_lock);
return NETDEV_TX_OK;
}
/****************************************************************
* kaweth_set_rx_mode
****************************************************************/
static void kaweth_set_rx_mode(struct net_device *net)
{
struct kaweth_device *kaweth = netdev_priv(net);
__u16 packet_filter_bitmap = KAWETH_PACKET_FILTER_DIRECTED |
KAWETH_PACKET_FILTER_BROADCAST |
KAWETH_PACKET_FILTER_MULTICAST;
dbg("Setting Rx mode to %d", packet_filter_bitmap);
netif_stop_queue(net);
if (net->flags & IFF_PROMISC) {
packet_filter_bitmap |= KAWETH_PACKET_FILTER_PROMISCUOUS;
}
else if (!netdev_mc_empty(net) || (net->flags & IFF_ALLMULTI)) {
packet_filter_bitmap |= KAWETH_PACKET_FILTER_ALL_MULTICAST;
}
kaweth->packet_filter_bitmap = packet_filter_bitmap;
netif_wake_queue(net);
}
/****************************************************************
* kaweth_async_set_rx_mode
****************************************************************/
static void kaweth_async_set_rx_mode(struct kaweth_device *kaweth)
{
int result;
__u16 packet_filter_bitmap = kaweth->packet_filter_bitmap;
kaweth->packet_filter_bitmap = 0;
if (packet_filter_bitmap == 0)
return;
if (in_interrupt())
return;
result = kaweth_control(kaweth,
usb_sndctrlpipe(kaweth->dev, 0),
KAWETH_COMMAND_SET_PACKET_FILTER,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
packet_filter_bitmap,
0,
(void *)&kaweth->scratch,
0,
KAWETH_CONTROL_TIMEOUT);
if(result < 0) {
err("Failed to set Rx mode: %d", result);
}
else {
dbg("Set Rx mode to %d", packet_filter_bitmap);
}
}
/****************************************************************
* kaweth_netdev_stats
****************************************************************/
static struct net_device_stats *kaweth_netdev_stats(struct net_device *dev)
{
struct kaweth_device *kaweth = netdev_priv(dev);
return &kaweth->stats;
}
/****************************************************************
* kaweth_tx_timeout
****************************************************************/
static void kaweth_tx_timeout(struct net_device *net)
{
struct kaweth_device *kaweth = netdev_priv(net);
dev_warn(&net->dev, "%s: Tx timed out. Resetting.\n", net->name);
kaweth->stats.tx_errors++;
net->trans_start = jiffies;
usb_unlink_urb(kaweth->tx_urb);
}
/****************************************************************
* kaweth_suspend
****************************************************************/
static int kaweth_suspend(struct usb_interface *intf, pm_message_t message)
{
struct kaweth_device *kaweth = usb_get_intfdata(intf);
unsigned long flags;
dbg("Suspending device");
spin_lock_irqsave(&kaweth->device_lock, flags);
kaweth->status |= KAWETH_STATUS_SUSPENDING;
spin_unlock_irqrestore(&kaweth->device_lock, flags);
kaweth_kill_urbs(kaweth);
return 0;
}
/****************************************************************
* kaweth_resume
****************************************************************/
static int kaweth_resume(struct usb_interface *intf)
{
struct kaweth_device *kaweth = usb_get_intfdata(intf);
unsigned long flags;
dbg("Resuming device");
spin_lock_irqsave(&kaweth->device_lock, flags);
kaweth->status &= ~KAWETH_STATUS_SUSPENDING;
spin_unlock_irqrestore(&kaweth->device_lock, flags);
if (!kaweth->opened)
return 0;
kaweth_resubmit_rx_urb(kaweth, GFP_NOIO);
kaweth_resubmit_int_urb(kaweth, GFP_NOIO);
return 0;
}
/****************************************************************
* kaweth_probe
****************************************************************/
static const struct net_device_ops kaweth_netdev_ops = {
.ndo_open = kaweth_open,
.ndo_stop = kaweth_close,
.ndo_start_xmit = kaweth_start_xmit,
.ndo_tx_timeout = kaweth_tx_timeout,
.ndo_set_multicast_list = kaweth_set_rx_mode,
.ndo_get_stats = kaweth_netdev_stats,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static int kaweth_probe(
struct usb_interface *intf,
const struct usb_device_id *id /* from id_table */
)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct kaweth_device *kaweth;
struct net_device *netdev;
const eth_addr_t bcast_addr = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
int result = 0;
dbg("Kawasaki Device Probe (Device number:%d): 0x%4.4x:0x%4.4x:0x%4.4x",
dev->devnum,
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct),
le16_to_cpu(dev->descriptor.bcdDevice));
dbg("Device at %p", dev);
dbg("Descriptor length: %x type: %x",
(int)dev->descriptor.bLength,
(int)dev->descriptor.bDescriptorType);
netdev = alloc_etherdev(sizeof(*kaweth));
if (!netdev)
return -ENOMEM;
kaweth = netdev_priv(netdev);
kaweth->dev = dev;
kaweth->net = netdev;
spin_lock_init(&kaweth->device_lock);
init_waitqueue_head(&kaweth->term_wait);
dbg("Resetting.");
kaweth_reset(kaweth);
/*
* If high byte of bcdDevice is nonzero, firmware is already
* downloaded. Don't try to do it again, or we'll hang the device.
*/
if (le16_to_cpu(dev->descriptor.bcdDevice) >> 8) {
dev_info(&intf->dev, "Firmware present in device.\n");
} else {
/* Download the firmware */
dev_info(&intf->dev, "Downloading firmware...\n");
kaweth->firmware_buf = (__u8 *)__get_free_page(GFP_KERNEL);
if ((result = kaweth_download_firmware(kaweth,
"kaweth/new_code.bin",
100,
2)) < 0) {
err("Error downloading firmware (%d)", result);
goto err_fw;
}
if ((result = kaweth_download_firmware(kaweth,
"kaweth/new_code_fix.bin",
100,
3)) < 0) {
err("Error downloading firmware fix (%d)", result);
goto err_fw;
}
if ((result = kaweth_download_firmware(kaweth,
"kaweth/trigger_code.bin",
126,
2)) < 0) {
err("Error downloading trigger code (%d)", result);
goto err_fw;
}
if ((result = kaweth_download_firmware(kaweth,
"kaweth/trigger_code_fix.bin",
126,
3)) < 0) {
err("Error downloading trigger code fix (%d)", result);
goto err_fw;
}
if ((result = kaweth_trigger_firmware(kaweth, 126)) < 0) {
err("Error triggering firmware (%d)", result);
goto err_fw;
}
/* Device will now disappear for a moment... */
dev_info(&intf->dev, "Firmware loaded. I'll be back...\n");
err_fw:
free_page((unsigned long)kaweth->firmware_buf);
free_netdev(netdev);
return -EIO;
}
result = kaweth_read_configuration(kaweth);
if(result < 0) {
err("Error reading configuration (%d), no net device created", result);
goto err_free_netdev;
}
dev_info(&intf->dev, "Statistics collection: %x\n", kaweth->configuration.statistics_mask);
dev_info(&intf->dev, "Multicast filter limit: %x\n", kaweth->configuration.max_multicast_filters & ((1 << 15) - 1));
dev_info(&intf->dev, "MTU: %d\n", le16_to_cpu(kaweth->configuration.segment_size));
dev_info(&intf->dev, "Read MAC address %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n",
(int)kaweth->configuration.hw_addr[0],
(int)kaweth->configuration.hw_addr[1],
(int)kaweth->configuration.hw_addr[2],
(int)kaweth->configuration.hw_addr[3],
(int)kaweth->configuration.hw_addr[4],
(int)kaweth->configuration.hw_addr[5]);
if(!memcmp(&kaweth->configuration.hw_addr,
&bcast_addr,
sizeof(bcast_addr))) {
err("Firmware not functioning properly, no net device created");
goto err_free_netdev;
}
if(kaweth_set_urb_size(kaweth, KAWETH_BUF_SIZE) < 0) {
dbg("Error setting URB size");
goto err_free_netdev;
}
if(kaweth_set_sofs_wait(kaweth, KAWETH_SOFS_TO_WAIT) < 0) {
err("Error setting SOFS wait");
goto err_free_netdev;
}
result = kaweth_set_receive_filter(kaweth,
KAWETH_PACKET_FILTER_DIRECTED |
KAWETH_PACKET_FILTER_BROADCAST |
KAWETH_PACKET_FILTER_MULTICAST);
if(result < 0) {
err("Error setting receive filter");
goto err_free_netdev;
}
dbg("Initializing net device.");
kaweth->intf = intf;
kaweth->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!kaweth->tx_urb)
goto err_free_netdev;
kaweth->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!kaweth->rx_urb)
goto err_only_tx;
kaweth->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!kaweth->irq_urb)
goto err_tx_and_rx;
kaweth->intbuffer = usb_alloc_coherent( kaweth->dev,
INTBUFFERSIZE,
GFP_KERNEL,
&kaweth->intbufferhandle);
if (!kaweth->intbuffer)
goto err_tx_and_rx_and_irq;
kaweth->rx_buf = usb_alloc_coherent( kaweth->dev,
KAWETH_BUF_SIZE,
GFP_KERNEL,
&kaweth->rxbufferhandle);
if (!kaweth->rx_buf)
goto err_all_but_rxbuf;
memcpy(netdev->broadcast, &bcast_addr, sizeof(bcast_addr));
memcpy(netdev->dev_addr, &kaweth->configuration.hw_addr,
sizeof(kaweth->configuration.hw_addr));
netdev->netdev_ops = &kaweth_netdev_ops;
netdev->watchdog_timeo = KAWETH_TX_TIMEOUT;
netdev->mtu = le16_to_cpu(kaweth->configuration.segment_size);
SET_ETHTOOL_OPS(netdev, &ops);
/* kaweth is zeroed as part of alloc_netdev */
INIT_DELAYED_WORK(&kaweth->lowmem_work, kaweth_resubmit_tl);
usb_set_intfdata(intf, kaweth);
#if 0
// dma_supported() is deeply broken on almost all architectures
if (dma_supported (&intf->dev, 0xffffffffffffffffULL))
kaweth->net->features |= NETIF_F_HIGHDMA;
#endif
SET_NETDEV_DEV(netdev, &intf->dev);
if (register_netdev(netdev) != 0) {
err("Error registering netdev.");
goto err_intfdata;
}
dev_info(&intf->dev, "kaweth interface created at %s\n",
kaweth->net->name);
dbg("Kaweth probe returning.");
return 0;
err_intfdata:
usb_set_intfdata(intf, NULL);
usb_free_coherent(kaweth->dev, KAWETH_BUF_SIZE, (void *)kaweth->rx_buf, kaweth->rxbufferhandle);
err_all_but_rxbuf:
usb_free_coherent(kaweth->dev, INTBUFFERSIZE, (void *)kaweth->intbuffer, kaweth->intbufferhandle);
err_tx_and_rx_and_irq:
usb_free_urb(kaweth->irq_urb);
err_tx_and_rx:
usb_free_urb(kaweth->rx_urb);
err_only_tx:
usb_free_urb(kaweth->tx_urb);
err_free_netdev:
free_netdev(netdev);
return -EIO;
}
/****************************************************************
* kaweth_disconnect
****************************************************************/
static void kaweth_disconnect(struct usb_interface *intf)
{
struct kaweth_device *kaweth = usb_get_intfdata(intf);
struct net_device *netdev;
dev_info(&intf->dev, "Unregistering\n");
usb_set_intfdata(intf, NULL);
if (!kaweth) {
dev_warn(&intf->dev, "unregistering non-existant device\n");
return;
}
netdev = kaweth->net;
dbg("Unregistering net device");
unregister_netdev(netdev);
usb_free_urb(kaweth->rx_urb);
usb_free_urb(kaweth->tx_urb);
usb_free_urb(kaweth->irq_urb);
usb_free_coherent(kaweth->dev, KAWETH_BUF_SIZE, (void *)kaweth->rx_buf, kaweth->rxbufferhandle);
usb_free_coherent(kaweth->dev, INTBUFFERSIZE, (void *)kaweth->intbuffer, kaweth->intbufferhandle);
free_netdev(netdev);
}
// FIXME this completion stuff is a modified clone of
// an OLD version of some stuff in usb.c ...
struct usb_api_data {
wait_queue_head_t wqh;
int done;
};
/*-------------------------------------------------------------------*
* completion handler for compatibility wrappers (sync control/bulk) *
*-------------------------------------------------------------------*/
static void usb_api_blocking_completion(struct urb *urb)
{
struct usb_api_data *awd = (struct usb_api_data *)urb->context;
awd->done=1;
wake_up(&awd->wqh);
}
/*-------------------------------------------------------------------*
* COMPATIBILITY STUFF *
*-------------------------------------------------------------------*/
// Starts urb and waits for completion or timeout
static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
{
struct usb_api_data awd;
int status;
init_waitqueue_head(&awd.wqh);
awd.done = 0;
urb->context = &awd;
status = usb_submit_urb(urb, GFP_NOIO);
if (status) {
// something went wrong
usb_free_urb(urb);
return status;
}
if (!wait_event_timeout(awd.wqh, awd.done, timeout)) {
// timeout
dev_warn(&urb->dev->dev, "usb_control/bulk_msg: timeout\n");
usb_kill_urb(urb); // remove urb safely
status = -ETIMEDOUT;
}
else {
status = urb->status;
}
if (actual_length) {
*actual_length = urb->actual_length;
}
usb_free_urb(urb);
return status;
}
/*-------------------------------------------------------------------*/
// returns status (negative) or length (positive)
static int kaweth_internal_control_msg(struct usb_device *usb_dev,
unsigned int pipe,
struct usb_ctrlrequest *cmd, void *data,
int len, int timeout)
{
struct urb *urb;
int retv;
int length = 0; /* shut up GCC */
urb = usb_alloc_urb(0, GFP_NOIO);
if (!urb)
return -ENOMEM;
usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char*)cmd, data,
len, usb_api_blocking_completion, NULL);
retv = usb_start_wait_urb(urb, timeout, &length);
if (retv < 0) {
return retv;
}
else {
return length;
}
}
/****************************************************************
* kaweth_init
****************************************************************/
static int __init kaweth_init(void)
{
dbg("Driver loading");
return usb_register(&kaweth_driver);
}
/****************************************************************
* kaweth_exit
****************************************************************/
static void __exit kaweth_exit(void)
{
usb_deregister(&kaweth_driver);
}
module_init(kaweth_init);
module_exit(kaweth_exit);
| gpl-2.0 |
zuch0698o/lge-kernel-startablet | arch/arm/plat-samsung/wakeup-mask.c | 1015 | 1097 | /* arch/arm/plat-samsung/wakeup-mask.c
*
* Copyright 2010 Ben Dooks <ben-linux@fluff.org>
*
* Support for wakeup mask interrupts on newer SoCs
*
* 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/spinlock.h>
#include <linux/sysdev.h>
#include <linux/types.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <plat/wakeup-mask.h>
#include <plat/pm.h>
void samsung_sync_wakemask(void __iomem *reg,
struct samsung_wakeup_mask *mask, int nr_mask)
{
struct irq_desc *desc;
u32 val;
val = __raw_readl(reg);
for (; nr_mask > 0; nr_mask--, mask++) {
if (mask->irq == NO_WAKEUP_IRQ) {
val |= mask->bit;
continue;
}
desc = irq_to_desc(mask->irq);
/* bit of a liberty to read this directly from irq_desc. */
if (desc->wake_depth > 0)
val &= ~mask->bit;
else
val |= mask->bit;
}
printk(KERN_INFO "wakemask %08x => %08x\n", __raw_readl(reg), val);
__raw_writel(val, reg);
}
| gpl-2.0 |
Pafcholini/Beta_TW | drivers/scsi/sr.c | 2039 | 26655 | /*
* sr.c Copyright (C) 1992 David Giller
* Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
*
* adapted from:
* sd.c Copyright (C) 1992 Drew Eckhardt
* Linux scsi disk driver by
* Drew Eckhardt <drew@colorado.edu>
*
* Modified by Eric Youngdale ericy@andante.org to
* add scatter-gather, multiple outstanding request, and other
* enhancements.
*
* Modified by Eric Youngdale eric@andante.org to support loadable
* low-level scsi drivers.
*
* Modified by Thomas Quinot thomas@melchior.cuivre.fdn.fr to
* provide auto-eject.
*
* Modified by Gerd Knorr <kraxel@cs.tu-berlin.de> to support the
* generic cdrom interface
*
* Modified by Jens Axboe <axboe@suse.de> - Uniform sr_packet()
* interface, capabilities probe additions, ioctl cleanups, etc.
*
* Modified by Richard Gooch <rgooch@atnf.csiro.au> to support devfs
*
* Modified by Jens Axboe <axboe@suse.de> - support DVD-RAM
* transparently and lose the GHOST hack
*
* Modified by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* check resource allocation in sr_init and some cleanups
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/bio.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/cdrom.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/pm_runtime.h>
#include <asm/uaccess.h>
#include <scsi/scsi.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_driver.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_ioctl.h> /* For the door lock/unlock commands */
#include "scsi_logging.h"
#include "sr.h"
MODULE_DESCRIPTION("SCSI cdrom (sr) driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_CDROM_MAJOR);
MODULE_ALIAS_SCSI_DEVICE(TYPE_ROM);
MODULE_ALIAS_SCSI_DEVICE(TYPE_WORM);
#define SR_DISKS 256
#define SR_CAPABILITIES \
(CDC_CLOSE_TRAY|CDC_OPEN_TRAY|CDC_LOCK|CDC_SELECT_SPEED| \
CDC_SELECT_DISC|CDC_MULTI_SESSION|CDC_MCN|CDC_MEDIA_CHANGED| \
CDC_PLAY_AUDIO|CDC_RESET|CDC_DRIVE_STATUS| \
CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_DVD_RAM|CDC_GENERIC_PACKET| \
CDC_MRW|CDC_MRW_W|CDC_RAM)
static DEFINE_MUTEX(sr_mutex);
static int sr_probe(struct device *);
static int sr_remove(struct device *);
static int sr_done(struct scsi_cmnd *);
static int sr_runtime_suspend(struct device *dev);
static struct dev_pm_ops sr_pm_ops = {
.runtime_suspend = sr_runtime_suspend,
};
static struct scsi_driver sr_template = {
.owner = THIS_MODULE,
.gendrv = {
.name = "sr",
.probe = sr_probe,
.remove = sr_remove,
.pm = &sr_pm_ops,
},
.done = sr_done,
};
static unsigned long sr_index_bits[SR_DISKS / BITS_PER_LONG];
static DEFINE_SPINLOCK(sr_index_lock);
/* This semaphore is used to mediate the 0->1 reference get in the
* face of object destruction (i.e. we can't allow a get on an
* object after last put) */
static DEFINE_MUTEX(sr_ref_mutex);
static int sr_open(struct cdrom_device_info *, int);
static void sr_release(struct cdrom_device_info *);
static void get_sectorsize(struct scsi_cd *);
static void get_capabilities(struct scsi_cd *);
static unsigned int sr_check_events(struct cdrom_device_info *cdi,
unsigned int clearing, int slot);
static int sr_packet(struct cdrom_device_info *, struct packet_command *);
static struct cdrom_device_ops sr_dops = {
.open = sr_open,
.release = sr_release,
.drive_status = sr_drive_status,
.check_events = sr_check_events,
.tray_move = sr_tray_move,
.lock_door = sr_lock_door,
.select_speed = sr_select_speed,
.get_last_session = sr_get_last_session,
.get_mcn = sr_get_mcn,
.reset = sr_reset,
.audio_ioctl = sr_audio_ioctl,
.capability = SR_CAPABILITIES,
.generic_packet = sr_packet,
};
static void sr_kref_release(struct kref *kref);
static inline struct scsi_cd *scsi_cd(struct gendisk *disk)
{
return container_of(disk->private_data, struct scsi_cd, driver);
}
static int sr_runtime_suspend(struct device *dev)
{
struct scsi_cd *cd = dev_get_drvdata(dev);
if (cd->media_present)
return -EBUSY;
else
return 0;
}
/*
* The get and put routines for the struct scsi_cd. Note this entity
* has a scsi_device pointer and owns a reference to this.
*/
static inline struct scsi_cd *scsi_cd_get(struct gendisk *disk)
{
struct scsi_cd *cd = NULL;
mutex_lock(&sr_ref_mutex);
if (disk->private_data == NULL)
goto out;
cd = scsi_cd(disk);
kref_get(&cd->kref);
if (scsi_device_get(cd->device))
goto out_put;
if (!scsi_autopm_get_device(cd->device))
goto out;
out_put:
kref_put(&cd->kref, sr_kref_release);
cd = NULL;
out:
mutex_unlock(&sr_ref_mutex);
return cd;
}
static void scsi_cd_put(struct scsi_cd *cd)
{
struct scsi_device *sdev = cd->device;
mutex_lock(&sr_ref_mutex);
kref_put(&cd->kref, sr_kref_release);
scsi_autopm_put_device(sdev);
scsi_device_put(sdev);
mutex_unlock(&sr_ref_mutex);
}
static unsigned int sr_get_events(struct scsi_device *sdev)
{
u8 buf[8];
u8 cmd[] = { GET_EVENT_STATUS_NOTIFICATION,
1, /* polled */
0, 0, /* reserved */
1 << 4, /* notification class: media */
0, 0, /* reserved */
0, sizeof(buf), /* allocation length */
0, /* control */
};
struct event_header *eh = (void *)buf;
struct media_event_desc *med = (void *)(buf + 4);
struct scsi_sense_hdr sshdr;
int result;
result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buf, sizeof(buf),
&sshdr, SR_TIMEOUT, MAX_RETRIES, NULL);
if (scsi_sense_valid(&sshdr) && sshdr.sense_key == UNIT_ATTENTION)
return DISK_EVENT_MEDIA_CHANGE;
if (result || be16_to_cpu(eh->data_len) < sizeof(*med))
return 0;
if (eh->nea || eh->notification_class != 0x4)
return 0;
if (med->media_event_code == 1)
return DISK_EVENT_EJECT_REQUEST;
else if (med->media_event_code == 2)
return DISK_EVENT_MEDIA_CHANGE;
return 0;
}
/*
* This function checks to see if the media has been changed or eject
* button has been pressed. It is possible that we have already
* sensed a change, or the drive may have sensed one and not yet
* reported it. The past events are accumulated in sdev->changed and
* returned together with the current state.
*/
static unsigned int sr_check_events(struct cdrom_device_info *cdi,
unsigned int clearing, int slot)
{
struct scsi_cd *cd = cdi->handle;
bool last_present;
struct scsi_sense_hdr sshdr;
unsigned int events;
int ret;
/* no changer support */
if (CDSL_CURRENT != slot)
return 0;
events = sr_get_events(cd->device);
cd->get_event_changed |= events & DISK_EVENT_MEDIA_CHANGE;
/*
* If earlier GET_EVENT_STATUS_NOTIFICATION and TUR did not agree
* for several times in a row. We rely on TUR only for this likely
* broken device, to prevent generating incorrect media changed
* events for every open().
*/
if (cd->ignore_get_event) {
events &= ~DISK_EVENT_MEDIA_CHANGE;
goto do_tur;
}
/*
* GET_EVENT_STATUS_NOTIFICATION is enough unless MEDIA_CHANGE
* is being cleared. Note that there are devices which hang
* if asked to execute TUR repeatedly.
*/
if (cd->device->changed) {
events |= DISK_EVENT_MEDIA_CHANGE;
cd->device->changed = 0;
cd->tur_changed = true;
}
if (!(clearing & DISK_EVENT_MEDIA_CHANGE))
return events;
do_tur:
/* let's see whether the media is there with TUR */
last_present = cd->media_present;
ret = scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr);
/*
* Media is considered to be present if TUR succeeds or fails with
* sense data indicating something other than media-not-present
* (ASC 0x3a).
*/
cd->media_present = scsi_status_is_good(ret) ||
(scsi_sense_valid(&sshdr) && sshdr.asc != 0x3a);
if (last_present != cd->media_present)
cd->device->changed = 1;
if (cd->device->changed) {
events |= DISK_EVENT_MEDIA_CHANGE;
cd->device->changed = 0;
cd->tur_changed = true;
}
if (cd->ignore_get_event)
return events;
/* check whether GET_EVENT is reporting spurious MEDIA_CHANGE */
if (!cd->tur_changed) {
if (cd->get_event_changed) {
if (cd->tur_mismatch++ > 8) {
sdev_printk(KERN_WARNING, cd->device,
"GET_EVENT and TUR disagree continuously, suppress GET_EVENT events\n");
cd->ignore_get_event = true;
}
} else {
cd->tur_mismatch = 0;
}
}
cd->tur_changed = false;
cd->get_event_changed = false;
return events;
}
/*
* sr_done is the interrupt routine for the device driver.
*
* It will be notified on the end of a SCSI read / write, and will take one
* of several actions based on success or failure.
*/
static int sr_done(struct scsi_cmnd *SCpnt)
{
int result = SCpnt->result;
int this_count = scsi_bufflen(SCpnt);
int good_bytes = (result == 0 ? this_count : 0);
int block_sectors = 0;
long error_sector;
struct scsi_cd *cd = scsi_cd(SCpnt->request->rq_disk);
#ifdef DEBUG
printk("sr.c done: %x\n", result);
#endif
/*
* Handle MEDIUM ERRORs or VOLUME OVERFLOWs that indicate partial
* success. Since this is a relatively rare error condition, no
* care is taken to avoid unnecessary additional work such as
* memcpy's that could be avoided.
*/
if (driver_byte(result) != 0 && /* An error occurred */
(SCpnt->sense_buffer[0] & 0x7f) == 0x70) { /* Sense current */
switch (SCpnt->sense_buffer[2]) {
case MEDIUM_ERROR:
case VOLUME_OVERFLOW:
case ILLEGAL_REQUEST:
if (!(SCpnt->sense_buffer[0] & 0x90))
break;
error_sector = (SCpnt->sense_buffer[3] << 24) |
(SCpnt->sense_buffer[4] << 16) |
(SCpnt->sense_buffer[5] << 8) |
SCpnt->sense_buffer[6];
if (SCpnt->request->bio != NULL)
block_sectors =
bio_sectors(SCpnt->request->bio);
if (block_sectors < 4)
block_sectors = 4;
if (cd->device->sector_size == 2048)
error_sector <<= 2;
error_sector &= ~(block_sectors - 1);
good_bytes = (error_sector -
blk_rq_pos(SCpnt->request)) << 9;
if (good_bytes < 0 || good_bytes >= this_count)
good_bytes = 0;
/*
* The SCSI specification allows for the value
* returned by READ CAPACITY to be up to 75 2K
* sectors past the last readable block.
* Therefore, if we hit a medium error within the
* last 75 2K sectors, we decrease the saved size
* value.
*/
if (error_sector < get_capacity(cd->disk) &&
cd->capacity - error_sector < 4 * 75)
set_capacity(cd->disk, error_sector);
break;
case RECOVERED_ERROR:
good_bytes = this_count;
break;
default:
break;
}
}
return good_bytes;
}
static int sr_prep_fn(struct request_queue *q, struct request *rq)
{
int block = 0, this_count, s_size;
struct scsi_cd *cd;
struct scsi_cmnd *SCpnt;
struct scsi_device *sdp = q->queuedata;
int ret;
if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
ret = scsi_setup_blk_pc_cmnd(sdp, rq);
goto out;
} else if (rq->cmd_type != REQ_TYPE_FS) {
ret = BLKPREP_KILL;
goto out;
}
ret = scsi_setup_fs_cmnd(sdp, rq);
if (ret != BLKPREP_OK)
goto out;
SCpnt = rq->special;
cd = scsi_cd(rq->rq_disk);
/* from here on until we're complete, any goto out
* is used for a killable error condition */
ret = BLKPREP_KILL;
SCSI_LOG_HLQUEUE(1, printk("Doing sr request, dev = %s, block = %d\n",
cd->disk->disk_name, block));
if (!cd->device || !scsi_device_online(cd->device)) {
SCSI_LOG_HLQUEUE(2, printk("Finishing %u sectors\n",
blk_rq_sectors(rq)));
SCSI_LOG_HLQUEUE(2, printk("Retry with 0x%p\n", SCpnt));
goto out;
}
if (cd->device->changed) {
/*
* quietly refuse to do anything to a changed disc until the
* changed bit has been reset
*/
goto out;
}
/*
* we do lazy blocksize switching (when reading XA sectors,
* see CDROMREADMODE2 ioctl)
*/
s_size = cd->device->sector_size;
if (s_size > 2048) {
if (!in_interrupt())
sr_set_blocklength(cd, 2048);
else
printk("sr: can't switch blocksize: in interrupt\n");
}
if (s_size != 512 && s_size != 1024 && s_size != 2048) {
scmd_printk(KERN_ERR, SCpnt, "bad sector size %d\n", s_size);
goto out;
}
if (rq_data_dir(rq) == WRITE) {
if (!cd->device->writeable)
goto out;
SCpnt->cmnd[0] = WRITE_10;
SCpnt->sc_data_direction = DMA_TO_DEVICE;
cd->cdi.media_written = 1;
} else if (rq_data_dir(rq) == READ) {
SCpnt->cmnd[0] = READ_10;
SCpnt->sc_data_direction = DMA_FROM_DEVICE;
} else {
blk_dump_rq_flags(rq, "Unknown sr command");
goto out;
}
{
struct scatterlist *sg;
int i, size = 0, sg_count = scsi_sg_count(SCpnt);
scsi_for_each_sg(SCpnt, sg, sg_count, i)
size += sg->length;
if (size != scsi_bufflen(SCpnt)) {
scmd_printk(KERN_ERR, SCpnt,
"mismatch count %d, bytes %d\n",
size, scsi_bufflen(SCpnt));
if (scsi_bufflen(SCpnt) > size)
SCpnt->sdb.length = size;
}
}
/*
* request doesn't start on hw block boundary, add scatter pads
*/
if (((unsigned int)blk_rq_pos(rq) % (s_size >> 9)) ||
(scsi_bufflen(SCpnt) % s_size)) {
scmd_printk(KERN_NOTICE, SCpnt, "unaligned transfer\n");
goto out;
}
this_count = (scsi_bufflen(SCpnt) >> 9) / (s_size >> 9);
SCSI_LOG_HLQUEUE(2, printk("%s : %s %d/%u 512 byte blocks.\n",
cd->cdi.name,
(rq_data_dir(rq) == WRITE) ?
"writing" : "reading",
this_count, blk_rq_sectors(rq)));
SCpnt->cmnd[1] = 0;
block = (unsigned int)blk_rq_pos(rq) / (s_size >> 9);
if (this_count > 0xffff) {
this_count = 0xffff;
SCpnt->sdb.length = this_count * s_size;
}
SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
SCpnt->cmnd[5] = (unsigned char) block & 0xff;
SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
/*
* We shouldn't disconnect in the middle of a sector, so with a dumb
* host adapter, it's safe to assume that we can at least transfer
* this many bytes between each connect / disconnect.
*/
SCpnt->transfersize = cd->device->sector_size;
SCpnt->underflow = this_count << 9;
SCpnt->allowed = MAX_RETRIES;
/*
* This indicates that the command is ready from our end to be
* queued.
*/
ret = BLKPREP_OK;
out:
return scsi_prep_return(q, rq, ret);
}
static int sr_block_open(struct block_device *bdev, fmode_t mode)
{
struct scsi_cd *cd;
int ret = -ENXIO;
mutex_lock(&sr_mutex);
cd = scsi_cd_get(bdev->bd_disk);
if (cd) {
ret = cdrom_open(&cd->cdi, bdev, mode);
if (ret)
scsi_cd_put(cd);
}
mutex_unlock(&sr_mutex);
return ret;
}
static void sr_block_release(struct gendisk *disk, fmode_t mode)
{
struct scsi_cd *cd = scsi_cd(disk);
mutex_lock(&sr_mutex);
cdrom_release(&cd->cdi, mode);
scsi_cd_put(cd);
mutex_unlock(&sr_mutex);
}
static int sr_block_ioctl(struct block_device *bdev, fmode_t mode, unsigned cmd,
unsigned long arg)
{
struct scsi_cd *cd = scsi_cd(bdev->bd_disk);
struct scsi_device *sdev = cd->device;
void __user *argp = (void __user *)arg;
int ret;
scsi_autopm_get_device(cd->device);
mutex_lock(&sr_mutex);
/*
* Send SCSI addressing ioctls directly to mid level, send other
* ioctls to cdrom/block level.
*/
switch (cmd) {
case SCSI_IOCTL_GET_IDLUN:
case SCSI_IOCTL_GET_BUS_NUMBER:
ret = scsi_ioctl(sdev, cmd, argp);
goto out;
}
ret = cdrom_ioctl(&cd->cdi, bdev, mode, cmd, arg);
if (ret != -ENOSYS)
goto out;
/*
* ENODEV means that we didn't recognise the ioctl, or that we
* cannot execute it in the current device state. In either
* case fall through to scsi_ioctl, which will return ENDOEV again
* if it doesn't recognise the ioctl
*/
ret = scsi_nonblockable_ioctl(sdev, cmd, argp,
(mode & FMODE_NDELAY) != 0);
if (ret != -ENODEV)
goto out;
ret = scsi_ioctl(sdev, cmd, argp);
out:
mutex_unlock(&sr_mutex);
scsi_autopm_put_device(cd->device);
return ret;
}
static unsigned int sr_block_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct scsi_cd *cd = scsi_cd(disk);
unsigned int ret;
if (atomic_read(&cd->device->disk_events_disable_depth) == 0) {
scsi_autopm_get_device(cd->device);
ret = cdrom_check_events(&cd->cdi, clearing);
scsi_autopm_put_device(cd->device);
} else {
ret = 0;
}
return ret;
}
static int sr_block_revalidate_disk(struct gendisk *disk)
{
struct scsi_cd *cd = scsi_cd(disk);
struct scsi_sense_hdr sshdr;
scsi_autopm_get_device(cd->device);
/* if the unit is not ready, nothing more to do */
if (scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr))
goto out;
sr_cd_check(&cd->cdi);
get_sectorsize(cd);
out:
scsi_autopm_put_device(cd->device);
return 0;
}
static const struct block_device_operations sr_bdops =
{
.owner = THIS_MODULE,
.open = sr_block_open,
.release = sr_block_release,
.ioctl = sr_block_ioctl,
.check_events = sr_block_check_events,
.revalidate_disk = sr_block_revalidate_disk,
/*
* No compat_ioctl for now because sr_block_ioctl never
* seems to pass arbitrary ioctls down to host drivers.
*/
};
static int sr_open(struct cdrom_device_info *cdi, int purpose)
{
struct scsi_cd *cd = cdi->handle;
struct scsi_device *sdev = cd->device;
int retval;
/*
* If the device is in error recovery, wait until it is done.
* If the device is offline, then disallow any access to it.
*/
retval = -ENXIO;
if (!scsi_block_when_processing_errors(sdev))
goto error_out;
return 0;
error_out:
return retval;
}
static void sr_release(struct cdrom_device_info *cdi)
{
struct scsi_cd *cd = cdi->handle;
if (cd->device->sector_size > 2048)
sr_set_blocklength(cd, 2048);
}
static int sr_probe(struct device *dev)
{
struct scsi_device *sdev = to_scsi_device(dev);
struct gendisk *disk;
struct scsi_cd *cd;
int minor, error;
error = -ENODEV;
if (sdev->type != TYPE_ROM && sdev->type != TYPE_WORM)
goto fail;
error = -ENOMEM;
cd = kzalloc(sizeof(*cd), GFP_KERNEL);
if (!cd)
goto fail;
kref_init(&cd->kref);
disk = alloc_disk(1);
if (!disk)
goto fail_free;
spin_lock(&sr_index_lock);
minor = find_first_zero_bit(sr_index_bits, SR_DISKS);
if (minor == SR_DISKS) {
spin_unlock(&sr_index_lock);
error = -EBUSY;
goto fail_put;
}
__set_bit(minor, sr_index_bits);
spin_unlock(&sr_index_lock);
disk->major = SCSI_CDROM_MAJOR;
disk->first_minor = minor;
sprintf(disk->disk_name, "sr%d", minor);
disk->fops = &sr_bdops;
disk->flags = GENHD_FL_CD | GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
disk->events = DISK_EVENT_MEDIA_CHANGE | DISK_EVENT_EJECT_REQUEST;
blk_queue_rq_timeout(sdev->request_queue, SR_TIMEOUT);
cd->device = sdev;
cd->disk = disk;
cd->driver = &sr_template;
cd->disk = disk;
cd->capacity = 0x1fffff;
cd->device->changed = 1; /* force recheck CD type */
cd->media_present = 1;
cd->use = 1;
cd->readcd_known = 0;
cd->readcd_cdda = 0;
cd->cdi.ops = &sr_dops;
cd->cdi.handle = cd;
cd->cdi.mask = 0;
cd->cdi.capacity = 1;
sprintf(cd->cdi.name, "sr%d", minor);
sdev->sector_size = 2048; /* A guess, just in case */
/* FIXME: need to handle a get_capabilities failure properly ?? */
get_capabilities(cd);
blk_queue_prep_rq(sdev->request_queue, sr_prep_fn);
sr_vendor_init(cd);
disk->driverfs_dev = &sdev->sdev_gendev;
set_capacity(disk, cd->capacity);
disk->private_data = &cd->driver;
disk->queue = sdev->request_queue;
cd->cdi.disk = disk;
if (register_cdrom(&cd->cdi))
goto fail_put;
dev_set_drvdata(dev, cd);
disk->flags |= GENHD_FL_REMOVABLE;
add_disk(disk);
sdev_printk(KERN_DEBUG, sdev,
"Attached scsi CD-ROM %s\n", cd->cdi.name);
scsi_autopm_put_device(cd->device);
return 0;
fail_put:
put_disk(disk);
fail_free:
kfree(cd);
fail:
return error;
}
static void get_sectorsize(struct scsi_cd *cd)
{
unsigned char cmd[10];
unsigned char buffer[8];
int the_result, retries = 3;
int sector_size;
struct request_queue *queue;
do {
cmd[0] = READ_CAPACITY;
memset((void *) &cmd[1], 0, 9);
memset(buffer, 0, sizeof(buffer));
/* Do the command and wait.. */
the_result = scsi_execute_req(cd->device, cmd, DMA_FROM_DEVICE,
buffer, sizeof(buffer), NULL,
SR_TIMEOUT, MAX_RETRIES, NULL);
retries--;
} while (the_result && retries);
if (the_result) {
cd->capacity = 0x1fffff;
sector_size = 2048; /* A guess, just in case */
} else {
long last_written;
cd->capacity = 1 + ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
/*
* READ_CAPACITY doesn't return the correct size on
* certain UDF media. If last_written is larger, use
* it instead.
*
* http://bugzilla.kernel.org/show_bug.cgi?id=9668
*/
if (!cdrom_get_last_written(&cd->cdi, &last_written))
cd->capacity = max_t(long, cd->capacity, last_written);
sector_size = (buffer[4] << 24) |
(buffer[5] << 16) | (buffer[6] << 8) | buffer[7];
switch (sector_size) {
/*
* HP 4020i CD-Recorder reports 2340 byte sectors
* Philips CD-Writers report 2352 byte sectors
*
* Use 2k sectors for them..
*/
case 0:
case 2340:
case 2352:
sector_size = 2048;
/* fall through */
case 2048:
cd->capacity *= 4;
/* fall through */
case 512:
break;
default:
printk("%s: unsupported sector size %d.\n",
cd->cdi.name, sector_size);
cd->capacity = 0;
}
cd->device->sector_size = sector_size;
/*
* Add this so that we have the ability to correctly gauge
* what the device is capable of.
*/
set_capacity(cd->disk, cd->capacity);
}
queue = cd->device->request_queue;
blk_queue_logical_block_size(queue, sector_size);
return;
}
static void get_capabilities(struct scsi_cd *cd)
{
unsigned char *buffer;
struct scsi_mode_data data;
struct scsi_sense_hdr sshdr;
int rc, n;
static const char *loadmech[] =
{
"caddy",
"tray",
"pop-up",
"",
"changer",
"cartridge changer",
"",
""
};
/* allocate transfer buffer */
buffer = kmalloc(512, GFP_KERNEL | GFP_DMA);
if (!buffer) {
printk(KERN_ERR "sr: out of memory.\n");
return;
}
/* eat unit attentions */
scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr);
/* ask for mode page 0x2a */
rc = scsi_mode_sense(cd->device, 0, 0x2a, buffer, 128,
SR_TIMEOUT, 3, &data, NULL);
if (!scsi_status_is_good(rc)) {
/* failed, drive doesn't have capabilities mode page */
cd->cdi.speed = 1;
cd->cdi.mask |= (CDC_CD_R | CDC_CD_RW | CDC_DVD_R |
CDC_DVD | CDC_DVD_RAM |
CDC_SELECT_DISC | CDC_SELECT_SPEED |
CDC_MRW | CDC_MRW_W | CDC_RAM);
kfree(buffer);
printk("%s: scsi-1 drive\n", cd->cdi.name);
return;
}
n = data.header_length + data.block_descriptor_length;
cd->cdi.speed = ((buffer[n + 8] << 8) + buffer[n + 9]) / 176;
cd->readcd_known = 1;
cd->readcd_cdda = buffer[n + 5] & 0x01;
/* print some capability bits */
printk("%s: scsi3-mmc drive: %dx/%dx %s%s%s%s%s%s\n", cd->cdi.name,
((buffer[n + 14] << 8) + buffer[n + 15]) / 176,
cd->cdi.speed,
buffer[n + 3] & 0x01 ? "writer " : "", /* CD Writer */
buffer[n + 3] & 0x20 ? "dvd-ram " : "",
buffer[n + 2] & 0x02 ? "cd/rw " : "", /* can read rewriteable */
buffer[n + 4] & 0x20 ? "xa/form2 " : "", /* can read xa/from2 */
buffer[n + 5] & 0x01 ? "cdda " : "", /* can read audio data */
loadmech[buffer[n + 6] >> 5]);
if ((buffer[n + 6] >> 5) == 0)
/* caddy drives can't close tray... */
cd->cdi.mask |= CDC_CLOSE_TRAY;
if ((buffer[n + 2] & 0x8) == 0)
/* not a DVD drive */
cd->cdi.mask |= CDC_DVD;
if ((buffer[n + 3] & 0x20) == 0)
/* can't write DVD-RAM media */
cd->cdi.mask |= CDC_DVD_RAM;
if ((buffer[n + 3] & 0x10) == 0)
/* can't write DVD-R media */
cd->cdi.mask |= CDC_DVD_R;
if ((buffer[n + 3] & 0x2) == 0)
/* can't write CD-RW media */
cd->cdi.mask |= CDC_CD_RW;
if ((buffer[n + 3] & 0x1) == 0)
/* can't write CD-R media */
cd->cdi.mask |= CDC_CD_R;
if ((buffer[n + 6] & 0x8) == 0)
/* can't eject */
cd->cdi.mask |= CDC_OPEN_TRAY;
if ((buffer[n + 6] >> 5) == mechtype_individual_changer ||
(buffer[n + 6] >> 5) == mechtype_cartridge_changer)
cd->cdi.capacity =
cdrom_number_of_slots(&cd->cdi);
if (cd->cdi.capacity <= 1)
/* not a changer */
cd->cdi.mask |= CDC_SELECT_DISC;
/*else I don't think it can close its tray
cd->cdi.mask |= CDC_CLOSE_TRAY; */
/*
* if DVD-RAM, MRW-W or CD-RW, we are randomly writable
*/
if ((cd->cdi.mask & (CDC_DVD_RAM | CDC_MRW_W | CDC_RAM | CDC_CD_RW)) !=
(CDC_DVD_RAM | CDC_MRW_W | CDC_RAM | CDC_CD_RW)) {
cd->device->writeable = 1;
}
kfree(buffer);
}
/*
* sr_packet() is the entry point for the generic commands generated
* by the Uniform CD-ROM layer.
*/
static int sr_packet(struct cdrom_device_info *cdi,
struct packet_command *cgc)
{
struct scsi_cd *cd = cdi->handle;
struct scsi_device *sdev = cd->device;
if (cgc->cmd[0] == GPCMD_READ_DISC_INFO && sdev->no_read_disc_info)
return -EDRIVE_CANT_DO_THIS;
if (cgc->timeout <= 0)
cgc->timeout = IOCTL_TIMEOUT;
sr_do_ioctl(cd, cgc);
return cgc->stat;
}
/**
* sr_kref_release - Called to free the scsi_cd structure
* @kref: pointer to embedded kref
*
* sr_ref_mutex must be held entering this routine. Because it is
* called on last put, you should always use the scsi_cd_get()
* scsi_cd_put() helpers which manipulate the semaphore directly
* and never do a direct kref_put().
**/
static void sr_kref_release(struct kref *kref)
{
struct scsi_cd *cd = container_of(kref, struct scsi_cd, kref);
struct gendisk *disk = cd->disk;
spin_lock(&sr_index_lock);
clear_bit(MINOR(disk_devt(disk)), sr_index_bits);
spin_unlock(&sr_index_lock);
unregister_cdrom(&cd->cdi);
disk->private_data = NULL;
put_disk(disk);
kfree(cd);
}
static int sr_remove(struct device *dev)
{
struct scsi_cd *cd = dev_get_drvdata(dev);
scsi_autopm_get_device(cd->device);
blk_queue_prep_rq(cd->device->request_queue, scsi_prep_fn);
del_gendisk(cd->disk);
mutex_lock(&sr_ref_mutex);
kref_put(&cd->kref, sr_kref_release);
mutex_unlock(&sr_ref_mutex);
return 0;
}
static int __init init_sr(void)
{
int rc;
rc = register_blkdev(SCSI_CDROM_MAJOR, "sr");
if (rc)
return rc;
rc = scsi_register_driver(&sr_template.gendrv);
if (rc)
unregister_blkdev(SCSI_CDROM_MAJOR, "sr");
return rc;
}
static void __exit exit_sr(void)
{
scsi_unregister_driver(&sr_template.gendrv);
unregister_blkdev(SCSI_CDROM_MAJOR, "sr");
}
module_init(init_sr);
module_exit(exit_sr);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Blackspark-VRUAME7/android_kernel_samsung_jfltevzw | drivers/devfreq/governor_userspace.c | 2807 | 2843 | /*
* linux/drivers/devfreq/governor_simpleondemand.c
*
* Copyright (C) 2011 Samsung Electronics
* MyungJoo Ham <myungjoo.ham@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/devfreq.h>
#include <linux/pm.h>
#include <linux/mutex.h>
#include "governor.h"
struct userspace_data {
unsigned long user_frequency;
bool valid;
};
static int devfreq_userspace_func(struct devfreq *df, unsigned long *freq)
{
struct userspace_data *data = df->data;
if (data->valid) {
unsigned long adjusted_freq = data->user_frequency;
if (df->max_freq && adjusted_freq > df->max_freq)
adjusted_freq = df->max_freq;
if (df->min_freq && adjusted_freq < df->min_freq)
adjusted_freq = df->min_freq;
*freq = adjusted_freq;
} else {
*freq = df->previous_freq; /* No user freq specified yet */
}
return 0;
}
static ssize_t store_freq(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct devfreq *devfreq = to_devfreq(dev);
struct userspace_data *data;
unsigned long wanted;
int err = 0;
mutex_lock(&devfreq->lock);
data = devfreq->data;
sscanf(buf, "%lu", &wanted);
data->user_frequency = wanted;
data->valid = true;
err = update_devfreq(devfreq);
if (err == 0)
err = count;
mutex_unlock(&devfreq->lock);
return err;
}
static ssize_t show_freq(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct devfreq *devfreq = to_devfreq(dev);
struct userspace_data *data;
int err = 0;
mutex_lock(&devfreq->lock);
data = devfreq->data;
if (data->valid)
err = sprintf(buf, "%lu\n", data->user_frequency);
else
err = sprintf(buf, "undefined\n");
mutex_unlock(&devfreq->lock);
return err;
}
static DEVICE_ATTR(set_freq, 0644, show_freq, store_freq);
static struct attribute *dev_entries[] = {
&dev_attr_set_freq.attr,
NULL,
};
static struct attribute_group dev_attr_group = {
.name = "userspace",
.attrs = dev_entries,
};
static int userspace_init(struct devfreq *devfreq)
{
int err = 0;
struct userspace_data *data = kzalloc(sizeof(struct userspace_data),
GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto out;
}
data->valid = false;
devfreq->data = data;
err = sysfs_create_group(&devfreq->dev.kobj, &dev_attr_group);
out:
return err;
}
static void userspace_exit(struct devfreq *devfreq)
{
sysfs_remove_group(&devfreq->dev.kobj, &dev_attr_group);
kfree(devfreq->data);
devfreq->data = NULL;
}
const struct devfreq_governor devfreq_userspace = {
.name = "userspace",
.get_target_freq = devfreq_userspace_func,
.init = userspace_init,
.exit = userspace_exit,
.no_central_polling = true,
};
| gpl-2.0 |
kumajaya/android_kernel_samsung_lt01 | drivers/staging/ath6kl/os/linux/export_hci_transport.c | 2807 | 5019 | //------------------------------------------------------------------------------
// Copyright (c) 2009-2010 Atheros Corporation. All rights reserved.
//
//
// 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.
//
//
//------------------------------------------------------------------------------
//==============================================================================
// HCI bridge implementation
//
// Author(s): ="Atheros"
//==============================================================================
#include <a_config.h>
#include <athdefs.h>
#include "a_osapi.h"
#include "htc_api.h"
#include "a_drv.h"
#include "hif.h"
#include "common_drv.h"
#include "a_debug.h"
#include "hci_transport_api.h"
#include "AR6002/hw4.0/hw/apb_athr_wlan_map.h"
#include "AR6002/hw4.0/hw/uart_reg.h"
#include "AR6002/hw4.0/hw/rtc_wlan_reg.h"
HCI_TRANSPORT_HANDLE (*_HCI_TransportAttach)(void *HTCHandle, struct hci_transport_config_info *pInfo);
void (*_HCI_TransportDetach)(HCI_TRANSPORT_HANDLE HciTrans);
int (*_HCI_TransportAddReceivePkts)(HCI_TRANSPORT_HANDLE HciTrans, struct htc_packet_queue *pQueue);
int (*_HCI_TransportSendPkt)(HCI_TRANSPORT_HANDLE HciTrans, struct htc_packet *pPacket, bool Synchronous);
void (*_HCI_TransportStop)(HCI_TRANSPORT_HANDLE HciTrans);
int (*_HCI_TransportStart)(HCI_TRANSPORT_HANDLE HciTrans);
int (*_HCI_TransportEnableDisableAsyncRecv)(HCI_TRANSPORT_HANDLE HciTrans, bool Enable);
int (*_HCI_TransportRecvHCIEventSync)(HCI_TRANSPORT_HANDLE HciTrans,
struct htc_packet *pPacket,
int MaxPollMS);
int (*_HCI_TransportSetBaudRate)(HCI_TRANSPORT_HANDLE HciTrans, u32 Baud);
int (*_HCI_TransportEnablePowerMgmt)(HCI_TRANSPORT_HANDLE HciTrans, bool Enable);
extern struct hci_transport_callbacks ar6kHciTransCallbacks;
int ar6000_register_hci_transport(struct hci_transport_callbacks *hciTransCallbacks)
{
ar6kHciTransCallbacks = *hciTransCallbacks;
_HCI_TransportAttach = HCI_TransportAttach;
_HCI_TransportDetach = HCI_TransportDetach;
_HCI_TransportAddReceivePkts = HCI_TransportAddReceivePkts;
_HCI_TransportSendPkt = HCI_TransportSendPkt;
_HCI_TransportStop = HCI_TransportStop;
_HCI_TransportStart = HCI_TransportStart;
_HCI_TransportEnableDisableAsyncRecv = HCI_TransportEnableDisableAsyncRecv;
_HCI_TransportRecvHCIEventSync = HCI_TransportRecvHCIEventSync;
_HCI_TransportSetBaudRate = HCI_TransportSetBaudRate;
_HCI_TransportEnablePowerMgmt = HCI_TransportEnablePowerMgmt;
return 0;
}
int
ar6000_get_hif_dev(struct hif_device *device, void *config)
{
int status;
status = HIFConfigureDevice(device,
HIF_DEVICE_GET_OS_DEVICE,
(struct hif_device_os_device_info *)config,
sizeof(struct hif_device_os_device_info));
return status;
}
int ar6000_set_uart_config(struct hif_device *hifDevice,
u32 scale,
u32 step)
{
u32 regAddress;
u32 regVal;
int status;
regAddress = WLAN_UART_BASE_ADDRESS | UART_CLKDIV_ADDRESS;
regVal = ((u32)scale << 16) | step;
/* change the HCI UART scale/step values through the diagnostic window */
status = ar6000_WriteRegDiag(hifDevice, ®Address, ®Val);
return status;
}
int ar6000_get_core_clock_config(struct hif_device *hifDevice, u32 *data)
{
u32 regAddress;
int status;
regAddress = WLAN_RTC_BASE_ADDRESS | WLAN_CPU_CLOCK_ADDRESS;
/* read CPU clock settings*/
status = ar6000_ReadRegDiag(hifDevice, ®Address, data);
return status;
}
EXPORT_SYMBOL(ar6000_register_hci_transport);
EXPORT_SYMBOL(ar6000_get_hif_dev);
EXPORT_SYMBOL(ar6000_set_uart_config);
EXPORT_SYMBOL(ar6000_get_core_clock_config);
EXPORT_SYMBOL(_HCI_TransportAttach);
EXPORT_SYMBOL(_HCI_TransportDetach);
EXPORT_SYMBOL(_HCI_TransportAddReceivePkts);
EXPORT_SYMBOL(_HCI_TransportSendPkt);
EXPORT_SYMBOL(_HCI_TransportStop);
EXPORT_SYMBOL(_HCI_TransportStart);
EXPORT_SYMBOL(_HCI_TransportEnableDisableAsyncRecv);
EXPORT_SYMBOL(_HCI_TransportRecvHCIEventSync);
EXPORT_SYMBOL(_HCI_TransportSetBaudRate);
EXPORT_SYMBOL(_HCI_TransportEnablePowerMgmt);
| gpl-2.0 |
TeamEOS/kernel_oppo_find7 | fs/xfs/xfs_ioctl32.c | 3831 | 18411 | /*
* Copyright (c) 2004-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/compat.h>
#include <linux/ioctl.h>
#include <linux/mount.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_vnode.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_itable.h"
#include "xfs_error.h"
#include "xfs_dfrag.h"
#include "xfs_vnodeops.h"
#include "xfs_fsops.h"
#include "xfs_alloc.h"
#include "xfs_rtalloc.h"
#include "xfs_attr.h"
#include "xfs_ioctl.h"
#include "xfs_ioctl32.h"
#include "xfs_trace.h"
#define _NATIVE_IOC(cmd, type) \
_IOC(_IOC_DIR(cmd), _IOC_TYPE(cmd), _IOC_NR(cmd), sizeof(type))
#ifdef BROKEN_X86_ALIGNMENT
STATIC int
xfs_compat_flock64_copyin(
xfs_flock64_t *bf,
compat_xfs_flock64_t __user *arg32)
{
if (get_user(bf->l_type, &arg32->l_type) ||
get_user(bf->l_whence, &arg32->l_whence) ||
get_user(bf->l_start, &arg32->l_start) ||
get_user(bf->l_len, &arg32->l_len) ||
get_user(bf->l_sysid, &arg32->l_sysid) ||
get_user(bf->l_pid, &arg32->l_pid) ||
copy_from_user(bf->l_pad, &arg32->l_pad, 4*sizeof(u32)))
return -XFS_ERROR(EFAULT);
return 0;
}
STATIC int
xfs_compat_ioc_fsgeometry_v1(
struct xfs_mount *mp,
compat_xfs_fsop_geom_v1_t __user *arg32)
{
xfs_fsop_geom_t fsgeo;
int error;
error = xfs_fs_geometry(mp, &fsgeo, 3);
if (error)
return -error;
/* The 32-bit variant simply has some padding at the end */
if (copy_to_user(arg32, &fsgeo, sizeof(struct compat_xfs_fsop_geom_v1)))
return -XFS_ERROR(EFAULT);
return 0;
}
STATIC int
xfs_compat_growfs_data_copyin(
struct xfs_growfs_data *in,
compat_xfs_growfs_data_t __user *arg32)
{
if (get_user(in->newblocks, &arg32->newblocks) ||
get_user(in->imaxpct, &arg32->imaxpct))
return -XFS_ERROR(EFAULT);
return 0;
}
STATIC int
xfs_compat_growfs_rt_copyin(
struct xfs_growfs_rt *in,
compat_xfs_growfs_rt_t __user *arg32)
{
if (get_user(in->newblocks, &arg32->newblocks) ||
get_user(in->extsize, &arg32->extsize))
return -XFS_ERROR(EFAULT);
return 0;
}
STATIC int
xfs_inumbers_fmt_compat(
void __user *ubuffer,
const xfs_inogrp_t *buffer,
long count,
long *written)
{
compat_xfs_inogrp_t __user *p32 = ubuffer;
long i;
for (i = 0; i < count; i++) {
if (put_user(buffer[i].xi_startino, &p32[i].xi_startino) ||
put_user(buffer[i].xi_alloccount, &p32[i].xi_alloccount) ||
put_user(buffer[i].xi_allocmask, &p32[i].xi_allocmask))
return -XFS_ERROR(EFAULT);
}
*written = count * sizeof(*p32);
return 0;
}
#else
#define xfs_inumbers_fmt_compat xfs_inumbers_fmt
#endif /* BROKEN_X86_ALIGNMENT */
STATIC int
xfs_ioctl32_bstime_copyin(
xfs_bstime_t *bstime,
compat_xfs_bstime_t __user *bstime32)
{
compat_time_t sec32; /* tv_sec differs on 64 vs. 32 */
if (get_user(sec32, &bstime32->tv_sec) ||
get_user(bstime->tv_nsec, &bstime32->tv_nsec))
return -XFS_ERROR(EFAULT);
bstime->tv_sec = sec32;
return 0;
}
/* xfs_bstat_t has differing alignment on intel, & bstime_t sizes everywhere */
STATIC int
xfs_ioctl32_bstat_copyin(
xfs_bstat_t *bstat,
compat_xfs_bstat_t __user *bstat32)
{
if (get_user(bstat->bs_ino, &bstat32->bs_ino) ||
get_user(bstat->bs_mode, &bstat32->bs_mode) ||
get_user(bstat->bs_nlink, &bstat32->bs_nlink) ||
get_user(bstat->bs_uid, &bstat32->bs_uid) ||
get_user(bstat->bs_gid, &bstat32->bs_gid) ||
get_user(bstat->bs_rdev, &bstat32->bs_rdev) ||
get_user(bstat->bs_blksize, &bstat32->bs_blksize) ||
get_user(bstat->bs_size, &bstat32->bs_size) ||
xfs_ioctl32_bstime_copyin(&bstat->bs_atime, &bstat32->bs_atime) ||
xfs_ioctl32_bstime_copyin(&bstat->bs_mtime, &bstat32->bs_mtime) ||
xfs_ioctl32_bstime_copyin(&bstat->bs_ctime, &bstat32->bs_ctime) ||
get_user(bstat->bs_blocks, &bstat32->bs_size) ||
get_user(bstat->bs_xflags, &bstat32->bs_size) ||
get_user(bstat->bs_extsize, &bstat32->bs_extsize) ||
get_user(bstat->bs_extents, &bstat32->bs_extents) ||
get_user(bstat->bs_gen, &bstat32->bs_gen) ||
get_user(bstat->bs_projid_lo, &bstat32->bs_projid_lo) ||
get_user(bstat->bs_projid_hi, &bstat32->bs_projid_hi) ||
get_user(bstat->bs_dmevmask, &bstat32->bs_dmevmask) ||
get_user(bstat->bs_dmstate, &bstat32->bs_dmstate) ||
get_user(bstat->bs_aextents, &bstat32->bs_aextents))
return -XFS_ERROR(EFAULT);
return 0;
}
/* XFS_IOC_FSBULKSTAT and friends */
STATIC int
xfs_bstime_store_compat(
compat_xfs_bstime_t __user *p32,
const xfs_bstime_t *p)
{
__s32 sec32;
sec32 = p->tv_sec;
if (put_user(sec32, &p32->tv_sec) ||
put_user(p->tv_nsec, &p32->tv_nsec))
return -XFS_ERROR(EFAULT);
return 0;
}
/* Return 0 on success or positive error (to xfs_bulkstat()) */
STATIC int
xfs_bulkstat_one_fmt_compat(
void __user *ubuffer,
int ubsize,
int *ubused,
const xfs_bstat_t *buffer)
{
compat_xfs_bstat_t __user *p32 = ubuffer;
if (ubsize < sizeof(*p32))
return XFS_ERROR(ENOMEM);
if (put_user(buffer->bs_ino, &p32->bs_ino) ||
put_user(buffer->bs_mode, &p32->bs_mode) ||
put_user(buffer->bs_nlink, &p32->bs_nlink) ||
put_user(buffer->bs_uid, &p32->bs_uid) ||
put_user(buffer->bs_gid, &p32->bs_gid) ||
put_user(buffer->bs_rdev, &p32->bs_rdev) ||
put_user(buffer->bs_blksize, &p32->bs_blksize) ||
put_user(buffer->bs_size, &p32->bs_size) ||
xfs_bstime_store_compat(&p32->bs_atime, &buffer->bs_atime) ||
xfs_bstime_store_compat(&p32->bs_mtime, &buffer->bs_mtime) ||
xfs_bstime_store_compat(&p32->bs_ctime, &buffer->bs_ctime) ||
put_user(buffer->bs_blocks, &p32->bs_blocks) ||
put_user(buffer->bs_xflags, &p32->bs_xflags) ||
put_user(buffer->bs_extsize, &p32->bs_extsize) ||
put_user(buffer->bs_extents, &p32->bs_extents) ||
put_user(buffer->bs_gen, &p32->bs_gen) ||
put_user(buffer->bs_projid, &p32->bs_projid) ||
put_user(buffer->bs_projid_hi, &p32->bs_projid_hi) ||
put_user(buffer->bs_dmevmask, &p32->bs_dmevmask) ||
put_user(buffer->bs_dmstate, &p32->bs_dmstate) ||
put_user(buffer->bs_aextents, &p32->bs_aextents))
return XFS_ERROR(EFAULT);
if (ubused)
*ubused = sizeof(*p32);
return 0;
}
STATIC int
xfs_bulkstat_one_compat(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_ino_t ino, /* inode number to get data for */
void __user *buffer, /* buffer to place output in */
int ubsize, /* size of buffer */
int *ubused, /* bytes used by me */
int *stat) /* BULKSTAT_RV_... */
{
return xfs_bulkstat_one_int(mp, ino, buffer, ubsize,
xfs_bulkstat_one_fmt_compat,
ubused, stat);
}
/* copied from xfs_ioctl.c */
STATIC int
xfs_compat_ioc_bulkstat(
xfs_mount_t *mp,
unsigned int cmd,
compat_xfs_fsop_bulkreq_t __user *p32)
{
u32 addr;
xfs_fsop_bulkreq_t bulkreq;
int count; /* # of records returned */
xfs_ino_t inlast; /* last inode number */
int done;
int error;
/* done = 1 if there are more stats to get and if bulkstat */
/* should be called again (unused here, but used in dmapi) */
if (!capable(CAP_SYS_ADMIN))
return -XFS_ERROR(EPERM);
if (XFS_FORCED_SHUTDOWN(mp))
return -XFS_ERROR(EIO);
if (get_user(addr, &p32->lastip))
return -XFS_ERROR(EFAULT);
bulkreq.lastip = compat_ptr(addr);
if (get_user(bulkreq.icount, &p32->icount) ||
get_user(addr, &p32->ubuffer))
return -XFS_ERROR(EFAULT);
bulkreq.ubuffer = compat_ptr(addr);
if (get_user(addr, &p32->ocount))
return -XFS_ERROR(EFAULT);
bulkreq.ocount = compat_ptr(addr);
if (copy_from_user(&inlast, bulkreq.lastip, sizeof(__s64)))
return -XFS_ERROR(EFAULT);
if ((count = bulkreq.icount) <= 0)
return -XFS_ERROR(EINVAL);
if (bulkreq.ubuffer == NULL)
return -XFS_ERROR(EINVAL);
if (cmd == XFS_IOC_FSINUMBERS_32) {
error = xfs_inumbers(mp, &inlast, &count,
bulkreq.ubuffer, xfs_inumbers_fmt_compat);
} else if (cmd == XFS_IOC_FSBULKSTAT_SINGLE_32) {
int res;
error = xfs_bulkstat_one_compat(mp, inlast, bulkreq.ubuffer,
sizeof(compat_xfs_bstat_t), NULL, &res);
} else if (cmd == XFS_IOC_FSBULKSTAT_32) {
error = xfs_bulkstat(mp, &inlast, &count,
xfs_bulkstat_one_compat, sizeof(compat_xfs_bstat_t),
bulkreq.ubuffer, &done);
} else
error = XFS_ERROR(EINVAL);
if (error)
return -error;
if (bulkreq.ocount != NULL) {
if (copy_to_user(bulkreq.lastip, &inlast,
sizeof(xfs_ino_t)))
return -XFS_ERROR(EFAULT);
if (copy_to_user(bulkreq.ocount, &count, sizeof(count)))
return -XFS_ERROR(EFAULT);
}
return 0;
}
STATIC int
xfs_compat_handlereq_copyin(
xfs_fsop_handlereq_t *hreq,
compat_xfs_fsop_handlereq_t __user *arg32)
{
compat_xfs_fsop_handlereq_t hreq32;
if (copy_from_user(&hreq32, arg32, sizeof(compat_xfs_fsop_handlereq_t)))
return -XFS_ERROR(EFAULT);
hreq->fd = hreq32.fd;
hreq->path = compat_ptr(hreq32.path);
hreq->oflags = hreq32.oflags;
hreq->ihandle = compat_ptr(hreq32.ihandle);
hreq->ihandlen = hreq32.ihandlen;
hreq->ohandle = compat_ptr(hreq32.ohandle);
hreq->ohandlen = compat_ptr(hreq32.ohandlen);
return 0;
}
STATIC struct dentry *
xfs_compat_handlereq_to_dentry(
struct file *parfilp,
compat_xfs_fsop_handlereq_t *hreq)
{
return xfs_handle_to_dentry(parfilp,
compat_ptr(hreq->ihandle), hreq->ihandlen);
}
STATIC int
xfs_compat_attrlist_by_handle(
struct file *parfilp,
void __user *arg)
{
int error;
attrlist_cursor_kern_t *cursor;
compat_xfs_fsop_attrlist_handlereq_t al_hreq;
struct dentry *dentry;
char *kbuf;
if (!capable(CAP_SYS_ADMIN))
return -XFS_ERROR(EPERM);
if (copy_from_user(&al_hreq, arg,
sizeof(compat_xfs_fsop_attrlist_handlereq_t)))
return -XFS_ERROR(EFAULT);
if (al_hreq.buflen > XATTR_LIST_MAX)
return -XFS_ERROR(EINVAL);
/*
* Reject flags, only allow namespaces.
*/
if (al_hreq.flags & ~(ATTR_ROOT | ATTR_SECURE))
return -XFS_ERROR(EINVAL);
dentry = xfs_compat_handlereq_to_dentry(parfilp, &al_hreq.hreq);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
error = -ENOMEM;
kbuf = kmalloc(al_hreq.buflen, GFP_KERNEL);
if (!kbuf)
goto out_dput;
cursor = (attrlist_cursor_kern_t *)&al_hreq.pos;
error = -xfs_attr_list(XFS_I(dentry->d_inode), kbuf, al_hreq.buflen,
al_hreq.flags, cursor);
if (error)
goto out_kfree;
if (copy_to_user(compat_ptr(al_hreq.buffer), kbuf, al_hreq.buflen))
error = -EFAULT;
out_kfree:
kfree(kbuf);
out_dput:
dput(dentry);
return error;
}
STATIC int
xfs_compat_attrmulti_by_handle(
struct file *parfilp,
void __user *arg)
{
int error;
compat_xfs_attr_multiop_t *ops;
compat_xfs_fsop_attrmulti_handlereq_t am_hreq;
struct dentry *dentry;
unsigned int i, size;
unsigned char *attr_name;
if (!capable(CAP_SYS_ADMIN))
return -XFS_ERROR(EPERM);
if (copy_from_user(&am_hreq, arg,
sizeof(compat_xfs_fsop_attrmulti_handlereq_t)))
return -XFS_ERROR(EFAULT);
/* overflow check */
if (am_hreq.opcount >= INT_MAX / sizeof(compat_xfs_attr_multiop_t))
return -E2BIG;
dentry = xfs_compat_handlereq_to_dentry(parfilp, &am_hreq.hreq);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
error = E2BIG;
size = am_hreq.opcount * sizeof(compat_xfs_attr_multiop_t);
if (!size || size > 16 * PAGE_SIZE)
goto out_dput;
ops = memdup_user(compat_ptr(am_hreq.ops), size);
if (IS_ERR(ops)) {
error = PTR_ERR(ops);
goto out_dput;
}
attr_name = kmalloc(MAXNAMELEN, GFP_KERNEL);
if (!attr_name)
goto out_kfree_ops;
error = 0;
for (i = 0; i < am_hreq.opcount; i++) {
ops[i].am_error = strncpy_from_user((char *)attr_name,
compat_ptr(ops[i].am_attrname),
MAXNAMELEN);
if (ops[i].am_error == 0 || ops[i].am_error == MAXNAMELEN)
error = -ERANGE;
if (ops[i].am_error < 0)
break;
switch (ops[i].am_opcode) {
case ATTR_OP_GET:
ops[i].am_error = xfs_attrmulti_attr_get(
dentry->d_inode, attr_name,
compat_ptr(ops[i].am_attrvalue),
&ops[i].am_length, ops[i].am_flags);
break;
case ATTR_OP_SET:
ops[i].am_error = mnt_want_write_file(parfilp);
if (ops[i].am_error)
break;
ops[i].am_error = xfs_attrmulti_attr_set(
dentry->d_inode, attr_name,
compat_ptr(ops[i].am_attrvalue),
ops[i].am_length, ops[i].am_flags);
mnt_drop_write_file(parfilp);
break;
case ATTR_OP_REMOVE:
ops[i].am_error = mnt_want_write_file(parfilp);
if (ops[i].am_error)
break;
ops[i].am_error = xfs_attrmulti_attr_remove(
dentry->d_inode, attr_name,
ops[i].am_flags);
mnt_drop_write_file(parfilp);
break;
default:
ops[i].am_error = EINVAL;
}
}
if (copy_to_user(compat_ptr(am_hreq.ops), ops, size))
error = XFS_ERROR(EFAULT);
kfree(attr_name);
out_kfree_ops:
kfree(ops);
out_dput:
dput(dentry);
return -error;
}
STATIC int
xfs_compat_fssetdm_by_handle(
struct file *parfilp,
void __user *arg)
{
int error;
struct fsdmidata fsd;
compat_xfs_fsop_setdm_handlereq_t dmhreq;
struct dentry *dentry;
if (!capable(CAP_MKNOD))
return -XFS_ERROR(EPERM);
if (copy_from_user(&dmhreq, arg,
sizeof(compat_xfs_fsop_setdm_handlereq_t)))
return -XFS_ERROR(EFAULT);
dentry = xfs_compat_handlereq_to_dentry(parfilp, &dmhreq.hreq);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (IS_IMMUTABLE(dentry->d_inode) || IS_APPEND(dentry->d_inode)) {
error = -XFS_ERROR(EPERM);
goto out;
}
if (copy_from_user(&fsd, compat_ptr(dmhreq.data), sizeof(fsd))) {
error = -XFS_ERROR(EFAULT);
goto out;
}
error = -xfs_set_dmattrs(XFS_I(dentry->d_inode), fsd.fsd_dmevmask,
fsd.fsd_dmstate);
out:
dput(dentry);
return error;
}
long
xfs_file_compat_ioctl(
struct file *filp,
unsigned cmd,
unsigned long p)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct xfs_inode *ip = XFS_I(inode);
struct xfs_mount *mp = ip->i_mount;
void __user *arg = (void __user *)p;
int ioflags = 0;
int error;
if (filp->f_mode & FMODE_NOCMTIME)
ioflags |= IO_INVIS;
trace_xfs_file_compat_ioctl(ip);
switch (cmd) {
/* No size or alignment issues on any arch */
case XFS_IOC_DIOINFO:
case XFS_IOC_FSGEOMETRY:
case XFS_IOC_FSGETXATTR:
case XFS_IOC_FSSETXATTR:
case XFS_IOC_FSGETXATTRA:
case XFS_IOC_FSSETDM:
case XFS_IOC_GETBMAP:
case XFS_IOC_GETBMAPA:
case XFS_IOC_GETBMAPX:
case XFS_IOC_FSCOUNTS:
case XFS_IOC_SET_RESBLKS:
case XFS_IOC_GET_RESBLKS:
case XFS_IOC_FSGROWFSLOG:
case XFS_IOC_GOINGDOWN:
case XFS_IOC_ERROR_INJECTION:
case XFS_IOC_ERROR_CLEARALL:
return xfs_file_ioctl(filp, cmd, p);
#ifndef BROKEN_X86_ALIGNMENT
/* These are handled fine if no alignment issues */
case XFS_IOC_ALLOCSP:
case XFS_IOC_FREESP:
case XFS_IOC_RESVSP:
case XFS_IOC_UNRESVSP:
case XFS_IOC_ALLOCSP64:
case XFS_IOC_FREESP64:
case XFS_IOC_RESVSP64:
case XFS_IOC_UNRESVSP64:
case XFS_IOC_FSGEOMETRY_V1:
case XFS_IOC_FSGROWFSDATA:
case XFS_IOC_FSGROWFSRT:
case XFS_IOC_ZERO_RANGE:
return xfs_file_ioctl(filp, cmd, p);
#else
case XFS_IOC_ALLOCSP_32:
case XFS_IOC_FREESP_32:
case XFS_IOC_ALLOCSP64_32:
case XFS_IOC_FREESP64_32:
case XFS_IOC_RESVSP_32:
case XFS_IOC_UNRESVSP_32:
case XFS_IOC_RESVSP64_32:
case XFS_IOC_UNRESVSP64_32:
case XFS_IOC_ZERO_RANGE_32: {
struct xfs_flock64 bf;
if (xfs_compat_flock64_copyin(&bf, arg))
return -XFS_ERROR(EFAULT);
cmd = _NATIVE_IOC(cmd, struct xfs_flock64);
return xfs_ioc_space(ip, inode, filp, ioflags, cmd, &bf);
}
case XFS_IOC_FSGEOMETRY_V1_32:
return xfs_compat_ioc_fsgeometry_v1(mp, arg);
case XFS_IOC_FSGROWFSDATA_32: {
struct xfs_growfs_data in;
if (xfs_compat_growfs_data_copyin(&in, arg))
return -XFS_ERROR(EFAULT);
error = xfs_growfs_data(mp, &in);
return -error;
}
case XFS_IOC_FSGROWFSRT_32: {
struct xfs_growfs_rt in;
if (xfs_compat_growfs_rt_copyin(&in, arg))
return -XFS_ERROR(EFAULT);
error = xfs_growfs_rt(mp, &in);
return -error;
}
#endif
/* long changes size, but xfs only copiese out 32 bits */
case XFS_IOC_GETXFLAGS_32:
case XFS_IOC_SETXFLAGS_32:
case XFS_IOC_GETVERSION_32:
cmd = _NATIVE_IOC(cmd, long);
return xfs_file_ioctl(filp, cmd, p);
case XFS_IOC_SWAPEXT_32: {
struct xfs_swapext sxp;
struct compat_xfs_swapext __user *sxu = arg;
/* Bulk copy in up to the sx_stat field, then copy bstat */
if (copy_from_user(&sxp, sxu,
offsetof(struct xfs_swapext, sx_stat)) ||
xfs_ioctl32_bstat_copyin(&sxp.sx_stat, &sxu->sx_stat))
return -XFS_ERROR(EFAULT);
error = xfs_swapext(&sxp);
return -error;
}
case XFS_IOC_FSBULKSTAT_32:
case XFS_IOC_FSBULKSTAT_SINGLE_32:
case XFS_IOC_FSINUMBERS_32:
return xfs_compat_ioc_bulkstat(mp, cmd, arg);
case XFS_IOC_FD_TO_HANDLE_32:
case XFS_IOC_PATH_TO_HANDLE_32:
case XFS_IOC_PATH_TO_FSHANDLE_32: {
struct xfs_fsop_handlereq hreq;
if (xfs_compat_handlereq_copyin(&hreq, arg))
return -XFS_ERROR(EFAULT);
cmd = _NATIVE_IOC(cmd, struct xfs_fsop_handlereq);
return xfs_find_handle(cmd, &hreq);
}
case XFS_IOC_OPEN_BY_HANDLE_32: {
struct xfs_fsop_handlereq hreq;
if (xfs_compat_handlereq_copyin(&hreq, arg))
return -XFS_ERROR(EFAULT);
return xfs_open_by_handle(filp, &hreq);
}
case XFS_IOC_READLINK_BY_HANDLE_32: {
struct xfs_fsop_handlereq hreq;
if (xfs_compat_handlereq_copyin(&hreq, arg))
return -XFS_ERROR(EFAULT);
return xfs_readlink_by_handle(filp, &hreq);
}
case XFS_IOC_ATTRLIST_BY_HANDLE_32:
return xfs_compat_attrlist_by_handle(filp, arg);
case XFS_IOC_ATTRMULTI_BY_HANDLE_32:
return xfs_compat_attrmulti_by_handle(filp, arg);
case XFS_IOC_FSSETDM_BY_HANDLE_32:
return xfs_compat_fssetdm_by_handle(filp, arg);
default:
return -XFS_ERROR(ENOIOCTLCMD);
}
}
| gpl-2.0 |
bio4554/ker.nl | drivers/net/can/usb/peak_usb/pcan_usb.c | 4087 | 20350 | /*
* CAN driver for PEAK System PCAN-USB adapter
* Derived from the PCAN project file driver/src/pcan_usb.c
*
* Copyright (C) 2003-2010 PEAK System-Technik GmbH
* Copyright (C) 2011-2012 Stephane Grosjean <s.grosjean@peak-system.com>
*
* Many thanks to Klaus Hitschler <klaus.hitschler@gmx.de>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published
* by the Free Software Foundation; 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/netdevice.h>
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include "pcan_usb_core.h"
MODULE_SUPPORTED_DEVICE("PEAK-System PCAN-USB adapter");
/* PCAN-USB Endpoints */
#define PCAN_USB_EP_CMDOUT 1
#define PCAN_USB_EP_CMDIN (PCAN_USB_EP_CMDOUT | USB_DIR_IN)
#define PCAN_USB_EP_MSGOUT 2
#define PCAN_USB_EP_MSGIN (PCAN_USB_EP_MSGOUT | USB_DIR_IN)
/* PCAN-USB command struct */
#define PCAN_USB_CMD_FUNC 0
#define PCAN_USB_CMD_NUM 1
#define PCAN_USB_CMD_ARGS 2
#define PCAN_USB_CMD_ARGS_LEN 14
#define PCAN_USB_CMD_LEN (PCAN_USB_CMD_ARGS + \
PCAN_USB_CMD_ARGS_LEN)
/* PCAN-USB command timeout (ms.) */
#define PCAN_USB_COMMAND_TIMEOUT 1000
/* PCAN-USB startup timeout (ms.) */
#define PCAN_USB_STARTUP_TIMEOUT 10
/* PCAN-USB rx/tx buffers size */
#define PCAN_USB_RX_BUFFER_SIZE 64
#define PCAN_USB_TX_BUFFER_SIZE 64
#define PCAN_USB_MSG_HEADER_LEN 2
/* PCAN-USB adapter internal clock (MHz) */
#define PCAN_USB_CRYSTAL_HZ 16000000
/* PCAN-USB USB message record status/len field */
#define PCAN_USB_STATUSLEN_TIMESTAMP (1 << 7)
#define PCAN_USB_STATUSLEN_INTERNAL (1 << 6)
#define PCAN_USB_STATUSLEN_EXT_ID (1 << 5)
#define PCAN_USB_STATUSLEN_RTR (1 << 4)
#define PCAN_USB_STATUSLEN_DLC (0xf)
/* PCAN-USB error flags */
#define PCAN_USB_ERROR_TXFULL 0x01
#define PCAN_USB_ERROR_RXQOVR 0x02
#define PCAN_USB_ERROR_BUS_LIGHT 0x04
#define PCAN_USB_ERROR_BUS_HEAVY 0x08
#define PCAN_USB_ERROR_BUS_OFF 0x10
#define PCAN_USB_ERROR_RXQEMPTY 0x20
#define PCAN_USB_ERROR_QOVR 0x40
#define PCAN_USB_ERROR_TXQFULL 0x80
/* SJA1000 modes */
#define SJA1000_MODE_NORMAL 0x00
#define SJA1000_MODE_INIT 0x01
/*
* tick duration = 42.666 us =>
* (tick_number * 44739243) >> 20 ~ (tick_number * 42666) / 1000
* accuracy = 10^-7
*/
#define PCAN_USB_TS_DIV_SHIFTER 20
#define PCAN_USB_TS_US_PER_TICK 44739243
/* PCAN-USB messages record types */
#define PCAN_USB_REC_ERROR 1
#define PCAN_USB_REC_ANALOG 2
#define PCAN_USB_REC_BUSLOAD 3
#define PCAN_USB_REC_TS 4
#define PCAN_USB_REC_BUSEVT 5
/* private to PCAN-USB adapter */
struct pcan_usb {
struct peak_usb_device dev;
struct peak_time_ref time_ref;
struct timer_list restart_timer;
};
/* incoming message context for decoding */
struct pcan_usb_msg_context {
u16 ts16;
u8 prev_ts8;
u8 *ptr;
u8 *end;
u8 rec_cnt;
u8 rec_idx;
u8 rec_data_idx;
struct net_device *netdev;
struct pcan_usb *pdev;
};
/*
* send a command
*/
static int pcan_usb_send_cmd(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
{
int err;
int actual_length;
/* usb device unregistered? */
if (!(dev->state & PCAN_USB_STATE_CONNECTED))
return 0;
dev->cmd_buf[PCAN_USB_CMD_FUNC] = f;
dev->cmd_buf[PCAN_USB_CMD_NUM] = n;
if (p)
memcpy(dev->cmd_buf + PCAN_USB_CMD_ARGS,
p, PCAN_USB_CMD_ARGS_LEN);
err = usb_bulk_msg(dev->udev,
usb_sndbulkpipe(dev->udev, PCAN_USB_EP_CMDOUT),
dev->cmd_buf, PCAN_USB_CMD_LEN, &actual_length,
PCAN_USB_COMMAND_TIMEOUT);
if (err)
netdev_err(dev->netdev,
"sending cmd f=0x%x n=0x%x failure: %d\n",
f, n, err);
return err;
}
/*
* send a command then wait for its response
*/
static int pcan_usb_wait_rsp(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
{
int err;
int actual_length;
/* usb device unregistered? */
if (!(dev->state & PCAN_USB_STATE_CONNECTED))
return 0;
/* first, send command */
err = pcan_usb_send_cmd(dev, f, n, NULL);
if (err)
return err;
err = usb_bulk_msg(dev->udev,
usb_rcvbulkpipe(dev->udev, PCAN_USB_EP_CMDIN),
dev->cmd_buf, PCAN_USB_CMD_LEN, &actual_length,
PCAN_USB_COMMAND_TIMEOUT);
if (err)
netdev_err(dev->netdev,
"waiting rsp f=0x%x n=0x%x failure: %d\n", f, n, err);
else if (p)
memcpy(p, dev->cmd_buf + PCAN_USB_CMD_ARGS,
PCAN_USB_CMD_ARGS_LEN);
return err;
}
static int pcan_usb_set_sja1000(struct peak_usb_device *dev, u8 mode)
{
u8 args[PCAN_USB_CMD_ARGS_LEN] = {
[1] = mode,
};
return pcan_usb_send_cmd(dev, 9, 2, args);
}
static int pcan_usb_set_bus(struct peak_usb_device *dev, u8 onoff)
{
u8 args[PCAN_USB_CMD_ARGS_LEN] = {
[0] = !!onoff,
};
return pcan_usb_send_cmd(dev, 3, 2, args);
}
static int pcan_usb_set_silent(struct peak_usb_device *dev, u8 onoff)
{
u8 args[PCAN_USB_CMD_ARGS_LEN] = {
[0] = !!onoff,
};
return pcan_usb_send_cmd(dev, 3, 3, args);
}
static int pcan_usb_set_ext_vcc(struct peak_usb_device *dev, u8 onoff)
{
u8 args[PCAN_USB_CMD_ARGS_LEN] = {
[0] = !!onoff,
};
return pcan_usb_send_cmd(dev, 10, 2, args);
}
/*
* set bittiming value to can
*/
static int pcan_usb_set_bittiming(struct peak_usb_device *dev,
struct can_bittiming *bt)
{
u8 args[PCAN_USB_CMD_ARGS_LEN];
u8 btr0, btr1;
btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
(((bt->phase_seg2 - 1) & 0x7) << 4);
if (dev->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
btr1 |= 0x80;
netdev_info(dev->netdev, "setting BTR0=0x%02x BTR1=0x%02x\n",
btr0, btr1);
args[0] = btr1;
args[1] = btr0;
return pcan_usb_send_cmd(dev, 1, 2, args);
}
/*
* init/reset can
*/
static int pcan_usb_write_mode(struct peak_usb_device *dev, u8 onoff)
{
int err;
err = pcan_usb_set_bus(dev, onoff);
if (err)
return err;
if (!onoff) {
err = pcan_usb_set_sja1000(dev, SJA1000_MODE_INIT);
} else {
/* the PCAN-USB needs time to init */
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(msecs_to_jiffies(PCAN_USB_STARTUP_TIMEOUT));
}
return err;
}
/*
* handle end of waiting for the device to reset
*/
static void pcan_usb_restart(unsigned long arg)
{
/* notify candev and netdev */
peak_usb_restart_complete((struct peak_usb_device *)arg);
}
/*
* handle the submission of the restart urb
*/
static void pcan_usb_restart_pending(struct urb *urb)
{
struct pcan_usb *pdev = urb->context;
/* the PCAN-USB needs time to restart */
mod_timer(&pdev->restart_timer,
jiffies + msecs_to_jiffies(PCAN_USB_STARTUP_TIMEOUT));
/* can delete usb resources */
peak_usb_async_complete(urb);
}
/*
* handle asynchronous restart
*/
static int pcan_usb_restart_async(struct peak_usb_device *dev, struct urb *urb,
u8 *buf)
{
struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
if (timer_pending(&pdev->restart_timer))
return -EBUSY;
/* set bus on */
buf[PCAN_USB_CMD_FUNC] = 3;
buf[PCAN_USB_CMD_NUM] = 2;
buf[PCAN_USB_CMD_ARGS] = 1;
usb_fill_bulk_urb(urb, dev->udev,
usb_sndbulkpipe(dev->udev, PCAN_USB_EP_CMDOUT),
buf, PCAN_USB_CMD_LEN,
pcan_usb_restart_pending, pdev);
return usb_submit_urb(urb, GFP_ATOMIC);
}
/*
* read serial number from device
*/
static int pcan_usb_get_serial(struct peak_usb_device *dev, u32 *serial_number)
{
u8 args[PCAN_USB_CMD_ARGS_LEN];
int err;
err = pcan_usb_wait_rsp(dev, 6, 1, args);
if (err) {
netdev_err(dev->netdev, "getting serial failure: %d\n", err);
} else if (serial_number) {
u32 tmp32;
memcpy(&tmp32, args, 4);
*serial_number = le32_to_cpu(tmp32);
}
return err;
}
/*
* read device id from device
*/
static int pcan_usb_get_device_id(struct peak_usb_device *dev, u32 *device_id)
{
u8 args[PCAN_USB_CMD_ARGS_LEN];
int err;
err = pcan_usb_wait_rsp(dev, 4, 1, args);
if (err)
netdev_err(dev->netdev, "getting device id failure: %d\n", err);
else if (device_id)
*device_id = args[0];
return err;
}
/*
* update current time ref with received timestamp
*/
static int pcan_usb_update_ts(struct pcan_usb_msg_context *mc)
{
u16 tmp16;
if ((mc->ptr+2) > mc->end)
return -EINVAL;
memcpy(&tmp16, mc->ptr, 2);
mc->ts16 = le16_to_cpu(tmp16);
if (mc->rec_idx > 0)
peak_usb_update_ts_now(&mc->pdev->time_ref, mc->ts16);
else
peak_usb_set_ts_now(&mc->pdev->time_ref, mc->ts16);
return 0;
}
/*
* decode received timestamp
*/
static int pcan_usb_decode_ts(struct pcan_usb_msg_context *mc, u8 first_packet)
{
/* only 1st packet supplies a word timestamp */
if (first_packet) {
u16 tmp16;
if ((mc->ptr + 2) > mc->end)
return -EINVAL;
memcpy(&tmp16, mc->ptr, 2);
mc->ptr += 2;
mc->ts16 = le16_to_cpu(tmp16);
mc->prev_ts8 = mc->ts16 & 0x00ff;
} else {
u8 ts8;
if ((mc->ptr + 1) > mc->end)
return -EINVAL;
ts8 = *mc->ptr++;
if (ts8 < mc->prev_ts8)
mc->ts16 += 0x100;
mc->ts16 &= 0xff00;
mc->ts16 |= ts8;
mc->prev_ts8 = ts8;
}
return 0;
}
static int pcan_usb_decode_error(struct pcan_usb_msg_context *mc, u8 n,
u8 status_len)
{
struct sk_buff *skb;
struct can_frame *cf;
struct timeval tv;
enum can_state new_state;
/* ignore this error until 1st ts received */
if (n == PCAN_USB_ERROR_QOVR)
if (!mc->pdev->time_ref.tick_count)
return 0;
new_state = mc->pdev->dev.can.state;
switch (mc->pdev->dev.can.state) {
case CAN_STATE_ERROR_ACTIVE:
if (n & PCAN_USB_ERROR_BUS_LIGHT) {
new_state = CAN_STATE_ERROR_WARNING;
break;
}
case CAN_STATE_ERROR_WARNING:
if (n & PCAN_USB_ERROR_BUS_HEAVY) {
new_state = CAN_STATE_ERROR_PASSIVE;
break;
}
if (n & PCAN_USB_ERROR_BUS_OFF) {
new_state = CAN_STATE_BUS_OFF;
break;
}
if (n & (PCAN_USB_ERROR_RXQOVR | PCAN_USB_ERROR_QOVR)) {
/*
* trick to bypass next comparison and process other
* errors
*/
new_state = CAN_STATE_MAX;
break;
}
if ((n & PCAN_USB_ERROR_BUS_LIGHT) == 0) {
/* no error (back to active state) */
mc->pdev->dev.can.state = CAN_STATE_ERROR_ACTIVE;
return 0;
}
break;
case CAN_STATE_ERROR_PASSIVE:
if (n & PCAN_USB_ERROR_BUS_OFF) {
new_state = CAN_STATE_BUS_OFF;
break;
}
if (n & PCAN_USB_ERROR_BUS_LIGHT) {
new_state = CAN_STATE_ERROR_WARNING;
break;
}
if (n & (PCAN_USB_ERROR_RXQOVR | PCAN_USB_ERROR_QOVR)) {
/*
* trick to bypass next comparison and process other
* errors
*/
new_state = CAN_STATE_MAX;
break;
}
if ((n & PCAN_USB_ERROR_BUS_HEAVY) == 0) {
/* no error (back to active state) */
mc->pdev->dev.can.state = CAN_STATE_ERROR_ACTIVE;
return 0;
}
break;
default:
/* do nothing waiting for restart */
return 0;
}
/* donot post any error if current state didn't change */
if (mc->pdev->dev.can.state == new_state)
return 0;
/* allocate an skb to store the error frame */
skb = alloc_can_err_skb(mc->netdev, &cf);
if (!skb)
return -ENOMEM;
switch (new_state) {
case CAN_STATE_BUS_OFF:
cf->can_id |= CAN_ERR_BUSOFF;
can_bus_off(mc->netdev);
break;
case CAN_STATE_ERROR_PASSIVE:
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] |= CAN_ERR_CRTL_TX_PASSIVE |
CAN_ERR_CRTL_RX_PASSIVE;
mc->pdev->dev.can.can_stats.error_passive++;
break;
case CAN_STATE_ERROR_WARNING:
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] |= CAN_ERR_CRTL_TX_WARNING |
CAN_ERR_CRTL_RX_WARNING;
mc->pdev->dev.can.can_stats.error_warning++;
break;
default:
/* CAN_STATE_MAX (trick to handle other errors) */
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
mc->netdev->stats.rx_over_errors++;
mc->netdev->stats.rx_errors++;
new_state = mc->pdev->dev.can.state;
break;
}
mc->pdev->dev.can.state = new_state;
if (status_len & PCAN_USB_STATUSLEN_TIMESTAMP) {
struct skb_shared_hwtstamps *hwts = skb_hwtstamps(skb);
peak_usb_get_ts_tv(&mc->pdev->time_ref, mc->ts16, &tv);
hwts->hwtstamp = timeval_to_ktime(tv);
}
netif_rx(skb);
mc->netdev->stats.rx_packets++;
mc->netdev->stats.rx_bytes += cf->can_dlc;
return 0;
}
/*
* decode non-data usb message
*/
static int pcan_usb_decode_status(struct pcan_usb_msg_context *mc,
u8 status_len)
{
u8 rec_len = status_len & PCAN_USB_STATUSLEN_DLC;
u8 f, n;
int err;
/* check whether function and number can be read */
if ((mc->ptr + 2) > mc->end)
return -EINVAL;
f = mc->ptr[PCAN_USB_CMD_FUNC];
n = mc->ptr[PCAN_USB_CMD_NUM];
mc->ptr += PCAN_USB_CMD_ARGS;
if (status_len & PCAN_USB_STATUSLEN_TIMESTAMP) {
int err = pcan_usb_decode_ts(mc, !mc->rec_idx);
if (err)
return err;
}
switch (f) {
case PCAN_USB_REC_ERROR:
err = pcan_usb_decode_error(mc, n, status_len);
if (err)
return err;
break;
case PCAN_USB_REC_ANALOG:
/* analog values (ignored) */
rec_len = 2;
break;
case PCAN_USB_REC_BUSLOAD:
/* bus load (ignored) */
rec_len = 1;
break;
case PCAN_USB_REC_TS:
/* only timestamp */
if (pcan_usb_update_ts(mc))
return -EINVAL;
break;
case PCAN_USB_REC_BUSEVT:
/* error frame/bus event */
if (n & PCAN_USB_ERROR_TXQFULL)
netdev_dbg(mc->netdev, "device Tx queue full)\n");
break;
default:
netdev_err(mc->netdev, "unexpected function %u\n", f);
break;
}
if ((mc->ptr + rec_len) > mc->end)
return -EINVAL;
mc->ptr += rec_len;
return 0;
}
/*
* decode data usb message
*/
static int pcan_usb_decode_data(struct pcan_usb_msg_context *mc, u8 status_len)
{
u8 rec_len = status_len & PCAN_USB_STATUSLEN_DLC;
struct sk_buff *skb;
struct can_frame *cf;
struct timeval tv;
struct skb_shared_hwtstamps *hwts;
skb = alloc_can_skb(mc->netdev, &cf);
if (!skb)
return -ENOMEM;
if (status_len & PCAN_USB_STATUSLEN_EXT_ID) {
u32 tmp32;
if ((mc->ptr + 4) > mc->end)
goto decode_failed;
memcpy(&tmp32, mc->ptr, 4);
mc->ptr += 4;
cf->can_id = le32_to_cpu(tmp32 >> 3) | CAN_EFF_FLAG;
} else {
u16 tmp16;
if ((mc->ptr + 2) > mc->end)
goto decode_failed;
memcpy(&tmp16, mc->ptr, 2);
mc->ptr += 2;
cf->can_id = le16_to_cpu(tmp16 >> 5);
}
cf->can_dlc = get_can_dlc(rec_len);
/* first data packet timestamp is a word */
if (pcan_usb_decode_ts(mc, !mc->rec_data_idx))
goto decode_failed;
/* read data */
memset(cf->data, 0x0, sizeof(cf->data));
if (status_len & PCAN_USB_STATUSLEN_RTR) {
cf->can_id |= CAN_RTR_FLAG;
} else {
if ((mc->ptr + rec_len) > mc->end)
goto decode_failed;
memcpy(cf->data, mc->ptr, cf->can_dlc);
mc->ptr += rec_len;
}
/* convert timestamp into kernel time */
peak_usb_get_ts_tv(&mc->pdev->time_ref, mc->ts16, &tv);
hwts = skb_hwtstamps(skb);
hwts->hwtstamp = timeval_to_ktime(tv);
/* push the skb */
netif_rx(skb);
/* update statistics */
mc->netdev->stats.rx_packets++;
mc->netdev->stats.rx_bytes += cf->can_dlc;
return 0;
decode_failed:
dev_kfree_skb(skb);
return -EINVAL;
}
/*
* process incoming message
*/
static int pcan_usb_decode_msg(struct peak_usb_device *dev, u8 *ibuf, u32 lbuf)
{
struct pcan_usb_msg_context mc = {
.rec_cnt = ibuf[1],
.ptr = ibuf + PCAN_USB_MSG_HEADER_LEN,
.end = ibuf + lbuf,
.netdev = dev->netdev,
.pdev = container_of(dev, struct pcan_usb, dev),
};
int err;
for (err = 0; mc.rec_idx < mc.rec_cnt && !err; mc.rec_idx++) {
u8 sl = *mc.ptr++;
/* handle status and error frames here */
if (sl & PCAN_USB_STATUSLEN_INTERNAL) {
err = pcan_usb_decode_status(&mc, sl);
/* handle normal can frames here */
} else {
err = pcan_usb_decode_data(&mc, sl);
mc.rec_data_idx++;
}
}
return err;
}
/*
* process any incoming buffer
*/
static int pcan_usb_decode_buf(struct peak_usb_device *dev, struct urb *urb)
{
int err = 0;
if (urb->actual_length > PCAN_USB_MSG_HEADER_LEN) {
err = pcan_usb_decode_msg(dev, urb->transfer_buffer,
urb->actual_length);
} else if (urb->actual_length > 0) {
netdev_err(dev->netdev, "usb message length error (%u)\n",
urb->actual_length);
err = -EINVAL;
}
return err;
}
/*
* process outgoing packet
*/
static int pcan_usb_encode_msg(struct peak_usb_device *dev, struct sk_buff *skb,
u8 *obuf, size_t *size)
{
struct net_device *netdev = dev->netdev;
struct net_device_stats *stats = &netdev->stats;
struct can_frame *cf = (struct can_frame *)skb->data;
u8 *pc;
obuf[0] = 2;
obuf[1] = 1;
pc = obuf + PCAN_USB_MSG_HEADER_LEN;
/* status/len byte */
*pc = cf->can_dlc;
if (cf->can_id & CAN_RTR_FLAG)
*pc |= PCAN_USB_STATUSLEN_RTR;
/* can id */
if (cf->can_id & CAN_EFF_FLAG) {
__le32 tmp32 = cpu_to_le32((cf->can_id & CAN_ERR_MASK) << 3);
*pc |= PCAN_USB_STATUSLEN_EXT_ID;
memcpy(++pc, &tmp32, 4);
pc += 4;
} else {
__le16 tmp16 = cpu_to_le16((cf->can_id & CAN_ERR_MASK) << 5);
memcpy(++pc, &tmp16, 2);
pc += 2;
}
/* can data */
if (!(cf->can_id & CAN_RTR_FLAG)) {
memcpy(pc, cf->data, cf->can_dlc);
pc += cf->can_dlc;
}
obuf[(*size)-1] = (u8)(stats->tx_packets & 0xff);
return 0;
}
/*
* start interface
*/
static int pcan_usb_start(struct peak_usb_device *dev)
{
struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
/* number of bits used in timestamps read from adapter struct */
peak_usb_init_time_ref(&pdev->time_ref, &pcan_usb);
/* if revision greater than 3, can put silent mode on/off */
if (dev->device_rev > 3) {
int err;
err = pcan_usb_set_silent(dev,
dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY);
if (err)
return err;
}
return pcan_usb_set_ext_vcc(dev, 0);
}
static int pcan_usb_init(struct peak_usb_device *dev)
{
struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
u32 serial_number;
int err;
/* initialize a timer needed to wait for hardware restart */
init_timer(&pdev->restart_timer);
pdev->restart_timer.function = pcan_usb_restart;
pdev->restart_timer.data = (unsigned long)dev;
/*
* explicit use of dev_xxx() instead of netdev_xxx() here:
* information displayed are related to the device itself, not
* to the canx netdevice.
*/
err = pcan_usb_get_serial(dev, &serial_number);
if (err) {
dev_err(dev->netdev->dev.parent,
"unable to read %s serial number (err %d)\n",
pcan_usb.name, err);
return err;
}
dev_info(dev->netdev->dev.parent,
"PEAK-System %s adapter hwrev %u serial %08X (%u channel)\n",
pcan_usb.name, dev->device_rev, serial_number,
pcan_usb.ctrl_count);
return 0;
}
/*
* probe function for new PCAN-USB usb interface
*/
static int pcan_usb_probe(struct usb_interface *intf)
{
struct usb_host_interface *if_desc;
int i;
if_desc = intf->altsetting;
/* check interface endpoint addresses */
for (i = 0; i < if_desc->desc.bNumEndpoints; i++) {
struct usb_endpoint_descriptor *ep = &if_desc->endpoint[i].desc;
switch (ep->bEndpointAddress) {
case PCAN_USB_EP_CMDOUT:
case PCAN_USB_EP_CMDIN:
case PCAN_USB_EP_MSGOUT:
case PCAN_USB_EP_MSGIN:
break;
default:
return -ENODEV;
}
}
return 0;
}
/*
* describe the PCAN-USB adapter
*/
struct peak_usb_adapter pcan_usb = {
.name = "PCAN-USB",
.device_id = PCAN_USB_PRODUCT_ID,
.ctrl_count = 1,
.clock = {
.freq = PCAN_USB_CRYSTAL_HZ / 2 ,
},
.bittiming_const = {
.name = "pcan_usb",
.tseg1_min = 1,
.tseg1_max = 16,
.tseg2_min = 1,
.tseg2_max = 8,
.sjw_max = 4,
.brp_min = 1,
.brp_max = 64,
.brp_inc = 1,
},
/* size of device private data */
.sizeof_dev_private = sizeof(struct pcan_usb),
/* timestamps usage */
.ts_used_bits = 16,
.ts_period = 24575, /* calibration period in ts. */
.us_per_ts_scale = PCAN_USB_TS_US_PER_TICK, /* us=(ts*scale) */
.us_per_ts_shift = PCAN_USB_TS_DIV_SHIFTER, /* >> shift */
/* give here messages in/out endpoints */
.ep_msg_in = PCAN_USB_EP_MSGIN,
.ep_msg_out = {PCAN_USB_EP_MSGOUT},
/* size of rx/tx usb buffers */
.rx_buffer_size = PCAN_USB_RX_BUFFER_SIZE,
.tx_buffer_size = PCAN_USB_TX_BUFFER_SIZE,
/* device callbacks */
.intf_probe = pcan_usb_probe,
.dev_init = pcan_usb_init,
.dev_set_bus = pcan_usb_write_mode,
.dev_set_bittiming = pcan_usb_set_bittiming,
.dev_get_device_id = pcan_usb_get_device_id,
.dev_decode_buf = pcan_usb_decode_buf,
.dev_encode_msg = pcan_usb_encode_msg,
.dev_start = pcan_usb_start,
.dev_restart_async = pcan_usb_restart_async,
};
| gpl-2.0 |
DirtyUnicorns-Ports/android_kernel_samsung_jf | drivers/acpi/acpica/hwesleep.c | 4855 | 8078 | /******************************************************************************
*
* Name: hwesleep.c - ACPI Hardware Sleep/Wake Support functions for the
* extended FADT-V5 sleep registers.
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#define _COMPONENT ACPI_HARDWARE
ACPI_MODULE_NAME("hwesleep")
/*******************************************************************************
*
* FUNCTION: acpi_hw_execute_sleep_method
*
* PARAMETERS: method_pathname - Pathname of method to execute
* integer_argument - Argument to pass to the method
*
* RETURN: None
*
* DESCRIPTION: Execute a sleep/wake related method with one integer argument
* and no return value.
*
******************************************************************************/
void acpi_hw_execute_sleep_method(char *method_pathname, u32 integer_argument)
{
struct acpi_object_list arg_list;
union acpi_object arg;
acpi_status status;
ACPI_FUNCTION_TRACE(hw_execute_sleep_method);
/* One argument, integer_argument; No return value expected */
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = (u64)integer_argument;
status = acpi_evaluate_object(NULL, method_pathname, &arg_list, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
ACPI_EXCEPTION((AE_INFO, status, "While executing method %s",
method_pathname));
}
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_extended_sleep
*
* PARAMETERS: sleep_state - Which sleep state to enter
* Flags - ACPI_EXECUTE_GTS to run optional method
*
* RETURN: Status
*
* DESCRIPTION: Enter a system sleep state via the extended FADT sleep
* registers (V5 FADT).
* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED
*
******************************************************************************/
acpi_status acpi_hw_extended_sleep(u8 sleep_state, u8 flags)
{
acpi_status status;
u8 sleep_type_value;
u64 sleep_status;
ACPI_FUNCTION_TRACE(hw_extended_sleep);
/* Extended sleep registers must be valid */
if (!acpi_gbl_FADT.sleep_control.address ||
!acpi_gbl_FADT.sleep_status.address) {
return_ACPI_STATUS(AE_NOT_EXIST);
}
/* Clear wake status (WAK_STS) */
status = acpi_write(ACPI_X_WAKE_STATUS, &acpi_gbl_FADT.sleep_status);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
acpi_gbl_system_awake_and_running = FALSE;
/* Optionally execute _GTS (Going To Sleep) */
if (flags & ACPI_EXECUTE_GTS) {
acpi_hw_execute_sleep_method(METHOD_PATHNAME__GTS, sleep_state);
}
/* Flush caches, as per ACPI specification */
ACPI_FLUSH_CPU_CACHE();
/*
* Set the SLP_TYP and SLP_EN bits.
*
* Note: We only use the first value returned by the \_Sx method
* (acpi_gbl_sleep_type_a) - As per ACPI specification.
*/
ACPI_DEBUG_PRINT((ACPI_DB_INIT,
"Entering sleep state [S%u]\n", sleep_state));
sleep_type_value =
((acpi_gbl_sleep_type_a << ACPI_X_SLEEP_TYPE_POSITION) &
ACPI_X_SLEEP_TYPE_MASK);
status = acpi_write((sleep_type_value | ACPI_X_SLEEP_ENABLE),
&acpi_gbl_FADT.sleep_control);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Wait for transition back to Working State */
do {
status = acpi_read(&sleep_status, &acpi_gbl_FADT.sleep_status);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
} while (!(((u8)sleep_status) & ACPI_X_WAKE_STATUS));
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_extended_wake_prep
*
* PARAMETERS: sleep_state - Which sleep state we just exited
* Flags - ACPI_EXECUTE_BFS to run optional method
*
* RETURN: Status
*
* DESCRIPTION: Perform first part of OS-independent ACPI cleanup after
* a sleep. Called with interrupts ENABLED.
*
******************************************************************************/
acpi_status acpi_hw_extended_wake_prep(u8 sleep_state, u8 flags)
{
acpi_status status;
u8 sleep_type_value;
ACPI_FUNCTION_TRACE(hw_extended_wake_prep);
status = acpi_get_sleep_type_data(ACPI_STATE_S0,
&acpi_gbl_sleep_type_a,
&acpi_gbl_sleep_type_b);
if (ACPI_SUCCESS(status)) {
sleep_type_value =
((acpi_gbl_sleep_type_a << ACPI_X_SLEEP_TYPE_POSITION) &
ACPI_X_SLEEP_TYPE_MASK);
(void)acpi_write((sleep_type_value | ACPI_X_SLEEP_ENABLE),
&acpi_gbl_FADT.sleep_control);
}
/* Optionally execute _BFS (Back From Sleep) */
if (flags & ACPI_EXECUTE_BFS) {
acpi_hw_execute_sleep_method(METHOD_PATHNAME__BFS, sleep_state);
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_extended_wake
*
* PARAMETERS: sleep_state - Which sleep state we just exited
* Flags - Reserved, set to zero
*
* RETURN: Status
*
* DESCRIPTION: Perform OS-independent ACPI cleanup after a sleep
* Called with interrupts ENABLED.
*
******************************************************************************/
acpi_status acpi_hw_extended_wake(u8 sleep_state, u8 flags)
{
ACPI_FUNCTION_TRACE(hw_extended_wake);
/* Ensure enter_sleep_state_prep -> enter_sleep_state ordering */
acpi_gbl_sleep_type_a = ACPI_SLEEP_TYPE_INVALID;
/* Execute the wake methods */
acpi_hw_execute_sleep_method(METHOD_PATHNAME__SST, ACPI_SST_WAKING);
acpi_hw_execute_sleep_method(METHOD_PATHNAME__WAK, sleep_state);
/*
* Some BIOS code assumes that WAK_STS will be cleared on resume
* and use it to determine whether the system is rebooting or
* resuming. Clear WAK_STS for compatibility.
*/
(void)acpi_write(ACPI_X_WAKE_STATUS, &acpi_gbl_FADT.sleep_status);
acpi_gbl_system_awake_and_running = TRUE;
acpi_hw_execute_sleep_method(METHOD_PATHNAME__SST, ACPI_SST_WORKING);
return_ACPI_STATUS(AE_OK);
}
| gpl-2.0 |
SubhrajyotiSen/HelioxKernelOnyx | drivers/i2c/i2c-smbus.c | 4855 | 7252 | /*
* i2c-smbus.c - SMBus extensions to the I2C protocol
*
* Copyright (C) 2008 David Brownell
* Copyright (C) 2010 Jean Delvare <khali@linux-fr.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/i2c.h>
#include <linux/i2c-smbus.h>
#include <linux/slab.h>
struct i2c_smbus_alert {
unsigned int alert_edge_triggered:1;
int irq;
struct work_struct alert;
struct i2c_client *ara; /* Alert response address */
};
struct alert_data {
unsigned short addr;
u8 flag:1;
};
/* If this is the alerting device, notify its driver */
static int smbus_do_alert(struct device *dev, void *addrp)
{
struct i2c_client *client = i2c_verify_client(dev);
struct alert_data *data = addrp;
if (!client || client->addr != data->addr)
return 0;
if (client->flags & I2C_CLIENT_TEN)
return 0;
/*
* Drivers should either disable alerts, or provide at least
* a minimal handler. Lock so client->driver won't change.
*/
device_lock(dev);
if (client->driver) {
if (client->driver->alert)
client->driver->alert(client, data->flag);
else
dev_warn(&client->dev, "no driver alert()!\n");
} else
dev_dbg(&client->dev, "alert with no driver\n");
device_unlock(dev);
/* Stop iterating after we find the device */
return -EBUSY;
}
/*
* The alert IRQ handler needs to hand work off to a task which can issue
* SMBus calls, because those sleeping calls can't be made in IRQ context.
*/
static void smbus_alert(struct work_struct *work)
{
struct i2c_smbus_alert *alert;
struct i2c_client *ara;
unsigned short prev_addr = 0; /* Not a valid address */
alert = container_of(work, struct i2c_smbus_alert, alert);
ara = alert->ara;
for (;;) {
s32 status;
struct alert_data data;
/*
* Devices with pending alerts reply in address order, low
* to high, because of slave transmit arbitration. After
* responding, an SMBus device stops asserting SMBALERT#.
*
* Note that SMBus 2.0 reserves 10-bit addresess for future
* use. We neither handle them, nor try to use PEC here.
*/
status = i2c_smbus_read_byte(ara);
if (status < 0)
break;
data.flag = status & 1;
data.addr = status >> 1;
if (data.addr == prev_addr) {
dev_warn(&ara->dev, "Duplicate SMBALERT# from dev "
"0x%02x, skipping\n", data.addr);
break;
}
dev_dbg(&ara->dev, "SMBALERT# from dev 0x%02x, flag %d\n",
data.addr, data.flag);
/* Notify driver for the device which issued the alert */
device_for_each_child(&ara->adapter->dev, &data,
smbus_do_alert);
prev_addr = data.addr;
}
/* We handled all alerts; re-enable level-triggered IRQs */
if (!alert->alert_edge_triggered)
enable_irq(alert->irq);
}
static irqreturn_t smbalert_irq(int irq, void *d)
{
struct i2c_smbus_alert *alert = d;
/* Disable level-triggered IRQs until we handle them */
if (!alert->alert_edge_triggered)
disable_irq_nosync(irq);
schedule_work(&alert->alert);
return IRQ_HANDLED;
}
/* Setup SMBALERT# infrastructure */
static int smbalert_probe(struct i2c_client *ara,
const struct i2c_device_id *id)
{
struct i2c_smbus_alert_setup *setup = ara->dev.platform_data;
struct i2c_smbus_alert *alert;
struct i2c_adapter *adapter = ara->adapter;
int res;
alert = kzalloc(sizeof(struct i2c_smbus_alert), GFP_KERNEL);
if (!alert)
return -ENOMEM;
alert->alert_edge_triggered = setup->alert_edge_triggered;
alert->irq = setup->irq;
INIT_WORK(&alert->alert, smbus_alert);
alert->ara = ara;
if (setup->irq > 0) {
res = devm_request_irq(&ara->dev, setup->irq, smbalert_irq,
0, "smbus_alert", alert);
if (res) {
kfree(alert);
return res;
}
}
i2c_set_clientdata(ara, alert);
dev_info(&adapter->dev, "supports SMBALERT#, %s trigger\n",
setup->alert_edge_triggered ? "edge" : "level");
return 0;
}
/* IRQ resource is managed so it is freed automatically */
static int smbalert_remove(struct i2c_client *ara)
{
struct i2c_smbus_alert *alert = i2c_get_clientdata(ara);
cancel_work_sync(&alert->alert);
kfree(alert);
return 0;
}
static const struct i2c_device_id smbalert_ids[] = {
{ "smbus_alert", 0 },
{ /* LIST END */ }
};
MODULE_DEVICE_TABLE(i2c, smbalert_ids);
static struct i2c_driver smbalert_driver = {
.driver = {
.name = "smbus_alert",
},
.probe = smbalert_probe,
.remove = smbalert_remove,
.id_table = smbalert_ids,
};
/**
* i2c_setup_smbus_alert - Setup SMBus alert support
* @adapter: the target adapter
* @setup: setup data for the SMBus alert handler
* Context: can sleep
*
* Setup handling of the SMBus alert protocol on a given I2C bus segment.
*
* Handling can be done either through our IRQ handler, or by the
* adapter (from its handler, periodic polling, or whatever).
*
* NOTE that if we manage the IRQ, we *MUST* know if it's level or
* edge triggered in order to hand it to the workqueue correctly.
* If triggering the alert seems to wedge the system, you probably
* should have said it's level triggered.
*
* This returns the ara client, which should be saved for later use with
* i2c_handle_smbus_alert() and ultimately i2c_unregister_device(); or NULL
* to indicate an error.
*/
struct i2c_client *i2c_setup_smbus_alert(struct i2c_adapter *adapter,
struct i2c_smbus_alert_setup *setup)
{
struct i2c_board_info ara_board_info = {
I2C_BOARD_INFO("smbus_alert", 0x0c),
.platform_data = setup,
};
return i2c_new_device(adapter, &ara_board_info);
}
EXPORT_SYMBOL_GPL(i2c_setup_smbus_alert);
/**
* i2c_handle_smbus_alert - Handle an SMBus alert
* @ara: the ARA client on the relevant adapter
* Context: can't sleep
*
* Helper function to be called from an I2C bus driver's interrupt
* handler. It will schedule the alert work, in turn calling the
* corresponding I2C device driver's alert function.
*
* It is assumed that ara is a valid i2c client previously returned by
* i2c_setup_smbus_alert().
*/
int i2c_handle_smbus_alert(struct i2c_client *ara)
{
struct i2c_smbus_alert *alert = i2c_get_clientdata(ara);
return schedule_work(&alert->alert);
}
EXPORT_SYMBOL_GPL(i2c_handle_smbus_alert);
static int __init i2c_smbus_init(void)
{
return i2c_add_driver(&smbalert_driver);
}
static void __exit i2c_smbus_exit(void)
{
i2c_del_driver(&smbalert_driver);
}
module_init(i2c_smbus_init);
module_exit(i2c_smbus_exit);
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("SMBus protocol extensions support");
MODULE_LICENSE("GPL");
| gpl-2.0 |
hiikezoe/android_kernel_kyocera_msm8960 | arch/arm/mach-davinci/da850.c | 4855 | 29832 | /*
* TI DA850/OMAP-L138 chip specific setup
*
* Copyright (C) 2009 Texas Instruments Incorporated - http://www.ti.com/
*
* Derived from: arch/arm/mach-davinci/da830.c
* Original Copyrights follow:
*
* 2009 (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/gpio.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/cpufreq.h>
#include <linux/regulator/consumer.h>
#include <asm/mach/map.h>
#include <mach/psc.h>
#include <mach/irqs.h>
#include <mach/cputype.h>
#include <mach/common.h>
#include <mach/time.h>
#include <mach/da8xx.h>
#include <mach/cpufreq.h>
#include <mach/pm.h>
#include <mach/gpio-davinci.h>
#include "clock.h"
#include "mux.h"
/* SoC specific clock flags */
#define DA850_CLK_ASYNC3 BIT(16)
#define DA850_PLL1_BASE 0x01e1a000
#define DA850_TIMER64P2_BASE 0x01f0c000
#define DA850_TIMER64P3_BASE 0x01f0d000
#define DA850_REF_FREQ 24000000
#define CFGCHIP3_ASYNC3_CLKSRC BIT(4)
#define CFGCHIP3_PLL1_MASTER_LOCK BIT(5)
#define CFGCHIP0_PLL_MASTER_LOCK BIT(4)
static int da850_set_armrate(struct clk *clk, unsigned long rate);
static int da850_round_armrate(struct clk *clk, unsigned long rate);
static int da850_set_pll0rate(struct clk *clk, unsigned long armrate);
static struct pll_data pll0_data = {
.num = 1,
.phys_base = DA8XX_PLL0_BASE,
.flags = PLL_HAS_PREDIV | PLL_HAS_POSTDIV,
};
static struct clk ref_clk = {
.name = "ref_clk",
.rate = DA850_REF_FREQ,
.set_rate = davinci_simple_set_rate,
};
static struct clk pll0_clk = {
.name = "pll0",
.parent = &ref_clk,
.pll_data = &pll0_data,
.flags = CLK_PLL,
.set_rate = da850_set_pll0rate,
};
static struct clk pll0_aux_clk = {
.name = "pll0_aux_clk",
.parent = &pll0_clk,
.flags = CLK_PLL | PRE_PLL,
};
static struct clk pll0_sysclk2 = {
.name = "pll0_sysclk2",
.parent = &pll0_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV2,
};
static struct clk pll0_sysclk3 = {
.name = "pll0_sysclk3",
.parent = &pll0_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV3,
.set_rate = davinci_set_sysclk_rate,
.maxrate = 100000000,
};
static struct clk pll0_sysclk4 = {
.name = "pll0_sysclk4",
.parent = &pll0_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV4,
};
static struct clk pll0_sysclk5 = {
.name = "pll0_sysclk5",
.parent = &pll0_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV5,
};
static struct clk pll0_sysclk6 = {
.name = "pll0_sysclk6",
.parent = &pll0_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV6,
};
static struct clk pll0_sysclk7 = {
.name = "pll0_sysclk7",
.parent = &pll0_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV7,
};
static struct pll_data pll1_data = {
.num = 2,
.phys_base = DA850_PLL1_BASE,
.flags = PLL_HAS_POSTDIV,
};
static struct clk pll1_clk = {
.name = "pll1",
.parent = &ref_clk,
.pll_data = &pll1_data,
.flags = CLK_PLL,
};
static struct clk pll1_aux_clk = {
.name = "pll1_aux_clk",
.parent = &pll1_clk,
.flags = CLK_PLL | PRE_PLL,
};
static struct clk pll1_sysclk2 = {
.name = "pll1_sysclk2",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV2,
};
static struct clk pll1_sysclk3 = {
.name = "pll1_sysclk3",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV3,
};
static struct clk i2c0_clk = {
.name = "i2c0",
.parent = &pll0_aux_clk,
};
static struct clk timerp64_0_clk = {
.name = "timer0",
.parent = &pll0_aux_clk,
};
static struct clk timerp64_1_clk = {
.name = "timer1",
.parent = &pll0_aux_clk,
};
static struct clk arm_rom_clk = {
.name = "arm_rom",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_ARM_RAM_ROM,
.flags = ALWAYS_ENABLED,
};
static struct clk tpcc0_clk = {
.name = "tpcc0",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_TPCC,
.flags = ALWAYS_ENABLED | CLK_PSC,
};
static struct clk tptc0_clk = {
.name = "tptc0",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_TPTC0,
.flags = ALWAYS_ENABLED,
};
static struct clk tptc1_clk = {
.name = "tptc1",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_TPTC1,
.flags = ALWAYS_ENABLED,
};
static struct clk tpcc1_clk = {
.name = "tpcc1",
.parent = &pll0_sysclk2,
.lpsc = DA850_LPSC1_TPCC1,
.gpsc = 1,
.flags = CLK_PSC | ALWAYS_ENABLED,
};
static struct clk tptc2_clk = {
.name = "tptc2",
.parent = &pll0_sysclk2,
.lpsc = DA850_LPSC1_TPTC2,
.gpsc = 1,
.flags = ALWAYS_ENABLED,
};
static struct clk uart0_clk = {
.name = "uart0",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_UART0,
};
static struct clk uart1_clk = {
.name = "uart1",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC1_UART1,
.gpsc = 1,
.flags = DA850_CLK_ASYNC3,
};
static struct clk uart2_clk = {
.name = "uart2",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC1_UART2,
.gpsc = 1,
.flags = DA850_CLK_ASYNC3,
};
static struct clk aintc_clk = {
.name = "aintc",
.parent = &pll0_sysclk4,
.lpsc = DA8XX_LPSC0_AINTC,
.flags = ALWAYS_ENABLED,
};
static struct clk gpio_clk = {
.name = "gpio",
.parent = &pll0_sysclk4,
.lpsc = DA8XX_LPSC1_GPIO,
.gpsc = 1,
};
static struct clk i2c1_clk = {
.name = "i2c1",
.parent = &pll0_sysclk4,
.lpsc = DA8XX_LPSC1_I2C,
.gpsc = 1,
};
static struct clk emif3_clk = {
.name = "emif3",
.parent = &pll0_sysclk5,
.lpsc = DA8XX_LPSC1_EMIF3C,
.gpsc = 1,
.flags = ALWAYS_ENABLED,
};
static struct clk arm_clk = {
.name = "arm",
.parent = &pll0_sysclk6,
.lpsc = DA8XX_LPSC0_ARM,
.flags = ALWAYS_ENABLED,
.set_rate = da850_set_armrate,
.round_rate = da850_round_armrate,
};
static struct clk rmii_clk = {
.name = "rmii",
.parent = &pll0_sysclk7,
};
static struct clk emac_clk = {
.name = "emac",
.parent = &pll0_sysclk4,
.lpsc = DA8XX_LPSC1_CPGMAC,
.gpsc = 1,
};
static struct clk mcasp_clk = {
.name = "mcasp",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC1_McASP0,
.gpsc = 1,
.flags = DA850_CLK_ASYNC3,
};
static struct clk lcdc_clk = {
.name = "lcdc",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC1_LCDC,
.gpsc = 1,
};
static struct clk mmcsd0_clk = {
.name = "mmcsd0",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_MMC_SD,
};
static struct clk mmcsd1_clk = {
.name = "mmcsd1",
.parent = &pll0_sysclk2,
.lpsc = DA850_LPSC1_MMC_SD1,
.gpsc = 1,
};
static struct clk aemif_clk = {
.name = "aemif",
.parent = &pll0_sysclk3,
.lpsc = DA8XX_LPSC0_EMIF25,
.flags = ALWAYS_ENABLED,
};
static struct clk usb11_clk = {
.name = "usb11",
.parent = &pll0_sysclk4,
.lpsc = DA8XX_LPSC1_USB11,
.gpsc = 1,
};
static struct clk usb20_clk = {
.name = "usb20",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC1_USB20,
.gpsc = 1,
};
static struct clk spi0_clk = {
.name = "spi0",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC0_SPI0,
};
static struct clk spi1_clk = {
.name = "spi1",
.parent = &pll0_sysclk2,
.lpsc = DA8XX_LPSC1_SPI1,
.gpsc = 1,
.flags = DA850_CLK_ASYNC3,
};
static struct clk sata_clk = {
.name = "sata",
.parent = &pll0_sysclk2,
.lpsc = DA850_LPSC1_SATA,
.gpsc = 1,
.flags = PSC_FORCE,
};
static struct clk_lookup da850_clks[] = {
CLK(NULL, "ref", &ref_clk),
CLK(NULL, "pll0", &pll0_clk),
CLK(NULL, "pll0_aux", &pll0_aux_clk),
CLK(NULL, "pll0_sysclk2", &pll0_sysclk2),
CLK(NULL, "pll0_sysclk3", &pll0_sysclk3),
CLK(NULL, "pll0_sysclk4", &pll0_sysclk4),
CLK(NULL, "pll0_sysclk5", &pll0_sysclk5),
CLK(NULL, "pll0_sysclk6", &pll0_sysclk6),
CLK(NULL, "pll0_sysclk7", &pll0_sysclk7),
CLK(NULL, "pll1", &pll1_clk),
CLK(NULL, "pll1_aux", &pll1_aux_clk),
CLK(NULL, "pll1_sysclk2", &pll1_sysclk2),
CLK(NULL, "pll1_sysclk3", &pll1_sysclk3),
CLK("i2c_davinci.1", NULL, &i2c0_clk),
CLK(NULL, "timer0", &timerp64_0_clk),
CLK("watchdog", NULL, &timerp64_1_clk),
CLK(NULL, "arm_rom", &arm_rom_clk),
CLK(NULL, "tpcc0", &tpcc0_clk),
CLK(NULL, "tptc0", &tptc0_clk),
CLK(NULL, "tptc1", &tptc1_clk),
CLK(NULL, "tpcc1", &tpcc1_clk),
CLK(NULL, "tptc2", &tptc2_clk),
CLK(NULL, "uart0", &uart0_clk),
CLK(NULL, "uart1", &uart1_clk),
CLK(NULL, "uart2", &uart2_clk),
CLK(NULL, "aintc", &aintc_clk),
CLK(NULL, "gpio", &gpio_clk),
CLK("i2c_davinci.2", NULL, &i2c1_clk),
CLK(NULL, "emif3", &emif3_clk),
CLK(NULL, "arm", &arm_clk),
CLK(NULL, "rmii", &rmii_clk),
CLK("davinci_emac.1", NULL, &emac_clk),
CLK("davinci-mcasp.0", NULL, &mcasp_clk),
CLK("da8xx_lcdc.0", NULL, &lcdc_clk),
CLK("davinci_mmc.0", NULL, &mmcsd0_clk),
CLK("davinci_mmc.1", NULL, &mmcsd1_clk),
CLK(NULL, "aemif", &aemif_clk),
CLK(NULL, "usb11", &usb11_clk),
CLK(NULL, "usb20", &usb20_clk),
CLK("spi_davinci.0", NULL, &spi0_clk),
CLK("spi_davinci.1", NULL, &spi1_clk),
CLK("ahci", NULL, &sata_clk),
CLK(NULL, NULL, NULL),
};
/*
* Device specific mux setup
*
* soc description mux mode mode mux dbg
* reg offset mask mode
*/
static const struct mux_config da850_pins[] = {
#ifdef CONFIG_DAVINCI_MUX
/* UART0 function */
MUX_CFG(DA850, NUART0_CTS, 3, 24, 15, 2, false)
MUX_CFG(DA850, NUART0_RTS, 3, 28, 15, 2, false)
MUX_CFG(DA850, UART0_RXD, 3, 16, 15, 2, false)
MUX_CFG(DA850, UART0_TXD, 3, 20, 15, 2, false)
/* UART1 function */
MUX_CFG(DA850, UART1_RXD, 4, 24, 15, 2, false)
MUX_CFG(DA850, UART1_TXD, 4, 28, 15, 2, false)
/* UART2 function */
MUX_CFG(DA850, UART2_RXD, 4, 16, 15, 2, false)
MUX_CFG(DA850, UART2_TXD, 4, 20, 15, 2, false)
/* I2C1 function */
MUX_CFG(DA850, I2C1_SCL, 4, 16, 15, 4, false)
MUX_CFG(DA850, I2C1_SDA, 4, 20, 15, 4, false)
/* I2C0 function */
MUX_CFG(DA850, I2C0_SDA, 4, 12, 15, 2, false)
MUX_CFG(DA850, I2C0_SCL, 4, 8, 15, 2, false)
/* EMAC function */
MUX_CFG(DA850, MII_TXEN, 2, 4, 15, 8, false)
MUX_CFG(DA850, MII_TXCLK, 2, 8, 15, 8, false)
MUX_CFG(DA850, MII_COL, 2, 12, 15, 8, false)
MUX_CFG(DA850, MII_TXD_3, 2, 16, 15, 8, false)
MUX_CFG(DA850, MII_TXD_2, 2, 20, 15, 8, false)
MUX_CFG(DA850, MII_TXD_1, 2, 24, 15, 8, false)
MUX_CFG(DA850, MII_TXD_0, 2, 28, 15, 8, false)
MUX_CFG(DA850, MII_RXCLK, 3, 0, 15, 8, false)
MUX_CFG(DA850, MII_RXDV, 3, 4, 15, 8, false)
MUX_CFG(DA850, MII_RXER, 3, 8, 15, 8, false)
MUX_CFG(DA850, MII_CRS, 3, 12, 15, 8, false)
MUX_CFG(DA850, MII_RXD_3, 3, 16, 15, 8, false)
MUX_CFG(DA850, MII_RXD_2, 3, 20, 15, 8, false)
MUX_CFG(DA850, MII_RXD_1, 3, 24, 15, 8, false)
MUX_CFG(DA850, MII_RXD_0, 3, 28, 15, 8, false)
MUX_CFG(DA850, MDIO_CLK, 4, 0, 15, 8, false)
MUX_CFG(DA850, MDIO_D, 4, 4, 15, 8, false)
MUX_CFG(DA850, RMII_TXD_0, 14, 12, 15, 8, false)
MUX_CFG(DA850, RMII_TXD_1, 14, 8, 15, 8, false)
MUX_CFG(DA850, RMII_TXEN, 14, 16, 15, 8, false)
MUX_CFG(DA850, RMII_CRS_DV, 15, 4, 15, 8, false)
MUX_CFG(DA850, RMII_RXD_0, 14, 24, 15, 8, false)
MUX_CFG(DA850, RMII_RXD_1, 14, 20, 15, 8, false)
MUX_CFG(DA850, RMII_RXER, 14, 28, 15, 8, false)
MUX_CFG(DA850, RMII_MHZ_50_CLK, 15, 0, 15, 0, false)
/* McASP function */
MUX_CFG(DA850, ACLKR, 0, 0, 15, 1, false)
MUX_CFG(DA850, ACLKX, 0, 4, 15, 1, false)
MUX_CFG(DA850, AFSR, 0, 8, 15, 1, false)
MUX_CFG(DA850, AFSX, 0, 12, 15, 1, false)
MUX_CFG(DA850, AHCLKR, 0, 16, 15, 1, false)
MUX_CFG(DA850, AHCLKX, 0, 20, 15, 1, false)
MUX_CFG(DA850, AMUTE, 0, 24, 15, 1, false)
MUX_CFG(DA850, AXR_15, 1, 0, 15, 1, false)
MUX_CFG(DA850, AXR_14, 1, 4, 15, 1, false)
MUX_CFG(DA850, AXR_13, 1, 8, 15, 1, false)
MUX_CFG(DA850, AXR_12, 1, 12, 15, 1, false)
MUX_CFG(DA850, AXR_11, 1, 16, 15, 1, false)
MUX_CFG(DA850, AXR_10, 1, 20, 15, 1, false)
MUX_CFG(DA850, AXR_9, 1, 24, 15, 1, false)
MUX_CFG(DA850, AXR_8, 1, 28, 15, 1, false)
MUX_CFG(DA850, AXR_7, 2, 0, 15, 1, false)
MUX_CFG(DA850, AXR_6, 2, 4, 15, 1, false)
MUX_CFG(DA850, AXR_5, 2, 8, 15, 1, false)
MUX_CFG(DA850, AXR_4, 2, 12, 15, 1, false)
MUX_CFG(DA850, AXR_3, 2, 16, 15, 1, false)
MUX_CFG(DA850, AXR_2, 2, 20, 15, 1, false)
MUX_CFG(DA850, AXR_1, 2, 24, 15, 1, false)
MUX_CFG(DA850, AXR_0, 2, 28, 15, 1, false)
/* LCD function */
MUX_CFG(DA850, LCD_D_7, 16, 8, 15, 2, false)
MUX_CFG(DA850, LCD_D_6, 16, 12, 15, 2, false)
MUX_CFG(DA850, LCD_D_5, 16, 16, 15, 2, false)
MUX_CFG(DA850, LCD_D_4, 16, 20, 15, 2, false)
MUX_CFG(DA850, LCD_D_3, 16, 24, 15, 2, false)
MUX_CFG(DA850, LCD_D_2, 16, 28, 15, 2, false)
MUX_CFG(DA850, LCD_D_1, 17, 0, 15, 2, false)
MUX_CFG(DA850, LCD_D_0, 17, 4, 15, 2, false)
MUX_CFG(DA850, LCD_D_15, 17, 8, 15, 2, false)
MUX_CFG(DA850, LCD_D_14, 17, 12, 15, 2, false)
MUX_CFG(DA850, LCD_D_13, 17, 16, 15, 2, false)
MUX_CFG(DA850, LCD_D_12, 17, 20, 15, 2, false)
MUX_CFG(DA850, LCD_D_11, 17, 24, 15, 2, false)
MUX_CFG(DA850, LCD_D_10, 17, 28, 15, 2, false)
MUX_CFG(DA850, LCD_D_9, 18, 0, 15, 2, false)
MUX_CFG(DA850, LCD_D_8, 18, 4, 15, 2, false)
MUX_CFG(DA850, LCD_PCLK, 18, 24, 15, 2, false)
MUX_CFG(DA850, LCD_HSYNC, 19, 0, 15, 2, false)
MUX_CFG(DA850, LCD_VSYNC, 19, 4, 15, 2, false)
MUX_CFG(DA850, NLCD_AC_ENB_CS, 19, 24, 15, 2, false)
/* MMC/SD0 function */
MUX_CFG(DA850, MMCSD0_DAT_0, 10, 8, 15, 2, false)
MUX_CFG(DA850, MMCSD0_DAT_1, 10, 12, 15, 2, false)
MUX_CFG(DA850, MMCSD0_DAT_2, 10, 16, 15, 2, false)
MUX_CFG(DA850, MMCSD0_DAT_3, 10, 20, 15, 2, false)
MUX_CFG(DA850, MMCSD0_CLK, 10, 0, 15, 2, false)
MUX_CFG(DA850, MMCSD0_CMD, 10, 4, 15, 2, false)
/* MMC/SD1 function */
MUX_CFG(DA850, MMCSD1_DAT_0, 18, 8, 15, 2, false)
MUX_CFG(DA850, MMCSD1_DAT_1, 19, 16, 15, 2, false)
MUX_CFG(DA850, MMCSD1_DAT_2, 19, 12, 15, 2, false)
MUX_CFG(DA850, MMCSD1_DAT_3, 19, 8, 15, 2, false)
MUX_CFG(DA850, MMCSD1_CLK, 18, 12, 15, 2, false)
MUX_CFG(DA850, MMCSD1_CMD, 18, 16, 15, 2, false)
/* EMIF2.5/EMIFA function */
MUX_CFG(DA850, EMA_D_7, 9, 0, 15, 1, false)
MUX_CFG(DA850, EMA_D_6, 9, 4, 15, 1, false)
MUX_CFG(DA850, EMA_D_5, 9, 8, 15, 1, false)
MUX_CFG(DA850, EMA_D_4, 9, 12, 15, 1, false)
MUX_CFG(DA850, EMA_D_3, 9, 16, 15, 1, false)
MUX_CFG(DA850, EMA_D_2, 9, 20, 15, 1, false)
MUX_CFG(DA850, EMA_D_1, 9, 24, 15, 1, false)
MUX_CFG(DA850, EMA_D_0, 9, 28, 15, 1, false)
MUX_CFG(DA850, EMA_A_1, 12, 24, 15, 1, false)
MUX_CFG(DA850, EMA_A_2, 12, 20, 15, 1, false)
MUX_CFG(DA850, NEMA_CS_3, 7, 4, 15, 1, false)
MUX_CFG(DA850, NEMA_CS_4, 7, 8, 15, 1, false)
MUX_CFG(DA850, NEMA_WE, 7, 16, 15, 1, false)
MUX_CFG(DA850, NEMA_OE, 7, 20, 15, 1, false)
MUX_CFG(DA850, EMA_A_0, 12, 28, 15, 1, false)
MUX_CFG(DA850, EMA_A_3, 12, 16, 15, 1, false)
MUX_CFG(DA850, EMA_A_4, 12, 12, 15, 1, false)
MUX_CFG(DA850, EMA_A_5, 12, 8, 15, 1, false)
MUX_CFG(DA850, EMA_A_6, 12, 4, 15, 1, false)
MUX_CFG(DA850, EMA_A_7, 12, 0, 15, 1, false)
MUX_CFG(DA850, EMA_A_8, 11, 28, 15, 1, false)
MUX_CFG(DA850, EMA_A_9, 11, 24, 15, 1, false)
MUX_CFG(DA850, EMA_A_10, 11, 20, 15, 1, false)
MUX_CFG(DA850, EMA_A_11, 11, 16, 15, 1, false)
MUX_CFG(DA850, EMA_A_12, 11, 12, 15, 1, false)
MUX_CFG(DA850, EMA_A_13, 11, 8, 15, 1, false)
MUX_CFG(DA850, EMA_A_14, 11, 4, 15, 1, false)
MUX_CFG(DA850, EMA_A_15, 11, 0, 15, 1, false)
MUX_CFG(DA850, EMA_A_16, 10, 28, 15, 1, false)
MUX_CFG(DA850, EMA_A_17, 10, 24, 15, 1, false)
MUX_CFG(DA850, EMA_A_18, 10, 20, 15, 1, false)
MUX_CFG(DA850, EMA_A_19, 10, 16, 15, 1, false)
MUX_CFG(DA850, EMA_A_20, 10, 12, 15, 1, false)
MUX_CFG(DA850, EMA_A_21, 10, 8, 15, 1, false)
MUX_CFG(DA850, EMA_A_22, 10, 4, 15, 1, false)
MUX_CFG(DA850, EMA_A_23, 10, 0, 15, 1, false)
MUX_CFG(DA850, EMA_D_8, 8, 28, 15, 1, false)
MUX_CFG(DA850, EMA_D_9, 8, 24, 15, 1, false)
MUX_CFG(DA850, EMA_D_10, 8, 20, 15, 1, false)
MUX_CFG(DA850, EMA_D_11, 8, 16, 15, 1, false)
MUX_CFG(DA850, EMA_D_12, 8, 12, 15, 1, false)
MUX_CFG(DA850, EMA_D_13, 8, 8, 15, 1, false)
MUX_CFG(DA850, EMA_D_14, 8, 4, 15, 1, false)
MUX_CFG(DA850, EMA_D_15, 8, 0, 15, 1, false)
MUX_CFG(DA850, EMA_BA_1, 5, 24, 15, 1, false)
MUX_CFG(DA850, EMA_CLK, 6, 0, 15, 1, false)
MUX_CFG(DA850, EMA_WAIT_1, 6, 24, 15, 1, false)
MUX_CFG(DA850, NEMA_CS_2, 7, 0, 15, 1, false)
/* GPIO function */
MUX_CFG(DA850, GPIO2_4, 6, 12, 15, 8, false)
MUX_CFG(DA850, GPIO2_6, 6, 4, 15, 8, false)
MUX_CFG(DA850, GPIO2_8, 5, 28, 15, 8, false)
MUX_CFG(DA850, GPIO2_15, 5, 0, 15, 8, false)
MUX_CFG(DA850, GPIO3_12, 7, 12, 15, 8, false)
MUX_CFG(DA850, GPIO3_13, 7, 8, 15, 8, false)
MUX_CFG(DA850, GPIO4_0, 10, 28, 15, 8, false)
MUX_CFG(DA850, GPIO4_1, 10, 24, 15, 8, false)
MUX_CFG(DA850, GPIO6_9, 13, 24, 15, 8, false)
MUX_CFG(DA850, GPIO6_10, 13, 20, 15, 8, false)
MUX_CFG(DA850, GPIO6_13, 13, 8, 15, 8, false)
MUX_CFG(DA850, RTC_ALARM, 0, 28, 15, 2, false)
#endif
};
const short da850_i2c0_pins[] __initdata = {
DA850_I2C0_SDA, DA850_I2C0_SCL,
-1
};
const short da850_i2c1_pins[] __initdata = {
DA850_I2C1_SCL, DA850_I2C1_SDA,
-1
};
const short da850_lcdcntl_pins[] __initdata = {
DA850_LCD_D_0, DA850_LCD_D_1, DA850_LCD_D_2, DA850_LCD_D_3,
DA850_LCD_D_4, DA850_LCD_D_5, DA850_LCD_D_6, DA850_LCD_D_7,
DA850_LCD_D_8, DA850_LCD_D_9, DA850_LCD_D_10, DA850_LCD_D_11,
DA850_LCD_D_12, DA850_LCD_D_13, DA850_LCD_D_14, DA850_LCD_D_15,
DA850_LCD_PCLK, DA850_LCD_HSYNC, DA850_LCD_VSYNC, DA850_NLCD_AC_ENB_CS,
-1
};
/* FIQ are pri 0-1; otherwise 2-7, with 7 lowest priority */
static u8 da850_default_priorities[DA850_N_CP_INTC_IRQ] = {
[IRQ_DA8XX_COMMTX] = 7,
[IRQ_DA8XX_COMMRX] = 7,
[IRQ_DA8XX_NINT] = 7,
[IRQ_DA8XX_EVTOUT0] = 7,
[IRQ_DA8XX_EVTOUT1] = 7,
[IRQ_DA8XX_EVTOUT2] = 7,
[IRQ_DA8XX_EVTOUT3] = 7,
[IRQ_DA8XX_EVTOUT4] = 7,
[IRQ_DA8XX_EVTOUT5] = 7,
[IRQ_DA8XX_EVTOUT6] = 7,
[IRQ_DA8XX_EVTOUT7] = 7,
[IRQ_DA8XX_CCINT0] = 7,
[IRQ_DA8XX_CCERRINT] = 7,
[IRQ_DA8XX_TCERRINT0] = 7,
[IRQ_DA8XX_AEMIFINT] = 7,
[IRQ_DA8XX_I2CINT0] = 7,
[IRQ_DA8XX_MMCSDINT0] = 7,
[IRQ_DA8XX_MMCSDINT1] = 7,
[IRQ_DA8XX_ALLINT0] = 7,
[IRQ_DA8XX_RTC] = 7,
[IRQ_DA8XX_SPINT0] = 7,
[IRQ_DA8XX_TINT12_0] = 7,
[IRQ_DA8XX_TINT34_0] = 7,
[IRQ_DA8XX_TINT12_1] = 7,
[IRQ_DA8XX_TINT34_1] = 7,
[IRQ_DA8XX_UARTINT0] = 7,
[IRQ_DA8XX_KEYMGRINT] = 7,
[IRQ_DA850_MPUADDRERR0] = 7,
[IRQ_DA8XX_CHIPINT0] = 7,
[IRQ_DA8XX_CHIPINT1] = 7,
[IRQ_DA8XX_CHIPINT2] = 7,
[IRQ_DA8XX_CHIPINT3] = 7,
[IRQ_DA8XX_TCERRINT1] = 7,
[IRQ_DA8XX_C0_RX_THRESH_PULSE] = 7,
[IRQ_DA8XX_C0_RX_PULSE] = 7,
[IRQ_DA8XX_C0_TX_PULSE] = 7,
[IRQ_DA8XX_C0_MISC_PULSE] = 7,
[IRQ_DA8XX_C1_RX_THRESH_PULSE] = 7,
[IRQ_DA8XX_C1_RX_PULSE] = 7,
[IRQ_DA8XX_C1_TX_PULSE] = 7,
[IRQ_DA8XX_C1_MISC_PULSE] = 7,
[IRQ_DA8XX_MEMERR] = 7,
[IRQ_DA8XX_GPIO0] = 7,
[IRQ_DA8XX_GPIO1] = 7,
[IRQ_DA8XX_GPIO2] = 7,
[IRQ_DA8XX_GPIO3] = 7,
[IRQ_DA8XX_GPIO4] = 7,
[IRQ_DA8XX_GPIO5] = 7,
[IRQ_DA8XX_GPIO6] = 7,
[IRQ_DA8XX_GPIO7] = 7,
[IRQ_DA8XX_GPIO8] = 7,
[IRQ_DA8XX_I2CINT1] = 7,
[IRQ_DA8XX_LCDINT] = 7,
[IRQ_DA8XX_UARTINT1] = 7,
[IRQ_DA8XX_MCASPINT] = 7,
[IRQ_DA8XX_ALLINT1] = 7,
[IRQ_DA8XX_SPINT1] = 7,
[IRQ_DA8XX_UHPI_INT1] = 7,
[IRQ_DA8XX_USB_INT] = 7,
[IRQ_DA8XX_IRQN] = 7,
[IRQ_DA8XX_RWAKEUP] = 7,
[IRQ_DA8XX_UARTINT2] = 7,
[IRQ_DA8XX_DFTSSINT] = 7,
[IRQ_DA8XX_EHRPWM0] = 7,
[IRQ_DA8XX_EHRPWM0TZ] = 7,
[IRQ_DA8XX_EHRPWM1] = 7,
[IRQ_DA8XX_EHRPWM1TZ] = 7,
[IRQ_DA850_SATAINT] = 7,
[IRQ_DA850_TINTALL_2] = 7,
[IRQ_DA8XX_ECAP0] = 7,
[IRQ_DA8XX_ECAP1] = 7,
[IRQ_DA8XX_ECAP2] = 7,
[IRQ_DA850_MMCSDINT0_1] = 7,
[IRQ_DA850_MMCSDINT1_1] = 7,
[IRQ_DA850_T12CMPINT0_2] = 7,
[IRQ_DA850_T12CMPINT1_2] = 7,
[IRQ_DA850_T12CMPINT2_2] = 7,
[IRQ_DA850_T12CMPINT3_2] = 7,
[IRQ_DA850_T12CMPINT4_2] = 7,
[IRQ_DA850_T12CMPINT5_2] = 7,
[IRQ_DA850_T12CMPINT6_2] = 7,
[IRQ_DA850_T12CMPINT7_2] = 7,
[IRQ_DA850_T12CMPINT0_3] = 7,
[IRQ_DA850_T12CMPINT1_3] = 7,
[IRQ_DA850_T12CMPINT2_3] = 7,
[IRQ_DA850_T12CMPINT3_3] = 7,
[IRQ_DA850_T12CMPINT4_3] = 7,
[IRQ_DA850_T12CMPINT5_3] = 7,
[IRQ_DA850_T12CMPINT6_3] = 7,
[IRQ_DA850_T12CMPINT7_3] = 7,
[IRQ_DA850_RPIINT] = 7,
[IRQ_DA850_VPIFINT] = 7,
[IRQ_DA850_CCINT1] = 7,
[IRQ_DA850_CCERRINT1] = 7,
[IRQ_DA850_TCERRINT2] = 7,
[IRQ_DA850_TINTALL_3] = 7,
[IRQ_DA850_MCBSP0RINT] = 7,
[IRQ_DA850_MCBSP0XINT] = 7,
[IRQ_DA850_MCBSP1RINT] = 7,
[IRQ_DA850_MCBSP1XINT] = 7,
[IRQ_DA8XX_ARMCLKSTOPREQ] = 7,
};
static struct map_desc da850_io_desc[] = {
{
.virtual = IO_VIRT,
.pfn = __phys_to_pfn(IO_PHYS),
.length = IO_SIZE,
.type = MT_DEVICE
},
{
.virtual = DA8XX_CP_INTC_VIRT,
.pfn = __phys_to_pfn(DA8XX_CP_INTC_BASE),
.length = DA8XX_CP_INTC_SIZE,
.type = MT_DEVICE
},
{
.virtual = SRAM_VIRT,
.pfn = __phys_to_pfn(DA8XX_ARM_RAM_BASE),
.length = SZ_8K,
.type = MT_DEVICE
},
};
static u32 da850_psc_bases[] = { DA8XX_PSC0_BASE, DA8XX_PSC1_BASE };
/* Contents of JTAG ID register used to identify exact cpu type */
static struct davinci_id da850_ids[] = {
{
.variant = 0x0,
.part_no = 0xb7d1,
.manufacturer = 0x017, /* 0x02f >> 1 */
.cpu_id = DAVINCI_CPU_ID_DA850,
.name = "da850/omap-l138",
},
{
.variant = 0x1,
.part_no = 0xb7d1,
.manufacturer = 0x017, /* 0x02f >> 1 */
.cpu_id = DAVINCI_CPU_ID_DA850,
.name = "da850/omap-l138/am18x",
},
};
static struct davinci_timer_instance da850_timer_instance[4] = {
{
.base = DA8XX_TIMER64P0_BASE,
.bottom_irq = IRQ_DA8XX_TINT12_0,
.top_irq = IRQ_DA8XX_TINT34_0,
},
{
.base = DA8XX_TIMER64P1_BASE,
.bottom_irq = IRQ_DA8XX_TINT12_1,
.top_irq = IRQ_DA8XX_TINT34_1,
},
{
.base = DA850_TIMER64P2_BASE,
.bottom_irq = IRQ_DA850_TINT12_2,
.top_irq = IRQ_DA850_TINT34_2,
},
{
.base = DA850_TIMER64P3_BASE,
.bottom_irq = IRQ_DA850_TINT12_3,
.top_irq = IRQ_DA850_TINT34_3,
},
};
/*
* T0_BOT: Timer 0, bottom : Used for clock_event
* T0_TOP: Timer 0, top : Used for clocksource
* T1_BOT, T1_TOP: Timer 1, bottom & top: Used for watchdog timer
*/
static struct davinci_timer_info da850_timer_info = {
.timers = da850_timer_instance,
.clockevent_id = T0_BOT,
.clocksource_id = T0_TOP,
};
static void da850_set_async3_src(int pllnum)
{
struct clk *clk, *newparent = pllnum ? &pll1_sysclk2 : &pll0_sysclk2;
struct clk_lookup *c;
unsigned int v;
int ret;
for (c = da850_clks; c->clk; c++) {
clk = c->clk;
if (clk->flags & DA850_CLK_ASYNC3) {
ret = clk_set_parent(clk, newparent);
WARN(ret, "DA850: unable to re-parent clock %s",
clk->name);
}
}
v = __raw_readl(DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP3_REG));
if (pllnum)
v |= CFGCHIP3_ASYNC3_CLKSRC;
else
v &= ~CFGCHIP3_ASYNC3_CLKSRC;
__raw_writel(v, DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP3_REG));
}
#ifdef CONFIG_CPU_FREQ
/*
* Notes:
* According to the TRM, minimum PLLM results in maximum power savings.
* The OPP definitions below should keep the PLLM as low as possible.
*
* The output of the PLLM must be between 300 to 600 MHz.
*/
struct da850_opp {
unsigned int freq; /* in KHz */
unsigned int prediv;
unsigned int mult;
unsigned int postdiv;
unsigned int cvdd_min; /* in uV */
unsigned int cvdd_max; /* in uV */
};
static const struct da850_opp da850_opp_456 = {
.freq = 456000,
.prediv = 1,
.mult = 19,
.postdiv = 1,
.cvdd_min = 1300000,
.cvdd_max = 1350000,
};
static const struct da850_opp da850_opp_408 = {
.freq = 408000,
.prediv = 1,
.mult = 17,
.postdiv = 1,
.cvdd_min = 1300000,
.cvdd_max = 1350000,
};
static const struct da850_opp da850_opp_372 = {
.freq = 372000,
.prediv = 2,
.mult = 31,
.postdiv = 1,
.cvdd_min = 1200000,
.cvdd_max = 1320000,
};
static const struct da850_opp da850_opp_300 = {
.freq = 300000,
.prediv = 1,
.mult = 25,
.postdiv = 2,
.cvdd_min = 1200000,
.cvdd_max = 1320000,
};
static const struct da850_opp da850_opp_200 = {
.freq = 200000,
.prediv = 1,
.mult = 25,
.postdiv = 3,
.cvdd_min = 1100000,
.cvdd_max = 1160000,
};
static const struct da850_opp da850_opp_96 = {
.freq = 96000,
.prediv = 1,
.mult = 20,
.postdiv = 5,
.cvdd_min = 1000000,
.cvdd_max = 1050000,
};
#define OPP(freq) \
{ \
.index = (unsigned int) &da850_opp_##freq, \
.frequency = freq * 1000, \
}
static struct cpufreq_frequency_table da850_freq_table[] = {
OPP(456),
OPP(408),
OPP(372),
OPP(300),
OPP(200),
OPP(96),
{
.index = 0,
.frequency = CPUFREQ_TABLE_END,
},
};
#ifdef CONFIG_REGULATOR
static int da850_set_voltage(unsigned int index);
static int da850_regulator_init(void);
#endif
static struct davinci_cpufreq_config cpufreq_info = {
.freq_table = da850_freq_table,
#ifdef CONFIG_REGULATOR
.init = da850_regulator_init,
.set_voltage = da850_set_voltage,
#endif
};
#ifdef CONFIG_REGULATOR
static struct regulator *cvdd;
static int da850_set_voltage(unsigned int index)
{
struct da850_opp *opp;
if (!cvdd)
return -ENODEV;
opp = (struct da850_opp *) cpufreq_info.freq_table[index].index;
return regulator_set_voltage(cvdd, opp->cvdd_min, opp->cvdd_max);
}
static int da850_regulator_init(void)
{
cvdd = regulator_get(NULL, "cvdd");
if (WARN(IS_ERR(cvdd), "Unable to obtain voltage regulator for CVDD;"
" voltage scaling unsupported\n")) {
return PTR_ERR(cvdd);
}
return 0;
}
#endif
static struct platform_device da850_cpufreq_device = {
.name = "cpufreq-davinci",
.dev = {
.platform_data = &cpufreq_info,
},
.id = -1,
};
unsigned int da850_max_speed = 300000;
int __init da850_register_cpufreq(char *async_clk)
{
int i;
/* cpufreq driver can help keep an "async" clock constant */
if (async_clk)
clk_add_alias("async", da850_cpufreq_device.name,
async_clk, NULL);
for (i = 0; i < ARRAY_SIZE(da850_freq_table); i++) {
if (da850_freq_table[i].frequency <= da850_max_speed) {
cpufreq_info.freq_table = &da850_freq_table[i];
break;
}
}
return platform_device_register(&da850_cpufreq_device);
}
static int da850_round_armrate(struct clk *clk, unsigned long rate)
{
int i, ret = 0, diff;
unsigned int best = (unsigned int) -1;
struct cpufreq_frequency_table *table = cpufreq_info.freq_table;
rate /= 1000; /* convert to kHz */
for (i = 0; table[i].frequency != CPUFREQ_TABLE_END; i++) {
diff = table[i].frequency - rate;
if (diff < 0)
diff = -diff;
if (diff < best) {
best = diff;
ret = table[i].frequency;
}
}
return ret * 1000;
}
static int da850_set_armrate(struct clk *clk, unsigned long index)
{
struct clk *pllclk = &pll0_clk;
return clk_set_rate(pllclk, index);
}
static int da850_set_pll0rate(struct clk *clk, unsigned long index)
{
unsigned int prediv, mult, postdiv;
struct da850_opp *opp;
struct pll_data *pll = clk->pll_data;
int ret;
opp = (struct da850_opp *) cpufreq_info.freq_table[index].index;
prediv = opp->prediv;
mult = opp->mult;
postdiv = opp->postdiv;
ret = davinci_set_pllrate(pll, prediv, mult, postdiv);
if (WARN_ON(ret))
return ret;
return 0;
}
#else
int __init da850_register_cpufreq(char *async_clk)
{
return 0;
}
static int da850_set_armrate(struct clk *clk, unsigned long rate)
{
return -EINVAL;
}
static int da850_set_pll0rate(struct clk *clk, unsigned long armrate)
{
return -EINVAL;
}
static int da850_round_armrate(struct clk *clk, unsigned long rate)
{
return clk->rate;
}
#endif
int __init da850_register_pm(struct platform_device *pdev)
{
int ret;
struct davinci_pm_config *pdata = pdev->dev.platform_data;
ret = davinci_cfg_reg(DA850_RTC_ALARM);
if (ret)
return ret;
pdata->ddr2_ctlr_base = da8xx_get_mem_ctlr();
pdata->deepsleep_reg = DA8XX_SYSCFG1_VIRT(DA8XX_DEEPSLEEP_REG);
pdata->ddrpsc_num = DA8XX_LPSC1_EMIF3C;
pdata->cpupll_reg_base = ioremap(DA8XX_PLL0_BASE, SZ_4K);
if (!pdata->cpupll_reg_base)
return -ENOMEM;
pdata->ddrpll_reg_base = ioremap(DA850_PLL1_BASE, SZ_4K);
if (!pdata->ddrpll_reg_base) {
ret = -ENOMEM;
goto no_ddrpll_mem;
}
pdata->ddrpsc_reg_base = ioremap(DA8XX_PSC1_BASE, SZ_4K);
if (!pdata->ddrpsc_reg_base) {
ret = -ENOMEM;
goto no_ddrpsc_mem;
}
return platform_device_register(pdev);
no_ddrpsc_mem:
iounmap(pdata->ddrpll_reg_base);
no_ddrpll_mem:
iounmap(pdata->cpupll_reg_base);
return ret;
}
static struct davinci_soc_info davinci_soc_info_da850 = {
.io_desc = da850_io_desc,
.io_desc_num = ARRAY_SIZE(da850_io_desc),
.jtag_id_reg = DA8XX_SYSCFG0_BASE + DA8XX_JTAG_ID_REG,
.ids = da850_ids,
.ids_num = ARRAY_SIZE(da850_ids),
.cpu_clks = da850_clks,
.psc_bases = da850_psc_bases,
.psc_bases_num = ARRAY_SIZE(da850_psc_bases),
.pinmux_base = DA8XX_SYSCFG0_BASE + 0x120,
.pinmux_pins = da850_pins,
.pinmux_pins_num = ARRAY_SIZE(da850_pins),
.intc_base = DA8XX_CP_INTC_BASE,
.intc_type = DAVINCI_INTC_TYPE_CP_INTC,
.intc_irq_prios = da850_default_priorities,
.intc_irq_num = DA850_N_CP_INTC_IRQ,
.timer_info = &da850_timer_info,
.gpio_type = GPIO_TYPE_DAVINCI,
.gpio_base = DA8XX_GPIO_BASE,
.gpio_num = 144,
.gpio_irq = IRQ_DA8XX_GPIO0,
.serial_dev = &da8xx_serial_device,
.emac_pdata = &da8xx_emac_pdata,
.sram_dma = DA8XX_ARM_RAM_BASE,
.sram_len = SZ_8K,
};
void __init da850_init(void)
{
unsigned int v;
davinci_common_init(&davinci_soc_info_da850);
da8xx_syscfg0_base = ioremap(DA8XX_SYSCFG0_BASE, SZ_4K);
if (WARN(!da8xx_syscfg0_base, "Unable to map syscfg0 module"))
return;
da8xx_syscfg1_base = ioremap(DA8XX_SYSCFG1_BASE, SZ_4K);
if (WARN(!da8xx_syscfg1_base, "Unable to map syscfg1 module"))
return;
/*
* Move the clock source of Async3 domain to PLL1 SYSCLK2.
* This helps keeping the peripherals on this domain insulated
* from CPU frequency changes caused by DVFS. The firmware sets
* both PLL0 and PLL1 to the same frequency so, there should not
* be any noticeable change even in non-DVFS use cases.
*/
da850_set_async3_src(1);
/* Unlock writing to PLL0 registers */
v = __raw_readl(DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP0_REG));
v &= ~CFGCHIP0_PLL_MASTER_LOCK;
__raw_writel(v, DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP0_REG));
/* Unlock writing to PLL1 registers */
v = __raw_readl(DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP3_REG));
v &= ~CFGCHIP3_PLL1_MASTER_LOCK;
__raw_writel(v, DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP3_REG));
}
| gpl-2.0 |
Renzo-Olivares/android_kernel_htc_m7-gpe | drivers/platform/x86/eeepc-wmi.c | 4855 | 6803 | /*
* Eee PC WMI hotkey driver
*
* Copyright(C) 2010 Intel Corporation.
* Copyright(C) 2010-2011 Corentin Chary <corentin.chary@gmail.com>
*
* Portions based on wistron_btns.c:
* Copyright (C) 2005 Miloslav Trmac <mitr@volny.cz>
* Copyright (C) 2005 Bernhard Rosenkraenzer <bero@arklinux.org>
* Copyright (C) 2005 Dmitry Torokhov <dtor@mail.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/dmi.h>
#include <linux/fb.h>
#include <acpi/acpi_bus.h>
#include "asus-wmi.h"
#define EEEPC_WMI_FILE "eeepc-wmi"
MODULE_AUTHOR("Corentin Chary <corentincj@iksaif.net>");
MODULE_DESCRIPTION("Eee PC WMI Hotkey Driver");
MODULE_LICENSE("GPL");
#define EEEPC_ACPI_HID "ASUS010" /* old _HID used in eeepc-laptop */
#define EEEPC_WMI_EVENT_GUID "ABBC0F72-8EA1-11D1-00A0-C90629100000"
MODULE_ALIAS("wmi:"EEEPC_WMI_EVENT_GUID);
static bool hotplug_wireless;
module_param(hotplug_wireless, bool, 0444);
MODULE_PARM_DESC(hotplug_wireless,
"Enable hotplug for wireless device. "
"If your laptop needs that, please report to "
"acpi4asus-user@lists.sourceforge.net.");
/* Values for T101MT "Home" key */
#define HOME_PRESS 0xe4
#define HOME_HOLD 0xea
#define HOME_RELEASE 0xe5
static const struct key_entry eeepc_wmi_keymap[] = {
/* Sleep already handled via generic ACPI code */
{ KE_KEY, 0x30, { KEY_VOLUMEUP } },
{ KE_KEY, 0x31, { KEY_VOLUMEDOWN } },
{ KE_KEY, 0x32, { KEY_MUTE } },
{ KE_KEY, 0x5c, { KEY_F15 } }, /* Power Gear key */
{ KE_KEY, 0x5d, { KEY_WLAN } },
{ KE_KEY, 0x6b, { KEY_TOUCHPAD_TOGGLE } }, /* Toggle Touchpad */
{ KE_KEY, 0x82, { KEY_CAMERA } },
{ KE_KEY, 0x83, { KEY_CAMERA_ZOOMIN } },
{ KE_KEY, 0x88, { KEY_WLAN } },
{ KE_KEY, 0xbd, { KEY_CAMERA } },
{ KE_KEY, 0xcc, { KEY_SWITCHVIDEOMODE } },
{ KE_KEY, 0xe0, { KEY_PROG1 } }, /* Task Manager */
{ KE_KEY, 0xe1, { KEY_F14 } }, /* Change Resolution */
{ KE_KEY, HOME_PRESS, { KEY_CONFIG } }, /* Home/Express gate key */
{ KE_KEY, 0xe8, { KEY_SCREENLOCK } },
{ KE_KEY, 0xe9, { KEY_BRIGHTNESS_ZERO } },
{ KE_KEY, 0xeb, { KEY_CAMERA_ZOOMOUT } },
{ KE_KEY, 0xec, { KEY_CAMERA_UP } },
{ KE_KEY, 0xed, { KEY_CAMERA_DOWN } },
{ KE_KEY, 0xee, { KEY_CAMERA_LEFT } },
{ KE_KEY, 0xef, { KEY_CAMERA_RIGHT } },
{ KE_KEY, 0xf3, { KEY_MENU } },
{ KE_KEY, 0xf5, { KEY_HOMEPAGE } },
{ KE_KEY, 0xf6, { KEY_ESC } },
{ KE_END, 0},
};
static struct quirk_entry quirk_asus_unknown = {
};
static struct quirk_entry quirk_asus_1000h = {
.hotplug_wireless = true,
};
static struct quirk_entry quirk_asus_et2012_type1 = {
.store_backlight_power = true,
};
static struct quirk_entry quirk_asus_et2012_type3 = {
.scalar_panel_brightness = true,
.store_backlight_power = true,
};
static struct quirk_entry *quirks;
static void et2012_quirks(void)
{
const struct dmi_device *dev = NULL;
char oemstring[30];
while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
if (sscanf(dev->name, "AEMS%24c", oemstring) == 1) {
if (oemstring[18] == '1')
quirks = &quirk_asus_et2012_type1;
else if (oemstring[18] == '3')
quirks = &quirk_asus_et2012_type3;
break;
}
}
}
static int dmi_matched(const struct dmi_system_id *dmi)
{
char *model;
quirks = dmi->driver_data;
model = (char *)dmi->matches[1].substr;
if (unlikely(strncmp(model, "ET2012", 6) == 0))
et2012_quirks();
return 1;
}
static struct dmi_system_id asus_quirks[] = {
{
.callback = dmi_matched,
.ident = "ASUSTeK Computer INC. 1000H",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_PRODUCT_NAME, "1000H"),
},
.driver_data = &quirk_asus_1000h,
},
{
.callback = dmi_matched,
.ident = "ASUSTeK Computer INC. ET2012E/I",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_PRODUCT_NAME, "ET2012"),
},
.driver_data = &quirk_asus_unknown,
},
{},
};
static void eeepc_wmi_key_filter(struct asus_wmi_driver *asus_wmi, int *code,
unsigned int *value, bool *autorelease)
{
switch (*code) {
case HOME_PRESS:
*value = 1;
*autorelease = 0;
break;
case HOME_HOLD:
*code = ASUS_WMI_KEY_IGNORE;
break;
case HOME_RELEASE:
*code = HOME_PRESS;
*value = 0;
*autorelease = 0;
break;
}
}
static acpi_status eeepc_wmi_parse_device(acpi_handle handle, u32 level,
void *context, void **retval)
{
pr_warn("Found legacy ATKD device (%s)\n", EEEPC_ACPI_HID);
*(bool *)context = true;
return AE_CTRL_TERMINATE;
}
static int eeepc_wmi_check_atkd(void)
{
acpi_status status;
bool found = false;
status = acpi_get_devices(EEEPC_ACPI_HID, eeepc_wmi_parse_device,
&found, NULL);
if (ACPI_FAILURE(status) || !found)
return 0;
return -1;
}
static int eeepc_wmi_probe(struct platform_device *pdev)
{
if (eeepc_wmi_check_atkd()) {
pr_warn("WMI device present, but legacy ATKD device is also "
"present and enabled\n");
pr_warn("You probably booted with acpi_osi=\"Linux\" or "
"acpi_osi=\"!Windows 2009\"\n");
pr_warn("Can't load eeepc-wmi, use default acpi_osi "
"(preferred) or eeepc-laptop\n");
return -EBUSY;
}
return 0;
}
static void eeepc_wmi_quirks(struct asus_wmi_driver *driver)
{
quirks = &quirk_asus_unknown;
quirks->hotplug_wireless = hotplug_wireless;
dmi_check_system(asus_quirks);
driver->quirks = quirks;
driver->quirks->wapf = -1;
driver->panel_power = FB_BLANK_UNBLANK;
}
static struct asus_wmi_driver asus_wmi_driver = {
.name = EEEPC_WMI_FILE,
.owner = THIS_MODULE,
.event_guid = EEEPC_WMI_EVENT_GUID,
.keymap = eeepc_wmi_keymap,
.input_name = "Eee PC WMI hotkeys",
.input_phys = EEEPC_WMI_FILE "/input0",
.key_filter = eeepc_wmi_key_filter,
.probe = eeepc_wmi_probe,
.detect_quirks = eeepc_wmi_quirks,
};
static int __init eeepc_wmi_init(void)
{
return asus_wmi_register_driver(&asus_wmi_driver);
}
static void __exit eeepc_wmi_exit(void)
{
asus_wmi_unregister_driver(&asus_wmi_driver);
}
module_init(eeepc_wmi_init);
module_exit(eeepc_wmi_exit);
| gpl-2.0 |
JustAkan/jolla-kernel_GK-GPRO_Gen3 | drivers/s390/cio/qdio_thinint.c | 5111 | 7642 | /*
* linux/drivers/s390/cio/thinint_qdio.c
*
* Copyright 2000,2009 IBM Corp.
* Author(s): Utz Bacher <utz.bacher@de.ibm.com>
* Cornelia Huck <cornelia.huck@de.ibm.com>
* Jan Glauber <jang@linux.vnet.ibm.com>
*/
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/kernel_stat.h>
#include <linux/atomic.h>
#include <asm/debug.h>
#include <asm/qdio.h>
#include <asm/airq.h>
#include <asm/isc.h>
#include "cio.h"
#include "ioasm.h"
#include "qdio.h"
#include "qdio_debug.h"
/*
* Restriction: only 63 iqdio subchannels would have its own indicator,
* after that, subsequent subchannels share one indicator
*/
#define TIQDIO_NR_NONSHARED_IND 63
#define TIQDIO_NR_INDICATORS (TIQDIO_NR_NONSHARED_IND + 1)
#define TIQDIO_SHARED_IND 63
/* device state change indicators */
struct indicator_t {
u32 ind; /* u32 because of compare-and-swap performance */
atomic_t count; /* use count, 0 or 1 for non-shared indicators */
};
/* list of thin interrupt input queues */
static LIST_HEAD(tiq_list);
static DEFINE_MUTEX(tiq_list_lock);
/* adapter local summary indicator */
static u8 *tiqdio_alsi;
static struct indicator_t *q_indicators;
u64 last_ai_time;
/* returns addr for the device state change indicator */
static u32 *get_indicator(void)
{
int i;
for (i = 0; i < TIQDIO_NR_NONSHARED_IND; i++)
if (!atomic_read(&q_indicators[i].count)) {
atomic_set(&q_indicators[i].count, 1);
return &q_indicators[i].ind;
}
/* use the shared indicator */
atomic_inc(&q_indicators[TIQDIO_SHARED_IND].count);
return &q_indicators[TIQDIO_SHARED_IND].ind;
}
static void put_indicator(u32 *addr)
{
int i;
if (!addr)
return;
i = ((unsigned long)addr - (unsigned long)q_indicators) /
sizeof(struct indicator_t);
atomic_dec(&q_indicators[i].count);
}
void tiqdio_add_input_queues(struct qdio_irq *irq_ptr)
{
mutex_lock(&tiq_list_lock);
BUG_ON(irq_ptr->nr_input_qs < 1);
list_add_rcu(&irq_ptr->input_qs[0]->entry, &tiq_list);
mutex_unlock(&tiq_list_lock);
xchg(irq_ptr->dsci, 1 << 7);
}
void tiqdio_remove_input_queues(struct qdio_irq *irq_ptr)
{
struct qdio_q *q;
BUG_ON(irq_ptr->nr_input_qs < 1);
q = irq_ptr->input_qs[0];
/* if establish triggered an error */
if (!q || !q->entry.prev || !q->entry.next)
return;
mutex_lock(&tiq_list_lock);
list_del_rcu(&q->entry);
mutex_unlock(&tiq_list_lock);
synchronize_rcu();
}
static inline int has_multiple_inq_on_dsci(struct qdio_irq *irq_ptr)
{
return irq_ptr->nr_input_qs > 1;
}
static inline int references_shared_dsci(struct qdio_irq *irq_ptr)
{
return irq_ptr->dsci == &q_indicators[TIQDIO_SHARED_IND].ind;
}
static inline int shared_ind(struct qdio_irq *irq_ptr)
{
return references_shared_dsci(irq_ptr) ||
has_multiple_inq_on_dsci(irq_ptr);
}
void clear_nonshared_ind(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return;
if (shared_ind(irq_ptr))
return;
xchg(irq_ptr->dsci, 0);
}
int test_nonshared_ind(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return 0;
if (shared_ind(irq_ptr))
return 0;
if (*irq_ptr->dsci)
return 1;
else
return 0;
}
static inline u32 clear_shared_ind(void)
{
if (!atomic_read(&q_indicators[TIQDIO_SHARED_IND].count))
return 0;
return xchg(&q_indicators[TIQDIO_SHARED_IND].ind, 0);
}
static inline void tiqdio_call_inq_handlers(struct qdio_irq *irq)
{
struct qdio_q *q;
int i;
for_each_input_queue(irq, q, i) {
if (!references_shared_dsci(irq) &&
has_multiple_inq_on_dsci(irq))
xchg(q->irq_ptr->dsci, 0);
if (q->u.in.queue_start_poll) {
/* skip if polling is enabled or already in work */
if (test_and_set_bit(QDIO_QUEUE_IRQS_DISABLED,
&q->u.in.queue_irq_state)) {
qperf_inc(q, int_discarded);
continue;
}
/* avoid dsci clear here, done after processing */
q->u.in.queue_start_poll(q->irq_ptr->cdev, q->nr,
q->irq_ptr->int_parm);
} else {
if (!shared_ind(q->irq_ptr))
xchg(q->irq_ptr->dsci, 0);
/*
* Call inbound processing but not directly
* since that could starve other thinint queues.
*/
tasklet_schedule(&q->tasklet);
}
}
}
/**
* tiqdio_thinint_handler - thin interrupt handler for qdio
* @alsi: pointer to adapter local summary indicator
* @data: NULL
*/
static void tiqdio_thinint_handler(void *alsi, void *data)
{
u32 si_used = clear_shared_ind();
struct qdio_q *q;
last_ai_time = S390_lowcore.int_clock;
kstat_cpu(smp_processor_id()).irqs[IOINT_QAI]++;
/* protect tiq_list entries, only changed in activate or shutdown */
rcu_read_lock();
/* check for work on all inbound thinint queues */
list_for_each_entry_rcu(q, &tiq_list, entry) {
struct qdio_irq *irq;
/* only process queues from changed sets */
irq = q->irq_ptr;
if (unlikely(references_shared_dsci(irq))) {
if (!si_used)
continue;
} else if (!*irq->dsci)
continue;
tiqdio_call_inq_handlers(irq);
qperf_inc(q, adapter_int);
}
rcu_read_unlock();
}
static int set_subchannel_ind(struct qdio_irq *irq_ptr, int reset)
{
struct scssc_area *scssc_area;
int rc;
scssc_area = (struct scssc_area *)irq_ptr->chsc_page;
memset(scssc_area, 0, PAGE_SIZE);
if (reset) {
scssc_area->summary_indicator_addr = 0;
scssc_area->subchannel_indicator_addr = 0;
} else {
scssc_area->summary_indicator_addr = virt_to_phys(tiqdio_alsi);
scssc_area->subchannel_indicator_addr =
virt_to_phys(irq_ptr->dsci);
}
scssc_area->request = (struct chsc_header) {
.length = 0x0fe0,
.code = 0x0021,
};
scssc_area->operation_code = 0;
scssc_area->ks = PAGE_DEFAULT_KEY >> 4;
scssc_area->kc = PAGE_DEFAULT_KEY >> 4;
scssc_area->isc = QDIO_AIRQ_ISC;
scssc_area->schid = irq_ptr->schid;
/* enable the time delay disablement facility */
if (css_general_characteristics.aif_tdd)
scssc_area->word_with_d_bit = 0x10000000;
rc = chsc(scssc_area);
if (rc)
return -EIO;
rc = chsc_error_from_response(scssc_area->response.code);
if (rc) {
DBF_ERROR("%4x SSI r:%4x", irq_ptr->schid.sch_no,
scssc_area->response.code);
DBF_ERROR_HEX(&scssc_area->response, sizeof(void *));
return rc;
}
DBF_EVENT("setscind");
DBF_HEX(&scssc_area->summary_indicator_addr, sizeof(unsigned long));
DBF_HEX(&scssc_area->subchannel_indicator_addr, sizeof(unsigned long));
return 0;
}
/* allocate non-shared indicators and shared indicator */
int __init tiqdio_allocate_memory(void)
{
q_indicators = kzalloc(sizeof(struct indicator_t) * TIQDIO_NR_INDICATORS,
GFP_KERNEL);
if (!q_indicators)
return -ENOMEM;
return 0;
}
void tiqdio_free_memory(void)
{
kfree(q_indicators);
}
int __init tiqdio_register_thinints(void)
{
isc_register(QDIO_AIRQ_ISC);
tiqdio_alsi = s390_register_adapter_interrupt(&tiqdio_thinint_handler,
NULL, QDIO_AIRQ_ISC);
if (IS_ERR(tiqdio_alsi)) {
DBF_EVENT("RTI:%lx", PTR_ERR(tiqdio_alsi));
tiqdio_alsi = NULL;
isc_unregister(QDIO_AIRQ_ISC);
return -ENOMEM;
}
return 0;
}
int qdio_establish_thinint(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return 0;
return set_subchannel_ind(irq_ptr, 0);
}
void qdio_setup_thinint(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return;
irq_ptr->dsci = get_indicator();
DBF_HEX(&irq_ptr->dsci, sizeof(void *));
}
void qdio_shutdown_thinint(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return;
/* reset adapter interrupt indicators */
set_subchannel_ind(irq_ptr, 1);
put_indicator(irq_ptr->dsci);
}
void __exit tiqdio_unregister_thinints(void)
{
WARN_ON(!list_empty(&tiq_list));
if (tiqdio_alsi) {
s390_unregister_adapter_interrupt(tiqdio_alsi, QDIO_AIRQ_ISC);
isc_unregister(QDIO_AIRQ_ISC);
}
}
| gpl-2.0 |
AOSP-Nexus/android_kernel_msm | drivers/s390/cio/qdio_thinint.c | 5111 | 7642 | /*
* linux/drivers/s390/cio/thinint_qdio.c
*
* Copyright 2000,2009 IBM Corp.
* Author(s): Utz Bacher <utz.bacher@de.ibm.com>
* Cornelia Huck <cornelia.huck@de.ibm.com>
* Jan Glauber <jang@linux.vnet.ibm.com>
*/
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/kernel_stat.h>
#include <linux/atomic.h>
#include <asm/debug.h>
#include <asm/qdio.h>
#include <asm/airq.h>
#include <asm/isc.h>
#include "cio.h"
#include "ioasm.h"
#include "qdio.h"
#include "qdio_debug.h"
/*
* Restriction: only 63 iqdio subchannels would have its own indicator,
* after that, subsequent subchannels share one indicator
*/
#define TIQDIO_NR_NONSHARED_IND 63
#define TIQDIO_NR_INDICATORS (TIQDIO_NR_NONSHARED_IND + 1)
#define TIQDIO_SHARED_IND 63
/* device state change indicators */
struct indicator_t {
u32 ind; /* u32 because of compare-and-swap performance */
atomic_t count; /* use count, 0 or 1 for non-shared indicators */
};
/* list of thin interrupt input queues */
static LIST_HEAD(tiq_list);
static DEFINE_MUTEX(tiq_list_lock);
/* adapter local summary indicator */
static u8 *tiqdio_alsi;
static struct indicator_t *q_indicators;
u64 last_ai_time;
/* returns addr for the device state change indicator */
static u32 *get_indicator(void)
{
int i;
for (i = 0; i < TIQDIO_NR_NONSHARED_IND; i++)
if (!atomic_read(&q_indicators[i].count)) {
atomic_set(&q_indicators[i].count, 1);
return &q_indicators[i].ind;
}
/* use the shared indicator */
atomic_inc(&q_indicators[TIQDIO_SHARED_IND].count);
return &q_indicators[TIQDIO_SHARED_IND].ind;
}
static void put_indicator(u32 *addr)
{
int i;
if (!addr)
return;
i = ((unsigned long)addr - (unsigned long)q_indicators) /
sizeof(struct indicator_t);
atomic_dec(&q_indicators[i].count);
}
void tiqdio_add_input_queues(struct qdio_irq *irq_ptr)
{
mutex_lock(&tiq_list_lock);
BUG_ON(irq_ptr->nr_input_qs < 1);
list_add_rcu(&irq_ptr->input_qs[0]->entry, &tiq_list);
mutex_unlock(&tiq_list_lock);
xchg(irq_ptr->dsci, 1 << 7);
}
void tiqdio_remove_input_queues(struct qdio_irq *irq_ptr)
{
struct qdio_q *q;
BUG_ON(irq_ptr->nr_input_qs < 1);
q = irq_ptr->input_qs[0];
/* if establish triggered an error */
if (!q || !q->entry.prev || !q->entry.next)
return;
mutex_lock(&tiq_list_lock);
list_del_rcu(&q->entry);
mutex_unlock(&tiq_list_lock);
synchronize_rcu();
}
static inline int has_multiple_inq_on_dsci(struct qdio_irq *irq_ptr)
{
return irq_ptr->nr_input_qs > 1;
}
static inline int references_shared_dsci(struct qdio_irq *irq_ptr)
{
return irq_ptr->dsci == &q_indicators[TIQDIO_SHARED_IND].ind;
}
static inline int shared_ind(struct qdio_irq *irq_ptr)
{
return references_shared_dsci(irq_ptr) ||
has_multiple_inq_on_dsci(irq_ptr);
}
void clear_nonshared_ind(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return;
if (shared_ind(irq_ptr))
return;
xchg(irq_ptr->dsci, 0);
}
int test_nonshared_ind(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return 0;
if (shared_ind(irq_ptr))
return 0;
if (*irq_ptr->dsci)
return 1;
else
return 0;
}
static inline u32 clear_shared_ind(void)
{
if (!atomic_read(&q_indicators[TIQDIO_SHARED_IND].count))
return 0;
return xchg(&q_indicators[TIQDIO_SHARED_IND].ind, 0);
}
static inline void tiqdio_call_inq_handlers(struct qdio_irq *irq)
{
struct qdio_q *q;
int i;
for_each_input_queue(irq, q, i) {
if (!references_shared_dsci(irq) &&
has_multiple_inq_on_dsci(irq))
xchg(q->irq_ptr->dsci, 0);
if (q->u.in.queue_start_poll) {
/* skip if polling is enabled or already in work */
if (test_and_set_bit(QDIO_QUEUE_IRQS_DISABLED,
&q->u.in.queue_irq_state)) {
qperf_inc(q, int_discarded);
continue;
}
/* avoid dsci clear here, done after processing */
q->u.in.queue_start_poll(q->irq_ptr->cdev, q->nr,
q->irq_ptr->int_parm);
} else {
if (!shared_ind(q->irq_ptr))
xchg(q->irq_ptr->dsci, 0);
/*
* Call inbound processing but not directly
* since that could starve other thinint queues.
*/
tasklet_schedule(&q->tasklet);
}
}
}
/**
* tiqdio_thinint_handler - thin interrupt handler for qdio
* @alsi: pointer to adapter local summary indicator
* @data: NULL
*/
static void tiqdio_thinint_handler(void *alsi, void *data)
{
u32 si_used = clear_shared_ind();
struct qdio_q *q;
last_ai_time = S390_lowcore.int_clock;
kstat_cpu(smp_processor_id()).irqs[IOINT_QAI]++;
/* protect tiq_list entries, only changed in activate or shutdown */
rcu_read_lock();
/* check for work on all inbound thinint queues */
list_for_each_entry_rcu(q, &tiq_list, entry) {
struct qdio_irq *irq;
/* only process queues from changed sets */
irq = q->irq_ptr;
if (unlikely(references_shared_dsci(irq))) {
if (!si_used)
continue;
} else if (!*irq->dsci)
continue;
tiqdio_call_inq_handlers(irq);
qperf_inc(q, adapter_int);
}
rcu_read_unlock();
}
static int set_subchannel_ind(struct qdio_irq *irq_ptr, int reset)
{
struct scssc_area *scssc_area;
int rc;
scssc_area = (struct scssc_area *)irq_ptr->chsc_page;
memset(scssc_area, 0, PAGE_SIZE);
if (reset) {
scssc_area->summary_indicator_addr = 0;
scssc_area->subchannel_indicator_addr = 0;
} else {
scssc_area->summary_indicator_addr = virt_to_phys(tiqdio_alsi);
scssc_area->subchannel_indicator_addr =
virt_to_phys(irq_ptr->dsci);
}
scssc_area->request = (struct chsc_header) {
.length = 0x0fe0,
.code = 0x0021,
};
scssc_area->operation_code = 0;
scssc_area->ks = PAGE_DEFAULT_KEY >> 4;
scssc_area->kc = PAGE_DEFAULT_KEY >> 4;
scssc_area->isc = QDIO_AIRQ_ISC;
scssc_area->schid = irq_ptr->schid;
/* enable the time delay disablement facility */
if (css_general_characteristics.aif_tdd)
scssc_area->word_with_d_bit = 0x10000000;
rc = chsc(scssc_area);
if (rc)
return -EIO;
rc = chsc_error_from_response(scssc_area->response.code);
if (rc) {
DBF_ERROR("%4x SSI r:%4x", irq_ptr->schid.sch_no,
scssc_area->response.code);
DBF_ERROR_HEX(&scssc_area->response, sizeof(void *));
return rc;
}
DBF_EVENT("setscind");
DBF_HEX(&scssc_area->summary_indicator_addr, sizeof(unsigned long));
DBF_HEX(&scssc_area->subchannel_indicator_addr, sizeof(unsigned long));
return 0;
}
/* allocate non-shared indicators and shared indicator */
int __init tiqdio_allocate_memory(void)
{
q_indicators = kzalloc(sizeof(struct indicator_t) * TIQDIO_NR_INDICATORS,
GFP_KERNEL);
if (!q_indicators)
return -ENOMEM;
return 0;
}
void tiqdio_free_memory(void)
{
kfree(q_indicators);
}
int __init tiqdio_register_thinints(void)
{
isc_register(QDIO_AIRQ_ISC);
tiqdio_alsi = s390_register_adapter_interrupt(&tiqdio_thinint_handler,
NULL, QDIO_AIRQ_ISC);
if (IS_ERR(tiqdio_alsi)) {
DBF_EVENT("RTI:%lx", PTR_ERR(tiqdio_alsi));
tiqdio_alsi = NULL;
isc_unregister(QDIO_AIRQ_ISC);
return -ENOMEM;
}
return 0;
}
int qdio_establish_thinint(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return 0;
return set_subchannel_ind(irq_ptr, 0);
}
void qdio_setup_thinint(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return;
irq_ptr->dsci = get_indicator();
DBF_HEX(&irq_ptr->dsci, sizeof(void *));
}
void qdio_shutdown_thinint(struct qdio_irq *irq_ptr)
{
if (!is_thinint_irq(irq_ptr))
return;
/* reset adapter interrupt indicators */
set_subchannel_ind(irq_ptr, 1);
put_indicator(irq_ptr->dsci);
}
void __exit tiqdio_unregister_thinints(void)
{
WARN_ON(!list_empty(&tiq_list));
if (tiqdio_alsi) {
s390_unregister_adapter_interrupt(tiqdio_alsi, QDIO_AIRQ_ISC);
isc_unregister(QDIO_AIRQ_ISC);
}
}
| gpl-2.0 |
xpaum/kernel_stock_g3815 | drivers/media/common/tuners/mt2131.c | 8439 | 7983 | /*
* Driver for Microtune MT2131 "QAM/8VSB single chip tuner"
*
* Copyright (c) 2006 Steven Toth <stoth@linuxtv.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/module.h>
#include <linux/delay.h>
#include <linux/dvb/frontend.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "mt2131.h"
#include "mt2131_priv.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
#define dprintk(level,fmt, arg...) if (debug >= level) \
printk(KERN_INFO "%s: " fmt, "mt2131", ## arg)
static u8 mt2131_config1[] = {
0x01,
0x50, 0x00, 0x50, 0x80, 0x00, 0x49, 0xfa, 0x88,
0x08, 0x77, 0x41, 0x04, 0x00, 0x00, 0x00, 0x32,
0x7f, 0xda, 0x4c, 0x00, 0x10, 0xaa, 0x78, 0x80,
0xff, 0x68, 0xa0, 0xff, 0xdd, 0x00, 0x00
};
static u8 mt2131_config2[] = {
0x10,
0x7f, 0xc8, 0x0a, 0x5f, 0x00, 0x04
};
static int mt2131_readreg(struct mt2131_priv *priv, u8 reg, u8 *val)
{
struct i2c_msg msg[2] = {
{ .addr = priv->cfg->i2c_address, .flags = 0,
.buf = ®, .len = 1 },
{ .addr = priv->cfg->i2c_address, .flags = I2C_M_RD,
.buf = val, .len = 1 },
};
if (i2c_transfer(priv->i2c, msg, 2) != 2) {
printk(KERN_WARNING "mt2131 I2C read failed\n");
return -EREMOTEIO;
}
return 0;
}
static int mt2131_writereg(struct mt2131_priv *priv, u8 reg, u8 val)
{
u8 buf[2] = { reg, val };
struct i2c_msg msg = { .addr = priv->cfg->i2c_address, .flags = 0,
.buf = buf, .len = 2 };
if (i2c_transfer(priv->i2c, &msg, 1) != 1) {
printk(KERN_WARNING "mt2131 I2C write failed\n");
return -EREMOTEIO;
}
return 0;
}
static int mt2131_writeregs(struct mt2131_priv *priv,u8 *buf, u8 len)
{
struct i2c_msg msg = { .addr = priv->cfg->i2c_address,
.flags = 0, .buf = buf, .len = len };
if (i2c_transfer(priv->i2c, &msg, 1) != 1) {
printk(KERN_WARNING "mt2131 I2C write failed (len=%i)\n",
(int)len);
return -EREMOTEIO;
}
return 0;
}
static int mt2131_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct mt2131_priv *priv;
int ret=0, i;
u32 freq;
u8 if_band_center;
u32 f_lo1, f_lo2;
u32 div1, num1, div2, num2;
u8 b[8];
u8 lockval = 0;
priv = fe->tuner_priv;
freq = c->frequency / 1000; /* Hz -> kHz */
dprintk(1, "%s() freq=%d\n", __func__, freq);
f_lo1 = freq + MT2131_IF1 * 1000;
f_lo1 = (f_lo1 / 250) * 250;
f_lo2 = f_lo1 - freq - MT2131_IF2;
priv->frequency = (f_lo1 - f_lo2 - MT2131_IF2) * 1000;
/* Frequency LO1 = 16MHz * (DIV1 + NUM1/8192 ) */
num1 = f_lo1 * 64 / (MT2131_FREF / 128);
div1 = num1 / 8192;
num1 &= 0x1fff;
/* Frequency LO2 = 16MHz * (DIV2 + NUM2/8192 ) */
num2 = f_lo2 * 64 / (MT2131_FREF / 128);
div2 = num2 / 8192;
num2 &= 0x1fff;
if (freq <= 82500) if_band_center = 0x00; else
if (freq <= 137500) if_band_center = 0x01; else
if (freq <= 192500) if_band_center = 0x02; else
if (freq <= 247500) if_band_center = 0x03; else
if (freq <= 302500) if_band_center = 0x04; else
if (freq <= 357500) if_band_center = 0x05; else
if (freq <= 412500) if_band_center = 0x06; else
if (freq <= 467500) if_band_center = 0x07; else
if (freq <= 522500) if_band_center = 0x08; else
if (freq <= 577500) if_band_center = 0x09; else
if (freq <= 632500) if_band_center = 0x0A; else
if (freq <= 687500) if_band_center = 0x0B; else
if (freq <= 742500) if_band_center = 0x0C; else
if (freq <= 797500) if_band_center = 0x0D; else
if (freq <= 852500) if_band_center = 0x0E; else
if (freq <= 907500) if_band_center = 0x0F; else
if (freq <= 962500) if_band_center = 0x10; else
if (freq <= 1017500) if_band_center = 0x11; else
if (freq <= 1072500) if_band_center = 0x12; else if_band_center = 0x13;
b[0] = 1;
b[1] = (num1 >> 5) & 0xFF;
b[2] = (num1 & 0x1F);
b[3] = div1;
b[4] = (num2 >> 5) & 0xFF;
b[5] = num2 & 0x1F;
b[6] = div2;
dprintk(1, "IF1: %dMHz IF2: %dMHz\n", MT2131_IF1, MT2131_IF2);
dprintk(1, "PLL freq=%dkHz band=%d\n", (int)freq, (int)if_band_center);
dprintk(1, "PLL f_lo1=%dkHz f_lo2=%dkHz\n", (int)f_lo1, (int)f_lo2);
dprintk(1, "PLL div1=%d num1=%d div2=%d num2=%d\n",
(int)div1, (int)num1, (int)div2, (int)num2);
dprintk(1, "PLL [1..6]: %2x %2x %2x %2x %2x %2x\n",
(int)b[1], (int)b[2], (int)b[3], (int)b[4], (int)b[5],
(int)b[6]);
ret = mt2131_writeregs(priv,b,7);
if (ret < 0)
return ret;
mt2131_writereg(priv, 0x0b, if_band_center);
/* Wait for lock */
i = 0;
do {
mt2131_readreg(priv, 0x08, &lockval);
if ((lockval & 0x88) == 0x88)
break;
msleep(4);
i++;
} while (i < 10);
return ret;
}
static int mt2131_get_frequency(struct dvb_frontend *fe, u32 *frequency)
{
struct mt2131_priv *priv = fe->tuner_priv;
dprintk(1, "%s()\n", __func__);
*frequency = priv->frequency;
return 0;
}
static int mt2131_get_status(struct dvb_frontend *fe, u32 *status)
{
struct mt2131_priv *priv = fe->tuner_priv;
u8 lock_status = 0;
u8 afc_status = 0;
*status = 0;
mt2131_readreg(priv, 0x08, &lock_status);
if ((lock_status & 0x88) == 0x88)
*status = TUNER_STATUS_LOCKED;
mt2131_readreg(priv, 0x09, &afc_status);
dprintk(1, "%s() - LO Status = 0x%x, AFC Status = 0x%x\n",
__func__, lock_status, afc_status);
return 0;
}
static int mt2131_init(struct dvb_frontend *fe)
{
struct mt2131_priv *priv = fe->tuner_priv;
int ret;
dprintk(1, "%s()\n", __func__);
if ((ret = mt2131_writeregs(priv, mt2131_config1,
sizeof(mt2131_config1))) < 0)
return ret;
mt2131_writereg(priv, 0x0b, 0x09);
mt2131_writereg(priv, 0x15, 0x47);
mt2131_writereg(priv, 0x07, 0xf2);
mt2131_writereg(priv, 0x0b, 0x01);
if ((ret = mt2131_writeregs(priv, mt2131_config2,
sizeof(mt2131_config2))) < 0)
return ret;
return ret;
}
static int mt2131_release(struct dvb_frontend *fe)
{
dprintk(1, "%s()\n", __func__);
kfree(fe->tuner_priv);
fe->tuner_priv = NULL;
return 0;
}
static const struct dvb_tuner_ops mt2131_tuner_ops = {
.info = {
.name = "Microtune MT2131",
.frequency_min = 48000000,
.frequency_max = 860000000,
.frequency_step = 50000,
},
.release = mt2131_release,
.init = mt2131_init,
.set_params = mt2131_set_params,
.get_frequency = mt2131_get_frequency,
.get_status = mt2131_get_status
};
struct dvb_frontend * mt2131_attach(struct dvb_frontend *fe,
struct i2c_adapter *i2c,
struct mt2131_config *cfg, u16 if1)
{
struct mt2131_priv *priv = NULL;
u8 id = 0;
dprintk(1, "%s()\n", __func__);
priv = kzalloc(sizeof(struct mt2131_priv), GFP_KERNEL);
if (priv == NULL)
return NULL;
priv->cfg = cfg;
priv->i2c = i2c;
if (mt2131_readreg(priv, 0, &id) != 0) {
kfree(priv);
return NULL;
}
if ( (id != 0x3E) && (id != 0x3F) ) {
printk(KERN_ERR "MT2131: Device not found at addr 0x%02x\n",
cfg->i2c_address);
kfree(priv);
return NULL;
}
printk(KERN_INFO "MT2131: successfully identified at address 0x%02x\n",
cfg->i2c_address);
memcpy(&fe->ops.tuner_ops, &mt2131_tuner_ops,
sizeof(struct dvb_tuner_ops));
fe->tuner_priv = priv;
return fe;
}
EXPORT_SYMBOL(mt2131_attach);
MODULE_AUTHOR("Steven Toth");
MODULE_DESCRIPTION("Microtune MT2131 silicon tuner driver");
MODULE_LICENSE("GPL");
/*
* Local variables:
* c-basic-offset: 8
*/
| gpl-2.0 |
HazyTeam/platform_kernel_oneplus_msm8974 | drivers/media/common/tuners/mt2131.c | 8439 | 7983 | /*
* Driver for Microtune MT2131 "QAM/8VSB single chip tuner"
*
* Copyright (c) 2006 Steven Toth <stoth@linuxtv.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/module.h>
#include <linux/delay.h>
#include <linux/dvb/frontend.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "mt2131.h"
#include "mt2131_priv.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
#define dprintk(level,fmt, arg...) if (debug >= level) \
printk(KERN_INFO "%s: " fmt, "mt2131", ## arg)
static u8 mt2131_config1[] = {
0x01,
0x50, 0x00, 0x50, 0x80, 0x00, 0x49, 0xfa, 0x88,
0x08, 0x77, 0x41, 0x04, 0x00, 0x00, 0x00, 0x32,
0x7f, 0xda, 0x4c, 0x00, 0x10, 0xaa, 0x78, 0x80,
0xff, 0x68, 0xa0, 0xff, 0xdd, 0x00, 0x00
};
static u8 mt2131_config2[] = {
0x10,
0x7f, 0xc8, 0x0a, 0x5f, 0x00, 0x04
};
static int mt2131_readreg(struct mt2131_priv *priv, u8 reg, u8 *val)
{
struct i2c_msg msg[2] = {
{ .addr = priv->cfg->i2c_address, .flags = 0,
.buf = ®, .len = 1 },
{ .addr = priv->cfg->i2c_address, .flags = I2C_M_RD,
.buf = val, .len = 1 },
};
if (i2c_transfer(priv->i2c, msg, 2) != 2) {
printk(KERN_WARNING "mt2131 I2C read failed\n");
return -EREMOTEIO;
}
return 0;
}
static int mt2131_writereg(struct mt2131_priv *priv, u8 reg, u8 val)
{
u8 buf[2] = { reg, val };
struct i2c_msg msg = { .addr = priv->cfg->i2c_address, .flags = 0,
.buf = buf, .len = 2 };
if (i2c_transfer(priv->i2c, &msg, 1) != 1) {
printk(KERN_WARNING "mt2131 I2C write failed\n");
return -EREMOTEIO;
}
return 0;
}
static int mt2131_writeregs(struct mt2131_priv *priv,u8 *buf, u8 len)
{
struct i2c_msg msg = { .addr = priv->cfg->i2c_address,
.flags = 0, .buf = buf, .len = len };
if (i2c_transfer(priv->i2c, &msg, 1) != 1) {
printk(KERN_WARNING "mt2131 I2C write failed (len=%i)\n",
(int)len);
return -EREMOTEIO;
}
return 0;
}
static int mt2131_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct mt2131_priv *priv;
int ret=0, i;
u32 freq;
u8 if_band_center;
u32 f_lo1, f_lo2;
u32 div1, num1, div2, num2;
u8 b[8];
u8 lockval = 0;
priv = fe->tuner_priv;
freq = c->frequency / 1000; /* Hz -> kHz */
dprintk(1, "%s() freq=%d\n", __func__, freq);
f_lo1 = freq + MT2131_IF1 * 1000;
f_lo1 = (f_lo1 / 250) * 250;
f_lo2 = f_lo1 - freq - MT2131_IF2;
priv->frequency = (f_lo1 - f_lo2 - MT2131_IF2) * 1000;
/* Frequency LO1 = 16MHz * (DIV1 + NUM1/8192 ) */
num1 = f_lo1 * 64 / (MT2131_FREF / 128);
div1 = num1 / 8192;
num1 &= 0x1fff;
/* Frequency LO2 = 16MHz * (DIV2 + NUM2/8192 ) */
num2 = f_lo2 * 64 / (MT2131_FREF / 128);
div2 = num2 / 8192;
num2 &= 0x1fff;
if (freq <= 82500) if_band_center = 0x00; else
if (freq <= 137500) if_band_center = 0x01; else
if (freq <= 192500) if_band_center = 0x02; else
if (freq <= 247500) if_band_center = 0x03; else
if (freq <= 302500) if_band_center = 0x04; else
if (freq <= 357500) if_band_center = 0x05; else
if (freq <= 412500) if_band_center = 0x06; else
if (freq <= 467500) if_band_center = 0x07; else
if (freq <= 522500) if_band_center = 0x08; else
if (freq <= 577500) if_band_center = 0x09; else
if (freq <= 632500) if_band_center = 0x0A; else
if (freq <= 687500) if_band_center = 0x0B; else
if (freq <= 742500) if_band_center = 0x0C; else
if (freq <= 797500) if_band_center = 0x0D; else
if (freq <= 852500) if_band_center = 0x0E; else
if (freq <= 907500) if_band_center = 0x0F; else
if (freq <= 962500) if_band_center = 0x10; else
if (freq <= 1017500) if_band_center = 0x11; else
if (freq <= 1072500) if_band_center = 0x12; else if_band_center = 0x13;
b[0] = 1;
b[1] = (num1 >> 5) & 0xFF;
b[2] = (num1 & 0x1F);
b[3] = div1;
b[4] = (num2 >> 5) & 0xFF;
b[5] = num2 & 0x1F;
b[6] = div2;
dprintk(1, "IF1: %dMHz IF2: %dMHz\n", MT2131_IF1, MT2131_IF2);
dprintk(1, "PLL freq=%dkHz band=%d\n", (int)freq, (int)if_band_center);
dprintk(1, "PLL f_lo1=%dkHz f_lo2=%dkHz\n", (int)f_lo1, (int)f_lo2);
dprintk(1, "PLL div1=%d num1=%d div2=%d num2=%d\n",
(int)div1, (int)num1, (int)div2, (int)num2);
dprintk(1, "PLL [1..6]: %2x %2x %2x %2x %2x %2x\n",
(int)b[1], (int)b[2], (int)b[3], (int)b[4], (int)b[5],
(int)b[6]);
ret = mt2131_writeregs(priv,b,7);
if (ret < 0)
return ret;
mt2131_writereg(priv, 0x0b, if_band_center);
/* Wait for lock */
i = 0;
do {
mt2131_readreg(priv, 0x08, &lockval);
if ((lockval & 0x88) == 0x88)
break;
msleep(4);
i++;
} while (i < 10);
return ret;
}
static int mt2131_get_frequency(struct dvb_frontend *fe, u32 *frequency)
{
struct mt2131_priv *priv = fe->tuner_priv;
dprintk(1, "%s()\n", __func__);
*frequency = priv->frequency;
return 0;
}
static int mt2131_get_status(struct dvb_frontend *fe, u32 *status)
{
struct mt2131_priv *priv = fe->tuner_priv;
u8 lock_status = 0;
u8 afc_status = 0;
*status = 0;
mt2131_readreg(priv, 0x08, &lock_status);
if ((lock_status & 0x88) == 0x88)
*status = TUNER_STATUS_LOCKED;
mt2131_readreg(priv, 0x09, &afc_status);
dprintk(1, "%s() - LO Status = 0x%x, AFC Status = 0x%x\n",
__func__, lock_status, afc_status);
return 0;
}
static int mt2131_init(struct dvb_frontend *fe)
{
struct mt2131_priv *priv = fe->tuner_priv;
int ret;
dprintk(1, "%s()\n", __func__);
if ((ret = mt2131_writeregs(priv, mt2131_config1,
sizeof(mt2131_config1))) < 0)
return ret;
mt2131_writereg(priv, 0x0b, 0x09);
mt2131_writereg(priv, 0x15, 0x47);
mt2131_writereg(priv, 0x07, 0xf2);
mt2131_writereg(priv, 0x0b, 0x01);
if ((ret = mt2131_writeregs(priv, mt2131_config2,
sizeof(mt2131_config2))) < 0)
return ret;
return ret;
}
static int mt2131_release(struct dvb_frontend *fe)
{
dprintk(1, "%s()\n", __func__);
kfree(fe->tuner_priv);
fe->tuner_priv = NULL;
return 0;
}
static const struct dvb_tuner_ops mt2131_tuner_ops = {
.info = {
.name = "Microtune MT2131",
.frequency_min = 48000000,
.frequency_max = 860000000,
.frequency_step = 50000,
},
.release = mt2131_release,
.init = mt2131_init,
.set_params = mt2131_set_params,
.get_frequency = mt2131_get_frequency,
.get_status = mt2131_get_status
};
struct dvb_frontend * mt2131_attach(struct dvb_frontend *fe,
struct i2c_adapter *i2c,
struct mt2131_config *cfg, u16 if1)
{
struct mt2131_priv *priv = NULL;
u8 id = 0;
dprintk(1, "%s()\n", __func__);
priv = kzalloc(sizeof(struct mt2131_priv), GFP_KERNEL);
if (priv == NULL)
return NULL;
priv->cfg = cfg;
priv->i2c = i2c;
if (mt2131_readreg(priv, 0, &id) != 0) {
kfree(priv);
return NULL;
}
if ( (id != 0x3E) && (id != 0x3F) ) {
printk(KERN_ERR "MT2131: Device not found at addr 0x%02x\n",
cfg->i2c_address);
kfree(priv);
return NULL;
}
printk(KERN_INFO "MT2131: successfully identified at address 0x%02x\n",
cfg->i2c_address);
memcpy(&fe->ops.tuner_ops, &mt2131_tuner_ops,
sizeof(struct dvb_tuner_ops));
fe->tuner_priv = priv;
return fe;
}
EXPORT_SYMBOL(mt2131_attach);
MODULE_AUTHOR("Steven Toth");
MODULE_DESCRIPTION("Microtune MT2131 silicon tuner driver");
MODULE_LICENSE("GPL");
/*
* Local variables:
* c-basic-offset: 8
*/
| gpl-2.0 |
tamilarasi/linux-kernel-beaglebone | drivers/char/hw_random/mxc-rnga.c | 9719 | 5804 | /*
* RNG driver for Freescale RNGA
*
* Copyright 2008-2009 Freescale Semiconductor, Inc. All Rights Reserved.
* Author: Alan Carvalho de Assis <acassis@gmail.com>
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*
* This driver is based on other RNG drivers.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/hw_random.h>
#include <linux/io.h>
/* RNGA Registers */
#define RNGA_CONTROL 0x00
#define RNGA_STATUS 0x04
#define RNGA_ENTROPY 0x08
#define RNGA_OUTPUT_FIFO 0x0c
#define RNGA_MODE 0x10
#define RNGA_VERIFICATION_CONTROL 0x14
#define RNGA_OSC_CONTROL_COUNTER 0x18
#define RNGA_OSC1_COUNTER 0x1c
#define RNGA_OSC2_COUNTER 0x20
#define RNGA_OSC_COUNTER_STATUS 0x24
/* RNGA Registers Range */
#define RNG_ADDR_RANGE 0x28
/* RNGA Control Register */
#define RNGA_CONTROL_SLEEP 0x00000010
#define RNGA_CONTROL_CLEAR_INT 0x00000008
#define RNGA_CONTROL_MASK_INTS 0x00000004
#define RNGA_CONTROL_HIGH_ASSURANCE 0x00000002
#define RNGA_CONTROL_GO 0x00000001
#define RNGA_STATUS_LEVEL_MASK 0x0000ff00
/* RNGA Status Register */
#define RNGA_STATUS_OSC_DEAD 0x80000000
#define RNGA_STATUS_SLEEP 0x00000010
#define RNGA_STATUS_ERROR_INT 0x00000008
#define RNGA_STATUS_FIFO_UNDERFLOW 0x00000004
#define RNGA_STATUS_LAST_READ_STATUS 0x00000002
#define RNGA_STATUS_SECURITY_VIOLATION 0x00000001
static struct platform_device *rng_dev;
static int mxc_rnga_data_present(struct hwrng *rng)
{
int level;
void __iomem *rng_base = (void __iomem *)rng->priv;
/* how many random numbers is in FIFO? [0-16] */
level = ((__raw_readl(rng_base + RNGA_STATUS) &
RNGA_STATUS_LEVEL_MASK) >> 8);
return level > 0 ? 1 : 0;
}
static int mxc_rnga_data_read(struct hwrng *rng, u32 * data)
{
int err;
u32 ctrl;
void __iomem *rng_base = (void __iomem *)rng->priv;
/* retrieve a random number from FIFO */
*data = __raw_readl(rng_base + RNGA_OUTPUT_FIFO);
/* some error while reading this random number? */
err = __raw_readl(rng_base + RNGA_STATUS) & RNGA_STATUS_ERROR_INT;
/* if error: clear error interrupt, but doesn't return random number */
if (err) {
dev_dbg(&rng_dev->dev, "Error while reading random number!\n");
ctrl = __raw_readl(rng_base + RNGA_CONTROL);
__raw_writel(ctrl | RNGA_CONTROL_CLEAR_INT,
rng_base + RNGA_CONTROL);
return 0;
} else
return 4;
}
static int mxc_rnga_init(struct hwrng *rng)
{
u32 ctrl, osc;
void __iomem *rng_base = (void __iomem *)rng->priv;
/* wake up */
ctrl = __raw_readl(rng_base + RNGA_CONTROL);
__raw_writel(ctrl & ~RNGA_CONTROL_SLEEP, rng_base + RNGA_CONTROL);
/* verify if oscillator is working */
osc = __raw_readl(rng_base + RNGA_STATUS);
if (osc & RNGA_STATUS_OSC_DEAD) {
dev_err(&rng_dev->dev, "RNGA Oscillator is dead!\n");
return -ENODEV;
}
/* go running */
ctrl = __raw_readl(rng_base + RNGA_CONTROL);
__raw_writel(ctrl | RNGA_CONTROL_GO, rng_base + RNGA_CONTROL);
return 0;
}
static void mxc_rnga_cleanup(struct hwrng *rng)
{
u32 ctrl;
void __iomem *rng_base = (void __iomem *)rng->priv;
ctrl = __raw_readl(rng_base + RNGA_CONTROL);
/* stop rnga */
__raw_writel(ctrl & ~RNGA_CONTROL_GO, rng_base + RNGA_CONTROL);
}
static struct hwrng mxc_rnga = {
.name = "mxc-rnga",
.init = mxc_rnga_init,
.cleanup = mxc_rnga_cleanup,
.data_present = mxc_rnga_data_present,
.data_read = mxc_rnga_data_read
};
static int __init mxc_rnga_probe(struct platform_device *pdev)
{
int err = -ENODEV;
struct clk *clk;
struct resource *res, *mem;
void __iomem *rng_base = NULL;
if (rng_dev)
return -EBUSY;
clk = clk_get(&pdev->dev, "rng");
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "Could not get rng_clk!\n");
err = PTR_ERR(clk);
goto out;
}
clk_enable(clk);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
err = -ENOENT;
goto err_region;
}
mem = request_mem_region(res->start, resource_size(res), pdev->name);
if (mem == NULL) {
err = -EBUSY;
goto err_region;
}
rng_base = ioremap(res->start, resource_size(res));
if (!rng_base) {
err = -ENOMEM;
goto err_ioremap;
}
mxc_rnga.priv = (unsigned long)rng_base;
err = hwrng_register(&mxc_rnga);
if (err) {
dev_err(&pdev->dev, "MXC RNGA registering failed (%d)\n", err);
goto err_register;
}
rng_dev = pdev;
dev_info(&pdev->dev, "MXC RNGA Registered.\n");
return 0;
err_register:
iounmap(rng_base);
rng_base = NULL;
err_ioremap:
release_mem_region(res->start, resource_size(res));
err_region:
clk_disable(clk);
clk_put(clk);
out:
return err;
}
static int __exit mxc_rnga_remove(struct platform_device *pdev)
{
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
void __iomem *rng_base = (void __iomem *)mxc_rnga.priv;
struct clk *clk = clk_get(&pdev->dev, "rng");
hwrng_unregister(&mxc_rnga);
iounmap(rng_base);
release_mem_region(res->start, resource_size(res));
clk_disable(clk);
clk_put(clk);
return 0;
}
static struct platform_driver mxc_rnga_driver = {
.driver = {
.name = "mxc_rnga",
.owner = THIS_MODULE,
},
.remove = __exit_p(mxc_rnga_remove),
};
static int __init mod_init(void)
{
return platform_driver_probe(&mxc_rnga_driver, mxc_rnga_probe);
}
static void __exit mod_exit(void)
{
platform_driver_unregister(&mxc_rnga_driver);
}
module_init(mod_init);
module_exit(mod_exit);
MODULE_AUTHOR("Freescale Semiconductor, Inc.");
MODULE_DESCRIPTION("H/W RNGA driver for i.MX");
MODULE_LICENSE("GPL");
| gpl-2.0 |
darkspr1te/seagate_central_cns3420_2-6-35 | drivers/media/dvb/dvb-core/dvb_ca_en50221.c | 760 | 45785 | /*
* dvb_ca.c: generic DVB functions for EN50221 CAM interfaces
*
* Copyright (C) 2004 Andrew de Quincey
*
* Parts of this file were based on sources as follows:
*
* Copyright (C) 2003 Ralph Metzler <rjkm@metzlerbros.de>
*
* based on code:
*
* Copyright (C) 1999-2002 Ralph Metzler
* & Marcus Metzler for convergence integrated media GmbH
*
* 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.
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/smp_lock.h>
#include <linux/kthread.h>
#include "dvb_ca_en50221.h"
#include "dvb_ringbuffer.h"
static int dvb_ca_en50221_debug;
module_param_named(cam_debug, dvb_ca_en50221_debug, int, 0644);
MODULE_PARM_DESC(cam_debug, "enable verbose debug messages");
#define dprintk if (dvb_ca_en50221_debug) printk
#define INIT_TIMEOUT_SECS 10
#define HOST_LINK_BUF_SIZE 0x200
#define RX_BUFFER_SIZE 65535
#define MAX_RX_PACKETS_PER_ITERATION 10
#define CTRLIF_DATA 0
#define CTRLIF_COMMAND 1
#define CTRLIF_STATUS 1
#define CTRLIF_SIZE_LOW 2
#define CTRLIF_SIZE_HIGH 3
#define CMDREG_HC 1 /* Host control */
#define CMDREG_SW 2 /* Size write */
#define CMDREG_SR 4 /* Size read */
#define CMDREG_RS 8 /* Reset interface */
#define CMDREG_FRIE 0x40 /* Enable FR interrupt */
#define CMDREG_DAIE 0x80 /* Enable DA interrupt */
#define IRQEN (CMDREG_DAIE)
#define STATUSREG_RE 1 /* read error */
#define STATUSREG_WE 2 /* write error */
#define STATUSREG_FR 0x40 /* module free */
#define STATUSREG_DA 0x80 /* data available */
#define STATUSREG_TXERR (STATUSREG_RE|STATUSREG_WE) /* general transfer error */
#define DVB_CA_SLOTSTATE_NONE 0
#define DVB_CA_SLOTSTATE_UNINITIALISED 1
#define DVB_CA_SLOTSTATE_RUNNING 2
#define DVB_CA_SLOTSTATE_INVALID 3
#define DVB_CA_SLOTSTATE_WAITREADY 4
#define DVB_CA_SLOTSTATE_VALIDATE 5
#define DVB_CA_SLOTSTATE_WAITFR 6
#define DVB_CA_SLOTSTATE_LINKINIT 7
/* Information on a CA slot */
struct dvb_ca_slot {
/* current state of the CAM */
int slot_state;
/* mutex used for serializing access to one CI slot */
struct mutex slot_lock;
/* Number of CAMCHANGES that have occurred since last processing */
atomic_t camchange_count;
/* Type of last CAMCHANGE */
int camchange_type;
/* base address of CAM config */
u32 config_base;
/* value to write into Config Control register */
u8 config_option;
/* if 1, the CAM supports DA IRQs */
u8 da_irq_supported:1;
/* size of the buffer to use when talking to the CAM */
int link_buf_size;
/* buffer for incoming packets */
struct dvb_ringbuffer rx_buffer;
/* timer used during various states of the slot */
unsigned long timeout;
};
/* Private CA-interface information */
struct dvb_ca_private {
/* pointer back to the public data structure */
struct dvb_ca_en50221 *pub;
/* the DVB device */
struct dvb_device *dvbdev;
/* Flags describing the interface (DVB_CA_FLAG_*) */
u32 flags;
/* number of slots supported by this CA interface */
unsigned int slot_count;
/* information on each slot */
struct dvb_ca_slot *slot_info;
/* wait queues for read() and write() operations */
wait_queue_head_t wait_queue;
/* PID of the monitoring thread */
struct task_struct *thread;
/* Flag indicating if the CA device is open */
unsigned int open:1;
/* Flag indicating the thread should wake up now */
unsigned int wakeup:1;
/* Delay the main thread should use */
unsigned long delay;
/* Slot to start looking for data to read from in the next user-space read operation */
int next_read_slot;
};
static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca);
static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot, u8 * ebuf, int ecount);
static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot, u8 * ebuf, int ecount);
/**
* Safely find needle in haystack.
*
* @param haystack Buffer to look in.
* @param hlen Number of bytes in haystack.
* @param needle Buffer to find.
* @param nlen Number of bytes in needle.
* @return Pointer into haystack needle was found at, or NULL if not found.
*/
static char *findstr(char * haystack, int hlen, char * needle, int nlen)
{
int i;
if (hlen < nlen)
return NULL;
for (i = 0; i <= hlen - nlen; i++) {
if (!strncmp(haystack + i, needle, nlen))
return haystack + i;
}
return NULL;
}
/* ******************************************************************************** */
/* EN50221 physical interface functions */
/**
* Check CAM status.
*/
static int dvb_ca_en50221_check_camstatus(struct dvb_ca_private *ca, int slot)
{
int slot_status;
int cam_present_now;
int cam_changed;
/* IRQ mode */
if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE) {
return (atomic_read(&ca->slot_info[slot].camchange_count) != 0);
}
/* poll mode */
slot_status = ca->pub->poll_slot_status(ca->pub, slot, ca->open);
cam_present_now = (slot_status & DVB_CA_EN50221_POLL_CAM_PRESENT) ? 1 : 0;
cam_changed = (slot_status & DVB_CA_EN50221_POLL_CAM_CHANGED) ? 1 : 0;
if (!cam_changed) {
int cam_present_old = (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE);
cam_changed = (cam_present_now != cam_present_old);
}
if (cam_changed) {
if (!cam_present_now) {
ca->slot_info[slot].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
} else {
ca->slot_info[slot].camchange_type = DVB_CA_EN50221_CAMCHANGE_INSERTED;
}
atomic_set(&ca->slot_info[slot].camchange_count, 1);
} else {
if ((ca->slot_info[slot].slot_state == DVB_CA_SLOTSTATE_WAITREADY) &&
(slot_status & DVB_CA_EN50221_POLL_CAM_READY)) {
// move to validate state if reset is completed
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_VALIDATE;
}
}
return cam_changed;
}
/**
* Wait for flags to become set on the STATUS register on a CAM interface,
* checking for errors and timeout.
*
* @param ca CA instance.
* @param slot Slot on interface.
* @param waitfor Flags to wait for.
* @param timeout_ms Timeout in milliseconds.
*
* @return 0 on success, nonzero on error.
*/
static int dvb_ca_en50221_wait_if_status(struct dvb_ca_private *ca, int slot,
u8 waitfor, int timeout_hz)
{
unsigned long timeout;
unsigned long start;
dprintk("%s\n", __func__);
/* loop until timeout elapsed */
start = jiffies;
timeout = jiffies + timeout_hz;
while (1) {
/* read the status and check for error */
int res = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
if (res < 0)
return -EIO;
/* if we got the flags, it was successful! */
if (res & waitfor) {
dprintk("%s succeeded timeout:%lu\n", __func__, jiffies - start);
return 0;
}
/* check for timeout */
if (time_after(jiffies, timeout)) {
break;
}
/* wait for a bit */
msleep(1);
}
dprintk("%s failed timeout:%lu\n", __func__, jiffies - start);
/* if we get here, we've timed out */
return -ETIMEDOUT;
}
/**
* Initialise the link layer connection to a CAM.
*
* @param ca CA instance.
* @param slot Slot id.
*
* @return 0 on success, nonzero on failure.
*/
static int dvb_ca_en50221_link_init(struct dvb_ca_private *ca, int slot)
{
int ret;
int buf_size;
u8 buf[2];
dprintk("%s\n", __func__);
/* we'll be determining these during this function */
ca->slot_info[slot].da_irq_supported = 0;
/* set the host link buffer size temporarily. it will be overwritten with the
* real negotiated size later. */
ca->slot_info[slot].link_buf_size = 2;
/* read the buffer size from the CAM */
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN | CMDREG_SR)) != 0)
return ret;
if ((ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_DA, HZ / 10)) != 0)
return ret;
if ((ret = dvb_ca_en50221_read_data(ca, slot, buf, 2)) != 2)
return -EIO;
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN)) != 0)
return ret;
/* store it, and choose the minimum of our buffer and the CAM's buffer size */
buf_size = (buf[0] << 8) | buf[1];
if (buf_size > HOST_LINK_BUF_SIZE)
buf_size = HOST_LINK_BUF_SIZE;
ca->slot_info[slot].link_buf_size = buf_size;
buf[0] = buf_size >> 8;
buf[1] = buf_size & 0xff;
dprintk("Chosen link buffer size of %i\n", buf_size);
/* write the buffer size to the CAM */
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN | CMDREG_SW)) != 0)
return ret;
if ((ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_FR, HZ / 10)) != 0)
return ret;
if ((ret = dvb_ca_en50221_write_data(ca, slot, buf, 2)) != 2)
return -EIO;
if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN)) != 0)
return ret;
/* success */
return 0;
}
/**
* Read a tuple from attribute memory.
*
* @param ca CA instance.
* @param slot Slot id.
* @param address Address to read from. Updated.
* @param tupleType Tuple id byte. Updated.
* @param tupleLength Tuple length. Updated.
* @param tuple Dest buffer for tuple (must be 256 bytes). Updated.
*
* @return 0 on success, nonzero on error.
*/
static int dvb_ca_en50221_read_tuple(struct dvb_ca_private *ca, int slot,
int *address, int *tupleType, int *tupleLength, u8 * tuple)
{
int i;
int _tupleType;
int _tupleLength;
int _address = *address;
/* grab the next tuple length and type */
if ((_tupleType = ca->pub->read_attribute_mem(ca->pub, slot, _address)) < 0)
return _tupleType;
if (_tupleType == 0xff) {
dprintk("END OF CHAIN TUPLE type:0x%x\n", _tupleType);
*address += 2;
*tupleType = _tupleType;
*tupleLength = 0;
return 0;
}
if ((_tupleLength = ca->pub->read_attribute_mem(ca->pub, slot, _address + 2)) < 0)
return _tupleLength;
_address += 4;
dprintk("TUPLE type:0x%x length:%i\n", _tupleType, _tupleLength);
/* read in the whole tuple */
for (i = 0; i < _tupleLength; i++) {
tuple[i] = ca->pub->read_attribute_mem(ca->pub, slot, _address + (i * 2));
dprintk(" 0x%02x: 0x%02x %c\n",
i, tuple[i] & 0xff,
((tuple[i] > 31) && (tuple[i] < 127)) ? tuple[i] : '.');
}
_address += (_tupleLength * 2);
// success
*tupleType = _tupleType;
*tupleLength = _tupleLength;
*address = _address;
return 0;
}
/**
* Parse attribute memory of a CAM module, extracting Config register, and checking
* it is a DVB CAM module.
*
* @param ca CA instance.
* @param slot Slot id.
*
* @return 0 on success, <0 on failure.
*/
static int dvb_ca_en50221_parse_attributes(struct dvb_ca_private *ca, int slot)
{
int address = 0;
int tupleLength;
int tupleType;
u8 tuple[257];
char *dvb_str;
int rasz;
int status;
int got_cftableentry = 0;
int end_chain = 0;
int i;
u16 manfid = 0;
u16 devid = 0;
// CISTPL_DEVICE_0A
if ((status =
dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x1D)
return -EINVAL;
// CISTPL_DEVICE_0C
if ((status =
dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x1C)
return -EINVAL;
// CISTPL_VERS_1
if ((status =
dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x15)
return -EINVAL;
// CISTPL_MANFID
if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
&tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x20)
return -EINVAL;
if (tupleLength != 4)
return -EINVAL;
manfid = (tuple[1] << 8) | tuple[0];
devid = (tuple[3] << 8) | tuple[2];
// CISTPL_CONFIG
if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
&tupleLength, tuple)) < 0)
return status;
if (tupleType != 0x1A)
return -EINVAL;
if (tupleLength < 3)
return -EINVAL;
/* extract the configbase */
rasz = tuple[0] & 3;
if (tupleLength < (3 + rasz + 14))
return -EINVAL;
ca->slot_info[slot].config_base = 0;
for (i = 0; i < rasz + 1; i++) {
ca->slot_info[slot].config_base |= (tuple[2 + i] << (8 * i));
}
/* check it contains the correct DVB string */
dvb_str = findstr((char *)tuple, tupleLength, "DVB_CI_V", 8);
if (dvb_str == NULL)
return -EINVAL;
if (tupleLength < ((dvb_str - (char *) tuple) + 12))
return -EINVAL;
/* is it a version we support? */
if (strncmp(dvb_str + 8, "1.00", 4)) {
printk("dvb_ca adapter %d: Unsupported DVB CAM module version %c%c%c%c\n",
ca->dvbdev->adapter->num, dvb_str[8], dvb_str[9], dvb_str[10], dvb_str[11]);
return -EINVAL;
}
/* process the CFTABLE_ENTRY tuples, and any after those */
while ((!end_chain) && (address < 0x1000)) {
if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
&tupleLength, tuple)) < 0)
return status;
switch (tupleType) {
case 0x1B: // CISTPL_CFTABLE_ENTRY
if (tupleLength < (2 + 11 + 17))
break;
/* if we've already parsed one, just use it */
if (got_cftableentry)
break;
/* get the config option */
ca->slot_info[slot].config_option = tuple[0] & 0x3f;
/* OK, check it contains the correct strings */
if ((findstr((char *)tuple, tupleLength, "DVB_HOST", 8) == NULL) ||
(findstr((char *)tuple, tupleLength, "DVB_CI_MODULE", 13) == NULL))
break;
got_cftableentry = 1;
break;
case 0x14: // CISTPL_NO_LINK
break;
case 0xFF: // CISTPL_END
end_chain = 1;
break;
default: /* Unknown tuple type - just skip this tuple and move to the next one */
dprintk("dvb_ca: Skipping unknown tuple type:0x%x length:0x%x\n", tupleType,
tupleLength);
break;
}
}
if ((address > 0x1000) || (!got_cftableentry))
return -EINVAL;
dprintk("Valid DVB CAM detected MANID:%x DEVID:%x CONFIGBASE:0x%x CONFIGOPTION:0x%x\n",
manfid, devid, ca->slot_info[slot].config_base, ca->slot_info[slot].config_option);
// success!
return 0;
}
/**
* Set CAM's configoption correctly.
*
* @param ca CA instance.
* @param slot Slot containing the CAM.
*/
static int dvb_ca_en50221_set_configoption(struct dvb_ca_private *ca, int slot)
{
int configoption;
dprintk("%s\n", __func__);
/* set the config option */
ca->pub->write_attribute_mem(ca->pub, slot,
ca->slot_info[slot].config_base,
ca->slot_info[slot].config_option);
/* check it */
configoption = ca->pub->read_attribute_mem(ca->pub, slot, ca->slot_info[slot].config_base);
dprintk("Set configoption 0x%x, read configoption 0x%x\n",
ca->slot_info[slot].config_option, configoption & 0x3f);
/* fine! */
return 0;
}
/**
* This function talks to an EN50221 CAM control interface. It reads a buffer of
* data from the CAM. The data can either be stored in a supplied buffer, or
* automatically be added to the slot's rx_buffer.
*
* @param ca CA instance.
* @param slot Slot to read from.
* @param ebuf If non-NULL, the data will be written to this buffer. If NULL,
* the data will be added into the buffering system as a normal fragment.
* @param ecount Size of ebuf. Ignored if ebuf is NULL.
*
* @return Number of bytes read, or < 0 on error
*/
static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot, u8 * ebuf, int ecount)
{
int bytes_read;
int status;
u8 buf[HOST_LINK_BUF_SIZE];
int i;
dprintk("%s\n", __func__);
/* check if we have space for a link buf in the rx_buffer */
if (ebuf == NULL) {
int buf_free;
if (ca->slot_info[slot].rx_buffer.data == NULL) {
status = -EIO;
goto exit;
}
buf_free = dvb_ringbuffer_free(&ca->slot_info[slot].rx_buffer);
if (buf_free < (ca->slot_info[slot].link_buf_size + DVB_RINGBUFFER_PKTHDRSIZE)) {
status = -EAGAIN;
goto exit;
}
}
/* check if there is data available */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (!(status & STATUSREG_DA)) {
/* no data */
status = 0;
goto exit;
}
/* read the amount of data */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_SIZE_HIGH)) < 0)
goto exit;
bytes_read = status << 8;
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_SIZE_LOW)) < 0)
goto exit;
bytes_read |= status;
/* check it will fit */
if (ebuf == NULL) {
if (bytes_read > ca->slot_info[slot].link_buf_size) {
printk("dvb_ca adapter %d: CAM tried to send a buffer larger than the link buffer size (%i > %i)!\n",
ca->dvbdev->adapter->num, bytes_read, ca->slot_info[slot].link_buf_size);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
if (bytes_read < 2) {
printk("dvb_ca adapter %d: CAM sent a buffer that was less than 2 bytes!\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
} else {
if (bytes_read > ecount) {
printk("dvb_ca adapter %d: CAM tried to send a buffer larger than the ecount size!\n",
ca->dvbdev->adapter->num);
status = -EIO;
goto exit;
}
}
/* fill the buffer */
for (i = 0; i < bytes_read; i++) {
/* read byte and check */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_DATA)) < 0)
goto exit;
/* OK, store it in the buffer */
buf[i] = status;
}
/* check for read error (RE should now be 0) */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (status & STATUSREG_RE) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
/* OK, add it to the receive buffer, or copy into external buffer if supplied */
if (ebuf == NULL) {
if (ca->slot_info[slot].rx_buffer.data == NULL) {
status = -EIO;
goto exit;
}
dvb_ringbuffer_pkt_write(&ca->slot_info[slot].rx_buffer, buf, bytes_read);
} else {
memcpy(ebuf, buf, bytes_read);
}
dprintk("Received CA packet for slot %i connection id 0x%x last_frag:%i size:0x%x\n", slot,
buf[0], (buf[1] & 0x80) == 0, bytes_read);
/* wake up readers when a last_fragment is received */
if ((buf[1] & 0x80) == 0x00) {
wake_up_interruptible(&ca->wait_queue);
}
status = bytes_read;
exit:
return status;
}
/**
* This function talks to an EN50221 CAM control interface. It writes a buffer of data
* to a CAM.
*
* @param ca CA instance.
* @param slot Slot to write to.
* @param ebuf The data in this buffer is treated as a complete link-level packet to
* be written.
* @param count Size of ebuf.
*
* @return Number of bytes written, or < 0 on error.
*/
static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot, u8 * buf, int bytes_write)
{
int status;
int i;
dprintk("%s\n", __func__);
/* sanity check */
if (bytes_write > ca->slot_info[slot].link_buf_size)
return -EINVAL;
/* it is possible we are dealing with a single buffer implementation,
thus if there is data available for read or if there is even a read
already in progress, we do nothing but awake the kernel thread to
process the data if necessary. */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exitnowrite;
if (status & (STATUSREG_DA | STATUSREG_RE)) {
if (status & STATUSREG_DA)
dvb_ca_en50221_thread_wakeup(ca);
status = -EAGAIN;
goto exitnowrite;
}
/* OK, set HC bit */
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND,
IRQEN | CMDREG_HC)) != 0)
goto exit;
/* check if interface is still free */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (!(status & STATUSREG_FR)) {
/* it wasn't free => try again later */
status = -EAGAIN;
goto exit;
}
/* send the amount of data */
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_HIGH, bytes_write >> 8)) != 0)
goto exit;
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_LOW,
bytes_write & 0xff)) != 0)
goto exit;
/* send the buffer */
for (i = 0; i < bytes_write; i++) {
if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_DATA, buf[i])) != 0)
goto exit;
}
/* check for write error (WE should now be 0) */
if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
goto exit;
if (status & STATUSREG_WE) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
status = -EIO;
goto exit;
}
status = bytes_write;
dprintk("Wrote CA packet for slot %i, connection id 0x%x last_frag:%i size:0x%x\n", slot,
buf[0], (buf[1] & 0x80) == 0, bytes_write);
exit:
ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN);
exitnowrite:
return status;
}
EXPORT_SYMBOL(dvb_ca_en50221_camchange_irq);
/* ******************************************************************************** */
/* EN50221 higher level functions */
/**
* A CAM has been removed => shut it down.
*
* @param ca CA instance.
* @param slot Slot to shut down.
*/
static int dvb_ca_en50221_slot_shutdown(struct dvb_ca_private *ca, int slot)
{
dprintk("%s\n", __func__);
ca->pub->slot_shutdown(ca->pub, slot);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
/* need to wake up all processes to check if they're now
trying to write to a defunct CAM */
wake_up_interruptible(&ca->wait_queue);
dprintk("Slot %i shutdown\n", slot);
/* success */
return 0;
}
EXPORT_SYMBOL(dvb_ca_en50221_camready_irq);
/**
* A CAMCHANGE IRQ has occurred.
*
* @param ca CA instance.
* @param slot Slot concerned.
* @param change_type One of the DVB_CA_CAMCHANGE_* values.
*/
void dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 *pubca, int slot, int change_type)
{
struct dvb_ca_private *ca = pubca->private;
dprintk("CAMCHANGE IRQ slot:%i change_type:%i\n", slot, change_type);
switch (change_type) {
case DVB_CA_EN50221_CAMCHANGE_REMOVED:
case DVB_CA_EN50221_CAMCHANGE_INSERTED:
break;
default:
return;
}
ca->slot_info[slot].camchange_type = change_type;
atomic_inc(&ca->slot_info[slot].camchange_count);
dvb_ca_en50221_thread_wakeup(ca);
}
EXPORT_SYMBOL(dvb_ca_en50221_frda_irq);
/**
* A CAMREADY IRQ has occurred.
*
* @param ca CA instance.
* @param slot Slot concerned.
*/
void dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 *pubca, int slot)
{
struct dvb_ca_private *ca = pubca->private;
dprintk("CAMREADY IRQ slot:%i\n", slot);
if (ca->slot_info[slot].slot_state == DVB_CA_SLOTSTATE_WAITREADY) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_VALIDATE;
dvb_ca_en50221_thread_wakeup(ca);
}
}
/**
* An FR or DA IRQ has occurred.
*
* @param ca CA instance.
* @param slot Slot concerned.
*/
void dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 *pubca, int slot)
{
struct dvb_ca_private *ca = pubca->private;
int flags;
dprintk("FR/DA IRQ slot:%i\n", slot);
switch (ca->slot_info[slot].slot_state) {
case DVB_CA_SLOTSTATE_LINKINIT:
flags = ca->pub->read_cam_control(pubca, slot, CTRLIF_STATUS);
if (flags & STATUSREG_DA) {
dprintk("CAM supports DA IRQ\n");
ca->slot_info[slot].da_irq_supported = 1;
}
break;
case DVB_CA_SLOTSTATE_RUNNING:
if (ca->open)
dvb_ca_en50221_thread_wakeup(ca);
break;
}
}
/* ******************************************************************************** */
/* EN50221 thread functions */
/**
* Wake up the DVB CA thread
*
* @param ca CA instance.
*/
static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca)
{
dprintk("%s\n", __func__);
ca->wakeup = 1;
mb();
wake_up_process(ca->thread);
}
/**
* Update the delay used by the thread.
*
* @param ca CA instance.
*/
static void dvb_ca_en50221_thread_update_delay(struct dvb_ca_private *ca)
{
int delay;
int curdelay = 100000000;
int slot;
/* Beware of too high polling frequency, because one polling
* call might take several hundred milliseconds until timeout!
*/
for (slot = 0; slot < ca->slot_count; slot++) {
switch (ca->slot_info[slot].slot_state) {
default:
case DVB_CA_SLOTSTATE_NONE:
delay = HZ * 60; /* 60s */
if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
delay = HZ * 5; /* 5s */
break;
case DVB_CA_SLOTSTATE_INVALID:
delay = HZ * 60; /* 60s */
if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
delay = HZ / 10; /* 100ms */
break;
case DVB_CA_SLOTSTATE_UNINITIALISED:
case DVB_CA_SLOTSTATE_WAITREADY:
case DVB_CA_SLOTSTATE_VALIDATE:
case DVB_CA_SLOTSTATE_WAITFR:
case DVB_CA_SLOTSTATE_LINKINIT:
delay = HZ / 10; /* 100ms */
break;
case DVB_CA_SLOTSTATE_RUNNING:
delay = HZ * 60; /* 60s */
if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
delay = HZ / 10; /* 100ms */
if (ca->open) {
if ((!ca->slot_info[slot].da_irq_supported) ||
(!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_DA)))
delay = HZ / 10; /* 100ms */
}
break;
}
if (delay < curdelay)
curdelay = delay;
}
ca->delay = curdelay;
}
/**
* Kernel thread which monitors CA slots for CAM changes, and performs data transfers.
*/
static int dvb_ca_en50221_thread(void *data)
{
struct dvb_ca_private *ca = data;
int slot;
int flags;
int status;
int pktcount;
void *rxbuf;
dprintk("%s\n", __func__);
/* choose the correct initial delay */
dvb_ca_en50221_thread_update_delay(ca);
/* main loop */
while (!kthread_should_stop()) {
/* sleep for a bit */
if (!ca->wakeup) {
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(ca->delay);
if (kthread_should_stop())
return 0;
}
ca->wakeup = 0;
/* go through all the slots processing them */
for (slot = 0; slot < ca->slot_count; slot++) {
mutex_lock(&ca->slot_info[slot].slot_lock);
// check the cam status + deal with CAMCHANGEs
while (dvb_ca_en50221_check_camstatus(ca, slot)) {
/* clear down an old CI slot if necessary */
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE)
dvb_ca_en50221_slot_shutdown(ca, slot);
/* if a CAM is NOW present, initialise it */
if (ca->slot_info[slot].camchange_type == DVB_CA_EN50221_CAMCHANGE_INSERTED) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_UNINITIALISED;
}
/* we've handled one CAMCHANGE */
dvb_ca_en50221_thread_update_delay(ca);
atomic_dec(&ca->slot_info[slot].camchange_count);
}
// CAM state machine
switch (ca->slot_info[slot].slot_state) {
case DVB_CA_SLOTSTATE_NONE:
case DVB_CA_SLOTSTATE_INVALID:
// no action needed
break;
case DVB_CA_SLOTSTATE_UNINITIALISED:
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_WAITREADY;
ca->pub->slot_reset(ca->pub, slot);
ca->slot_info[slot].timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
break;
case DVB_CA_SLOTSTATE_WAITREADY:
if (time_after(jiffies, ca->slot_info[slot].timeout)) {
printk("dvb_ca adaptor %d: PC card did not respond :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
// no other action needed; will automatically change state when ready
break;
case DVB_CA_SLOTSTATE_VALIDATE:
if (dvb_ca_en50221_parse_attributes(ca, slot) != 0) {
/* we need this extra check for annoying interfaces like the budget-av */
if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
(ca->pub->poll_slot_status)) {
status = ca->pub->poll_slot_status(ca->pub, slot, 0);
if (!(status & DVB_CA_EN50221_POLL_CAM_PRESENT)) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
}
printk("dvb_ca adapter %d: Invalid PC card inserted :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
if (dvb_ca_en50221_set_configoption(ca, slot) != 0) {
printk("dvb_ca adapter %d: Unable to initialise CAM :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
if (ca->pub->write_cam_control(ca->pub, slot,
CTRLIF_COMMAND, CMDREG_RS) != 0) {
printk("dvb_ca adapter %d: Unable to reset CAM IF\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
dprintk("DVB CAM validated successfully\n");
ca->slot_info[slot].timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_WAITFR;
ca->wakeup = 1;
break;
case DVB_CA_SLOTSTATE_WAITFR:
if (time_after(jiffies, ca->slot_info[slot].timeout)) {
printk("dvb_ca adapter %d: DVB CAM did not respond :(\n",
ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
flags = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
if (flags & STATUSREG_FR) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
ca->wakeup = 1;
}
break;
case DVB_CA_SLOTSTATE_LINKINIT:
if (dvb_ca_en50221_link_init(ca, slot) != 0) {
/* we need this extra check for annoying interfaces like the budget-av */
if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
(ca->pub->poll_slot_status)) {
status = ca->pub->poll_slot_status(ca->pub, slot, 0);
if (!(status & DVB_CA_EN50221_POLL_CAM_PRESENT)) {
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
}
printk("dvb_ca adapter %d: DVB CAM link initialisation failed :(\n", ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
if (ca->slot_info[slot].rx_buffer.data == NULL) {
rxbuf = vmalloc(RX_BUFFER_SIZE);
if (rxbuf == NULL) {
printk("dvb_ca adapter %d: Unable to allocate CAM rx buffer :(\n", ca->dvbdev->adapter->num);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
dvb_ca_en50221_thread_update_delay(ca);
break;
}
dvb_ringbuffer_init(&ca->slot_info[slot].rx_buffer, rxbuf, RX_BUFFER_SIZE);
}
ca->pub->slot_ts_enable(ca->pub, slot);
ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_RUNNING;
dvb_ca_en50221_thread_update_delay(ca);
printk("dvb_ca adapter %d: DVB CAM detected and initialised successfully\n", ca->dvbdev->adapter->num);
break;
case DVB_CA_SLOTSTATE_RUNNING:
if (!ca->open)
break;
// poll slots for data
pktcount = 0;
while ((status = dvb_ca_en50221_read_data(ca, slot, NULL, 0)) > 0) {
if (!ca->open)
break;
/* if a CAMCHANGE occurred at some point, do not do any more processing of this slot */
if (dvb_ca_en50221_check_camstatus(ca, slot)) {
// we dont want to sleep on the next iteration so we can handle the cam change
ca->wakeup = 1;
break;
}
/* check if we've hit our limit this time */
if (++pktcount >= MAX_RX_PACKETS_PER_ITERATION) {
// dont sleep; there is likely to be more data to read
ca->wakeup = 1;
break;
}
}
break;
}
mutex_unlock(&ca->slot_info[slot].slot_lock);
}
}
return 0;
}
/* ******************************************************************************** */
/* EN50221 IO interface functions */
/**
* Real ioctl implementation.
* NOTE: CA_SEND_MSG/CA_GET_MSG ioctls have userspace buffers passed to them.
*
* @param inode Inode concerned.
* @param file File concerned.
* @param cmd IOCTL command.
* @param arg Associated argument.
*
* @return 0 on success, <0 on error.
*/
static int dvb_ca_en50221_io_do_ioctl(struct file *file,
unsigned int cmd, void *parg)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int err = 0;
int slot;
dprintk("%s\n", __func__);
switch (cmd) {
case CA_RESET:
for (slot = 0; slot < ca->slot_count; slot++) {
mutex_lock(&ca->slot_info[slot].slot_lock);
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE) {
dvb_ca_en50221_slot_shutdown(ca, slot);
if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)
dvb_ca_en50221_camchange_irq(ca->pub,
slot,
DVB_CA_EN50221_CAMCHANGE_INSERTED);
}
mutex_unlock(&ca->slot_info[slot].slot_lock);
}
ca->next_read_slot = 0;
dvb_ca_en50221_thread_wakeup(ca);
break;
case CA_GET_CAP: {
struct ca_caps *caps = parg;
caps->slot_num = ca->slot_count;
caps->slot_type = CA_CI_LINK;
caps->descr_num = 0;
caps->descr_type = 0;
break;
}
case CA_GET_SLOT_INFO: {
struct ca_slot_info *info = parg;
if ((info->num > ca->slot_count) || (info->num < 0))
return -EINVAL;
info->type = CA_CI_LINK;
info->flags = 0;
if ((ca->slot_info[info->num].slot_state != DVB_CA_SLOTSTATE_NONE)
&& (ca->slot_info[info->num].slot_state != DVB_CA_SLOTSTATE_INVALID)) {
info->flags = CA_CI_MODULE_PRESENT;
}
if (ca->slot_info[info->num].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
info->flags |= CA_CI_MODULE_READY;
}
break;
}
default:
err = -EINVAL;
break;
}
return err;
}
/**
* Wrapper for ioctl implementation.
*
* @param inode Inode concerned.
* @param file File concerned.
* @param cmd IOCTL command.
* @param arg Associated argument.
*
* @return 0 on success, <0 on error.
*/
static long dvb_ca_en50221_io_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
int ret;
lock_kernel();
ret = dvb_usercopy(file, cmd, arg, dvb_ca_en50221_io_do_ioctl);
unlock_kernel();
return ret;
}
/**
* Implementation of write() syscall.
*
* @param file File structure.
* @param buf Source buffer.
* @param count Size of source buffer.
* @param ppos Position in file (ignored).
*
* @return Number of bytes read, or <0 on error.
*/
static ssize_t dvb_ca_en50221_io_write(struct file *file,
const char __user * buf, size_t count, loff_t * ppos)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
u8 slot, connection_id;
int status;
u8 fragbuf[HOST_LINK_BUF_SIZE];
int fragpos = 0;
int fraglen;
unsigned long timeout;
int written;
dprintk("%s\n", __func__);
/* Incoming packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
if (count < 2)
return -EINVAL;
/* extract slot & connection id */
if (copy_from_user(&slot, buf, 1))
return -EFAULT;
if (copy_from_user(&connection_id, buf + 1, 1))
return -EFAULT;
buf += 2;
count -= 2;
/* check if the slot is actually running */
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
return -EINVAL;
/* fragment the packets & store in the buffer */
while (fragpos < count) {
fraglen = ca->slot_info[slot].link_buf_size - 2;
if ((count - fragpos) < fraglen)
fraglen = count - fragpos;
fragbuf[0] = connection_id;
fragbuf[1] = ((fragpos + fraglen) < count) ? 0x80 : 0x00;
if ((status = copy_from_user(fragbuf + 2, buf + fragpos, fraglen)) != 0)
goto exit;
timeout = jiffies + HZ / 2;
written = 0;
while (!time_after(jiffies, timeout)) {
/* check the CAM hasn't been removed/reset in the meantime */
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING) {
status = -EIO;
goto exit;
}
mutex_lock(&ca->slot_info[slot].slot_lock);
status = dvb_ca_en50221_write_data(ca, slot, fragbuf, fraglen + 2);
mutex_unlock(&ca->slot_info[slot].slot_lock);
if (status == (fraglen + 2)) {
written = 1;
break;
}
if (status != -EAGAIN)
goto exit;
msleep(1);
}
if (!written) {
status = -EIO;
goto exit;
}
fragpos += fraglen;
}
status = count + 2;
exit:
return status;
}
/**
* Condition for waking up in dvb_ca_en50221_io_read_condition
*/
static int dvb_ca_en50221_io_read_condition(struct dvb_ca_private *ca,
int *result, int *_slot)
{
int slot;
int slot_count = 0;
int idx;
size_t fraglen;
int connection_id = -1;
int found = 0;
u8 hdr[2];
slot = ca->next_read_slot;
while ((slot_count < ca->slot_count) && (!found)) {
if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
goto nextslot;
if (ca->slot_info[slot].rx_buffer.data == NULL) {
return 0;
}
idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
while (idx != -1) {
dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
if (connection_id == -1)
connection_id = hdr[0];
if ((hdr[0] == connection_id) && ((hdr[1] & 0x80) == 0)) {
*_slot = slot;
found = 1;
break;
}
idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
}
nextslot:
slot = (slot + 1) % ca->slot_count;
slot_count++;
}
ca->next_read_slot = slot;
return found;
}
/**
* Implementation of read() syscall.
*
* @param file File structure.
* @param buf Destination buffer.
* @param count Size of destination buffer.
* @param ppos Position in file (ignored).
*
* @return Number of bytes read, or <0 on error.
*/
static ssize_t dvb_ca_en50221_io_read(struct file *file, char __user * buf,
size_t count, loff_t * ppos)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int status;
int result = 0;
u8 hdr[2];
int slot;
int connection_id = -1;
size_t idx, idx2;
int last_fragment = 0;
size_t fraglen;
int pktlen;
int dispose = 0;
dprintk("%s\n", __func__);
/* Outgoing packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
if (count < 2)
return -EINVAL;
/* wait for some data */
if ((status = dvb_ca_en50221_io_read_condition(ca, &result, &slot)) == 0) {
/* if we're in nonblocking mode, exit immediately */
if (file->f_flags & O_NONBLOCK)
return -EWOULDBLOCK;
/* wait for some data */
status = wait_event_interruptible(ca->wait_queue,
dvb_ca_en50221_io_read_condition
(ca, &result, &slot));
}
if ((status < 0) || (result < 0)) {
if (result)
return result;
return status;
}
idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
pktlen = 2;
do {
if (idx == -1) {
printk("dvb_ca adapter %d: BUG: read packet ended before last_fragment encountered\n", ca->dvbdev->adapter->num);
status = -EIO;
goto exit;
}
dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
if (connection_id == -1)
connection_id = hdr[0];
if (hdr[0] == connection_id) {
if (pktlen < count) {
if ((pktlen + fraglen - 2) > count) {
fraglen = count - pktlen;
} else {
fraglen -= 2;
}
if ((status = dvb_ringbuffer_pkt_read_user(&ca->slot_info[slot].rx_buffer, idx, 2,
buf + pktlen, fraglen)) < 0) {
goto exit;
}
pktlen += fraglen;
}
if ((hdr[1] & 0x80) == 0)
last_fragment = 1;
dispose = 1;
}
idx2 = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
if (dispose)
dvb_ringbuffer_pkt_dispose(&ca->slot_info[slot].rx_buffer, idx);
idx = idx2;
dispose = 0;
} while (!last_fragment);
hdr[0] = slot;
hdr[1] = connection_id;
if ((status = copy_to_user(buf, hdr, 2)) != 0)
goto exit;
status = pktlen;
exit:
return status;
}
/**
* Implementation of file open syscall.
*
* @param inode Inode concerned.
* @param file File concerned.
*
* @return 0 on success, <0 on failure.
*/
static int dvb_ca_en50221_io_open(struct inode *inode, struct file *file)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int err;
int i;
dprintk("%s\n", __func__);
if (!try_module_get(ca->pub->owner))
return -EIO;
err = dvb_generic_open(inode, file);
if (err < 0) {
module_put(ca->pub->owner);
return err;
}
for (i = 0; i < ca->slot_count; i++) {
if (ca->slot_info[i].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
if (ca->slot_info[i].rx_buffer.data != NULL) {
/* it is safe to call this here without locks because
* ca->open == 0. Data is not read in this case */
dvb_ringbuffer_flush(&ca->slot_info[i].rx_buffer);
}
}
}
ca->open = 1;
dvb_ca_en50221_thread_update_delay(ca);
dvb_ca_en50221_thread_wakeup(ca);
return 0;
}
/**
* Implementation of file close syscall.
*
* @param inode Inode concerned.
* @param file File concerned.
*
* @return 0 on success, <0 on failure.
*/
static int dvb_ca_en50221_io_release(struct inode *inode, struct file *file)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
int err;
dprintk("%s\n", __func__);
/* mark the CA device as closed */
ca->open = 0;
dvb_ca_en50221_thread_update_delay(ca);
err = dvb_generic_release(inode, file);
module_put(ca->pub->owner);
return err;
}
/**
* Implementation of poll() syscall.
*
* @param file File concerned.
* @param wait poll wait table.
*
* @return Standard poll mask.
*/
static unsigned int dvb_ca_en50221_io_poll(struct file *file, poll_table * wait)
{
struct dvb_device *dvbdev = file->private_data;
struct dvb_ca_private *ca = dvbdev->priv;
unsigned int mask = 0;
int slot;
int result = 0;
dprintk("%s\n", __func__);
if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
mask |= POLLIN;
}
/* if there is something, return now */
if (mask)
return mask;
/* wait for something to happen */
poll_wait(file, &ca->wait_queue, wait);
if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
mask |= POLLIN;
}
return mask;
}
EXPORT_SYMBOL(dvb_ca_en50221_init);
static const struct file_operations dvb_ca_fops = {
.owner = THIS_MODULE,
.read = dvb_ca_en50221_io_read,
.write = dvb_ca_en50221_io_write,
.unlocked_ioctl = dvb_ca_en50221_io_ioctl,
.open = dvb_ca_en50221_io_open,
.release = dvb_ca_en50221_io_release,
.poll = dvb_ca_en50221_io_poll,
};
static struct dvb_device dvbdev_ca = {
.priv = NULL,
.users = 1,
.readers = 1,
.writers = 1,
.fops = &dvb_ca_fops,
};
/* ******************************************************************************** */
/* Initialisation/shutdown functions */
/**
* Initialise a new DVB CA EN50221 interface device.
*
* @param dvb_adapter DVB adapter to attach the new CA device to.
* @param ca The dvb_ca instance.
* @param flags Flags describing the CA device (DVB_CA_FLAG_*).
* @param slot_count Number of slots supported.
*
* @return 0 on success, nonzero on failure
*/
int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter,
struct dvb_ca_en50221 *pubca, int flags, int slot_count)
{
int ret;
struct dvb_ca_private *ca = NULL;
int i;
dprintk("%s\n", __func__);
if (slot_count < 1)
return -EINVAL;
/* initialise the system data */
if ((ca = kzalloc(sizeof(struct dvb_ca_private), GFP_KERNEL)) == NULL) {
ret = -ENOMEM;
goto error;
}
ca->pub = pubca;
ca->flags = flags;
ca->slot_count = slot_count;
if ((ca->slot_info = kcalloc(slot_count, sizeof(struct dvb_ca_slot), GFP_KERNEL)) == NULL) {
ret = -ENOMEM;
goto error;
}
init_waitqueue_head(&ca->wait_queue);
ca->open = 0;
ca->wakeup = 0;
ca->next_read_slot = 0;
pubca->private = ca;
/* register the DVB device */
ret = dvb_register_device(dvb_adapter, &ca->dvbdev, &dvbdev_ca, ca, DVB_DEVICE_CA);
if (ret)
goto error;
/* now initialise each slot */
for (i = 0; i < slot_count; i++) {
memset(&ca->slot_info[i], 0, sizeof(struct dvb_ca_slot));
ca->slot_info[i].slot_state = DVB_CA_SLOTSTATE_NONE;
atomic_set(&ca->slot_info[i].camchange_count, 0);
ca->slot_info[i].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
mutex_init(&ca->slot_info[i].slot_lock);
}
if (signal_pending(current)) {
ret = -EINTR;
goto error;
}
mb();
/* create a kthread for monitoring this CA device */
ca->thread = kthread_run(dvb_ca_en50221_thread, ca, "kdvb-ca-%i:%i",
ca->dvbdev->adapter->num, ca->dvbdev->id);
if (IS_ERR(ca->thread)) {
ret = PTR_ERR(ca->thread);
printk("dvb_ca_init: failed to start kernel_thread (%d)\n",
ret);
goto error;
}
return 0;
error:
if (ca != NULL) {
if (ca->dvbdev != NULL)
dvb_unregister_device(ca->dvbdev);
kfree(ca->slot_info);
kfree(ca);
}
pubca->private = NULL;
return ret;
}
EXPORT_SYMBOL(dvb_ca_en50221_release);
/**
* Release a DVB CA EN50221 interface device.
*
* @param ca_dev The dvb_device_t instance for the CA device.
* @param ca The associated dvb_ca instance.
*/
void dvb_ca_en50221_release(struct dvb_ca_en50221 *pubca)
{
struct dvb_ca_private *ca = pubca->private;
int i;
dprintk("%s\n", __func__);
/* shutdown the thread if there was one */
kthread_stop(ca->thread);
for (i = 0; i < ca->slot_count; i++) {
dvb_ca_en50221_slot_shutdown(ca, i);
vfree(ca->slot_info[i].rx_buffer.data);
}
kfree(ca->slot_info);
dvb_unregister_device(ca->dvbdev);
kfree(ca);
pubca->private = NULL;
}
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_aries_KOR | drivers/regulator/lp3971.c | 760 | 13923 | /*
* Regulator driver for National Semiconductors LP3971 PMIC chip
*
* Copyright (C) 2009 Samsung Electronics
* Author: Marek Szyprowski <m.szyprowski@samsung.com>
*
* Based on wm8350.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/bug.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/kernel.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/lp3971.h>
#include <linux/slab.h>
struct lp3971 {
struct device *dev;
struct mutex io_lock;
struct i2c_client *i2c;
int num_regulators;
struct regulator_dev **rdev;
};
static u8 lp3971_reg_read(struct lp3971 *lp3971, u8 reg);
static int lp3971_set_bits(struct lp3971 *lp3971, u8 reg, u16 mask, u16 val);
#define LP3971_SYS_CONTROL1_REG 0x07
/* System control register 1 initial value,
bits 4 and 5 are EPROM programmable */
#define SYS_CONTROL1_INIT_VAL 0x40
#define SYS_CONTROL1_INIT_MASK 0xCF
#define LP3971_BUCK_VOL_ENABLE_REG 0x10
#define LP3971_BUCK_VOL_CHANGE_REG 0x20
/* Voltage control registers shift:
LP3971_BUCK1 -> 0
LP3971_BUCK2 -> 4
LP3971_BUCK3 -> 6
*/
#define BUCK_VOL_CHANGE_SHIFT(x) (((!!x) << 2) | (x & ~0x01))
#define BUCK_VOL_CHANGE_FLAG_GO 0x01
#define BUCK_VOL_CHANGE_FLAG_TARGET 0x02
#define BUCK_VOL_CHANGE_FLAG_MASK 0x03
#define LP3971_BUCK1_BASE 0x23
#define LP3971_BUCK2_BASE 0x29
#define LP3971_BUCK3_BASE 0x32
static const int buck_base_addr[] = {
LP3971_BUCK1_BASE,
LP3971_BUCK2_BASE,
LP3971_BUCK3_BASE,
};
#define LP3971_BUCK_TARGET_VOL1_REG(x) (buck_base_addr[x])
#define LP3971_BUCK_TARGET_VOL2_REG(x) (buck_base_addr[x]+1)
static const int buck_voltage_map[] = {
0, 800, 850, 900, 950, 1000, 1050, 1100,
1150, 1200, 1250, 1300, 1350, 1400, 1450, 1500,
1550, 1600, 1650, 1700, 1800, 1900, 2500, 2800,
3000, 3300,
};
#define BUCK_TARGET_VOL_MASK 0x3f
#define BUCK_TARGET_VOL_MIN_IDX 0x01
#define BUCK_TARGET_VOL_MAX_IDX 0x19
#define LP3971_BUCK_RAMP_REG(x) (buck_base_addr[x]+2)
#define LP3971_LDO_ENABLE_REG 0x12
#define LP3971_LDO_VOL_CONTR_BASE 0x39
/* Voltage control registers:
LP3971_LDO1 -> LP3971_LDO_VOL_CONTR_BASE + 0
LP3971_LDO2 -> LP3971_LDO_VOL_CONTR_BASE + 0
LP3971_LDO3 -> LP3971_LDO_VOL_CONTR_BASE + 1
LP3971_LDO4 -> LP3971_LDO_VOL_CONTR_BASE + 1
LP3971_LDO5 -> LP3971_LDO_VOL_CONTR_BASE + 2
*/
#define LP3971_LDO_VOL_CONTR_REG(x) (LP3971_LDO_VOL_CONTR_BASE + (x >> 1))
/* Voltage control registers shift:
LP3971_LDO1 -> 0, LP3971_LDO2 -> 4
LP3971_LDO3 -> 0, LP3971_LDO4 -> 4
LP3971_LDO5 -> 0
*/
#define LDO_VOL_CONTR_SHIFT(x) ((x & 1) << 2)
#define LDO_VOL_CONTR_MASK 0x0f
static const int ldo45_voltage_map[] = {
1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350,
1400, 1500, 1800, 1900, 2500, 2800, 3000, 3300,
};
static const int ldo123_voltage_map[] = {
1800, 1900, 2000, 2100, 2200, 2300, 2400, 2500,
2600, 2700, 2800, 2900, 3000, 3100, 3200, 3300,
};
static const int *ldo_voltage_map[] = {
ldo123_voltage_map, /* LDO1 */
ldo123_voltage_map, /* LDO2 */
ldo123_voltage_map, /* LDO3 */
ldo45_voltage_map, /* LDO4 */
ldo45_voltage_map, /* LDO5 */
};
#define LDO_VOL_VALUE_MAP(x) (ldo_voltage_map[(x - LP3971_LDO1)])
#define LDO_VOL_MIN_IDX 0x00
#define LDO_VOL_MAX_IDX 0x0f
static int lp3971_ldo_list_voltage(struct regulator_dev *dev, unsigned index)
{
int ldo = rdev_get_id(dev) - LP3971_LDO1;
return 1000 * LDO_VOL_VALUE_MAP(ldo)[index];
}
static int lp3971_ldo_is_enabled(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int ldo = rdev_get_id(dev) - LP3971_LDO1;
u16 mask = 1 << (1 + ldo);
u16 val;
val = lp3971_reg_read(lp3971, LP3971_LDO_ENABLE_REG);
return (val & mask) != 0;
}
static int lp3971_ldo_enable(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int ldo = rdev_get_id(dev) - LP3971_LDO1;
u16 mask = 1 << (1 + ldo);
return lp3971_set_bits(lp3971, LP3971_LDO_ENABLE_REG, mask, mask);
}
static int lp3971_ldo_disable(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int ldo = rdev_get_id(dev) - LP3971_LDO1;
u16 mask = 1 << (1 + ldo);
return lp3971_set_bits(lp3971, LP3971_LDO_ENABLE_REG, mask, 0);
}
static int lp3971_ldo_get_voltage(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int ldo = rdev_get_id(dev) - LP3971_LDO1;
u16 val, reg;
reg = lp3971_reg_read(lp3971, LP3971_LDO_VOL_CONTR_REG(ldo));
val = (reg >> LDO_VOL_CONTR_SHIFT(ldo)) & LDO_VOL_CONTR_MASK;
return 1000 * LDO_VOL_VALUE_MAP(ldo)[val];
}
static int lp3971_ldo_set_voltage(struct regulator_dev *dev,
int min_uV, int max_uV)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int ldo = rdev_get_id(dev) - LP3971_LDO1;
int min_vol = min_uV / 1000, max_vol = max_uV / 1000;
const int *vol_map = LDO_VOL_VALUE_MAP(ldo);
u16 val;
if (min_vol < vol_map[LDO_VOL_MIN_IDX] ||
min_vol > vol_map[LDO_VOL_MAX_IDX])
return -EINVAL;
for (val = LDO_VOL_MIN_IDX; val <= LDO_VOL_MAX_IDX; val++)
if (vol_map[val] >= min_vol)
break;
if (val > LDO_VOL_MAX_IDX || vol_map[val] > max_vol)
return -EINVAL;
return lp3971_set_bits(lp3971, LP3971_LDO_VOL_CONTR_REG(ldo),
LDO_VOL_CONTR_MASK << LDO_VOL_CONTR_SHIFT(ldo),
val << LDO_VOL_CONTR_SHIFT(ldo));
}
static struct regulator_ops lp3971_ldo_ops = {
.list_voltage = lp3971_ldo_list_voltage,
.is_enabled = lp3971_ldo_is_enabled,
.enable = lp3971_ldo_enable,
.disable = lp3971_ldo_disable,
.get_voltage = lp3971_ldo_get_voltage,
.set_voltage = lp3971_ldo_set_voltage,
};
static int lp3971_dcdc_list_voltage(struct regulator_dev *dev, unsigned index)
{
return 1000 * buck_voltage_map[index];
}
static int lp3971_dcdc_is_enabled(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int buck = rdev_get_id(dev) - LP3971_DCDC1;
u16 mask = 1 << (buck * 2);
u16 val;
val = lp3971_reg_read(lp3971, LP3971_BUCK_VOL_ENABLE_REG);
return (val & mask) != 0;
}
static int lp3971_dcdc_enable(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int buck = rdev_get_id(dev) - LP3971_DCDC1;
u16 mask = 1 << (buck * 2);
return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_ENABLE_REG, mask, mask);
}
static int lp3971_dcdc_disable(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int buck = rdev_get_id(dev) - LP3971_DCDC1;
u16 mask = 1 << (buck * 2);
return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_ENABLE_REG, mask, 0);
}
static int lp3971_dcdc_get_voltage(struct regulator_dev *dev)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int buck = rdev_get_id(dev) - LP3971_DCDC1;
u16 reg;
int val;
reg = lp3971_reg_read(lp3971, LP3971_BUCK_TARGET_VOL1_REG(buck));
reg &= BUCK_TARGET_VOL_MASK;
if (reg <= BUCK_TARGET_VOL_MAX_IDX)
val = 1000 * buck_voltage_map[reg];
else {
val = 0;
dev_warn(&dev->dev, "chip reported incorrect voltage value.\n");
}
return val;
}
static int lp3971_dcdc_set_voltage(struct regulator_dev *dev,
int min_uV, int max_uV)
{
struct lp3971 *lp3971 = rdev_get_drvdata(dev);
int buck = rdev_get_id(dev) - LP3971_DCDC1;
int min_vol = min_uV / 1000, max_vol = max_uV / 1000;
const int *vol_map = buck_voltage_map;
u16 val;
int ret;
if (min_vol < vol_map[BUCK_TARGET_VOL_MIN_IDX] ||
min_vol > vol_map[BUCK_TARGET_VOL_MAX_IDX])
return -EINVAL;
for (val = BUCK_TARGET_VOL_MIN_IDX; val <= BUCK_TARGET_VOL_MAX_IDX;
val++)
if (vol_map[val] >= min_vol)
break;
if (val > BUCK_TARGET_VOL_MAX_IDX || vol_map[val] > max_vol)
return -EINVAL;
ret = lp3971_set_bits(lp3971, LP3971_BUCK_TARGET_VOL1_REG(buck),
BUCK_TARGET_VOL_MASK, val);
if (ret)
return ret;
ret = lp3971_set_bits(lp3971, LP3971_BUCK_VOL_CHANGE_REG,
BUCK_VOL_CHANGE_FLAG_MASK << BUCK_VOL_CHANGE_SHIFT(buck),
BUCK_VOL_CHANGE_FLAG_GO << BUCK_VOL_CHANGE_SHIFT(buck));
if (ret)
return ret;
return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_CHANGE_REG,
BUCK_VOL_CHANGE_FLAG_MASK << BUCK_VOL_CHANGE_SHIFT(buck),
0 << BUCK_VOL_CHANGE_SHIFT(buck));
}
static struct regulator_ops lp3971_dcdc_ops = {
.list_voltage = lp3971_dcdc_list_voltage,
.is_enabled = lp3971_dcdc_is_enabled,
.enable = lp3971_dcdc_enable,
.disable = lp3971_dcdc_disable,
.get_voltage = lp3971_dcdc_get_voltage,
.set_voltage = lp3971_dcdc_set_voltage,
};
static struct regulator_desc regulators[] = {
{
.name = "LDO1",
.id = LP3971_LDO1,
.ops = &lp3971_ldo_ops,
.n_voltages = ARRAY_SIZE(ldo123_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "LDO2",
.id = LP3971_LDO2,
.ops = &lp3971_ldo_ops,
.n_voltages = ARRAY_SIZE(ldo123_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "LDO3",
.id = LP3971_LDO3,
.ops = &lp3971_ldo_ops,
.n_voltages = ARRAY_SIZE(ldo123_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "LDO4",
.id = LP3971_LDO4,
.ops = &lp3971_ldo_ops,
.n_voltages = ARRAY_SIZE(ldo45_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "LDO5",
.id = LP3971_LDO5,
.ops = &lp3971_ldo_ops,
.n_voltages = ARRAY_SIZE(ldo45_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "DCDC1",
.id = LP3971_DCDC1,
.ops = &lp3971_dcdc_ops,
.n_voltages = ARRAY_SIZE(buck_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "DCDC2",
.id = LP3971_DCDC2,
.ops = &lp3971_dcdc_ops,
.n_voltages = ARRAY_SIZE(buck_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
{
.name = "DCDC3",
.id = LP3971_DCDC3,
.ops = &lp3971_dcdc_ops,
.n_voltages = ARRAY_SIZE(buck_voltage_map),
.type = REGULATOR_VOLTAGE,
.owner = THIS_MODULE,
},
};
static int lp3971_i2c_read(struct i2c_client *i2c, char reg, int count,
u16 *dest)
{
int ret;
if (count != 1)
return -EIO;
ret = i2c_smbus_read_byte_data(i2c, reg);
if (ret < 0 || count != 1)
return -EIO;
*dest = ret;
return 0;
}
static int lp3971_i2c_write(struct i2c_client *i2c, char reg, int count,
const u16 *src)
{
int ret;
if (count != 1)
return -EIO;
ret = i2c_smbus_write_byte_data(i2c, reg, *src);
if (ret >= 0)
return 0;
return ret;
}
static u8 lp3971_reg_read(struct lp3971 *lp3971, u8 reg)
{
u16 val = 0;
mutex_lock(&lp3971->io_lock);
lp3971_i2c_read(lp3971->i2c, reg, 1, &val);
dev_dbg(lp3971->dev, "reg read 0x%02x -> 0x%02x\n", (int)reg,
(unsigned)val&0xff);
mutex_unlock(&lp3971->io_lock);
return val & 0xff;
}
static int lp3971_set_bits(struct lp3971 *lp3971, u8 reg, u16 mask, u16 val)
{
u16 tmp;
int ret;
mutex_lock(&lp3971->io_lock);
ret = lp3971_i2c_read(lp3971->i2c, reg, 1, &tmp);
tmp = (tmp & ~mask) | val;
if (ret == 0) {
ret = lp3971_i2c_write(lp3971->i2c, reg, 1, &tmp);
dev_dbg(lp3971->dev, "reg write 0x%02x -> 0x%02x\n", (int)reg,
(unsigned)val&0xff);
}
mutex_unlock(&lp3971->io_lock);
return ret;
}
static int __devinit setup_regulators(struct lp3971 *lp3971,
struct lp3971_platform_data *pdata)
{
int i, err;
lp3971->num_regulators = pdata->num_regulators;
lp3971->rdev = kcalloc(pdata->num_regulators,
sizeof(struct regulator_dev *), GFP_KERNEL);
if (!lp3971->rdev) {
err = -ENOMEM;
goto err_nomem;
}
/* Instantiate the regulators */
for (i = 0; i < pdata->num_regulators; i++) {
struct lp3971_regulator_subdev *reg = &pdata->regulators[i];
lp3971->rdev[i] = regulator_register(®ulators[reg->id],
lp3971->dev, reg->initdata, lp3971);
if (IS_ERR(lp3971->rdev[i])) {
err = PTR_ERR(lp3971->rdev[i]);
dev_err(lp3971->dev, "regulator init failed: %d\n",
err);
goto error;
}
}
return 0;
error:
while (--i >= 0)
regulator_unregister(lp3971->rdev[i]);
kfree(lp3971->rdev);
lp3971->rdev = NULL;
err_nomem:
return err;
}
static int __devinit lp3971_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct lp3971 *lp3971;
struct lp3971_platform_data *pdata = i2c->dev.platform_data;
int ret;
u16 val;
if (!pdata) {
dev_dbg(&i2c->dev, "No platform init data supplied\n");
return -ENODEV;
}
lp3971 = kzalloc(sizeof(struct lp3971), GFP_KERNEL);
if (lp3971 == NULL)
return -ENOMEM;
lp3971->i2c = i2c;
lp3971->dev = &i2c->dev;
mutex_init(&lp3971->io_lock);
/* Detect LP3971 */
ret = lp3971_i2c_read(i2c, LP3971_SYS_CONTROL1_REG, 1, &val);
if (ret == 0 && (val & SYS_CONTROL1_INIT_MASK) != SYS_CONTROL1_INIT_VAL)
ret = -ENODEV;
if (ret < 0) {
dev_err(&i2c->dev, "failed to detect device\n");
goto err_detect;
}
ret = setup_regulators(lp3971, pdata);
if (ret < 0)
goto err_detect;
i2c_set_clientdata(i2c, lp3971);
return 0;
err_detect:
kfree(lp3971);
return ret;
}
static int __devexit lp3971_i2c_remove(struct i2c_client *i2c)
{
struct lp3971 *lp3971 = i2c_get_clientdata(i2c);
int i;
for (i = 0; i < lp3971->num_regulators; i++)
regulator_unregister(lp3971->rdev[i]);
kfree(lp3971->rdev);
kfree(lp3971);
return 0;
}
static const struct i2c_device_id lp3971_i2c_id[] = {
{ "lp3971", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, lp3971_i2c_id);
static struct i2c_driver lp3971_i2c_driver = {
.driver = {
.name = "LP3971",
.owner = THIS_MODULE,
},
.probe = lp3971_i2c_probe,
.remove = __devexit_p(lp3971_i2c_remove),
.id_table = lp3971_i2c_id,
};
static int __init lp3971_module_init(void)
{
int ret;
ret = i2c_add_driver(&lp3971_i2c_driver);
if (ret != 0)
pr_err("Failed to register I2C driver: %d\n", ret);
return ret;
}
module_init(lp3971_module_init);
static void __exit lp3971_module_exit(void)
{
i2c_del_driver(&lp3971_i2c_driver);
}
module_exit(lp3971_module_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marek Szyprowski <m.szyprowski@samsung.com>");
MODULE_DESCRIPTION("LP3971 PMIC driver");
| gpl-2.0 |
gurifuxi/gb_kernel_sc05d | drivers/infiniband/hw/qib/qib_fs.c | 760 | 14658 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
* Copyright (c) 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/module.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/namei.h>
#include "qib.h"
#define QIBFS_MAGIC 0x726a77
static struct super_block *qib_super;
#define private2dd(file) ((file)->f_dentry->d_inode->i_private)
static int qibfs_mknod(struct inode *dir, struct dentry *dentry,
int mode, const struct file_operations *fops,
void *data)
{
int error;
struct inode *inode = new_inode(dir->i_sb);
if (!inode) {
error = -EPERM;
goto bail;
}
inode->i_mode = mode;
inode->i_uid = 0;
inode->i_gid = 0;
inode->i_blocks = 0;
inode->i_atime = CURRENT_TIME;
inode->i_mtime = inode->i_atime;
inode->i_ctime = inode->i_atime;
inode->i_private = data;
if ((mode & S_IFMT) == S_IFDIR) {
inode->i_op = &simple_dir_inode_operations;
inc_nlink(inode);
inc_nlink(dir);
}
inode->i_fop = fops;
d_instantiate(dentry, inode);
error = 0;
bail:
return error;
}
static int create_file(const char *name, mode_t mode,
struct dentry *parent, struct dentry **dentry,
const struct file_operations *fops, void *data)
{
int error;
*dentry = NULL;
mutex_lock(&parent->d_inode->i_mutex);
*dentry = lookup_one_len(name, parent, strlen(name));
if (!IS_ERR(*dentry))
error = qibfs_mknod(parent->d_inode, *dentry,
mode, fops, data);
else
error = PTR_ERR(*dentry);
mutex_unlock(&parent->d_inode->i_mutex);
return error;
}
static ssize_t driver_stats_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return simple_read_from_buffer(buf, count, ppos, &qib_stats,
sizeof qib_stats);
}
/*
* driver stats field names, one line per stat, single string. Used by
* programs like ipathstats to print the stats in a way which works for
* different versions of drivers, without changing program source.
* if qlogic_ib_stats changes, this needs to change. Names need to be
* 12 chars or less (w/o newline), for proper display by ipathstats utility.
*/
static const char qib_statnames[] =
"KernIntr\n"
"ErrorIntr\n"
"Tx_Errs\n"
"Rcv_Errs\n"
"H/W_Errs\n"
"NoPIOBufs\n"
"CtxtsOpen\n"
"RcvLen_Errs\n"
"EgrBufFull\n"
"EgrHdrFull\n"
;
static ssize_t driver_names_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return simple_read_from_buffer(buf, count, ppos, qib_statnames,
sizeof qib_statnames - 1); /* no null */
}
static const struct file_operations driver_ops[] = {
{ .read = driver_stats_read, },
{ .read = driver_names_read, },
};
/* read the per-device counters */
static ssize_t dev_counters_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
u64 *counters;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_cntrs(dd, *ppos, NULL, &counters);
return simple_read_from_buffer(buf, count, ppos, counters, avail);
}
/* read the per-device counters */
static ssize_t dev_names_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *names;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_cntrs(dd, *ppos, &names, NULL);
return simple_read_from_buffer(buf, count, ppos, names, avail);
}
static const struct file_operations cntr_ops[] = {
{ .read = dev_counters_read, },
{ .read = dev_names_read, },
};
/*
* Could use file->f_dentry->d_inode->i_ino to figure out which file,
* instead of separate routine for each, but for now, this works...
*/
/* read the per-port names (same for each port) */
static ssize_t portnames_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *names;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_portcntrs(dd, *ppos, 0, &names, NULL);
return simple_read_from_buffer(buf, count, ppos, names, avail);
}
/* read the per-port counters for port 1 (pidx 0) */
static ssize_t portcntrs_1_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
u64 *counters;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_portcntrs(dd, *ppos, 0, NULL, &counters);
return simple_read_from_buffer(buf, count, ppos, counters, avail);
}
/* read the per-port counters for port 2 (pidx 1) */
static ssize_t portcntrs_2_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
u64 *counters;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_portcntrs(dd, *ppos, 1, NULL, &counters);
return simple_read_from_buffer(buf, count, ppos, counters, avail);
}
static const struct file_operations portcntr_ops[] = {
{ .read = portnames_read, },
{ .read = portcntrs_1_read, },
{ .read = portcntrs_2_read, },
};
/*
* read the per-port QSFP data for port 1 (pidx 0)
*/
static ssize_t qsfp_1_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd = private2dd(file);
char *tmp;
int ret;
tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
ret = qib_qsfp_dump(dd->pport, tmp, PAGE_SIZE);
if (ret > 0)
ret = simple_read_from_buffer(buf, count, ppos, tmp, ret);
kfree(tmp);
return ret;
}
/*
* read the per-port QSFP data for port 2 (pidx 1)
*/
static ssize_t qsfp_2_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd = private2dd(file);
char *tmp;
int ret;
if (dd->num_pports < 2)
return -ENODEV;
tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
ret = qib_qsfp_dump(dd->pport + 1, tmp, PAGE_SIZE);
if (ret > 0)
ret = simple_read_from_buffer(buf, count, ppos, tmp, ret);
kfree(tmp);
return ret;
}
static const struct file_operations qsfp_ops[] = {
{ .read = qsfp_1_read, },
{ .read = qsfp_2_read, },
};
static ssize_t flash_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd;
ssize_t ret;
loff_t pos;
char *tmp;
pos = *ppos;
if (pos < 0) {
ret = -EINVAL;
goto bail;
}
if (pos >= sizeof(struct qib_flash)) {
ret = 0;
goto bail;
}
if (count > sizeof(struct qib_flash) - pos)
count = sizeof(struct qib_flash) - pos;
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp) {
ret = -ENOMEM;
goto bail;
}
dd = private2dd(file);
if (qib_eeprom_read(dd, pos, tmp, count)) {
qib_dev_err(dd, "failed to read from flash\n");
ret = -ENXIO;
goto bail_tmp;
}
if (copy_to_user(buf, tmp, count)) {
ret = -EFAULT;
goto bail_tmp;
}
*ppos = pos + count;
ret = count;
bail_tmp:
kfree(tmp);
bail:
return ret;
}
static ssize_t flash_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd;
ssize_t ret;
loff_t pos;
char *tmp;
pos = *ppos;
if (pos != 0) {
ret = -EINVAL;
goto bail;
}
if (count != sizeof(struct qib_flash)) {
ret = -EINVAL;
goto bail;
}
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp) {
ret = -ENOMEM;
goto bail;
}
if (copy_from_user(tmp, buf, count)) {
ret = -EFAULT;
goto bail_tmp;
}
dd = private2dd(file);
if (qib_eeprom_write(dd, pos, tmp, count)) {
ret = -ENXIO;
qib_dev_err(dd, "failed to write to flash\n");
goto bail_tmp;
}
*ppos = pos + count;
ret = count;
bail_tmp:
kfree(tmp);
bail:
return ret;
}
static const struct file_operations flash_ops = {
.read = flash_read,
.write = flash_write,
};
static int add_cntr_files(struct super_block *sb, struct qib_devdata *dd)
{
struct dentry *dir, *tmp;
char unit[10];
int ret, i;
/* create the per-unit directory */
snprintf(unit, sizeof unit, "%u", dd->unit);
ret = create_file(unit, S_IFDIR|S_IRUGO|S_IXUGO, sb->s_root, &dir,
&simple_dir_operations, dd);
if (ret) {
printk(KERN_ERR "create_file(%s) failed: %d\n", unit, ret);
goto bail;
}
/* create the files in the new directory */
ret = create_file("counters", S_IFREG|S_IRUGO, dir, &tmp,
&cntr_ops[0], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/counters) failed: %d\n",
unit, ret);
goto bail;
}
ret = create_file("counter_names", S_IFREG|S_IRUGO, dir, &tmp,
&cntr_ops[1], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/counter_names) failed: %d\n",
unit, ret);
goto bail;
}
ret = create_file("portcounter_names", S_IFREG|S_IRUGO, dir, &tmp,
&portcntr_ops[0], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/%s) failed: %d\n",
unit, "portcounter_names", ret);
goto bail;
}
for (i = 1; i <= dd->num_pports; i++) {
char fname[24];
sprintf(fname, "port%dcounters", i);
/* create the files in the new directory */
ret = create_file(fname, S_IFREG|S_IRUGO, dir, &tmp,
&portcntr_ops[i], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/%s) failed: %d\n",
unit, fname, ret);
goto bail;
}
if (!(dd->flags & QIB_HAS_QSFP))
continue;
sprintf(fname, "qsfp%d", i);
ret = create_file(fname, S_IFREG|S_IRUGO, dir, &tmp,
&qsfp_ops[i - 1], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/%s) failed: %d\n",
unit, fname, ret);
goto bail;
}
}
ret = create_file("flash", S_IFREG|S_IWUSR|S_IRUGO, dir, &tmp,
&flash_ops, dd);
if (ret)
printk(KERN_ERR "create_file(%s/flash) failed: %d\n",
unit, ret);
bail:
return ret;
}
static int remove_file(struct dentry *parent, char *name)
{
struct dentry *tmp;
int ret;
tmp = lookup_one_len(name, parent, strlen(name));
if (IS_ERR(tmp)) {
ret = PTR_ERR(tmp);
goto bail;
}
spin_lock(&dcache_lock);
spin_lock(&tmp->d_lock);
if (!(d_unhashed(tmp) && tmp->d_inode)) {
dget_locked(tmp);
__d_drop(tmp);
spin_unlock(&tmp->d_lock);
spin_unlock(&dcache_lock);
simple_unlink(parent->d_inode, tmp);
} else {
spin_unlock(&tmp->d_lock);
spin_unlock(&dcache_lock);
}
ret = 0;
bail:
/*
* We don't expect clients to care about the return value, but
* it's there if they need it.
*/
return ret;
}
static int remove_device_files(struct super_block *sb,
struct qib_devdata *dd)
{
struct dentry *dir, *root;
char unit[10];
int ret, i;
root = dget(sb->s_root);
mutex_lock(&root->d_inode->i_mutex);
snprintf(unit, sizeof unit, "%u", dd->unit);
dir = lookup_one_len(unit, root, strlen(unit));
if (IS_ERR(dir)) {
ret = PTR_ERR(dir);
printk(KERN_ERR "Lookup of %s failed\n", unit);
goto bail;
}
remove_file(dir, "counters");
remove_file(dir, "counter_names");
remove_file(dir, "portcounter_names");
for (i = 0; i < dd->num_pports; i++) {
char fname[24];
sprintf(fname, "port%dcounters", i + 1);
remove_file(dir, fname);
if (dd->flags & QIB_HAS_QSFP) {
sprintf(fname, "qsfp%d", i + 1);
remove_file(dir, fname);
}
}
remove_file(dir, "flash");
d_delete(dir);
ret = simple_rmdir(root->d_inode, dir);
bail:
mutex_unlock(&root->d_inode->i_mutex);
dput(root);
return ret;
}
/*
* This fills everything in when the fs is mounted, to handle umount/mount
* after device init. The direct add_cntr_files() call handles adding
* them from the init code, when the fs is already mounted.
*/
static int qibfs_fill_super(struct super_block *sb, void *data, int silent)
{
struct qib_devdata *dd, *tmp;
unsigned long flags;
int ret;
static struct tree_descr files[] = {
[2] = {"driver_stats", &driver_ops[0], S_IRUGO},
[3] = {"driver_stats_names", &driver_ops[1], S_IRUGO},
{""},
};
ret = simple_fill_super(sb, QIBFS_MAGIC, files);
if (ret) {
printk(KERN_ERR "simple_fill_super failed: %d\n", ret);
goto bail;
}
spin_lock_irqsave(&qib_devs_lock, flags);
list_for_each_entry_safe(dd, tmp, &qib_dev_list, list) {
spin_unlock_irqrestore(&qib_devs_lock, flags);
ret = add_cntr_files(sb, dd);
if (ret)
goto bail;
spin_lock_irqsave(&qib_devs_lock, flags);
}
spin_unlock_irqrestore(&qib_devs_lock, flags);
bail:
return ret;
}
static int qibfs_get_sb(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data, struct vfsmount *mnt)
{
int ret = get_sb_single(fs_type, flags, data,
qibfs_fill_super, mnt);
if (ret >= 0)
qib_super = mnt->mnt_sb;
return ret;
}
static void qibfs_kill_super(struct super_block *s)
{
kill_litter_super(s);
qib_super = NULL;
}
int qibfs_add(struct qib_devdata *dd)
{
int ret;
/*
* On first unit initialized, qib_super will not yet exist
* because nobody has yet tried to mount the filesystem, so
* we can't consider that to be an error; if an error occurs
* during the mount, that will get a complaint, so this is OK.
* add_cntr_files() for all units is done at mount from
* qibfs_fill_super(), so one way or another, everything works.
*/
if (qib_super == NULL)
ret = 0;
else
ret = add_cntr_files(qib_super, dd);
return ret;
}
int qibfs_remove(struct qib_devdata *dd)
{
int ret = 0;
if (qib_super)
ret = remove_device_files(qib_super, dd);
return ret;
}
static struct file_system_type qibfs_fs_type = {
.owner = THIS_MODULE,
.name = "ipathfs",
.get_sb = qibfs_get_sb,
.kill_sb = qibfs_kill_super,
};
int __init qib_init_qibfs(void)
{
return register_filesystem(&qibfs_fs_type);
}
int __exit qib_exit_qibfs(void)
{
return unregister_filesystem(&qibfs_fs_type);
}
| gpl-2.0 |
oschmidt/kernel_I8160P | drivers/media/video/cx88/cx88-input.c | 760 | 17047 | /*
*
* Device driver for GPIO attached remote control interfaces
* on Conexant 2388x based TV/DVB cards.
*
* Copyright (c) 2003 Pavel Machek
* Copyright (c) 2004 Gerd Knorr
* Copyright (c) 2004, 2005 Chris Pascoe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/hrtimer.h>
#include <linux/input.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/module.h>
#include "cx88.h"
#include <media/ir-common.h>
#define MODULE_NAME "cx88xx"
/* ---------------------------------------------------------------------- */
struct cx88_IR {
struct cx88_core *core;
struct input_dev *input;
struct ir_input_state ir;
struct ir_dev_props props;
int users;
char name[32];
char phys[32];
/* sample from gpio pin 16 */
u32 sampling;
u32 samples[16];
int scount;
unsigned long release;
/* poll external decoder */
int polling;
struct hrtimer timer;
u32 gpio_addr;
u32 last_gpio;
u32 mask_keycode;
u32 mask_keydown;
u32 mask_keyup;
};
static int ir_debug;
module_param(ir_debug, int, 0644); /* debug level [IR] */
MODULE_PARM_DESC(ir_debug, "enable debug messages [IR]");
#define ir_dprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s IR: " fmt , ir->core->name , ##arg)
/* ---------------------------------------------------------------------- */
static void cx88_ir_handle_key(struct cx88_IR *ir)
{
struct cx88_core *core = ir->core;
u32 gpio, data, auxgpio;
/* read gpio value */
gpio = cx_read(ir->gpio_addr);
switch (core->boardnr) {
case CX88_BOARD_NPGTECH_REALTV_TOP10FM:
/* This board apparently uses a combination of 2 GPIO
to represent the keys. Additionally, the second GPIO
can be used for parity.
Example:
for key "5"
gpio = 0x758, auxgpio = 0xe5 or 0xf5
for key "Power"
gpio = 0x758, auxgpio = 0xed or 0xfd
*/
auxgpio = cx_read(MO_GP1_IO);
/* Take out the parity part */
gpio=(gpio & 0x7fd) + (auxgpio & 0xef);
break;
case CX88_BOARD_WINFAST_DTV1000:
case CX88_BOARD_WINFAST_DTV1800H:
case CX88_BOARD_WINFAST_TV2000_XP_GLOBAL:
gpio = (gpio & 0x6ff) | ((cx_read(MO_GP1_IO) << 8) & 0x900);
auxgpio = gpio;
break;
default:
auxgpio = gpio;
}
if (ir->polling) {
if (ir->last_gpio == auxgpio)
return;
ir->last_gpio = auxgpio;
}
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
ir_dprintk("irq gpio=0x%x code=%d | %s%s%s\n",
gpio, data,
ir->polling ? "poll" : "irq",
(gpio & ir->mask_keydown) ? " down" : "",
(gpio & ir->mask_keyup) ? " up" : "");
if (ir->core->boardnr == CX88_BOARD_NORWOOD_MICRO) {
u32 gpio_key = cx_read(MO_GP0_IO);
data = (data << 4) | ((gpio_key & 0xf0) >> 4);
ir_input_keydown(ir->input, &ir->ir, data);
ir_input_nokey(ir->input, &ir->ir);
} else if (ir->mask_keydown) {
/* bit set on keydown */
if (gpio & ir->mask_keydown) {
ir_input_keydown(ir->input, &ir->ir, data);
} else {
ir_input_nokey(ir->input, &ir->ir);
}
} else if (ir->mask_keyup) {
/* bit cleared on keydown */
if (0 == (gpio & ir->mask_keyup)) {
ir_input_keydown(ir->input, &ir->ir, data);
} else {
ir_input_nokey(ir->input, &ir->ir);
}
} else {
/* can't distinguish keydown/up :-/ */
ir_input_keydown(ir->input, &ir->ir, data);
ir_input_nokey(ir->input, &ir->ir);
}
}
static enum hrtimer_restart cx88_ir_work(struct hrtimer *timer)
{
unsigned long missed;
struct cx88_IR *ir = container_of(timer, struct cx88_IR, timer);
cx88_ir_handle_key(ir);
missed = hrtimer_forward_now(&ir->timer,
ktime_set(0, ir->polling * 1000000));
if (missed > 1)
ir_dprintk("Missed ticks %ld\n", missed - 1);
return HRTIMER_RESTART;
}
static int __cx88_ir_start(void *priv)
{
struct cx88_core *core = priv;
struct cx88_IR *ir;
if (!core || !core->ir)
return -EINVAL;
ir = core->ir;
if (ir->polling) {
hrtimer_init(&ir->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
ir->timer.function = cx88_ir_work;
hrtimer_start(&ir->timer,
ktime_set(0, ir->polling * 1000000),
HRTIMER_MODE_REL);
}
if (ir->sampling) {
core->pci_irqmask |= PCI_INT_IR_SMPINT;
cx_write(MO_DDS_IO, 0xa80a80); /* 4 kHz sample rate */
cx_write(MO_DDSCFG_IO, 0x5); /* enable */
}
return 0;
}
static void __cx88_ir_stop(void *priv)
{
struct cx88_core *core = priv;
struct cx88_IR *ir;
if (!core || !core->ir)
return;
ir = core->ir;
if (ir->sampling) {
cx_write(MO_DDSCFG_IO, 0x0);
core->pci_irqmask &= ~PCI_INT_IR_SMPINT;
}
if (ir->polling)
hrtimer_cancel(&ir->timer);
}
int cx88_ir_start(struct cx88_core *core)
{
if (core->ir->users)
return __cx88_ir_start(core);
return 0;
}
void cx88_ir_stop(struct cx88_core *core)
{
if (core->ir->users)
__cx88_ir_stop(core);
}
static int cx88_ir_open(void *priv)
{
struct cx88_core *core = priv;
core->ir->users++;
return __cx88_ir_start(core);
}
static void cx88_ir_close(void *priv)
{
struct cx88_core *core = priv;
core->ir->users--;
if (!core->ir->users)
__cx88_ir_stop(core);
}
/* ---------------------------------------------------------------------- */
int cx88_ir_init(struct cx88_core *core, struct pci_dev *pci)
{
struct cx88_IR *ir;
struct input_dev *input_dev;
char *ir_codes = NULL;
u64 ir_type = IR_TYPE_OTHER;
int err = -ENOMEM;
u32 hardware_mask = 0; /* For devices with a hardware mask, when
* used with a full-code IR table
*/
ir = kzalloc(sizeof(*ir), GFP_KERNEL);
input_dev = input_allocate_device();
if (!ir || !input_dev)
goto err_out_free;
ir->input = input_dev;
/* detect & configure */
switch (core->boardnr) {
case CX88_BOARD_DNTV_LIVE_DVB_T:
case CX88_BOARD_KWORLD_DVB_T:
case CX88_BOARD_KWORLD_DVB_T_CX22702:
ir_codes = RC_MAP_DNTV_LIVE_DVB_T;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keycode = 0x1f;
ir->mask_keyup = 0x60;
ir->polling = 50; /* ms */
break;
case CX88_BOARD_TERRATEC_CINERGY_1400_DVB_T1:
ir_codes = RC_MAP_CINERGY_1400;
ir_type = IR_TYPE_NEC;
ir->sampling = 0xeb04; /* address */
break;
case CX88_BOARD_HAUPPAUGE:
case CX88_BOARD_HAUPPAUGE_DVB_T1:
case CX88_BOARD_HAUPPAUGE_NOVASE2_S1:
case CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1:
case CX88_BOARD_HAUPPAUGE_HVR1100:
case CX88_BOARD_HAUPPAUGE_HVR3000:
case CX88_BOARD_HAUPPAUGE_HVR4000:
case CX88_BOARD_HAUPPAUGE_HVR4000LITE:
case CX88_BOARD_PCHDTV_HD3000:
case CX88_BOARD_PCHDTV_HD5500:
case CX88_BOARD_HAUPPAUGE_IRONLY:
ir_codes = RC_MAP_HAUPPAUGE_NEW;
ir_type = IR_TYPE_RC5;
ir->sampling = 1;
break;
case CX88_BOARD_WINFAST_DTV2000H:
case CX88_BOARD_WINFAST_DTV2000H_J:
case CX88_BOARD_WINFAST_DTV1800H:
ir_codes = RC_MAP_WINFAST;
ir->gpio_addr = MO_GP0_IO;
ir->mask_keycode = 0x8f8;
ir->mask_keyup = 0x100;
ir->polling = 50; /* ms */
break;
case CX88_BOARD_WINFAST2000XP_EXPERT:
case CX88_BOARD_WINFAST_DTV1000:
case CX88_BOARD_WINFAST_TV2000_XP_GLOBAL:
ir_codes = RC_MAP_WINFAST;
ir->gpio_addr = MO_GP0_IO;
ir->mask_keycode = 0x8f8;
ir->mask_keyup = 0x100;
ir->polling = 1; /* ms */
break;
case CX88_BOARD_IODATA_GVBCTV7E:
ir_codes = RC_MAP_IODATA_BCTV7E;
ir->gpio_addr = MO_GP0_IO;
ir->mask_keycode = 0xfd;
ir->mask_keydown = 0x02;
ir->polling = 5; /* ms */
break;
case CX88_BOARD_PROLINK_PLAYTVPVR:
case CX88_BOARD_PIXELVIEW_PLAYTV_ULTRA_PRO:
/*
* It seems that this hardware is paired with NEC extended
* address 0x866b. So, unfortunately, its usage with other
* IR's with different address won't work. Still, there are
* other IR's from the same manufacturer that works, like the
* 002-T mini RC, provided with newer PV hardware
*/
ir_codes = RC_MAP_PIXELVIEW_MK12;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keyup = 0x80;
ir->polling = 10; /* ms */
hardware_mask = 0x3f; /* Hardware returns only 6 bits from command part */
break;
case CX88_BOARD_PROLINK_PV_8000GT:
case CX88_BOARD_PROLINK_PV_GLOBAL_XTREME:
ir_codes = RC_MAP_PIXELVIEW_NEW;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keycode = 0x3f;
ir->mask_keyup = 0x80;
ir->polling = 1; /* ms */
break;
case CX88_BOARD_KWORLD_LTV883:
ir_codes = RC_MAP_PIXELVIEW;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keycode = 0x1f;
ir->mask_keyup = 0x60;
ir->polling = 1; /* ms */
break;
case CX88_BOARD_ADSTECH_DVB_T_PCI:
ir_codes = RC_MAP_ADSTECH_DVB_T_PCI;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keycode = 0xbf;
ir->mask_keyup = 0x40;
ir->polling = 50; /* ms */
break;
case CX88_BOARD_MSI_TVANYWHERE_MASTER:
ir_codes = RC_MAP_MSI_TVANYWHERE;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keycode = 0x1f;
ir->mask_keyup = 0x40;
ir->polling = 1; /* ms */
break;
case CX88_BOARD_AVERTV_303:
case CX88_BOARD_AVERTV_STUDIO_303:
ir_codes = RC_MAP_AVERTV_303;
ir->gpio_addr = MO_GP2_IO;
ir->mask_keycode = 0xfb;
ir->mask_keydown = 0x02;
ir->polling = 50; /* ms */
break;
case CX88_BOARD_OMICOM_SS4_PCI:
case CX88_BOARD_SATTRADE_ST4200:
case CX88_BOARD_TBS_8920:
case CX88_BOARD_TBS_8910:
case CX88_BOARD_PROF_7300:
case CX88_BOARD_PROF_7301:
case CX88_BOARD_PROF_6200:
ir_codes = RC_MAP_TBS_NEC;
ir_type = IR_TYPE_NEC;
ir->sampling = 0xff00; /* address */
break;
case CX88_BOARD_TEVII_S460:
case CX88_BOARD_TEVII_S420:
ir_codes = RC_MAP_TEVII_NEC;
ir_type = IR_TYPE_NEC;
ir->sampling = 0xff00; /* address */
break;
case CX88_BOARD_DNTV_LIVE_DVB_T_PRO:
ir_codes = RC_MAP_DNTV_LIVE_DVBT_PRO;
ir_type = IR_TYPE_NEC;
ir->sampling = 0xff00; /* address */
break;
case CX88_BOARD_NORWOOD_MICRO:
ir_codes = RC_MAP_NORWOOD;
ir->gpio_addr = MO_GP1_IO;
ir->mask_keycode = 0x0e;
ir->mask_keyup = 0x80;
ir->polling = 50; /* ms */
break;
case CX88_BOARD_NPGTECH_REALTV_TOP10FM:
ir_codes = RC_MAP_NPGTECH;
ir->gpio_addr = MO_GP0_IO;
ir->mask_keycode = 0xfa;
ir->polling = 50; /* ms */
break;
case CX88_BOARD_PINNACLE_PCTV_HD_800i:
ir_codes = RC_MAP_PINNACLE_PCTV_HD;
ir_type = IR_TYPE_RC5;
ir->sampling = 1;
break;
case CX88_BOARD_POWERCOLOR_REAL_ANGEL:
ir_codes = RC_MAP_POWERCOLOR_REAL_ANGEL;
ir->gpio_addr = MO_GP2_IO;
ir->mask_keycode = 0x7e;
ir->polling = 100; /* ms */
break;
}
if (NULL == ir_codes) {
err = -ENODEV;
goto err_out_free;
}
/*
* The usage of mask_keycode were very convenient, due to several
* reasons. Among others, the scancode tables were using the scancode
* as the index elements. So, the less bits it was used, the smaller
* the table were stored. After the input changes, the better is to use
* the full scancodes, since it allows replacing the IR remote by
* another one. Unfortunately, there are still some hardware, like
* Pixelview Ultra Pro, where only part of the scancode is sent via
* GPIO. So, there's no way to get the full scancode. Due to that,
* hardware_mask were introduced here: it represents those hardware
* that has such limits.
*/
if (hardware_mask && !ir->mask_keycode)
ir->mask_keycode = hardware_mask;
/* init input device */
snprintf(ir->name, sizeof(ir->name), "cx88 IR (%s)", core->board.name);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0", pci_name(pci));
err = ir_input_init(input_dev, &ir->ir, ir_type);
if (err < 0)
goto err_out_free;
input_dev->name = ir->name;
input_dev->phys = ir->phys;
input_dev->id.bustype = BUS_PCI;
input_dev->id.version = 1;
if (pci->subsystem_vendor) {
input_dev->id.vendor = pci->subsystem_vendor;
input_dev->id.product = pci->subsystem_device;
} else {
input_dev->id.vendor = pci->vendor;
input_dev->id.product = pci->device;
}
input_dev->dev.parent = &pci->dev;
/* record handles to ourself */
ir->core = core;
core->ir = ir;
ir->props.priv = core;
ir->props.open = cx88_ir_open;
ir->props.close = cx88_ir_close;
ir->props.scanmask = hardware_mask;
/* all done */
err = ir_input_register(ir->input, ir_codes, &ir->props, MODULE_NAME);
if (err)
goto err_out_free;
return 0;
err_out_free:
core->ir = NULL;
kfree(ir);
return err;
}
int cx88_ir_fini(struct cx88_core *core)
{
struct cx88_IR *ir = core->ir;
/* skip detach on non attached boards */
if (NULL == ir)
return 0;
cx88_ir_stop(core);
ir_input_unregister(ir->input);
kfree(ir);
/* done */
core->ir = NULL;
return 0;
}
/* ---------------------------------------------------------------------- */
void cx88_ir_irq(struct cx88_core *core)
{
struct cx88_IR *ir = core->ir;
u32 samples, ircode;
int i, start, range, toggle, dev, code;
if (NULL == ir)
return;
if (!ir->sampling)
return;
samples = cx_read(MO_SAMPLE_IO);
if (0 != samples && 0xffffffff != samples) {
/* record sample data */
if (ir->scount < ARRAY_SIZE(ir->samples))
ir->samples[ir->scount++] = samples;
return;
}
if (!ir->scount) {
/* nothing to sample */
if (ir->ir.keypressed && time_after(jiffies, ir->release))
ir_input_nokey(ir->input, &ir->ir);
return;
}
/* have a complete sample */
if (ir->scount < ARRAY_SIZE(ir->samples))
ir->samples[ir->scount++] = samples;
for (i = 0; i < ir->scount; i++)
ir->samples[i] = ~ir->samples[i];
if (ir_debug)
ir_dump_samples(ir->samples, ir->scount);
/* decode it */
switch (core->boardnr) {
case CX88_BOARD_TEVII_S460:
case CX88_BOARD_TEVII_S420:
case CX88_BOARD_TERRATEC_CINERGY_1400_DVB_T1:
case CX88_BOARD_DNTV_LIVE_DVB_T_PRO:
case CX88_BOARD_OMICOM_SS4_PCI:
case CX88_BOARD_SATTRADE_ST4200:
case CX88_BOARD_TBS_8920:
case CX88_BOARD_TBS_8910:
case CX88_BOARD_PROF_7300:
case CX88_BOARD_PROF_7301:
case CX88_BOARD_PROF_6200:
ircode = ir_decode_pulsedistance(ir->samples, ir->scount, 1, 4);
if (ircode == 0xffffffff) { /* decoding error */
ir_dprintk("pulse distance decoding error\n");
break;
}
ir_dprintk("pulse distance decoded: %x\n", ircode);
if (ircode == 0) { /* key still pressed */
ir_dprintk("pulse distance decoded repeat code\n");
ir->release = jiffies + msecs_to_jiffies(120);
break;
}
if ((ircode & 0xffff) != (ir->sampling & 0xffff)) { /* wrong address */
ir_dprintk("pulse distance decoded wrong address\n");
break;
}
if (((~ircode >> 24) & 0xff) != ((ircode >> 16) & 0xff)) { /* wrong checksum */
ir_dprintk("pulse distance decoded wrong check sum\n");
break;
}
ir_dprintk("Key Code: %x\n", (ircode >> 16) & 0x7f);
ir_input_keydown(ir->input, &ir->ir, (ircode >> 16) & 0x7f);
ir->release = jiffies + msecs_to_jiffies(120);
break;
case CX88_BOARD_HAUPPAUGE:
case CX88_BOARD_HAUPPAUGE_DVB_T1:
case CX88_BOARD_HAUPPAUGE_NOVASE2_S1:
case CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1:
case CX88_BOARD_HAUPPAUGE_HVR1100:
case CX88_BOARD_HAUPPAUGE_HVR3000:
case CX88_BOARD_HAUPPAUGE_HVR4000:
case CX88_BOARD_HAUPPAUGE_HVR4000LITE:
case CX88_BOARD_PCHDTV_HD3000:
case CX88_BOARD_PCHDTV_HD5500:
case CX88_BOARD_HAUPPAUGE_IRONLY:
ircode = ir_decode_biphase(ir->samples, ir->scount, 5, 7);
ir_dprintk("biphase decoded: %x\n", ircode);
/*
* RC5 has an extension bit which adds a new range
* of available codes, this is detected here. Also
* hauppauge remotes (black/silver) always use
* specific device ids. If we do not filter the
* device ids then messages destined for devices
* such as TVs (id=0) will get through to the
* device causing mis-fired events.
*/
/* split rc5 data block ... */
start = (ircode & 0x2000) >> 13;
range = (ircode & 0x1000) >> 12;
toggle= (ircode & 0x0800) >> 11;
dev = (ircode & 0x07c0) >> 6;
code = (ircode & 0x003f) | ((range << 6) ^ 0x0040);
if( start != 1)
/* no key pressed */
break;
if ( dev != 0x1e && dev != 0x1f )
/* not a hauppauge remote */
break;
ir_input_keydown(ir->input, &ir->ir, code);
ir->release = jiffies + msecs_to_jiffies(120);
break;
case CX88_BOARD_PINNACLE_PCTV_HD_800i:
ircode = ir_decode_biphase(ir->samples, ir->scount, 5, 7);
ir_dprintk("biphase decoded: %x\n", ircode);
if ((ircode & 0xfffff000) != 0x3000)
break;
ir_input_keydown(ir->input, &ir->ir, ircode & 0x3f);
ir->release = jiffies + msecs_to_jiffies(120);
break;
}
ir->scount = 0;
return;
}
/* ---------------------------------------------------------------------- */
MODULE_AUTHOR("Gerd Knorr, Pavel Machek, Chris Pascoe");
MODULE_DESCRIPTION("input driver for cx88 GPIO-based IR remote controls");
MODULE_LICENSE("GPL");
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
ahnchan2/linux | drivers/net/ethernet/chelsio/cxgb/cxgb2.c | 1016 | 37405 | /*****************************************************************************
* *
* File: cxgb2.c *
* $Revision: 1.25 $ *
* $Date: 2005/06/22 00:43:25 $ *
* Description: *
* Chelsio 10Gb Ethernet Driver. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License, version 2, as *
* published by the Free Software Foundation. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, see <http://www.gnu.org/licenses/>. *
* *
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
* *
* http://www.chelsio.com *
* *
* Copyright (c) 2003 - 2005 Chelsio Communications, Inc. *
* All rights reserved. *
* *
* Maintainers: maintainers@chelsio.com *
* *
* Authors: Dimitrios Michailidis <dm@chelsio.com> *
* Tina Yang <tainay@chelsio.com> *
* Felix Marti <felix@chelsio.com> *
* Scott Bardone <sbardone@chelsio.com> *
* Kurt Ottaway <kottaway@chelsio.com> *
* Frank DiMambro <frank@chelsio.com> *
* *
* History: *
* *
****************************************************************************/
#include "common.h"
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/mii.h>
#include <linux/sockios.h>
#include <linux/dma-mapping.h>
#include <asm/uaccess.h>
#include "cpl5_cmd.h"
#include "regs.h"
#include "gmac.h"
#include "cphy.h"
#include "sge.h"
#include "tp.h"
#include "espi.h"
#include "elmer0.h"
#include <linux/workqueue.h>
static inline void schedule_mac_stats_update(struct adapter *ap, int secs)
{
schedule_delayed_work(&ap->stats_update_task, secs * HZ);
}
static inline void cancel_mac_stats_update(struct adapter *ap)
{
cancel_delayed_work(&ap->stats_update_task);
}
#define MAX_CMDQ_ENTRIES 16384
#define MAX_CMDQ1_ENTRIES 1024
#define MAX_RX_BUFFERS 16384
#define MAX_RX_JUMBO_BUFFERS 16384
#define MAX_TX_BUFFERS_HIGH 16384U
#define MAX_TX_BUFFERS_LOW 1536U
#define MAX_TX_BUFFERS 1460U
#define MIN_FL_ENTRIES 32
#define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
/*
* The EEPROM is actually bigger but only the first few bytes are used so we
* only report those.
*/
#define EEPROM_SIZE 32
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR("Chelsio Communications");
MODULE_LICENSE("GPL");
static int dflt_msg_enable = DFLT_MSG_ENABLE;
module_param(dflt_msg_enable, int, 0);
MODULE_PARM_DESC(dflt_msg_enable, "Chelsio T1 default message enable bitmap");
#define HCLOCK 0x0
#define LCLOCK 0x1
/* T1 cards powersave mode */
static int t1_clock(struct adapter *adapter, int mode);
static int t1powersave = 1; /* HW default is powersave mode. */
module_param(t1powersave, int, 0);
MODULE_PARM_DESC(t1powersave, "Enable/Disable T1 powersaving mode");
static int disable_msi = 0;
module_param(disable_msi, int, 0);
MODULE_PARM_DESC(disable_msi, "Disable Message Signaled Interrupt (MSI)");
static const char pci_speed[][4] = {
"33", "66", "100", "133"
};
/*
* Setup MAC to receive the types of packets we want.
*/
static void t1_set_rxmode(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
struct t1_rx_mode rm;
rm.dev = dev;
mac->ops->set_rx_mode(mac, &rm);
}
static void link_report(struct port_info *p)
{
if (!netif_carrier_ok(p->dev))
netdev_info(p->dev, "link down\n");
else {
const char *s = "10Mbps";
switch (p->link_config.speed) {
case SPEED_10000: s = "10Gbps"; break;
case SPEED_1000: s = "1000Mbps"; break;
case SPEED_100: s = "100Mbps"; break;
}
netdev_info(p->dev, "link up, %s, %s-duplex\n",
s, p->link_config.duplex == DUPLEX_FULL
? "full" : "half");
}
}
void t1_link_negotiated(struct adapter *adapter, int port_id, int link_stat,
int speed, int duplex, int pause)
{
struct port_info *p = &adapter->port[port_id];
if (link_stat != netif_carrier_ok(p->dev)) {
if (link_stat)
netif_carrier_on(p->dev);
else
netif_carrier_off(p->dev);
link_report(p);
/* multi-ports: inform toe */
if ((speed > 0) && (adapter->params.nports > 1)) {
unsigned int sched_speed = 10;
switch (speed) {
case SPEED_1000:
sched_speed = 1000;
break;
case SPEED_100:
sched_speed = 100;
break;
case SPEED_10:
sched_speed = 10;
break;
}
t1_sched_update_parms(adapter->sge, port_id, 0, sched_speed);
}
}
}
static void link_start(struct port_info *p)
{
struct cmac *mac = p->mac;
mac->ops->reset(mac);
if (mac->ops->macaddress_set)
mac->ops->macaddress_set(mac, p->dev->dev_addr);
t1_set_rxmode(p->dev);
t1_link_start(p->phy, mac, &p->link_config);
mac->ops->enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
}
static void enable_hw_csum(struct adapter *adapter)
{
if (adapter->port[0].dev->hw_features & NETIF_F_TSO)
t1_tp_set_ip_checksum_offload(adapter->tp, 1); /* for TSO only */
t1_tp_set_tcp_checksum_offload(adapter->tp, 1);
}
/*
* Things to do upon first use of a card.
* This must run with the rtnl lock held.
*/
static int cxgb_up(struct adapter *adapter)
{
int err = 0;
if (!(adapter->flags & FULL_INIT_DONE)) {
err = t1_init_hw_modules(adapter);
if (err)
goto out_err;
enable_hw_csum(adapter);
adapter->flags |= FULL_INIT_DONE;
}
t1_interrupts_clear(adapter);
adapter->params.has_msi = !disable_msi && !pci_enable_msi(adapter->pdev);
err = request_irq(adapter->pdev->irq, t1_interrupt,
adapter->params.has_msi ? 0 : IRQF_SHARED,
adapter->name, adapter);
if (err) {
if (adapter->params.has_msi)
pci_disable_msi(adapter->pdev);
goto out_err;
}
t1_sge_start(adapter->sge);
t1_interrupts_enable(adapter);
out_err:
return err;
}
/*
* Release resources when all the ports have been stopped.
*/
static void cxgb_down(struct adapter *adapter)
{
t1_sge_stop(adapter->sge);
t1_interrupts_disable(adapter);
free_irq(adapter->pdev->irq, adapter);
if (adapter->params.has_msi)
pci_disable_msi(adapter->pdev);
}
static int cxgb_open(struct net_device *dev)
{
int err;
struct adapter *adapter = dev->ml_priv;
int other_ports = adapter->open_device_map & PORT_MASK;
napi_enable(&adapter->napi);
if (!adapter->open_device_map && (err = cxgb_up(adapter)) < 0) {
napi_disable(&adapter->napi);
return err;
}
__set_bit(dev->if_port, &adapter->open_device_map);
link_start(&adapter->port[dev->if_port]);
netif_start_queue(dev);
if (!other_ports && adapter->params.stats_update_period)
schedule_mac_stats_update(adapter,
adapter->params.stats_update_period);
t1_vlan_mode(adapter, dev->features);
return 0;
}
static int cxgb_close(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct cmac *mac = p->mac;
netif_stop_queue(dev);
napi_disable(&adapter->napi);
mac->ops->disable(mac, MAC_DIRECTION_TX | MAC_DIRECTION_RX);
netif_carrier_off(dev);
clear_bit(dev->if_port, &adapter->open_device_map);
if (adapter->params.stats_update_period &&
!(adapter->open_device_map & PORT_MASK)) {
/* Stop statistics accumulation. */
smp_mb__after_atomic();
spin_lock(&adapter->work_lock); /* sync with update task */
spin_unlock(&adapter->work_lock);
cancel_mac_stats_update(adapter);
}
if (!adapter->open_device_map)
cxgb_down(adapter);
return 0;
}
static struct net_device_stats *t1_get_stats(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct net_device_stats *ns = &p->netstats;
const struct cmac_statistics *pstats;
/* Do a full update of the MAC stats */
pstats = p->mac->ops->statistics_update(p->mac,
MAC_STATS_UPDATE_FULL);
ns->tx_packets = pstats->TxUnicastFramesOK +
pstats->TxMulticastFramesOK + pstats->TxBroadcastFramesOK;
ns->rx_packets = pstats->RxUnicastFramesOK +
pstats->RxMulticastFramesOK + pstats->RxBroadcastFramesOK;
ns->tx_bytes = pstats->TxOctetsOK;
ns->rx_bytes = pstats->RxOctetsOK;
ns->tx_errors = pstats->TxLateCollisions + pstats->TxLengthErrors +
pstats->TxUnderrun + pstats->TxFramesAbortedDueToXSCollisions;
ns->rx_errors = pstats->RxDataErrors + pstats->RxJabberErrors +
pstats->RxFCSErrors + pstats->RxAlignErrors +
pstats->RxSequenceErrors + pstats->RxFrameTooLongErrors +
pstats->RxSymbolErrors + pstats->RxRuntErrors;
ns->multicast = pstats->RxMulticastFramesOK;
ns->collisions = pstats->TxTotalCollisions;
/* detailed rx_errors */
ns->rx_length_errors = pstats->RxFrameTooLongErrors +
pstats->RxJabberErrors;
ns->rx_over_errors = 0;
ns->rx_crc_errors = pstats->RxFCSErrors;
ns->rx_frame_errors = pstats->RxAlignErrors;
ns->rx_fifo_errors = 0;
ns->rx_missed_errors = 0;
/* detailed tx_errors */
ns->tx_aborted_errors = pstats->TxFramesAbortedDueToXSCollisions;
ns->tx_carrier_errors = 0;
ns->tx_fifo_errors = pstats->TxUnderrun;
ns->tx_heartbeat_errors = 0;
ns->tx_window_errors = pstats->TxLateCollisions;
return ns;
}
static u32 get_msglevel(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
return adapter->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct adapter *adapter = dev->ml_priv;
adapter->msg_enable = val;
}
static const char stats_strings[][ETH_GSTRING_LEN] = {
"TxOctetsOK",
"TxOctetsBad",
"TxUnicastFramesOK",
"TxMulticastFramesOK",
"TxBroadcastFramesOK",
"TxPauseFrames",
"TxFramesWithDeferredXmissions",
"TxLateCollisions",
"TxTotalCollisions",
"TxFramesAbortedDueToXSCollisions",
"TxUnderrun",
"TxLengthErrors",
"TxInternalMACXmitError",
"TxFramesWithExcessiveDeferral",
"TxFCSErrors",
"TxJumboFramesOk",
"TxJumboOctetsOk",
"RxOctetsOK",
"RxOctetsBad",
"RxUnicastFramesOK",
"RxMulticastFramesOK",
"RxBroadcastFramesOK",
"RxPauseFrames",
"RxFCSErrors",
"RxAlignErrors",
"RxSymbolErrors",
"RxDataErrors",
"RxSequenceErrors",
"RxRuntErrors",
"RxJabberErrors",
"RxInternalMACRcvError",
"RxInRangeLengthErrors",
"RxOutOfRangeLengthField",
"RxFrameTooLongErrors",
"RxJumboFramesOk",
"RxJumboOctetsOk",
/* Port stats */
"RxCsumGood",
"TxCsumOffload",
"TxTso",
"RxVlan",
"TxVlan",
"TxNeedHeadroom",
/* Interrupt stats */
"rx drops",
"pure_rsps",
"unhandled irqs",
"respQ_empty",
"respQ_overflow",
"freelistQ_empty",
"pkt_too_big",
"pkt_mismatch",
"cmdQ_full0",
"cmdQ_full1",
"espi_DIP2ParityErr",
"espi_DIP4Err",
"espi_RxDrops",
"espi_TxDrops",
"espi_RxOvfl",
"espi_ParityErr"
};
#define T2_REGMAP_SIZE (3 * 1024)
static int get_regs_len(struct net_device *dev)
{
return T2_REGMAP_SIZE;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct adapter *adapter = dev->ml_priv;
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(adapter->pdev),
sizeof(info->bus_info));
}
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(stats_strings);
default:
return -EOPNOTSUPP;
}
}
static void get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, stats_strings, sizeof(stats_strings));
}
static void get_stats(struct net_device *dev, struct ethtool_stats *stats,
u64 *data)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
const struct cmac_statistics *s;
const struct sge_intr_counts *t;
struct sge_port_stats ss;
s = mac->ops->statistics_update(mac, MAC_STATS_UPDATE_FULL);
t = t1_sge_get_intr_counts(adapter->sge);
t1_sge_get_port_stats(adapter->sge, dev->if_port, &ss);
*data++ = s->TxOctetsOK;
*data++ = s->TxOctetsBad;
*data++ = s->TxUnicastFramesOK;
*data++ = s->TxMulticastFramesOK;
*data++ = s->TxBroadcastFramesOK;
*data++ = s->TxPauseFrames;
*data++ = s->TxFramesWithDeferredXmissions;
*data++ = s->TxLateCollisions;
*data++ = s->TxTotalCollisions;
*data++ = s->TxFramesAbortedDueToXSCollisions;
*data++ = s->TxUnderrun;
*data++ = s->TxLengthErrors;
*data++ = s->TxInternalMACXmitError;
*data++ = s->TxFramesWithExcessiveDeferral;
*data++ = s->TxFCSErrors;
*data++ = s->TxJumboFramesOK;
*data++ = s->TxJumboOctetsOK;
*data++ = s->RxOctetsOK;
*data++ = s->RxOctetsBad;
*data++ = s->RxUnicastFramesOK;
*data++ = s->RxMulticastFramesOK;
*data++ = s->RxBroadcastFramesOK;
*data++ = s->RxPauseFrames;
*data++ = s->RxFCSErrors;
*data++ = s->RxAlignErrors;
*data++ = s->RxSymbolErrors;
*data++ = s->RxDataErrors;
*data++ = s->RxSequenceErrors;
*data++ = s->RxRuntErrors;
*data++ = s->RxJabberErrors;
*data++ = s->RxInternalMACRcvError;
*data++ = s->RxInRangeLengthErrors;
*data++ = s->RxOutOfRangeLengthField;
*data++ = s->RxFrameTooLongErrors;
*data++ = s->RxJumboFramesOK;
*data++ = s->RxJumboOctetsOK;
*data++ = ss.rx_cso_good;
*data++ = ss.tx_cso;
*data++ = ss.tx_tso;
*data++ = ss.vlan_xtract;
*data++ = ss.vlan_insert;
*data++ = ss.tx_need_hdrroom;
*data++ = t->rx_drops;
*data++ = t->pure_rsps;
*data++ = t->unhandled_irqs;
*data++ = t->respQ_empty;
*data++ = t->respQ_overflow;
*data++ = t->freelistQ_empty;
*data++ = t->pkt_too_big;
*data++ = t->pkt_mismatch;
*data++ = t->cmdQ_full[0];
*data++ = t->cmdQ_full[1];
if (adapter->espi) {
const struct espi_intr_counts *e;
e = t1_espi_get_intr_counts(adapter->espi);
*data++ = e->DIP2_parity_err;
*data++ = e->DIP4_err;
*data++ = e->rx_drops;
*data++ = e->tx_drops;
*data++ = e->rx_ovflw;
*data++ = e->parity_err;
}
}
static inline void reg_block_dump(struct adapter *ap, void *buf,
unsigned int start, unsigned int end)
{
u32 *p = buf + start;
for ( ; start <= end; start += sizeof(u32))
*p++ = readl(ap->regs + start);
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct adapter *ap = dev->ml_priv;
/*
* Version scheme: bits 0..9: chip version, bits 10..15: chip revision
*/
regs->version = 2;
memset(buf, 0, T2_REGMAP_SIZE);
reg_block_dump(ap, buf, 0, A_SG_RESPACCUTIMER);
reg_block_dump(ap, buf, A_MC3_CFG, A_MC4_INT_CAUSE);
reg_block_dump(ap, buf, A_TPI_ADDR, A_TPI_PAR);
reg_block_dump(ap, buf, A_TP_IN_CONFIG, A_TP_TX_DROP_COUNT);
reg_block_dump(ap, buf, A_RAT_ROUTE_CONTROL, A_RAT_INTR_CAUSE);
reg_block_dump(ap, buf, A_CSPI_RX_AE_WM, A_CSPI_INTR_ENABLE);
reg_block_dump(ap, buf, A_ESPI_SCH_TOKEN0, A_ESPI_GOSTAT);
reg_block_dump(ap, buf, A_ULP_ULIMIT, A_ULP_PIO_CTRL);
reg_block_dump(ap, buf, A_PL_ENABLE, A_PL_CAUSE);
reg_block_dump(ap, buf, A_MC5_CONFIG, A_MC5_MASK_WRITE_CMD);
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
cmd->supported = p->link_config.supported;
cmd->advertising = p->link_config.advertising;
if (netif_carrier_ok(dev)) {
ethtool_cmd_speed_set(cmd, p->link_config.speed);
cmd->duplex = p->link_config.duplex;
} else {
ethtool_cmd_speed_set(cmd, SPEED_UNKNOWN);
cmd->duplex = DUPLEX_UNKNOWN;
}
cmd->port = (cmd->supported & SUPPORTED_TP) ? PORT_TP : PORT_FIBRE;
cmd->phy_address = p->phy->mdio.prtad;
cmd->transceiver = XCVR_EXTERNAL;
cmd->autoneg = p->link_config.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static int speed_duplex_to_caps(int speed, int duplex)
{
int cap = 0;
switch (speed) {
case SPEED_10:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10baseT_Full;
else
cap = SUPPORTED_10baseT_Half;
break;
case SPEED_100:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_100baseT_Full;
else
cap = SUPPORTED_100baseT_Half;
break;
case SPEED_1000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_1000baseT_Full;
else
cap = SUPPORTED_1000baseT_Half;
break;
case SPEED_10000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10000baseT_Full;
}
return cap;
}
#define ADVERTISED_MASK (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \
ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \
ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full | \
ADVERTISED_10000baseT_Full)
static int set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct link_config *lc = &p->link_config;
if (!(lc->supported & SUPPORTED_Autoneg))
return -EOPNOTSUPP; /* can't change speed/duplex */
if (cmd->autoneg == AUTONEG_DISABLE) {
u32 speed = ethtool_cmd_speed(cmd);
int cap = speed_duplex_to_caps(speed, cmd->duplex);
if (!(lc->supported & cap) || (speed == SPEED_1000))
return -EINVAL;
lc->requested_speed = speed;
lc->requested_duplex = cmd->duplex;
lc->advertising = 0;
} else {
cmd->advertising &= ADVERTISED_MASK;
if (cmd->advertising & (cmd->advertising - 1))
cmd->advertising = lc->supported;
cmd->advertising &= lc->supported;
if (!cmd->advertising)
return -EINVAL;
lc->requested_speed = SPEED_INVALID;
lc->requested_duplex = DUPLEX_INVALID;
lc->advertising = cmd->advertising | ADVERTISED_Autoneg;
}
lc->autoneg = cmd->autoneg;
if (netif_running(dev))
t1_link_start(p->phy, p->mac, lc);
return 0;
}
static void get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
epause->autoneg = (p->link_config.requested_fc & PAUSE_AUTONEG) != 0;
epause->rx_pause = (p->link_config.fc & PAUSE_RX) != 0;
epause->tx_pause = (p->link_config.fc & PAUSE_TX) != 0;
}
static int set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct link_config *lc = &p->link_config;
if (epause->autoneg == AUTONEG_DISABLE)
lc->requested_fc = 0;
else if (lc->supported & SUPPORTED_Autoneg)
lc->requested_fc = PAUSE_AUTONEG;
else
return -EINVAL;
if (epause->rx_pause)
lc->requested_fc |= PAUSE_RX;
if (epause->tx_pause)
lc->requested_fc |= PAUSE_TX;
if (lc->autoneg == AUTONEG_ENABLE) {
if (netif_running(dev))
t1_link_start(p->phy, p->mac, lc);
} else {
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
if (netif_running(dev))
p->mac->ops->set_speed_duplex_fc(p->mac, -1, -1,
lc->fc);
}
return 0;
}
static void get_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct adapter *adapter = dev->ml_priv;
int jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
e->rx_max_pending = MAX_RX_BUFFERS;
e->rx_jumbo_max_pending = MAX_RX_JUMBO_BUFFERS;
e->tx_max_pending = MAX_CMDQ_ENTRIES;
e->rx_pending = adapter->params.sge.freelQ_size[!jumbo_fl];
e->rx_jumbo_pending = adapter->params.sge.freelQ_size[jumbo_fl];
e->tx_pending = adapter->params.sge.cmdQ_size[0];
}
static int set_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct adapter *adapter = dev->ml_priv;
int jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
if (e->rx_pending > MAX_RX_BUFFERS || e->rx_mini_pending ||
e->rx_jumbo_pending > MAX_RX_JUMBO_BUFFERS ||
e->tx_pending > MAX_CMDQ_ENTRIES ||
e->rx_pending < MIN_FL_ENTRIES ||
e->rx_jumbo_pending < MIN_FL_ENTRIES ||
e->tx_pending < (adapter->params.nports + 1) * (MAX_SKB_FRAGS + 1))
return -EINVAL;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
adapter->params.sge.freelQ_size[!jumbo_fl] = e->rx_pending;
adapter->params.sge.freelQ_size[jumbo_fl] = e->rx_jumbo_pending;
adapter->params.sge.cmdQ_size[0] = e->tx_pending;
adapter->params.sge.cmdQ_size[1] = e->tx_pending > MAX_CMDQ1_ENTRIES ?
MAX_CMDQ1_ENTRIES : e->tx_pending;
return 0;
}
static int set_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct adapter *adapter = dev->ml_priv;
adapter->params.sge.rx_coalesce_usecs = c->rx_coalesce_usecs;
adapter->params.sge.coalesce_enable = c->use_adaptive_rx_coalesce;
adapter->params.sge.sample_interval_usecs = c->rate_sample_interval;
t1_sge_set_coalesce_params(adapter->sge, &adapter->params.sge);
return 0;
}
static int get_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct adapter *adapter = dev->ml_priv;
c->rx_coalesce_usecs = adapter->params.sge.rx_coalesce_usecs;
c->rate_sample_interval = adapter->params.sge.sample_interval_usecs;
c->use_adaptive_rx_coalesce = adapter->params.sge.coalesce_enable;
return 0;
}
static int get_eeprom_len(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
return t1_is_asic(adapter) ? EEPROM_SIZE : 0;
}
#define EEPROM_MAGIC(ap) \
(PCI_VENDOR_ID_CHELSIO | ((ap)->params.chip_version << 16))
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *e,
u8 *data)
{
int i;
u8 buf[EEPROM_SIZE] __attribute__((aligned(4)));
struct adapter *adapter = dev->ml_priv;
e->magic = EEPROM_MAGIC(adapter);
for (i = e->offset & ~3; i < e->offset + e->len; i += sizeof(u32))
t1_seeprom_read(adapter, i, (__le32 *)&buf[i]);
memcpy(data, buf + e->offset, e->len);
return 0;
}
static const struct ethtool_ops t1_ethtool_ops = {
.get_settings = get_settings,
.set_settings = set_settings,
.get_drvinfo = get_drvinfo,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_ringparam = get_sge_param,
.set_ringparam = set_sge_param,
.get_coalesce = get_coalesce,
.set_coalesce = set_coalesce,
.get_eeprom_len = get_eeprom_len,
.get_eeprom = get_eeprom,
.get_pauseparam = get_pauseparam,
.set_pauseparam = set_pauseparam,
.get_link = ethtool_op_get_link,
.get_strings = get_strings,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_stats,
.get_regs_len = get_regs_len,
.get_regs = get_regs,
};
static int t1_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct adapter *adapter = dev->ml_priv;
struct mdio_if_info *mdio = &adapter->port[dev->if_port].phy->mdio;
return mdio_mii_ioctl(mdio, if_mii(req), cmd);
}
static int t1_change_mtu(struct net_device *dev, int new_mtu)
{
int ret;
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
if (!mac->ops->set_mtu)
return -EOPNOTSUPP;
if (new_mtu < 68)
return -EINVAL;
if ((ret = mac->ops->set_mtu(mac, new_mtu)))
return ret;
dev->mtu = new_mtu;
return 0;
}
static int t1_set_mac_addr(struct net_device *dev, void *p)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
struct sockaddr *addr = p;
if (!mac->ops->macaddress_set)
return -EOPNOTSUPP;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
mac->ops->macaddress_set(mac, dev->dev_addr);
return 0;
}
static netdev_features_t t1_fix_features(struct net_device *dev,
netdev_features_t features)
{
/*
* Since there is no support for separate rx/tx vlan accel
* enable/disable make sure tx flag is always in same state as rx.
*/
if (features & NETIF_F_HW_VLAN_CTAG_RX)
features |= NETIF_F_HW_VLAN_CTAG_TX;
else
features &= ~NETIF_F_HW_VLAN_CTAG_TX;
return features;
}
static int t1_set_features(struct net_device *dev, netdev_features_t features)
{
netdev_features_t changed = dev->features ^ features;
struct adapter *adapter = dev->ml_priv;
if (changed & NETIF_F_HW_VLAN_CTAG_RX)
t1_vlan_mode(adapter, features);
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void t1_netpoll(struct net_device *dev)
{
unsigned long flags;
struct adapter *adapter = dev->ml_priv;
local_irq_save(flags);
t1_interrupt(adapter->pdev->irq, adapter);
local_irq_restore(flags);
}
#endif
/*
* Periodic accumulation of MAC statistics. This is used only if the MAC
* does not have any other way to prevent stats counter overflow.
*/
static void mac_stats_task(struct work_struct *work)
{
int i;
struct adapter *adapter =
container_of(work, struct adapter, stats_update_task.work);
for_each_port(adapter, i) {
struct port_info *p = &adapter->port[i];
if (netif_running(p->dev))
p->mac->ops->statistics_update(p->mac,
MAC_STATS_UPDATE_FAST);
}
/* Schedule the next statistics update if any port is active. */
spin_lock(&adapter->work_lock);
if (adapter->open_device_map & PORT_MASK)
schedule_mac_stats_update(adapter,
adapter->params.stats_update_period);
spin_unlock(&adapter->work_lock);
}
/*
* Processes elmer0 external interrupts in process context.
*/
static void ext_intr_task(struct work_struct *work)
{
struct adapter *adapter =
container_of(work, struct adapter, ext_intr_handler_task);
t1_elmer0_ext_intr_handler(adapter);
/* Now reenable external interrupts */
spin_lock_irq(&adapter->async_lock);
adapter->slow_intr_mask |= F_PL_INTR_EXT;
writel(F_PL_INTR_EXT, adapter->regs + A_PL_CAUSE);
writel(adapter->slow_intr_mask | F_PL_INTR_SGE_DATA,
adapter->regs + A_PL_ENABLE);
spin_unlock_irq(&adapter->async_lock);
}
/*
* Interrupt-context handler for elmer0 external interrupts.
*/
void t1_elmer0_ext_intr(struct adapter *adapter)
{
/*
* Schedule a task to handle external interrupts as we require
* a process context. We disable EXT interrupts in the interim
* and let the task reenable them when it's done.
*/
adapter->slow_intr_mask &= ~F_PL_INTR_EXT;
writel(adapter->slow_intr_mask | F_PL_INTR_SGE_DATA,
adapter->regs + A_PL_ENABLE);
schedule_work(&adapter->ext_intr_handler_task);
}
void t1_fatal_err(struct adapter *adapter)
{
if (adapter->flags & FULL_INIT_DONE) {
t1_sge_stop(adapter->sge);
t1_interrupts_disable(adapter);
}
pr_alert("%s: encountered fatal error, operation suspended\n",
adapter->name);
}
static const struct net_device_ops cxgb_netdev_ops = {
.ndo_open = cxgb_open,
.ndo_stop = cxgb_close,
.ndo_start_xmit = t1_start_xmit,
.ndo_get_stats = t1_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = t1_set_rxmode,
.ndo_do_ioctl = t1_ioctl,
.ndo_change_mtu = t1_change_mtu,
.ndo_set_mac_address = t1_set_mac_addr,
.ndo_fix_features = t1_fix_features,
.ndo_set_features = t1_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = t1_netpoll,
#endif
};
static int init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int i, err, pci_using_dac = 0;
unsigned long mmio_start, mmio_len;
const struct board_info *bi;
struct adapter *adapter = NULL;
struct port_info *pi;
pr_info_once("%s - version %s\n", DRV_DESCRIPTION, DRV_VERSION);
err = pci_enable_device(pdev);
if (err)
return err;
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
pr_err("%s: cannot find PCI device memory base address\n",
pci_name(pdev));
err = -ENODEV;
goto out_disable_pdev;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
pci_using_dac = 1;
if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
pr_err("%s: unable to obtain 64-bit DMA for "
"consistent allocations\n", pci_name(pdev));
err = -ENODEV;
goto out_disable_pdev;
}
} else if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) {
pr_err("%s: no usable DMA configuration\n", pci_name(pdev));
goto out_disable_pdev;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
pr_err("%s: cannot obtain PCI resources\n", pci_name(pdev));
goto out_disable_pdev;
}
pci_set_master(pdev);
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
bi = t1_get_board_info(ent->driver_data);
for (i = 0; i < bi->port_number; ++i) {
struct net_device *netdev;
netdev = alloc_etherdev(adapter ? 0 : sizeof(*adapter));
if (!netdev) {
err = -ENOMEM;
goto out_free_dev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
if (!adapter) {
adapter = netdev_priv(netdev);
adapter->pdev = pdev;
adapter->port[0].dev = netdev; /* so we don't leak it */
adapter->regs = ioremap(mmio_start, mmio_len);
if (!adapter->regs) {
pr_err("%s: cannot map device registers\n",
pci_name(pdev));
err = -ENOMEM;
goto out_free_dev;
}
if (t1_get_board_rev(adapter, bi, &adapter->params)) {
err = -ENODEV; /* Can't handle this chip rev */
goto out_free_dev;
}
adapter->name = pci_name(pdev);
adapter->msg_enable = dflt_msg_enable;
adapter->mmio_len = mmio_len;
spin_lock_init(&adapter->tpi_lock);
spin_lock_init(&adapter->work_lock);
spin_lock_init(&adapter->async_lock);
spin_lock_init(&adapter->mac_lock);
INIT_WORK(&adapter->ext_intr_handler_task,
ext_intr_task);
INIT_DELAYED_WORK(&adapter->stats_update_task,
mac_stats_task);
pci_set_drvdata(pdev, netdev);
}
pi = &adapter->port[i];
pi->dev = netdev;
netif_carrier_off(netdev);
netdev->irq = pdev->irq;
netdev->if_port = i;
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len - 1;
netdev->ml_priv = adapter;
netdev->hw_features |= NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_RXCSUM;
netdev->features |= NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_RXCSUM | NETIF_F_LLTX;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
if (vlan_tso_capable(adapter)) {
netdev->features |=
NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
netdev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX;
/* T204: disable TSO */
if (!(is_T2(adapter)) || bi->port_number != 4) {
netdev->hw_features |= NETIF_F_TSO;
netdev->features |= NETIF_F_TSO;
}
}
netdev->netdev_ops = &cxgb_netdev_ops;
netdev->hard_header_len += (netdev->hw_features & NETIF_F_TSO) ?
sizeof(struct cpl_tx_pkt_lso) : sizeof(struct cpl_tx_pkt);
netif_napi_add(netdev, &adapter->napi, t1_poll, 64);
netdev->ethtool_ops = &t1_ethtool_ops;
}
if (t1_init_sw_modules(adapter, bi) < 0) {
err = -ENODEV;
goto out_free_dev;
}
/*
* The card is now ready to go. If any errors occur during device
* registration we do not fail the whole card but rather proceed only
* with the ports we manage to register successfully. However we must
* register at least one net device.
*/
for (i = 0; i < bi->port_number; ++i) {
err = register_netdev(adapter->port[i].dev);
if (err)
pr_warn("%s: cannot register net device %s, skipping\n",
pci_name(pdev), adapter->port[i].dev->name);
else {
/*
* Change the name we use for messages to the name of
* the first successfully registered interface.
*/
if (!adapter->registered_device_map)
adapter->name = adapter->port[i].dev->name;
__set_bit(i, &adapter->registered_device_map);
}
}
if (!adapter->registered_device_map) {
pr_err("%s: could not register any net devices\n",
pci_name(pdev));
goto out_release_adapter_res;
}
pr_info("%s: %s (rev %d), %s %dMHz/%d-bit\n",
adapter->name, bi->desc, adapter->params.chip_revision,
adapter->params.pci.is_pcix ? "PCIX" : "PCI",
adapter->params.pci.speed, adapter->params.pci.width);
/*
* Set the T1B ASIC and memory clocks.
*/
if (t1powersave)
adapter->t1powersave = LCLOCK; /* HW default is powersave mode. */
else
adapter->t1powersave = HCLOCK;
if (t1_is_T1B(adapter))
t1_clock(adapter, t1powersave);
return 0;
out_release_adapter_res:
t1_free_sw_modules(adapter);
out_free_dev:
if (adapter) {
if (adapter->regs)
iounmap(adapter->regs);
for (i = bi->port_number - 1; i >= 0; --i)
if (adapter->port[i].dev)
free_netdev(adapter->port[i].dev);
}
pci_release_regions(pdev);
out_disable_pdev:
pci_disable_device(pdev);
return err;
}
static void bit_bang(struct adapter *adapter, int bitdata, int nbits)
{
int data;
int i;
u32 val;
enum {
S_CLOCK = 1 << 3,
S_DATA = 1 << 4
};
for (i = (nbits - 1); i > -1; i--) {
udelay(50);
data = ((bitdata >> i) & 0x1);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
if (data)
val |= S_DATA;
else
val &= ~S_DATA;
udelay(50);
/* Set SCLOCK low */
val &= ~S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Write SCLOCK high */
val |= S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
}
}
static int t1_clock(struct adapter *adapter, int mode)
{
u32 val;
int M_CORE_VAL;
int M_MEM_VAL;
enum {
M_CORE_BITS = 9,
T_CORE_VAL = 0,
T_CORE_BITS = 2,
N_CORE_VAL = 0,
N_CORE_BITS = 2,
M_MEM_BITS = 9,
T_MEM_VAL = 0,
T_MEM_BITS = 2,
N_MEM_VAL = 0,
N_MEM_BITS = 2,
NP_LOAD = 1 << 17,
S_LOAD_MEM = 1 << 5,
S_LOAD_CORE = 1 << 6,
S_CLOCK = 1 << 3
};
if (!t1_is_T1B(adapter))
return -ENODEV; /* Can't re-clock this chip. */
if (mode & 2)
return 0; /* show current mode. */
if ((adapter->t1powersave & 1) == (mode & 1))
return -EALREADY; /* ASIC already running in mode. */
if ((mode & 1) == HCLOCK) {
M_CORE_VAL = 0x14;
M_MEM_VAL = 0x18;
adapter->t1powersave = HCLOCK; /* overclock */
} else {
M_CORE_VAL = 0xe;
M_MEM_VAL = 0x10;
adapter->t1powersave = LCLOCK; /* underclock */
}
/* Don't interrupt this serial stream! */
spin_lock(&adapter->tpi_lock);
/* Initialize for ASIC core */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= NP_LOAD;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_CORE;
val &= ~S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Serial program the ASIC clock synthesizer */
bit_bang(adapter, T_CORE_VAL, T_CORE_BITS);
bit_bang(adapter, N_CORE_VAL, N_CORE_BITS);
bit_bang(adapter, M_CORE_VAL, M_CORE_BITS);
udelay(50);
/* Finish ASIC core */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= S_LOAD_CORE;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_CORE;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Initialize for memory */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= NP_LOAD;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_MEM;
val &= ~S_CLOCK;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Serial program the memory clock synthesizer */
bit_bang(adapter, T_MEM_VAL, T_MEM_BITS);
bit_bang(adapter, N_MEM_VAL, N_MEM_BITS);
bit_bang(adapter, M_MEM_VAL, M_MEM_BITS);
udelay(50);
/* Finish memory */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= S_LOAD_MEM;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_MEM;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
spin_unlock(&adapter->tpi_lock);
return 0;
}
static inline void t1_sw_reset(struct pci_dev *pdev)
{
pci_write_config_dword(pdev, A_PCICFG_PM_CSR, 3);
pci_write_config_dword(pdev, A_PCICFG_PM_CSR, 0);
}
static void remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct adapter *adapter = dev->ml_priv;
int i;
for_each_port(adapter, i) {
if (test_bit(i, &adapter->registered_device_map))
unregister_netdev(adapter->port[i].dev);
}
t1_free_sw_modules(adapter);
iounmap(adapter->regs);
while (--i >= 0) {
if (adapter->port[i].dev)
free_netdev(adapter->port[i].dev);
}
pci_release_regions(pdev);
pci_disable_device(pdev);
t1_sw_reset(pdev);
}
static struct pci_driver cxgb_pci_driver = {
.name = DRV_NAME,
.id_table = t1_pci_tbl,
.probe = init_one,
.remove = remove_one,
};
module_pci_driver(cxgb_pci_driver);
| gpl-2.0 |
ybmaker/linux-sunxi | crypto/gcm.c | 2040 | 35665 | /*
* GCM: Galois/Counter Mode.
*
* Copyright (c) 2007 Nokia Siemens Networks - Mikko Herranen <mh1@iki.fi>
*
* 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 <crypto/gf128mul.h>
#include <crypto/internal/aead.h>
#include <crypto/internal/skcipher.h>
#include <crypto/internal/hash.h>
#include <crypto/scatterwalk.h>
#include <crypto/hash.h>
#include "internal.h"
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
struct gcm_instance_ctx {
struct crypto_skcipher_spawn ctr;
struct crypto_ahash_spawn ghash;
};
struct crypto_gcm_ctx {
struct crypto_ablkcipher *ctr;
struct crypto_ahash *ghash;
};
struct crypto_rfc4106_ctx {
struct crypto_aead *child;
u8 nonce[4];
};
struct crypto_rfc4543_ctx {
struct crypto_aead *child;
u8 nonce[4];
};
struct crypto_rfc4543_req_ctx {
u8 auth_tag[16];
u8 assocbuf[32];
struct scatterlist cipher[1];
struct scatterlist payload[2];
struct scatterlist assoc[2];
struct aead_request subreq;
};
struct crypto_gcm_ghash_ctx {
unsigned int cryptlen;
struct scatterlist *src;
void (*complete)(struct aead_request *req, int err);
};
struct crypto_gcm_req_priv_ctx {
u8 auth_tag[16];
u8 iauth_tag[16];
struct scatterlist src[2];
struct scatterlist dst[2];
struct crypto_gcm_ghash_ctx ghash_ctx;
union {
struct ahash_request ahreq;
struct ablkcipher_request abreq;
} u;
};
struct crypto_gcm_setkey_result {
int err;
struct completion completion;
};
static void *gcm_zeroes;
static inline struct crypto_gcm_req_priv_ctx *crypto_gcm_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 void crypto_gcm_setkey_done(struct crypto_async_request *req, int err)
{
struct crypto_gcm_setkey_result *result = req->data;
if (err == -EINPROGRESS)
return;
result->err = err;
complete(&result->completion);
}
static int crypto_gcm_setkey(struct crypto_aead *aead, const u8 *key,
unsigned int keylen)
{
struct crypto_gcm_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_ahash *ghash = ctx->ghash;
struct crypto_ablkcipher *ctr = ctx->ctr;
struct {
be128 hash;
u8 iv[8];
struct crypto_gcm_setkey_result result;
struct scatterlist sg[1];
struct ablkcipher_request req;
} *data;
int err;
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);
if (err)
return err;
crypto_aead_set_flags(aead, crypto_ablkcipher_get_flags(ctr) &
CRYPTO_TFM_RES_MASK);
data = kzalloc(sizeof(*data) + crypto_ablkcipher_reqsize(ctr),
GFP_KERNEL);
if (!data)
return -ENOMEM;
init_completion(&data->result.completion);
sg_init_one(data->sg, &data->hash, sizeof(data->hash));
ablkcipher_request_set_tfm(&data->req, ctr);
ablkcipher_request_set_callback(&data->req, CRYPTO_TFM_REQ_MAY_SLEEP |
CRYPTO_TFM_REQ_MAY_BACKLOG,
crypto_gcm_setkey_done,
&data->result);
ablkcipher_request_set_crypt(&data->req, data->sg, data->sg,
sizeof(data->hash), data->iv);
err = crypto_ablkcipher_encrypt(&data->req);
if (err == -EINPROGRESS || err == -EBUSY) {
err = wait_for_completion_interruptible(
&data->result.completion);
if (!err)
err = data->result.err;
}
if (err)
goto out;
crypto_ahash_clear_flags(ghash, CRYPTO_TFM_REQ_MASK);
crypto_ahash_set_flags(ghash, crypto_aead_get_flags(aead) &
CRYPTO_TFM_REQ_MASK);
err = crypto_ahash_setkey(ghash, (u8 *)&data->hash, sizeof(be128));
crypto_aead_set_flags(aead, crypto_ahash_get_flags(ghash) &
CRYPTO_TFM_RES_MASK);
out:
kfree(data);
return err;
}
static int crypto_gcm_setauthsize(struct crypto_aead *tfm,
unsigned int authsize)
{
switch (authsize) {
case 4:
case 8:
case 12:
case 13:
case 14:
case 15:
case 16:
break;
default:
return -EINVAL;
}
return 0;
}
static void crypto_gcm_init_crypt(struct ablkcipher_request *ablk_req,
struct aead_request *req,
unsigned int cryptlen)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_gcm_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct scatterlist *dst;
__be32 counter = cpu_to_be32(1);
memset(pctx->auth_tag, 0, sizeof(pctx->auth_tag));
memcpy(req->iv + 12, &counter, 4);
sg_init_table(pctx->src, 2);
sg_set_buf(pctx->src, pctx->auth_tag, sizeof(pctx->auth_tag));
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, pctx->auth_tag, sizeof(pctx->auth_tag));
scatterwalk_sg_chain(pctx->dst, 2, req->dst);
dst = pctx->dst;
}
ablkcipher_request_set_tfm(ablk_req, ctx->ctr);
ablkcipher_request_set_crypt(ablk_req, pctx->src, dst,
cryptlen + sizeof(pctx->auth_tag),
req->iv);
}
static inline unsigned int gcm_remain(unsigned int len)
{
len &= 0xfU;
return len ? 16 - len : 0;
}
static void gcm_hash_len_done(struct crypto_async_request *areq, int err);
static void gcm_hash_final_done(struct crypto_async_request *areq, int err);
static int gcm_hash_update(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx,
crypto_completion_t complete,
struct scatterlist *src,
unsigned int len)
{
struct ahash_request *ahreq = &pctx->u.ahreq;
ahash_request_set_callback(ahreq, aead_request_flags(req),
complete, req);
ahash_request_set_crypt(ahreq, src, NULL, len);
return crypto_ahash_update(ahreq);
}
static int gcm_hash_remain(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx,
unsigned int remain,
crypto_completion_t complete)
{
struct ahash_request *ahreq = &pctx->u.ahreq;
ahash_request_set_callback(ahreq, aead_request_flags(req),
complete, req);
sg_init_one(pctx->src, gcm_zeroes, remain);
ahash_request_set_crypt(ahreq, pctx->src, NULL, remain);
return crypto_ahash_update(ahreq);
}
static int gcm_hash_len(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx)
{
struct ahash_request *ahreq = &pctx->u.ahreq;
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
u128 lengths;
lengths.a = cpu_to_be64(req->assoclen * 8);
lengths.b = cpu_to_be64(gctx->cryptlen * 8);
memcpy(pctx->iauth_tag, &lengths, 16);
sg_init_one(pctx->src, pctx->iauth_tag, 16);
ahash_request_set_callback(ahreq, aead_request_flags(req),
gcm_hash_len_done, req);
ahash_request_set_crypt(ahreq, pctx->src,
NULL, sizeof(lengths));
return crypto_ahash_update(ahreq);
}
static int gcm_hash_final(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx)
{
struct ahash_request *ahreq = &pctx->u.ahreq;
ahash_request_set_callback(ahreq, aead_request_flags(req),
gcm_hash_final_done, req);
ahash_request_set_crypt(ahreq, NULL, pctx->iauth_tag, 0);
return crypto_ahash_final(ahreq);
}
static void __gcm_hash_final_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
if (!err)
crypto_xor(pctx->auth_tag, pctx->iauth_tag, 16);
gctx->complete(req, err);
}
static void gcm_hash_final_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
__gcm_hash_final_done(req, err);
}
static void __gcm_hash_len_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
if (!err) {
err = gcm_hash_final(req, pctx);
if (err == -EINPROGRESS || err == -EBUSY)
return;
}
__gcm_hash_final_done(req, err);
}
static void gcm_hash_len_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
__gcm_hash_len_done(req, err);
}
static void __gcm_hash_crypt_remain_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
if (!err) {
err = gcm_hash_len(req, pctx);
if (err == -EINPROGRESS || err == -EBUSY)
return;
}
__gcm_hash_len_done(req, err);
}
static void gcm_hash_crypt_remain_done(struct crypto_async_request *areq,
int err)
{
struct aead_request *req = areq->data;
__gcm_hash_crypt_remain_done(req, err);
}
static void __gcm_hash_crypt_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
unsigned int remain;
if (!err) {
remain = gcm_remain(gctx->cryptlen);
BUG_ON(!remain);
err = gcm_hash_remain(req, pctx, remain,
gcm_hash_crypt_remain_done);
if (err == -EINPROGRESS || err == -EBUSY)
return;
}
__gcm_hash_crypt_remain_done(req, err);
}
static void gcm_hash_crypt_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
__gcm_hash_crypt_done(req, err);
}
static void __gcm_hash_assoc_remain_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
crypto_completion_t complete;
unsigned int remain = 0;
if (!err && gctx->cryptlen) {
remain = gcm_remain(gctx->cryptlen);
complete = remain ? gcm_hash_crypt_done :
gcm_hash_crypt_remain_done;
err = gcm_hash_update(req, pctx, complete,
gctx->src, gctx->cryptlen);
if (err == -EINPROGRESS || err == -EBUSY)
return;
}
if (remain)
__gcm_hash_crypt_done(req, err);
else
__gcm_hash_crypt_remain_done(req, err);
}
static void gcm_hash_assoc_remain_done(struct crypto_async_request *areq,
int err)
{
struct aead_request *req = areq->data;
__gcm_hash_assoc_remain_done(req, err);
}
static void __gcm_hash_assoc_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
unsigned int remain;
if (!err) {
remain = gcm_remain(req->assoclen);
BUG_ON(!remain);
err = gcm_hash_remain(req, pctx, remain,
gcm_hash_assoc_remain_done);
if (err == -EINPROGRESS || err == -EBUSY)
return;
}
__gcm_hash_assoc_remain_done(req, err);
}
static void gcm_hash_assoc_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
__gcm_hash_assoc_done(req, err);
}
static void __gcm_hash_init_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
crypto_completion_t complete;
unsigned int remain = 0;
if (!err && req->assoclen) {
remain = gcm_remain(req->assoclen);
complete = remain ? gcm_hash_assoc_done :
gcm_hash_assoc_remain_done;
err = gcm_hash_update(req, pctx, complete,
req->assoc, req->assoclen);
if (err == -EINPROGRESS || err == -EBUSY)
return;
}
if (remain)
__gcm_hash_assoc_done(req, err);
else
__gcm_hash_assoc_remain_done(req, err);
}
static void gcm_hash_init_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
__gcm_hash_init_done(req, err);
}
static int gcm_hash(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx)
{
struct ahash_request *ahreq = &pctx->u.ahreq;
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
struct crypto_gcm_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
unsigned int remain;
crypto_completion_t complete;
int err;
ahash_request_set_tfm(ahreq, ctx->ghash);
ahash_request_set_callback(ahreq, aead_request_flags(req),
gcm_hash_init_done, req);
err = crypto_ahash_init(ahreq);
if (err)
return err;
remain = gcm_remain(req->assoclen);
complete = remain ? gcm_hash_assoc_done : gcm_hash_assoc_remain_done;
err = gcm_hash_update(req, pctx, complete, req->assoc, req->assoclen);
if (err)
return err;
if (remain) {
err = gcm_hash_remain(req, pctx, remain,
gcm_hash_assoc_remain_done);
if (err)
return err;
}
remain = gcm_remain(gctx->cryptlen);
complete = remain ? gcm_hash_crypt_done : gcm_hash_crypt_remain_done;
err = gcm_hash_update(req, pctx, complete, gctx->src, gctx->cryptlen);
if (err)
return err;
if (remain) {
err = gcm_hash_remain(req, pctx, remain,
gcm_hash_crypt_remain_done);
if (err)
return err;
}
err = gcm_hash_len(req, pctx);
if (err)
return err;
err = gcm_hash_final(req, pctx);
if (err)
return err;
return 0;
}
static void gcm_enc_copy_hash(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
u8 *auth_tag = pctx->auth_tag;
scatterwalk_map_and_copy(auth_tag, req->dst, req->cryptlen,
crypto_aead_authsize(aead), 1);
}
static void gcm_enc_hash_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
if (!err)
gcm_enc_copy_hash(req, pctx);
aead_request_complete(req, err);
}
static void gcm_encrypt_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
if (!err) {
err = gcm_hash(req, pctx);
if (err == -EINPROGRESS || err == -EBUSY)
return;
else if (!err) {
crypto_xor(pctx->auth_tag, pctx->iauth_tag, 16);
gcm_enc_copy_hash(req, pctx);
}
}
aead_request_complete(req, err);
}
static int crypto_gcm_encrypt(struct aead_request *req)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct ablkcipher_request *abreq = &pctx->u.abreq;
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
int err;
crypto_gcm_init_crypt(abreq, req, req->cryptlen);
ablkcipher_request_set_callback(abreq, aead_request_flags(req),
gcm_encrypt_done, req);
gctx->src = req->dst;
gctx->cryptlen = req->cryptlen;
gctx->complete = gcm_enc_hash_done;
err = crypto_ablkcipher_encrypt(abreq);
if (err)
return err;
err = gcm_hash(req, pctx);
if (err)
return err;
crypto_xor(pctx->auth_tag, pctx->iauth_tag, 16);
gcm_enc_copy_hash(req, pctx);
return 0;
}
static int crypto_gcm_verify(struct aead_request *req,
struct crypto_gcm_req_priv_ctx *pctx)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
u8 *auth_tag = pctx->auth_tag;
u8 *iauth_tag = pctx->iauth_tag;
unsigned int authsize = crypto_aead_authsize(aead);
unsigned int cryptlen = req->cryptlen - authsize;
crypto_xor(auth_tag, iauth_tag, 16);
scatterwalk_map_and_copy(iauth_tag, req->src, cryptlen, authsize, 0);
return memcmp(iauth_tag, auth_tag, authsize) ? -EBADMSG : 0;
}
static void gcm_decrypt_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
if (!err)
err = crypto_gcm_verify(req, pctx);
aead_request_complete(req, err);
}
static void gcm_dec_hash_done(struct aead_request *req, int err)
{
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct ablkcipher_request *abreq = &pctx->u.abreq;
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
if (!err) {
ablkcipher_request_set_callback(abreq, aead_request_flags(req),
gcm_decrypt_done, req);
crypto_gcm_init_crypt(abreq, req, gctx->cryptlen);
err = crypto_ablkcipher_decrypt(abreq);
if (err == -EINPROGRESS || err == -EBUSY)
return;
else if (!err)
err = crypto_gcm_verify(req, pctx);
}
aead_request_complete(req, err);
}
static int crypto_gcm_decrypt(struct aead_request *req)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);
struct ablkcipher_request *abreq = &pctx->u.abreq;
struct crypto_gcm_ghash_ctx *gctx = &pctx->ghash_ctx;
unsigned int authsize = crypto_aead_authsize(aead);
unsigned int cryptlen = req->cryptlen;
int err;
if (cryptlen < authsize)
return -EINVAL;
cryptlen -= authsize;
gctx->src = req->src;
gctx->cryptlen = cryptlen;
gctx->complete = gcm_dec_hash_done;
err = gcm_hash(req, pctx);
if (err)
return err;
ablkcipher_request_set_callback(abreq, aead_request_flags(req),
gcm_decrypt_done, req);
crypto_gcm_init_crypt(abreq, req, cryptlen);
err = crypto_ablkcipher_decrypt(abreq);
if (err)
return err;
return crypto_gcm_verify(req, pctx);
}
static int crypto_gcm_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct gcm_instance_ctx *ictx = crypto_instance_ctx(inst);
struct crypto_gcm_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_ablkcipher *ctr;
struct crypto_ahash *ghash;
unsigned long align;
int err;
ghash = crypto_spawn_ahash(&ictx->ghash);
if (IS_ERR(ghash))
return PTR_ERR(ghash);
ctr = crypto_spawn_skcipher(&ictx->ctr);
err = PTR_ERR(ctr);
if (IS_ERR(ctr))
goto err_free_hash;
ctx->ctr = ctr;
ctx->ghash = ghash;
align = crypto_tfm_alg_alignmask(tfm);
align &= ~(crypto_tfm_ctx_alignment() - 1);
tfm->crt_aead.reqsize = align +
offsetof(struct crypto_gcm_req_priv_ctx, u) +
max(sizeof(struct ablkcipher_request) +
crypto_ablkcipher_reqsize(ctr),
sizeof(struct ahash_request) +
crypto_ahash_reqsize(ghash));
return 0;
err_free_hash:
crypto_free_ahash(ghash);
return err;
}
static void crypto_gcm_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_gcm_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_ahash(ctx->ghash);
crypto_free_ablkcipher(ctx->ctr);
}
static struct crypto_instance *crypto_gcm_alloc_common(struct rtattr **tb,
const char *full_name,
const char *ctr_name,
const char *ghash_name)
{
struct crypto_attr_type *algt;
struct crypto_instance *inst;
struct crypto_alg *ctr;
struct crypto_alg *ghash_alg;
struct ahash_alg *ghash_ahash_alg;
struct gcm_instance_ctx *ctx;
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);
ghash_alg = crypto_find_alg(ghash_name, &crypto_ahash_type,
CRYPTO_ALG_TYPE_HASH,
CRYPTO_ALG_TYPE_AHASH_MASK);
err = PTR_ERR(ghash_alg);
if (IS_ERR(ghash_alg))
return ERR_PTR(err);
err = -ENOMEM;
inst = kzalloc(sizeof(*inst) + sizeof(*ctx), GFP_KERNEL);
if (!inst)
goto out_put_ghash;
ctx = crypto_instance_ctx(inst);
ghash_ahash_alg = container_of(ghash_alg, struct ahash_alg, halg.base);
err = crypto_init_ahash_spawn(&ctx->ghash, &ghash_ahash_alg->halg,
inst);
if (err)
goto err_free_inst;
crypto_set_skcipher_spawn(&ctx->ctr, inst);
err = crypto_grab_skcipher(&ctx->ctr, ctr_name, 0,
crypto_requires_sync(algt->type,
algt->mask));
if (err)
goto err_drop_ghash;
ctr = crypto_skcipher_spawn_alg(&ctx->ctr);
/* We only support 16-byte blocks. */
if (ctr->cra_ablkcipher.ivsize != 16)
goto out_put_ctr;
/* Not a stream cipher? */
err = -EINVAL;
if (ctr->cra_blocksize != 1)
goto out_put_ctr;
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"gcm_base(%s,%s)", ctr->cra_driver_name,
ghash_alg->cra_driver_name) >=
CRYPTO_MAX_ALG_NAME)
goto out_put_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 = ctr->cra_priority;
inst->alg.cra_blocksize = 1;
inst->alg.cra_alignmask = ctr->cra_alignmask | (__alignof__(u64) - 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_gcm_ctx);
inst->alg.cra_init = crypto_gcm_init_tfm;
inst->alg.cra_exit = crypto_gcm_exit_tfm;
inst->alg.cra_aead.setkey = crypto_gcm_setkey;
inst->alg.cra_aead.setauthsize = crypto_gcm_setauthsize;
inst->alg.cra_aead.encrypt = crypto_gcm_encrypt;
inst->alg.cra_aead.decrypt = crypto_gcm_decrypt;
out:
crypto_mod_put(ghash_alg);
return inst;
out_put_ctr:
crypto_drop_skcipher(&ctx->ctr);
err_drop_ghash:
crypto_drop_ahash(&ctx->ghash);
err_free_inst:
kfree(inst);
out_put_ghash:
inst = ERR_PTR(err);
goto out;
}
static struct crypto_instance *crypto_gcm_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, "gcm(%s)", cipher_name) >=
CRYPTO_MAX_ALG_NAME)
return ERR_PTR(-ENAMETOOLONG);
return crypto_gcm_alloc_common(tb, full_name, ctr_name, "ghash");
}
static void crypto_gcm_free(struct crypto_instance *inst)
{
struct gcm_instance_ctx *ctx = crypto_instance_ctx(inst);
crypto_drop_skcipher(&ctx->ctr);
crypto_drop_ahash(&ctx->ghash);
kfree(inst);
}
static struct crypto_template crypto_gcm_tmpl = {
.name = "gcm",
.alloc = crypto_gcm_alloc,
.free = crypto_gcm_free,
.module = THIS_MODULE,
};
static struct crypto_instance *crypto_gcm_base_alloc(struct rtattr **tb)
{
int err;
const char *ctr_name;
const char *ghash_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);
ghash_name = crypto_attr_alg_name(tb[2]);
err = PTR_ERR(ghash_name);
if (IS_ERR(ghash_name))
return ERR_PTR(err);
if (snprintf(full_name, CRYPTO_MAX_ALG_NAME, "gcm_base(%s,%s)",
ctr_name, ghash_name) >= CRYPTO_MAX_ALG_NAME)
return ERR_PTR(-ENAMETOOLONG);
return crypto_gcm_alloc_common(tb, full_name, ctr_name, ghash_name);
}
static struct crypto_template crypto_gcm_base_tmpl = {
.name = "gcm_base",
.alloc = crypto_gcm_base_alloc,
.free = crypto_gcm_free,
.module = THIS_MODULE,
};
static int crypto_rfc4106_setkey(struct crypto_aead *parent, const u8 *key,
unsigned int keylen)
{
struct crypto_rfc4106_ctx *ctx = crypto_aead_ctx(parent);
struct crypto_aead *child = ctx->child;
int err;
if (keylen < 4)
return -EINVAL;
keylen -= 4;
memcpy(ctx->nonce, key + keylen, 4);
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_rfc4106_setauthsize(struct crypto_aead *parent,
unsigned int authsize)
{
struct crypto_rfc4106_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_rfc4106_crypt(struct aead_request *req)
{
struct aead_request *subreq = aead_request_ctx(req);
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_rfc4106_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);
memcpy(iv, ctx->nonce, 4);
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_rfc4106_encrypt(struct aead_request *req)
{
req = crypto_rfc4106_crypt(req);
return crypto_aead_encrypt(req);
}
static int crypto_rfc4106_decrypt(struct aead_request *req)
{
req = crypto_rfc4106_crypt(req);
return crypto_aead_decrypt(req);
}
static int crypto_rfc4106_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_rfc4106_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_rfc4106_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_rfc4106_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_aead(ctx->child);
}
static struct crypto_instance *crypto_rfc4106_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,
"rfc4106(%s)", alg->cra_name) >= CRYPTO_MAX_ALG_NAME ||
snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"rfc4106(%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_rfc4106_ctx);
inst->alg.cra_init = crypto_rfc4106_init_tfm;
inst->alg.cra_exit = crypto_rfc4106_exit_tfm;
inst->alg.cra_aead.setkey = crypto_rfc4106_setkey;
inst->alg.cra_aead.setauthsize = crypto_rfc4106_setauthsize;
inst->alg.cra_aead.encrypt = crypto_rfc4106_encrypt;
inst->alg.cra_aead.decrypt = crypto_rfc4106_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_rfc4106_free(struct crypto_instance *inst)
{
crypto_drop_spawn(crypto_instance_ctx(inst));
kfree(inst);
}
static struct crypto_template crypto_rfc4106_tmpl = {
.name = "rfc4106",
.alloc = crypto_rfc4106_alloc,
.free = crypto_rfc4106_free,
.module = THIS_MODULE,
};
static inline struct crypto_rfc4543_req_ctx *crypto_rfc4543_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 crypto_rfc4543_setkey(struct crypto_aead *parent, const u8 *key,
unsigned int keylen)
{
struct crypto_rfc4543_ctx *ctx = crypto_aead_ctx(parent);
struct crypto_aead *child = ctx->child;
int err;
if (keylen < 4)
return -EINVAL;
keylen -= 4;
memcpy(ctx->nonce, key + keylen, 4);
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_rfc4543_setauthsize(struct crypto_aead *parent,
unsigned int authsize)
{
struct crypto_rfc4543_ctx *ctx = crypto_aead_ctx(parent);
if (authsize != 16)
return -EINVAL;
return crypto_aead_setauthsize(ctx->child, authsize);
}
static struct aead_request *crypto_rfc4543_crypt(struct aead_request *req,
int enc)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_rfc4543_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_rfc4543_req_ctx *rctx = crypto_rfc4543_reqctx(req);
struct aead_request *subreq = &rctx->subreq;
struct scatterlist *dst = req->dst;
struct scatterlist *cipher = rctx->cipher;
struct scatterlist *payload = rctx->payload;
struct scatterlist *assoc = rctx->assoc;
unsigned int authsize = crypto_aead_authsize(aead);
unsigned int assoclen = req->assoclen;
struct page *dstp;
u8 *vdst;
u8 *iv = PTR_ALIGN((u8 *)(rctx + 1) + crypto_aead_reqsize(ctx->child),
crypto_aead_alignmask(ctx->child) + 1);
memcpy(iv, ctx->nonce, 4);
memcpy(iv + 4, req->iv, 8);
/* construct cipher/plaintext */
if (enc)
memset(rctx->auth_tag, 0, authsize);
else
scatterwalk_map_and_copy(rctx->auth_tag, dst,
req->cryptlen - authsize,
authsize, 0);
sg_init_one(cipher, rctx->auth_tag, authsize);
/* construct the aad */
dstp = sg_page(dst);
vdst = PageHighMem(dstp) ? NULL : page_address(dstp) + dst->offset;
sg_init_table(payload, 2);
sg_set_buf(payload, req->iv, 8);
scatterwalk_crypto_chain(payload, dst, vdst == req->iv + 8, 2);
assoclen += 8 + req->cryptlen - (enc ? 0 : authsize);
if (req->assoc->length == req->assoclen) {
sg_init_table(assoc, 2);
sg_set_page(assoc, sg_page(req->assoc), req->assoc->length,
req->assoc->offset);
} else {
BUG_ON(req->assoclen > sizeof(rctx->assocbuf));
scatterwalk_map_and_copy(rctx->assocbuf, req->assoc, 0,
req->assoclen, 0);
sg_init_table(assoc, 2);
sg_set_buf(assoc, rctx->assocbuf, req->assoclen);
}
scatterwalk_crypto_chain(assoc, payload, 0, 2);
aead_request_set_tfm(subreq, ctx->child);
aead_request_set_callback(subreq, req->base.flags, req->base.complete,
req->base.data);
aead_request_set_crypt(subreq, cipher, cipher, enc ? 0 : authsize, iv);
aead_request_set_assoc(subreq, assoc, assoclen);
return subreq;
}
static int crypto_rfc4543_encrypt(struct aead_request *req)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_rfc4543_req_ctx *rctx = crypto_rfc4543_reqctx(req);
struct aead_request *subreq;
int err;
subreq = crypto_rfc4543_crypt(req, 1);
err = crypto_aead_encrypt(subreq);
if (err)
return err;
scatterwalk_map_and_copy(rctx->auth_tag, req->dst, req->cryptlen,
crypto_aead_authsize(aead), 1);
return 0;
}
static int crypto_rfc4543_decrypt(struct aead_request *req)
{
req = crypto_rfc4543_crypt(req, 0);
return crypto_aead_decrypt(req);
}
static int crypto_rfc4543_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_rfc4543_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 crypto_rfc4543_req_ctx) +
ALIGN(crypto_aead_reqsize(aead),
crypto_tfm_ctx_alignment()) +
align + 16;
return 0;
}
static void crypto_rfc4543_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_rfc4543_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_aead(ctx->child);
}
static struct crypto_instance *crypto_rfc4543_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,
"rfc4543(%s)", alg->cra_name) >= CRYPTO_MAX_ALG_NAME ||
snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"rfc4543(%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_rfc4543_ctx);
inst->alg.cra_init = crypto_rfc4543_init_tfm;
inst->alg.cra_exit = crypto_rfc4543_exit_tfm;
inst->alg.cra_aead.setkey = crypto_rfc4543_setkey;
inst->alg.cra_aead.setauthsize = crypto_rfc4543_setauthsize;
inst->alg.cra_aead.encrypt = crypto_rfc4543_encrypt;
inst->alg.cra_aead.decrypt = crypto_rfc4543_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_rfc4543_free(struct crypto_instance *inst)
{
crypto_drop_spawn(crypto_instance_ctx(inst));
kfree(inst);
}
static struct crypto_template crypto_rfc4543_tmpl = {
.name = "rfc4543",
.alloc = crypto_rfc4543_alloc,
.free = crypto_rfc4543_free,
.module = THIS_MODULE,
};
static int __init crypto_gcm_module_init(void)
{
int err;
gcm_zeroes = kzalloc(16, GFP_KERNEL);
if (!gcm_zeroes)
return -ENOMEM;
err = crypto_register_template(&crypto_gcm_base_tmpl);
if (err)
goto out;
err = crypto_register_template(&crypto_gcm_tmpl);
if (err)
goto out_undo_base;
err = crypto_register_template(&crypto_rfc4106_tmpl);
if (err)
goto out_undo_gcm;
err = crypto_register_template(&crypto_rfc4543_tmpl);
if (err)
goto out_undo_rfc4106;
return 0;
out_undo_rfc4106:
crypto_unregister_template(&crypto_rfc4106_tmpl);
out_undo_gcm:
crypto_unregister_template(&crypto_gcm_tmpl);
out_undo_base:
crypto_unregister_template(&crypto_gcm_base_tmpl);
out:
kfree(gcm_zeroes);
return err;
}
static void __exit crypto_gcm_module_exit(void)
{
kfree(gcm_zeroes);
crypto_unregister_template(&crypto_rfc4543_tmpl);
crypto_unregister_template(&crypto_rfc4106_tmpl);
crypto_unregister_template(&crypto_gcm_tmpl);
crypto_unregister_template(&crypto_gcm_base_tmpl);
}
module_init(crypto_gcm_module_init);
module_exit(crypto_gcm_module_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Galois/Counter Mode");
MODULE_AUTHOR("Mikko Herranen <mh1@iki.fi>");
MODULE_ALIAS("gcm_base");
MODULE_ALIAS("rfc4106");
MODULE_ALIAS("rfc4543");
| gpl-2.0 |
NhlalukoG/android_samsung_j7e3g | drivers/usb/gadget/f_loopback.c | 2296 | 11271 | /*
* f_loopback.c - USB peripheral loopback configuration driver
*
* Copyright (C) 2003-2008 David Brownell
* Copyright (C) 2008 by Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
/* #define VERBOSE_DEBUG */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/usb/composite.h>
#include "g_zero.h"
/*
* LOOPBACK FUNCTION ... a testing vehicle for USB peripherals,
*
* This takes messages of various sizes written OUT to a device, and loops
* them back so they can be read IN from it. It has been used by certain
* test applications. It supports limited testing of data queueing logic.
*
*
* This is currently packaged as a configuration driver, which can't be
* combined with other functions to make composite devices. However, it
* can be combined with other independent configurations.
*/
struct f_loopback {
struct usb_function function;
struct usb_ep *in_ep;
struct usb_ep *out_ep;
};
static inline struct f_loopback *func_to_loop(struct usb_function *f)
{
return container_of(f, struct f_loopback, function);
}
static unsigned qlen;
static unsigned buflen;
/*-------------------------------------------------------------------------*/
static struct usb_interface_descriptor loopback_intf = {
.bLength = sizeof loopback_intf,
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
/* .iInterface = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor fs_loop_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor fs_loop_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *fs_loopback_descs[] = {
(struct usb_descriptor_header *) &loopback_intf,
(struct usb_descriptor_header *) &fs_loop_sink_desc,
(struct usb_descriptor_header *) &fs_loop_source_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor hs_loop_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor hs_loop_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *hs_loopback_descs[] = {
(struct usb_descriptor_header *) &loopback_intf,
(struct usb_descriptor_header *) &hs_loop_source_desc,
(struct usb_descriptor_header *) &hs_loop_sink_desc,
NULL,
};
/* super speed support: */
static struct usb_endpoint_descriptor ss_loop_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
struct usb_ss_ep_comp_descriptor ss_loop_source_comp_desc = {
.bLength = USB_DT_SS_EP_COMP_SIZE,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
.bMaxBurst = 0,
.bmAttributes = 0,
.wBytesPerInterval = 0,
};
static struct usb_endpoint_descriptor ss_loop_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
struct usb_ss_ep_comp_descriptor ss_loop_sink_comp_desc = {
.bLength = USB_DT_SS_EP_COMP_SIZE,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
.bMaxBurst = 0,
.bmAttributes = 0,
.wBytesPerInterval = 0,
};
static struct usb_descriptor_header *ss_loopback_descs[] = {
(struct usb_descriptor_header *) &loopback_intf,
(struct usb_descriptor_header *) &ss_loop_source_desc,
(struct usb_descriptor_header *) &ss_loop_source_comp_desc,
(struct usb_descriptor_header *) &ss_loop_sink_desc,
(struct usb_descriptor_header *) &ss_loop_sink_comp_desc,
NULL,
};
/* function-specific strings: */
static struct usb_string strings_loopback[] = {
[0].s = "loop input to output",
{ } /* end of list */
};
static struct usb_gadget_strings stringtab_loop = {
.language = 0x0409, /* en-us */
.strings = strings_loopback,
};
static struct usb_gadget_strings *loopback_strings[] = {
&stringtab_loop,
NULL,
};
/*-------------------------------------------------------------------------*/
static int loopback_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_loopback *loop = func_to_loop(f);
int id;
int ret;
/* allocate interface ID(s) */
id = usb_interface_id(c, f);
if (id < 0)
return id;
loopback_intf.bInterfaceNumber = id;
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_loopback[0].id = id;
loopback_intf.iInterface = id;
/* allocate endpoints */
loop->in_ep = usb_ep_autoconfig(cdev->gadget, &fs_loop_source_desc);
if (!loop->in_ep) {
autoconf_fail:
ERROR(cdev, "%s: can't autoconfigure on %s\n",
f->name, cdev->gadget->name);
return -ENODEV;
}
loop->in_ep->driver_data = cdev; /* claim */
loop->out_ep = usb_ep_autoconfig(cdev->gadget, &fs_loop_sink_desc);
if (!loop->out_ep)
goto autoconf_fail;
loop->out_ep->driver_data = cdev; /* claim */
/* support high speed hardware */
hs_loop_source_desc.bEndpointAddress =
fs_loop_source_desc.bEndpointAddress;
hs_loop_sink_desc.bEndpointAddress = fs_loop_sink_desc.bEndpointAddress;
/* support super speed hardware */
ss_loop_source_desc.bEndpointAddress =
fs_loop_source_desc.bEndpointAddress;
ss_loop_sink_desc.bEndpointAddress = fs_loop_sink_desc.bEndpointAddress;
ret = usb_assign_descriptors(f, fs_loopback_descs, hs_loopback_descs,
ss_loopback_descs);
if (ret)
return ret;
DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
(gadget_is_superspeed(c->cdev->gadget) ? "super" :
(gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full")),
f->name, loop->in_ep->name, loop->out_ep->name);
return 0;
}
static void lb_free_func(struct usb_function *f)
{
usb_free_all_descriptors(f);
kfree(func_to_loop(f));
}
static void loopback_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_loopback *loop = ep->driver_data;
struct usb_composite_dev *cdev = loop->function.config->cdev;
int status = req->status;
switch (status) {
case 0: /* normal completion? */
if (ep == loop->out_ep) {
/* loop this OUT packet back IN to the host */
req->zero = (req->actual < req->length);
req->length = req->actual;
status = usb_ep_queue(loop->in_ep, req, GFP_ATOMIC);
if (status == 0)
return;
/* "should never get here" */
ERROR(cdev, "can't loop %s to %s: %d\n",
ep->name, loop->in_ep->name,
status);
}
/* queue the buffer for some later OUT packet */
req->length = buflen;
status = usb_ep_queue(loop->out_ep, req, GFP_ATOMIC);
if (status == 0)
return;
/* "should never get here" */
/* FALLTHROUGH */
default:
ERROR(cdev, "%s loop complete --> %d, %d/%d\n", ep->name,
status, req->actual, req->length);
/* FALLTHROUGH */
/* NOTE: since this driver doesn't maintain an explicit record
* of requests it submitted (just maintains qlen count), we
* rely on the hardware driver to clean up on disconnect or
* endpoint disable.
*/
case -ECONNABORTED: /* hardware forced ep reset */
case -ECONNRESET: /* request dequeued */
case -ESHUTDOWN: /* disconnect from host */
free_ep_req(ep, req);
return;
}
}
static void disable_loopback(struct f_loopback *loop)
{
struct usb_composite_dev *cdev;
cdev = loop->function.config->cdev;
disable_endpoints(cdev, loop->in_ep, loop->out_ep, NULL, NULL);
VDBG(cdev, "%s disabled\n", loop->function.name);
}
static int
enable_loopback(struct usb_composite_dev *cdev, struct f_loopback *loop)
{
int result = 0;
struct usb_ep *ep;
struct usb_request *req;
unsigned i;
/* one endpoint writes data back IN to the host */
ep = loop->in_ep;
result = config_ep_by_speed(cdev->gadget, &(loop->function), ep);
if (result)
return result;
result = usb_ep_enable(ep);
if (result < 0)
return result;
ep->driver_data = loop;
/* one endpoint just reads OUT packets */
ep = loop->out_ep;
result = config_ep_by_speed(cdev->gadget, &(loop->function), ep);
if (result)
goto fail0;
result = usb_ep_enable(ep);
if (result < 0) {
fail0:
ep = loop->in_ep;
usb_ep_disable(ep);
ep->driver_data = NULL;
return result;
}
ep->driver_data = loop;
/* allocate a bunch of read buffers and queue them all at once.
* we buffer at most 'qlen' transfers; fewer if any need more
* than 'buflen' bytes each.
*/
for (i = 0; i < qlen && result == 0; i++) {
req = alloc_ep_req(ep, 0);
if (req) {
req->complete = loopback_complete;
result = usb_ep_queue(ep, req, GFP_ATOMIC);
if (result)
ERROR(cdev, "%s queue req --> %d\n",
ep->name, result);
} else {
usb_ep_disable(ep);
ep->driver_data = NULL;
result = -ENOMEM;
goto fail0;
}
}
DBG(cdev, "%s enabled\n", loop->function.name);
return result;
}
static int loopback_set_alt(struct usb_function *f,
unsigned intf, unsigned alt)
{
struct f_loopback *loop = func_to_loop(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* we know alt is zero */
if (loop->in_ep->driver_data)
disable_loopback(loop);
return enable_loopback(cdev, loop);
}
static void loopback_disable(struct usb_function *f)
{
struct f_loopback *loop = func_to_loop(f);
disable_loopback(loop);
}
static struct usb_function *loopback_alloc(struct usb_function_instance *fi)
{
struct f_loopback *loop;
struct f_lb_opts *lb_opts;
loop = kzalloc(sizeof *loop, GFP_KERNEL);
if (!loop)
return ERR_PTR(-ENOMEM);
lb_opts = container_of(fi, struct f_lb_opts, func_inst);
buflen = lb_opts->bulk_buflen;
qlen = lb_opts->qlen;
if (!qlen)
qlen = 32;
loop->function.name = "loopback";
loop->function.bind = loopback_bind;
loop->function.set_alt = loopback_set_alt;
loop->function.disable = loopback_disable;
loop->function.strings = loopback_strings;
loop->function.free_func = lb_free_func;
return &loop->function;
}
static void lb_free_instance(struct usb_function_instance *fi)
{
struct f_lb_opts *lb_opts;
lb_opts = container_of(fi, struct f_lb_opts, func_inst);
kfree(lb_opts);
}
static struct usb_function_instance *loopback_alloc_instance(void)
{
struct f_lb_opts *lb_opts;
lb_opts = kzalloc(sizeof(*lb_opts), GFP_KERNEL);
if (!lb_opts)
return ERR_PTR(-ENOMEM);
lb_opts->func_inst.free_func_inst = lb_free_instance;
return &lb_opts->func_inst;
}
DECLARE_USB_FUNCTION(Loopback, loopback_alloc_instance, loopback_alloc);
int __init lb_modinit(void)
{
int ret;
ret = usb_function_register(&Loopbackusb_func);
if (ret)
return ret;
return ret;
}
void __exit lb_modexit(void)
{
usb_function_unregister(&Loopbackusb_func);
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
LeJay/android_kernel_samsung_jactiveltexx | drivers/net/ethernet/atheros/atlx/atl2.c | 4856 | 82644 | /*
* Copyright(c) 2006 - 2007 Atheros Corporation. All rights reserved.
* Copyright(c) 2007 - 2008 Chris Snook <csnook@redhat.com>
*
* Derived from Intel e1000 driver
* Copyright(c) 1999 - 2005 Intel 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; 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/atomic.h>
#include <linux/crc32.h>
#include <linux/dma-mapping.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/hardirq.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/interrupt.h>
#include <linux/ip.h>
#include <linux/irqflags.h>
#include <linux/irqreturn.h>
#include <linux/mii.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/pm.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/tcp.h>
#include <linux/timer.h>
#include <linux/types.h>
#include <linux/workqueue.h>
#include "atl2.h"
#define ATL2_DRV_VERSION "2.2.3"
static const char atl2_driver_name[] = "atl2";
static const char atl2_driver_string[] = "Atheros(R) L2 Ethernet Driver";
static const char atl2_copyright[] = "Copyright (c) 2007 Atheros Corporation.";
static const char atl2_driver_version[] = ATL2_DRV_VERSION;
MODULE_AUTHOR("Atheros Corporation <xiong.huang@atheros.com>, Chris Snook <csnook@redhat.com>");
MODULE_DESCRIPTION("Atheros Fast Ethernet Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(ATL2_DRV_VERSION);
/*
* atl2_pci_tbl - PCI Device ID Table
*/
static DEFINE_PCI_DEVICE_TABLE(atl2_pci_tbl) = {
{PCI_DEVICE(PCI_VENDOR_ID_ATTANSIC, PCI_DEVICE_ID_ATTANSIC_L2)},
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, atl2_pci_tbl);
static void atl2_set_ethtool_ops(struct net_device *netdev);
static void atl2_check_options(struct atl2_adapter *adapter);
/*
* atl2_sw_init - Initialize general software structures (struct atl2_adapter)
* @adapter: board private structure to initialize
*
* atl2_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
*/
static int __devinit atl2_sw_init(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_id = pdev->subsystem_device;
hw->revision_id = pdev->revision;
pci_read_config_word(pdev, PCI_COMMAND, &hw->pci_cmd_word);
adapter->wol = 0;
adapter->ict = 50000; /* ~100ms */
adapter->link_speed = SPEED_0; /* hardware init */
adapter->link_duplex = FULL_DUPLEX;
hw->phy_configured = false;
hw->preamble_len = 7;
hw->ipgt = 0x60;
hw->min_ifg = 0x50;
hw->ipgr1 = 0x40;
hw->ipgr2 = 0x60;
hw->retry_buf = 2;
hw->max_retry = 0xf;
hw->lcol = 0x37;
hw->jam_ipg = 7;
hw->fc_rxd_hi = 0;
hw->fc_rxd_lo = 0;
hw->max_frame_size = adapter->netdev->mtu;
spin_lock_init(&adapter->stats_lock);
set_bit(__ATL2_DOWN, &adapter->flags);
return 0;
}
/*
* atl2_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
*/
static void atl2_set_multi(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u32 rctl;
u32 hash_value;
/* Check for Promiscuous and All Multicast modes */
rctl = ATL2_READ_REG(hw, REG_MAC_CTRL);
if (netdev->flags & IFF_PROMISC) {
rctl |= MAC_CTRL_PROMIS_EN;
} else if (netdev->flags & IFF_ALLMULTI) {
rctl |= MAC_CTRL_MC_ALL_EN;
rctl &= ~MAC_CTRL_PROMIS_EN;
} else
rctl &= ~(MAC_CTRL_PROMIS_EN | MAC_CTRL_MC_ALL_EN);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, rctl);
/* clear the old settings from the multicast hash table */
ATL2_WRITE_REG(hw, REG_RX_HASH_TABLE, 0);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, 1, 0);
/* comoute mc addresses' hash value ,and put it into hash table */
netdev_for_each_mc_addr(ha, netdev) {
hash_value = atl2_hash_mc_addr(hw, ha->addr);
atl2_hash_set(hw, hash_value);
}
}
static void init_ring_ptrs(struct atl2_adapter *adapter)
{
/* Read / Write Ptr Initialize: */
adapter->txd_write_ptr = 0;
atomic_set(&adapter->txd_read_ptr, 0);
adapter->rxd_read_ptr = 0;
adapter->rxd_write_ptr = 0;
atomic_set(&adapter->txs_write_ptr, 0);
adapter->txs_next_clear = 0;
}
/*
* atl2_configure - Configure Transmit&Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Tx /Rx unit of the MAC after a reset.
*/
static int atl2_configure(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
u32 value;
/* clear interrupt status */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0xffffffff);
/* set MAC Address */
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5]));
ATL2_WRITE_REG(hw, REG_MAC_STA_ADDR, value);
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1]));
ATL2_WRITE_REG(hw, (REG_MAC_STA_ADDR+4), value);
/* HI base address */
ATL2_WRITE_REG(hw, REG_DESC_BASE_ADDR_HI,
(u32)((adapter->ring_dma & 0xffffffff00000000ULL) >> 32));
/* LO base address */
ATL2_WRITE_REG(hw, REG_TXD_BASE_ADDR_LO,
(u32)(adapter->txd_dma & 0x00000000ffffffffULL));
ATL2_WRITE_REG(hw, REG_TXS_BASE_ADDR_LO,
(u32)(adapter->txs_dma & 0x00000000ffffffffULL));
ATL2_WRITE_REG(hw, REG_RXD_BASE_ADDR_LO,
(u32)(adapter->rxd_dma & 0x00000000ffffffffULL));
/* element count */
ATL2_WRITE_REGW(hw, REG_TXD_MEM_SIZE, (u16)(adapter->txd_ring_size/4));
ATL2_WRITE_REGW(hw, REG_TXS_MEM_SIZE, (u16)adapter->txs_ring_size);
ATL2_WRITE_REGW(hw, REG_RXD_BUF_NUM, (u16)adapter->rxd_ring_size);
/* config Internal SRAM */
/*
ATL2_WRITE_REGW(hw, REG_SRAM_TXRAM_END, sram_tx_end);
ATL2_WRITE_REGW(hw, REG_SRAM_TXRAM_END, sram_rx_end);
*/
/* config IPG/IFG */
value = (((u32)hw->ipgt & MAC_IPG_IFG_IPGT_MASK) <<
MAC_IPG_IFG_IPGT_SHIFT) |
(((u32)hw->min_ifg & MAC_IPG_IFG_MIFG_MASK) <<
MAC_IPG_IFG_MIFG_SHIFT) |
(((u32)hw->ipgr1 & MAC_IPG_IFG_IPGR1_MASK) <<
MAC_IPG_IFG_IPGR1_SHIFT)|
(((u32)hw->ipgr2 & MAC_IPG_IFG_IPGR2_MASK) <<
MAC_IPG_IFG_IPGR2_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_IPG_IFG, value);
/* config Half-Duplex Control */
value = ((u32)hw->lcol & MAC_HALF_DUPLX_CTRL_LCOL_MASK) |
(((u32)hw->max_retry & MAC_HALF_DUPLX_CTRL_RETRY_MASK) <<
MAC_HALF_DUPLX_CTRL_RETRY_SHIFT) |
MAC_HALF_DUPLX_CTRL_EXC_DEF_EN |
(0xa << MAC_HALF_DUPLX_CTRL_ABEBT_SHIFT) |
(((u32)hw->jam_ipg & MAC_HALF_DUPLX_CTRL_JAMIPG_MASK) <<
MAC_HALF_DUPLX_CTRL_JAMIPG_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_HALF_DUPLX_CTRL, value);
/* set Interrupt Moderator Timer */
ATL2_WRITE_REGW(hw, REG_IRQ_MODU_TIMER_INIT, adapter->imt);
ATL2_WRITE_REG(hw, REG_MASTER_CTRL, MASTER_CTRL_ITIMER_EN);
/* set Interrupt Clear Timer */
ATL2_WRITE_REGW(hw, REG_CMBDISDMA_TIMER, adapter->ict);
/* set MTU */
ATL2_WRITE_REG(hw, REG_MTU, adapter->netdev->mtu +
ENET_HEADER_SIZE + VLAN_SIZE + ETHERNET_FCS_SIZE);
/* 1590 */
ATL2_WRITE_REG(hw, REG_TX_CUT_THRESH, 0x177);
/* flow control */
ATL2_WRITE_REGW(hw, REG_PAUSE_ON_TH, hw->fc_rxd_hi);
ATL2_WRITE_REGW(hw, REG_PAUSE_OFF_TH, hw->fc_rxd_lo);
/* Init mailbox */
ATL2_WRITE_REGW(hw, REG_MB_TXD_WR_IDX, (u16)adapter->txd_write_ptr);
ATL2_WRITE_REGW(hw, REG_MB_RXD_RD_IDX, (u16)adapter->rxd_read_ptr);
/* enable DMA read/write */
ATL2_WRITE_REGB(hw, REG_DMAR, DMAR_EN);
ATL2_WRITE_REGB(hw, REG_DMAW, DMAW_EN);
value = ATL2_READ_REG(&adapter->hw, REG_ISR);
if ((value & ISR_PHY_LINKDOWN) != 0)
value = 1; /* config failed */
else
value = 0;
/* clear all interrupt status */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0x3fffffff);
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return value;
}
/*
* atl2_setup_ring_resources - allocate Tx / RX descriptor resources
* @adapter: board private structure
*
* Return 0 on success, negative on failure
*/
static s32 atl2_setup_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int size;
u8 offset = 0;
/* real ring DMA buffer */
adapter->ring_size = size =
adapter->txd_ring_size * 1 + 7 + /* dword align */
adapter->txs_ring_size * 4 + 7 + /* dword align */
adapter->rxd_ring_size * 1536 + 127; /* 128bytes align */
adapter->ring_vir_addr = pci_alloc_consistent(pdev, size,
&adapter->ring_dma);
if (!adapter->ring_vir_addr)
return -ENOMEM;
memset(adapter->ring_vir_addr, 0, adapter->ring_size);
/* Init TXD Ring */
adapter->txd_dma = adapter->ring_dma ;
offset = (adapter->txd_dma & 0x7) ? (8 - (adapter->txd_dma & 0x7)) : 0;
adapter->txd_dma += offset;
adapter->txd_ring = adapter->ring_vir_addr + offset;
/* Init TXS Ring */
adapter->txs_dma = adapter->txd_dma + adapter->txd_ring_size;
offset = (adapter->txs_dma & 0x7) ? (8 - (adapter->txs_dma & 0x7)) : 0;
adapter->txs_dma += offset;
adapter->txs_ring = (struct tx_pkt_status *)
(((u8 *)adapter->txd_ring) + (adapter->txd_ring_size + offset));
/* Init RXD Ring */
adapter->rxd_dma = adapter->txs_dma + adapter->txs_ring_size * 4;
offset = (adapter->rxd_dma & 127) ?
(128 - (adapter->rxd_dma & 127)) : 0;
if (offset > 7)
offset -= 8;
else
offset += (128 - 8);
adapter->rxd_dma += offset;
adapter->rxd_ring = (struct rx_desc *) (((u8 *)adapter->txs_ring) +
(adapter->txs_ring_size * 4 + offset));
/*
* Read / Write Ptr Initialize:
* init_ring_ptrs(adapter);
*/
return 0;
}
/*
* atl2_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
*/
static inline void atl2_irq_enable(struct atl2_adapter *adapter)
{
ATL2_WRITE_REG(&adapter->hw, REG_IMR, IMR_NORMAL_MASK);
ATL2_WRITE_FLUSH(&adapter->hw);
}
/*
* atl2_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
*/
static inline void atl2_irq_disable(struct atl2_adapter *adapter)
{
ATL2_WRITE_REG(&adapter->hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(&adapter->hw);
synchronize_irq(adapter->pdev->irq);
}
static void __atl2_vlan_mode(netdev_features_t features, u32 *ctrl)
{
if (features & NETIF_F_HW_VLAN_RX) {
/* enable VLAN tag insert/strip */
*ctrl |= MAC_CTRL_RMV_VLAN;
} else {
/* disable VLAN tag insert/strip */
*ctrl &= ~MAC_CTRL_RMV_VLAN;
}
}
static void atl2_vlan_mode(struct net_device *netdev,
netdev_features_t features)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
u32 ctrl;
atl2_irq_disable(adapter);
ctrl = ATL2_READ_REG(&adapter->hw, REG_MAC_CTRL);
__atl2_vlan_mode(features, &ctrl);
ATL2_WRITE_REG(&adapter->hw, REG_MAC_CTRL, ctrl);
atl2_irq_enable(adapter);
}
static void atl2_restore_vlan(struct atl2_adapter *adapter)
{
atl2_vlan_mode(adapter->netdev, adapter->netdev->features);
}
static netdev_features_t atl2_fix_features(struct net_device *netdev,
netdev_features_t features)
{
/*
* Since there is no support for separate rx/tx vlan accel
* enable/disable make sure tx flag is always in same state as rx.
*/
if (features & NETIF_F_HW_VLAN_RX)
features |= NETIF_F_HW_VLAN_TX;
else
features &= ~NETIF_F_HW_VLAN_TX;
return features;
}
static int atl2_set_features(struct net_device *netdev,
netdev_features_t features)
{
netdev_features_t changed = netdev->features ^ features;
if (changed & NETIF_F_HW_VLAN_RX)
atl2_vlan_mode(netdev, features);
return 0;
}
static void atl2_intr_rx(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct rx_desc *rxd;
struct sk_buff *skb;
do {
rxd = adapter->rxd_ring+adapter->rxd_write_ptr;
if (!rxd->status.update)
break; /* end of tx */
/* clear this flag at once */
rxd->status.update = 0;
if (rxd->status.ok && rxd->status.pkt_size >= 60) {
int rx_size = (int)(rxd->status.pkt_size - 4);
/* alloc new buffer */
skb = netdev_alloc_skb_ip_align(netdev, rx_size);
if (NULL == skb) {
printk(KERN_WARNING
"%s: Mem squeeze, deferring packet.\n",
netdev->name);
/*
* Check that some rx space is free. If not,
* free one and mark stats->rx_dropped++.
*/
netdev->stats.rx_dropped++;
break;
}
memcpy(skb->data, rxd->packet, rx_size);
skb_put(skb, rx_size);
skb->protocol = eth_type_trans(skb, netdev);
if (rxd->status.vlan) {
u16 vlan_tag = (rxd->status.vtag>>4) |
((rxd->status.vtag&7) << 13) |
((rxd->status.vtag&8) << 9);
__vlan_hwaccel_put_tag(skb, vlan_tag);
}
netif_rx(skb);
netdev->stats.rx_bytes += rx_size;
netdev->stats.rx_packets++;
} else {
netdev->stats.rx_errors++;
if (rxd->status.ok && rxd->status.pkt_size <= 60)
netdev->stats.rx_length_errors++;
if (rxd->status.mcast)
netdev->stats.multicast++;
if (rxd->status.crc)
netdev->stats.rx_crc_errors++;
if (rxd->status.align)
netdev->stats.rx_frame_errors++;
}
/* advance write ptr */
if (++adapter->rxd_write_ptr == adapter->rxd_ring_size)
adapter->rxd_write_ptr = 0;
} while (1);
/* update mailbox? */
adapter->rxd_read_ptr = adapter->rxd_write_ptr;
ATL2_WRITE_REGW(&adapter->hw, REG_MB_RXD_RD_IDX, adapter->rxd_read_ptr);
}
static void atl2_intr_tx(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 txd_read_ptr;
u32 txs_write_ptr;
struct tx_pkt_status *txs;
struct tx_pkt_header *txph;
int free_hole = 0;
do {
txs_write_ptr = (u32) atomic_read(&adapter->txs_write_ptr);
txs = adapter->txs_ring + txs_write_ptr;
if (!txs->update)
break; /* tx stop here */
free_hole = 1;
txs->update = 0;
if (++txs_write_ptr == adapter->txs_ring_size)
txs_write_ptr = 0;
atomic_set(&adapter->txs_write_ptr, (int)txs_write_ptr);
txd_read_ptr = (u32) atomic_read(&adapter->txd_read_ptr);
txph = (struct tx_pkt_header *)
(((u8 *)adapter->txd_ring) + txd_read_ptr);
if (txph->pkt_size != txs->pkt_size) {
struct tx_pkt_status *old_txs = txs;
printk(KERN_WARNING
"%s: txs packet size not consistent with txd"
" txd_:0x%08x, txs_:0x%08x!\n",
adapter->netdev->name,
*(u32 *)txph, *(u32 *)txs);
printk(KERN_WARNING
"txd read ptr: 0x%x\n",
txd_read_ptr);
txs = adapter->txs_ring + txs_write_ptr;
printk(KERN_WARNING
"txs-behind:0x%08x\n",
*(u32 *)txs);
if (txs_write_ptr < 2) {
txs = adapter->txs_ring +
(adapter->txs_ring_size +
txs_write_ptr - 2);
} else {
txs = adapter->txs_ring + (txs_write_ptr - 2);
}
printk(KERN_WARNING
"txs-before:0x%08x\n",
*(u32 *)txs);
txs = old_txs;
}
/* 4for TPH */
txd_read_ptr += (((u32)(txph->pkt_size) + 7) & ~3);
if (txd_read_ptr >= adapter->txd_ring_size)
txd_read_ptr -= adapter->txd_ring_size;
atomic_set(&adapter->txd_read_ptr, (int)txd_read_ptr);
/* tx statistics: */
if (txs->ok) {
netdev->stats.tx_bytes += txs->pkt_size;
netdev->stats.tx_packets++;
}
else
netdev->stats.tx_errors++;
if (txs->defer)
netdev->stats.collisions++;
if (txs->abort_col)
netdev->stats.tx_aborted_errors++;
if (txs->late_col)
netdev->stats.tx_window_errors++;
if (txs->underun)
netdev->stats.tx_fifo_errors++;
} while (1);
if (free_hole) {
if (netif_queue_stopped(adapter->netdev) &&
netif_carrier_ok(adapter->netdev))
netif_wake_queue(adapter->netdev);
}
}
static void atl2_check_for_link(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u16 phy_data = 0;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(&adapter->hw, MII_BMSR, &phy_data);
spin_unlock(&adapter->stats_lock);
/* notify upper layer link down ASAP */
if (!(phy_data & BMSR_LSTATUS)) { /* Link Down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
printk(KERN_INFO "%s: %s NIC Link is Down\n",
atl2_driver_name, netdev->name);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
}
schedule_work(&adapter->link_chg_task);
}
static inline void atl2_clear_phy_int(struct atl2_adapter *adapter)
{
u16 phy_data;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, 19, &phy_data);
spin_unlock(&adapter->stats_lock);
}
/*
* atl2_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
* @pt_regs: CPU registers structure
*/
static irqreturn_t atl2_intr(int irq, void *data)
{
struct atl2_adapter *adapter = netdev_priv(data);
struct atl2_hw *hw = &adapter->hw;
u32 status;
status = ATL2_READ_REG(hw, REG_ISR);
if (0 == status)
return IRQ_NONE;
/* link event */
if (status & ISR_PHY)
atl2_clear_phy_int(adapter);
/* clear ISR status, and Enable CMB DMA/Disable Interrupt */
ATL2_WRITE_REG(hw, REG_ISR, status | ISR_DIS_INT);
/* check if PCIE PHY Link down */
if (status & ISR_PHY_LINKDOWN) {
if (netif_running(adapter->netdev)) { /* reset MAC */
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
}
/* check if DMA read/write error? */
if (status & (ISR_DMAR_TO_RST | ISR_DMAW_TO_RST)) {
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
/* link event */
if (status & (ISR_PHY | ISR_MANUAL)) {
adapter->netdev->stats.tx_carrier_errors++;
atl2_check_for_link(adapter);
}
/* transmit event */
if (status & ISR_TX_EVENT)
atl2_intr_tx(adapter);
/* rx exception */
if (status & ISR_RX_EVENT)
atl2_intr_rx(adapter);
/* re-enable Interrupt */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return IRQ_HANDLED;
}
static int atl2_request_irq(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int flags, err = 0;
flags = IRQF_SHARED;
adapter->have_msi = true;
err = pci_enable_msi(adapter->pdev);
if (err)
adapter->have_msi = false;
if (adapter->have_msi)
flags &= ~IRQF_SHARED;
return request_irq(adapter->pdev->irq, atl2_intr, flags, netdev->name,
netdev);
}
/*
* atl2_free_ring_resources - Free Tx / RX descriptor Resources
* @adapter: board private structure
*
* Free all transmit software resources
*/
static void atl2_free_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
pci_free_consistent(pdev, adapter->ring_size, adapter->ring_vir_addr,
adapter->ring_dma);
}
/*
* atl2_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
*/
static int atl2_open(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
int err;
u32 val;
/* disallow open during test */
if (test_bit(__ATL2_TESTING, &adapter->flags))
return -EBUSY;
/* allocate transmit descriptors */
err = atl2_setup_ring_resources(adapter);
if (err)
return err;
err = atl2_init_hw(&adapter->hw);
if (err) {
err = -EIO;
goto err_init_hw;
}
/* hardware has been reset, we need to reload some things */
atl2_set_multi(netdev);
init_ring_ptrs(adapter);
atl2_restore_vlan(adapter);
if (atl2_configure(adapter)) {
err = -EIO;
goto err_config;
}
err = atl2_request_irq(adapter);
if (err)
goto err_req_irq;
clear_bit(__ATL2_DOWN, &adapter->flags);
mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + 4*HZ));
val = ATL2_READ_REG(&adapter->hw, REG_MASTER_CTRL);
ATL2_WRITE_REG(&adapter->hw, REG_MASTER_CTRL,
val | MASTER_CTRL_MANUAL_INT);
atl2_irq_enable(adapter);
return 0;
err_init_hw:
err_req_irq:
err_config:
atl2_free_ring_resources(adapter);
atl2_reset_hw(&adapter->hw);
return err;
}
static void atl2_down(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
set_bit(__ATL2_DOWN, &adapter->flags);
netif_tx_disable(netdev);
/* reset MAC to disable all RX/TX */
atl2_reset_hw(&adapter->hw);
msleep(1);
atl2_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_config_timer);
clear_bit(0, &adapter->cfg_phy);
netif_carrier_off(netdev);
adapter->link_speed = SPEED_0;
adapter->link_duplex = -1;
}
static void atl2_free_irq(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
free_irq(adapter->pdev->irq, netdev);
#ifdef CONFIG_PCI_MSI
if (adapter->have_msi)
pci_disable_msi(adapter->pdev);
#endif
}
/*
* atl2_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
*/
static int atl2_close(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__ATL2_RESETTING, &adapter->flags));
atl2_down(adapter);
atl2_free_irq(adapter);
atl2_free_ring_resources(adapter);
return 0;
}
static inline int TxsFreeUnit(struct atl2_adapter *adapter)
{
u32 txs_write_ptr = (u32) atomic_read(&adapter->txs_write_ptr);
return (adapter->txs_next_clear >= txs_write_ptr) ?
(int) (adapter->txs_ring_size - adapter->txs_next_clear +
txs_write_ptr - 1) :
(int) (txs_write_ptr - adapter->txs_next_clear - 1);
}
static inline int TxdFreeBytes(struct atl2_adapter *adapter)
{
u32 txd_read_ptr = (u32)atomic_read(&adapter->txd_read_ptr);
return (adapter->txd_write_ptr >= txd_read_ptr) ?
(int) (adapter->txd_ring_size - adapter->txd_write_ptr +
txd_read_ptr - 1) :
(int) (txd_read_ptr - adapter->txd_write_ptr - 1);
}
static netdev_tx_t atl2_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct tx_pkt_header *txph;
u32 offset, copy_len;
int txs_unused;
int txbuf_unused;
if (test_bit(__ATL2_DOWN, &adapter->flags)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (unlikely(skb->len <= 0)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
txs_unused = TxsFreeUnit(adapter);
txbuf_unused = TxdFreeBytes(adapter);
if (skb->len + sizeof(struct tx_pkt_header) + 4 > txbuf_unused ||
txs_unused < 1) {
/* not enough resources */
netif_stop_queue(netdev);
return NETDEV_TX_BUSY;
}
offset = adapter->txd_write_ptr;
txph = (struct tx_pkt_header *) (((u8 *)adapter->txd_ring) + offset);
*(u32 *)txph = 0;
txph->pkt_size = skb->len;
offset += 4;
if (offset >= adapter->txd_ring_size)
offset -= adapter->txd_ring_size;
copy_len = adapter->txd_ring_size - offset;
if (copy_len >= skb->len) {
memcpy(((u8 *)adapter->txd_ring) + offset, skb->data, skb->len);
offset += ((u32)(skb->len + 3) & ~3);
} else {
memcpy(((u8 *)adapter->txd_ring)+offset, skb->data, copy_len);
memcpy((u8 *)adapter->txd_ring, skb->data+copy_len,
skb->len-copy_len);
offset = ((u32)(skb->len-copy_len + 3) & ~3);
}
#ifdef NETIF_F_HW_VLAN_TX
if (vlan_tx_tag_present(skb)) {
u16 vlan_tag = vlan_tx_tag_get(skb);
vlan_tag = (vlan_tag << 4) |
(vlan_tag >> 13) |
((vlan_tag >> 9) & 0x8);
txph->ins_vlan = 1;
txph->vlan = vlan_tag;
}
#endif
if (offset >= adapter->txd_ring_size)
offset -= adapter->txd_ring_size;
adapter->txd_write_ptr = offset;
/* clear txs before send */
adapter->txs_ring[adapter->txs_next_clear].update = 0;
if (++adapter->txs_next_clear == adapter->txs_ring_size)
adapter->txs_next_clear = 0;
ATL2_WRITE_REGW(&adapter->hw, REG_MB_TXD_WR_IDX,
(adapter->txd_write_ptr >> 2));
mmiowb();
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/*
* atl2_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
*/
static int atl2_change_mtu(struct net_device *netdev, int new_mtu)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
if ((new_mtu < 40) || (new_mtu > (ETH_DATA_LEN + VLAN_SIZE)))
return -EINVAL;
/* set MTU */
if (hw->max_frame_size != new_mtu) {
netdev->mtu = new_mtu;
ATL2_WRITE_REG(hw, REG_MTU, new_mtu + ENET_HEADER_SIZE +
VLAN_SIZE + ETHERNET_FCS_SIZE);
}
return 0;
}
/*
* atl2_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
*/
static int atl2_set_mac(struct net_device *netdev, void *p)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
if (netif_running(netdev))
return -EBUSY;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac_addr, addr->sa_data, netdev->addr_len);
atl2_set_mac_addr(&adapter->hw);
return 0;
}
/*
* atl2_mii_ioctl -
* @netdev:
* @ifreq:
* @cmd:
*/
static int atl2_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct mii_ioctl_data *data = if_mii(ifr);
unsigned long flags;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = 0;
break;
case SIOCGMIIREG:
spin_lock_irqsave(&adapter->stats_lock, flags);
if (atl2_read_phy_reg(&adapter->hw,
data->reg_num & 0x1F, &data->val_out)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
case SIOCSMIIREG:
if (data->reg_num & ~(0x1F))
return -EFAULT;
spin_lock_irqsave(&adapter->stats_lock, flags);
if (atl2_write_phy_reg(&adapter->hw, data->reg_num,
data->val_in)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
/*
* atl2_ioctl -
* @netdev:
* @ifreq:
* @cmd:
*/
static int atl2_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return atl2_mii_ioctl(netdev, ifr, cmd);
#ifdef ETHTOOL_OPS_COMPAT
case SIOCETHTOOL:
return ethtool_ioctl(ifr);
#endif
default:
return -EOPNOTSUPP;
}
}
/*
* atl2_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
*/
static void atl2_tx_timeout(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
schedule_work(&adapter->reset_task);
}
/*
* atl2_watchdog - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
*/
static void atl2_watchdog(unsigned long data)
{
struct atl2_adapter *adapter = (struct atl2_adapter *) data;
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
u32 drop_rxd, drop_rxs;
unsigned long flags;
spin_lock_irqsave(&adapter->stats_lock, flags);
drop_rxd = ATL2_READ_REG(&adapter->hw, REG_STS_RXD_OV);
drop_rxs = ATL2_READ_REG(&adapter->hw, REG_STS_RXS_OV);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
adapter->netdev->stats.rx_over_errors += drop_rxd + drop_rxs;
/* Reset the timer */
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + 4 * HZ));
}
}
/*
* atl2_phy_config - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
*/
static void atl2_phy_config(unsigned long data)
{
struct atl2_adapter *adapter = (struct atl2_adapter *) data;
struct atl2_hw *hw = &adapter->hw;
unsigned long flags;
spin_lock_irqsave(&adapter->stats_lock, flags);
atl2_write_phy_reg(hw, MII_ADVERTISE, hw->mii_autoneg_adv_reg);
atl2_write_phy_reg(hw, MII_BMCR, MII_CR_RESET | MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
clear_bit(0, &adapter->cfg_phy);
}
static int atl2_up(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0;
u32 val;
/* hardware has been reset, we need to reload some things */
err = atl2_init_hw(&adapter->hw);
if (err) {
err = -EIO;
return err;
}
atl2_set_multi(netdev);
init_ring_ptrs(adapter);
atl2_restore_vlan(adapter);
if (atl2_configure(adapter)) {
err = -EIO;
goto err_up;
}
clear_bit(__ATL2_DOWN, &adapter->flags);
val = ATL2_READ_REG(&adapter->hw, REG_MASTER_CTRL);
ATL2_WRITE_REG(&adapter->hw, REG_MASTER_CTRL, val |
MASTER_CTRL_MANUAL_INT);
atl2_irq_enable(adapter);
err_up:
return err;
}
static void atl2_reinit_locked(struct atl2_adapter *adapter)
{
WARN_ON(in_interrupt());
while (test_and_set_bit(__ATL2_RESETTING, &adapter->flags))
msleep(1);
atl2_down(adapter);
atl2_up(adapter);
clear_bit(__ATL2_RESETTING, &adapter->flags);
}
static void atl2_reset_task(struct work_struct *work)
{
struct atl2_adapter *adapter;
adapter = container_of(work, struct atl2_adapter, reset_task);
atl2_reinit_locked(adapter);
}
static void atl2_setup_mac_ctrl(struct atl2_adapter *adapter)
{
u32 value;
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
/* Config MAC CTRL Register */
value = MAC_CTRL_TX_EN | MAC_CTRL_RX_EN | MAC_CTRL_MACLP_CLK_PHY;
/* duplex */
if (FULL_DUPLEX == adapter->link_duplex)
value |= MAC_CTRL_DUPLX;
/* flow control */
value |= (MAC_CTRL_TX_FLOW | MAC_CTRL_RX_FLOW);
/* PAD & CRC */
value |= (MAC_CTRL_ADD_CRC | MAC_CTRL_PAD);
/* preamble length */
value |= (((u32)adapter->hw.preamble_len & MAC_CTRL_PRMLEN_MASK) <<
MAC_CTRL_PRMLEN_SHIFT);
/* vlan */
__atl2_vlan_mode(netdev->features, &value);
/* filter mode */
value |= MAC_CTRL_BC_EN;
if (netdev->flags & IFF_PROMISC)
value |= MAC_CTRL_PROMIS_EN;
else if (netdev->flags & IFF_ALLMULTI)
value |= MAC_CTRL_MC_ALL_EN;
/* half retry buffer */
value |= (((u32)(adapter->hw.retry_buf &
MAC_CTRL_HALF_LEFT_BUF_MASK)) << MAC_CTRL_HALF_LEFT_BUF_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
}
static int atl2_check_link(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
int ret_val;
u16 speed, duplex, phy_data;
int reconfig = 0;
/* MII_BMSR must read twise */
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
if (!(phy_data&BMSR_LSTATUS)) { /* link down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
return 0;
}
/* Link Up */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val)
return ret_val;
switch (hw->MediaType) {
case MEDIA_TYPE_100M_FULL:
if (speed != SPEED_100 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_100M_HALF:
if (speed != SPEED_100 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_FULL:
if (speed != SPEED_10 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_HALF:
if (speed != SPEED_10 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
}
/* link result is our setting */
if (reconfig == 0) {
if (adapter->link_speed != speed ||
adapter->link_duplex != duplex) {
adapter->link_speed = speed;
adapter->link_duplex = duplex;
atl2_setup_mac_ctrl(adapter);
printk(KERN_INFO "%s: %s NIC Link is Up<%d Mbps %s>\n",
atl2_driver_name, netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex");
}
if (!netif_carrier_ok(netdev)) { /* Link down -> Up */
netif_carrier_on(netdev);
netif_wake_queue(netdev);
}
return 0;
}
/* change original link status */
if (netif_carrier_ok(netdev)) {
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
/* auto-neg, insert timer to re-config phy
* (if interval smaller than 5 seconds, something strange) */
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
if (!test_and_set_bit(0, &adapter->cfg_phy))
mod_timer(&adapter->phy_config_timer,
round_jiffies(jiffies + 5 * HZ));
}
return 0;
}
/*
* atl2_link_chg_task - deal with link change event Out of interrupt context
* @netdev: network interface device structure
*/
static void atl2_link_chg_task(struct work_struct *work)
{
struct atl2_adapter *adapter;
unsigned long flags;
adapter = container_of(work, struct atl2_adapter, link_chg_task);
spin_lock_irqsave(&adapter->stats_lock, flags);
atl2_check_link(adapter);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
}
static void atl2_setup_pcicmd(struct pci_dev *pdev)
{
u16 cmd;
pci_read_config_word(pdev, PCI_COMMAND, &cmd);
if (cmd & PCI_COMMAND_INTX_DISABLE)
cmd &= ~PCI_COMMAND_INTX_DISABLE;
if (cmd & PCI_COMMAND_IO)
cmd &= ~PCI_COMMAND_IO;
if (0 == (cmd & PCI_COMMAND_MEMORY))
cmd |= PCI_COMMAND_MEMORY;
if (0 == (cmd & PCI_COMMAND_MASTER))
cmd |= PCI_COMMAND_MASTER;
pci_write_config_word(pdev, PCI_COMMAND, cmd);
/*
* some motherboards BIOS(PXE/EFI) driver may set PME
* while they transfer control to OS (Windows/Linux)
* so we should clear this bit before NIC work normally
*/
pci_write_config_dword(pdev, REG_PM_CTRLSTAT, 0);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void atl2_poll_controller(struct net_device *netdev)
{
disable_irq(netdev->irq);
atl2_intr(netdev->irq, netdev);
enable_irq(netdev->irq);
}
#endif
static const struct net_device_ops atl2_netdev_ops = {
.ndo_open = atl2_open,
.ndo_stop = atl2_close,
.ndo_start_xmit = atl2_xmit_frame,
.ndo_set_rx_mode = atl2_set_multi,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = atl2_set_mac,
.ndo_change_mtu = atl2_change_mtu,
.ndo_fix_features = atl2_fix_features,
.ndo_set_features = atl2_set_features,
.ndo_do_ioctl = atl2_ioctl,
.ndo_tx_timeout = atl2_tx_timeout,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = atl2_poll_controller,
#endif
};
/*
* atl2_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in atl2_pci_tbl
*
* Returns 0 on success, negative on failure
*
* atl2_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
*/
static int __devinit atl2_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct atl2_adapter *adapter;
static int cards_found;
unsigned long mmio_start;
int mmio_len;
int err;
cards_found = 0;
err = pci_enable_device(pdev);
if (err)
return err;
/*
* atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA
* until the kernel has the proper infrastructure to support 64-bit DMA
* on these devices.
*/
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) &&
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n");
goto err_dma;
}
/* Mark all PCI regions associated with PCI device
* pdev as being reserved by owner atl2_driver_name */
err = pci_request_regions(pdev, atl2_driver_name);
if (err)
goto err_pci_reg;
/* Enables bus-mastering on the device and calls
* pcibios_set_master to do the needed arch specific settings */
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct atl2_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
mmio_start = pci_resource_start(pdev, 0x0);
mmio_len = pci_resource_len(pdev, 0x0);
adapter->hw.mem_rang = (u32)mmio_len;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
atl2_setup_pcicmd(pdev);
netdev->netdev_ops = &atl2_netdev_ops;
atl2_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found;
adapter->pci_using_64 = false;
/* setup the private structure */
err = atl2_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_RX;
netdev->features |= (NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX);
/* Init PHY as early as possible due to power saving issue */
atl2_phy_init(&adapter->hw);
/* reset the controller to
* put the device in a known good starting state */
if (atl2_reset_hw(&adapter->hw)) {
err = -EIO;
goto err_reset;
}
/* copy the MAC address out of the EEPROM */
atl2_read_mac_addr(&adapter->hw);
memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len);
/* FIXME: do we still need this? */
#ifdef ETHTOOL_GPERMADDR
memcpy(netdev->perm_addr, adapter->hw.mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
#else
if (!is_valid_ether_addr(netdev->dev_addr)) {
#endif
err = -EIO;
goto err_eeprom;
}
atl2_check_options(adapter);
init_timer(&adapter->watchdog_timer);
adapter->watchdog_timer.function = atl2_watchdog;
adapter->watchdog_timer.data = (unsigned long) adapter;
init_timer(&adapter->phy_config_timer);
adapter->phy_config_timer.function = atl2_phy_config;
adapter->phy_config_timer.data = (unsigned long) adapter;
INIT_WORK(&adapter->reset_task, atl2_reset_task);
INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task);
strcpy(netdev->name, "eth%d"); /* ?? */
err = register_netdev(netdev);
if (err)
goto err_register;
/* assume we have no link for now */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
cards_found++;
return 0;
err_reset:
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/*
* atl2_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* atl2_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
*/
/* FIXME: write the original MAC address back in case it was changed from a
* BIOS-set value, as in atl1 -- CHS */
static void __devexit atl2_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
/* flush_scheduled work may reschedule our watchdog task, so
* explicitly disable watchdog tasks from being rescheduled */
set_bit(__ATL2_DOWN, &adapter->flags);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_config_timer);
cancel_work_sync(&adapter->reset_task);
cancel_work_sync(&adapter->link_chg_task);
unregister_netdev(netdev);
atl2_force_ps(&adapter->hw);
iounmap(adapter->hw.hw_addr);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
static int atl2_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u16 speed, duplex;
u32 ctrl = 0;
u32 wufc = adapter->wol;
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev)) {
WARN_ON(test_bit(__ATL2_RESETTING, &adapter->flags));
atl2_down(adapter);
}
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
atl2_read_phy_reg(hw, MII_BMSR, (u16 *)&ctrl);
atl2_read_phy_reg(hw, MII_BMSR, (u16 *)&ctrl);
if (ctrl & BMSR_LSTATUS)
wufc &= ~ATLX_WUFC_LNKC;
if (0 != (ctrl & BMSR_LSTATUS) && 0 != wufc) {
u32 ret_val;
/* get current link speed & duplex */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val) {
printk(KERN_DEBUG
"%s: get speed&duplex error while suspend\n",
atl2_driver_name);
goto wol_dis;
}
ctrl = 0;
/* turn on magic packet wol */
if (wufc & ATLX_WUFC_MAG)
ctrl |= (WOL_MAGIC_EN | WOL_MAGIC_PME_EN);
/* ignore Link Chg event when Link is up */
ATL2_WRITE_REG(hw, REG_WOL_CTRL, ctrl);
/* Config MAC CTRL Register */
ctrl = MAC_CTRL_RX_EN | MAC_CTRL_MACLP_CLK_PHY;
if (FULL_DUPLEX == adapter->link_duplex)
ctrl |= MAC_CTRL_DUPLX;
ctrl |= (MAC_CTRL_ADD_CRC | MAC_CTRL_PAD);
ctrl |= (((u32)adapter->hw.preamble_len &
MAC_CTRL_PRMLEN_MASK) << MAC_CTRL_PRMLEN_SHIFT);
ctrl |= (((u32)(adapter->hw.retry_buf &
MAC_CTRL_HALF_LEFT_BUF_MASK)) <<
MAC_CTRL_HALF_LEFT_BUF_SHIFT);
if (wufc & ATLX_WUFC_MAG) {
/* magic packet maybe Broadcast&multicast&Unicast */
ctrl |= MAC_CTRL_BC_EN;
}
ATL2_WRITE_REG(hw, REG_MAC_CTRL, ctrl);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
pci_enable_wake(pdev, pci_choose_state(pdev, state), 1);
goto suspend_exit;
}
if (0 == (ctrl&BMSR_LSTATUS) && 0 != (wufc&ATLX_WUFC_LNKC)) {
/* link is down, so only LINK CHG WOL event enable */
ctrl |= (WOL_LINK_CHG_EN | WOL_LINK_CHG_PME_EN);
ATL2_WRITE_REG(hw, REG_WOL_CTRL, ctrl);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, 0);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
hw->phy_configured = false; /* re-init PHY when resume */
pci_enable_wake(pdev, pci_choose_state(pdev, state), 1);
goto suspend_exit;
}
wol_dis:
/* WOL disabled */
ATL2_WRITE_REG(hw, REG_WOL_CTRL, 0);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
atl2_force_ps(hw);
hw->phy_configured = false; /* re-init PHY when resume */
pci_enable_wake(pdev, pci_choose_state(pdev, state), 0);
suspend_exit:
if (netif_running(netdev))
atl2_free_irq(adapter);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
#ifdef CONFIG_PM
static int atl2_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR
"atl2: Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
ATL2_READ_REG(&adapter->hw, REG_WOL_CTRL); /* clear WOL status */
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
ATL2_WRITE_REG(&adapter->hw, REG_WOL_CTRL, 0);
if (netif_running(netdev)) {
err = atl2_request_irq(adapter);
if (err)
return err;
}
atl2_reset_hw(&adapter->hw);
if (netif_running(netdev))
atl2_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif
static void atl2_shutdown(struct pci_dev *pdev)
{
atl2_suspend(pdev, PMSG_SUSPEND);
}
static struct pci_driver atl2_driver = {
.name = atl2_driver_name,
.id_table = atl2_pci_tbl,
.probe = atl2_probe,
.remove = __devexit_p(atl2_remove),
/* Power Management Hooks */
.suspend = atl2_suspend,
#ifdef CONFIG_PM
.resume = atl2_resume,
#endif
.shutdown = atl2_shutdown,
};
/*
* atl2_init_module - Driver Registration Routine
*
* atl2_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
*/
static int __init atl2_init_module(void)
{
printk(KERN_INFO "%s - version %s\n", atl2_driver_string,
atl2_driver_version);
printk(KERN_INFO "%s\n", atl2_copyright);
return pci_register_driver(&atl2_driver);
}
module_init(atl2_init_module);
/*
* atl2_exit_module - Driver Exit Cleanup Routine
*
* atl2_exit_module is called just before the driver is removed
* from memory.
*/
static void __exit atl2_exit_module(void)
{
pci_unregister_driver(&atl2_driver);
}
module_exit(atl2_exit_module);
static void atl2_read_pci_cfg(struct atl2_hw *hw, u32 reg, u16 *value)
{
struct atl2_adapter *adapter = hw->back;
pci_read_config_word(adapter->pdev, reg, value);
}
static void atl2_write_pci_cfg(struct atl2_hw *hw, u32 reg, u16 *value)
{
struct atl2_adapter *adapter = hw->back;
pci_write_config_word(adapter->pdev, reg, *value);
}
static int atl2_get_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
ecmd->supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_TP);
ecmd->advertising = ADVERTISED_TP;
ecmd->advertising |= ADVERTISED_Autoneg;
ecmd->advertising |= hw->autoneg_advertised;
ecmd->port = PORT_TP;
ecmd->phy_address = 0;
ecmd->transceiver = XCVR_INTERNAL;
if (adapter->link_speed != SPEED_0) {
ethtool_cmd_speed_set(ecmd, adapter->link_speed);
if (adapter->link_duplex == FULL_DUPLEX)
ecmd->duplex = DUPLEX_FULL;
else
ecmd->duplex = DUPLEX_HALF;
} else {
ethtool_cmd_speed_set(ecmd, -1);
ecmd->duplex = -1;
}
ecmd->autoneg = AUTONEG_ENABLE;
return 0;
}
static int atl2_set_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
while (test_and_set_bit(__ATL2_RESETTING, &adapter->flags))
msleep(1);
if (ecmd->autoneg == AUTONEG_ENABLE) {
#define MY_ADV_MASK (ADVERTISE_10_HALF | \
ADVERTISE_10_FULL | \
ADVERTISE_100_HALF| \
ADVERTISE_100_FULL)
if ((ecmd->advertising & MY_ADV_MASK) == MY_ADV_MASK) {
hw->MediaType = MEDIA_TYPE_AUTO_SENSOR;
hw->autoneg_advertised = MY_ADV_MASK;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_100_FULL) {
hw->MediaType = MEDIA_TYPE_100M_FULL;
hw->autoneg_advertised = ADVERTISE_100_FULL;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_100_HALF) {
hw->MediaType = MEDIA_TYPE_100M_HALF;
hw->autoneg_advertised = ADVERTISE_100_HALF;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_10_FULL) {
hw->MediaType = MEDIA_TYPE_10M_FULL;
hw->autoneg_advertised = ADVERTISE_10_FULL;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_10_HALF) {
hw->MediaType = MEDIA_TYPE_10M_HALF;
hw->autoneg_advertised = ADVERTISE_10_HALF;
} else {
clear_bit(__ATL2_RESETTING, &adapter->flags);
return -EINVAL;
}
ecmd->advertising = hw->autoneg_advertised |
ADVERTISED_TP | ADVERTISED_Autoneg;
} else {
clear_bit(__ATL2_RESETTING, &adapter->flags);
return -EINVAL;
}
/* reset the link */
if (netif_running(adapter->netdev)) {
atl2_down(adapter);
atl2_up(adapter);
} else
atl2_reset_hw(&adapter->hw);
clear_bit(__ATL2_RESETTING, &adapter->flags);
return 0;
}
static u32 atl2_get_msglevel(struct net_device *netdev)
{
return 0;
}
/*
* It's sane for this to be empty, but we might want to take advantage of this.
*/
static void atl2_set_msglevel(struct net_device *netdev, u32 data)
{
}
static int atl2_get_regs_len(struct net_device *netdev)
{
#define ATL2_REGS_LEN 42
return sizeof(u32) * ATL2_REGS_LEN;
}
static void atl2_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *p)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *regs_buff = p;
u16 phy_data;
memset(p, 0, sizeof(u32) * ATL2_REGS_LEN);
regs->version = (1 << 24) | (hw->revision_id << 16) | hw->device_id;
regs_buff[0] = ATL2_READ_REG(hw, REG_VPD_CAP);
regs_buff[1] = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
regs_buff[2] = ATL2_READ_REG(hw, REG_SPI_FLASH_CONFIG);
regs_buff[3] = ATL2_READ_REG(hw, REG_TWSI_CTRL);
regs_buff[4] = ATL2_READ_REG(hw, REG_PCIE_DEV_MISC_CTRL);
regs_buff[5] = ATL2_READ_REG(hw, REG_MASTER_CTRL);
regs_buff[6] = ATL2_READ_REG(hw, REG_MANUAL_TIMER_INIT);
regs_buff[7] = ATL2_READ_REG(hw, REG_IRQ_MODU_TIMER_INIT);
regs_buff[8] = ATL2_READ_REG(hw, REG_PHY_ENABLE);
regs_buff[9] = ATL2_READ_REG(hw, REG_CMBDISDMA_TIMER);
regs_buff[10] = ATL2_READ_REG(hw, REG_IDLE_STATUS);
regs_buff[11] = ATL2_READ_REG(hw, REG_MDIO_CTRL);
regs_buff[12] = ATL2_READ_REG(hw, REG_SERDES_LOCK);
regs_buff[13] = ATL2_READ_REG(hw, REG_MAC_CTRL);
regs_buff[14] = ATL2_READ_REG(hw, REG_MAC_IPG_IFG);
regs_buff[15] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR);
regs_buff[16] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR+4);
regs_buff[17] = ATL2_READ_REG(hw, REG_RX_HASH_TABLE);
regs_buff[18] = ATL2_READ_REG(hw, REG_RX_HASH_TABLE+4);
regs_buff[19] = ATL2_READ_REG(hw, REG_MAC_HALF_DUPLX_CTRL);
regs_buff[20] = ATL2_READ_REG(hw, REG_MTU);
regs_buff[21] = ATL2_READ_REG(hw, REG_WOL_CTRL);
regs_buff[22] = ATL2_READ_REG(hw, REG_SRAM_TXRAM_END);
regs_buff[23] = ATL2_READ_REG(hw, REG_DESC_BASE_ADDR_HI);
regs_buff[24] = ATL2_READ_REG(hw, REG_TXD_BASE_ADDR_LO);
regs_buff[25] = ATL2_READ_REG(hw, REG_TXD_MEM_SIZE);
regs_buff[26] = ATL2_READ_REG(hw, REG_TXS_BASE_ADDR_LO);
regs_buff[27] = ATL2_READ_REG(hw, REG_TXS_MEM_SIZE);
regs_buff[28] = ATL2_READ_REG(hw, REG_RXD_BASE_ADDR_LO);
regs_buff[29] = ATL2_READ_REG(hw, REG_RXD_BUF_NUM);
regs_buff[30] = ATL2_READ_REG(hw, REG_DMAR);
regs_buff[31] = ATL2_READ_REG(hw, REG_TX_CUT_THRESH);
regs_buff[32] = ATL2_READ_REG(hw, REG_DMAW);
regs_buff[33] = ATL2_READ_REG(hw, REG_PAUSE_ON_TH);
regs_buff[34] = ATL2_READ_REG(hw, REG_PAUSE_OFF_TH);
regs_buff[35] = ATL2_READ_REG(hw, REG_MB_TXD_WR_IDX);
regs_buff[36] = ATL2_READ_REG(hw, REG_MB_RXD_RD_IDX);
regs_buff[38] = ATL2_READ_REG(hw, REG_ISR);
regs_buff[39] = ATL2_READ_REG(hw, REG_IMR);
atl2_read_phy_reg(hw, MII_BMCR, &phy_data);
regs_buff[40] = (u32)phy_data;
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
regs_buff[41] = (u32)phy_data;
}
static int atl2_get_eeprom_len(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (!atl2_check_eeprom_exist(&adapter->hw))
return 512;
else
return 0;
}
static int atl2_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
int first_dword, last_dword;
int ret_val = 0;
int i;
if (eeprom->len == 0)
return -EINVAL;
if (atl2_check_eeprom_exist(hw))
return -EINVAL;
eeprom->magic = hw->vendor_id | (hw->device_id << 16);
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(sizeof(u32) * (last_dword - first_dword + 1),
GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
for (i = first_dword; i < last_dword; i++) {
if (!atl2_read_eeprom(hw, i*4, &(eeprom_buff[i-first_dword]))) {
ret_val = -EIO;
goto free;
}
}
memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 3),
eeprom->len);
free:
kfree(eeprom_buff);
return ret_val;
}
static int atl2_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
u32 *ptr;
int max_len, first_dword, last_dword, ret_val = 0;
int i;
if (eeprom->len == 0)
return -EOPNOTSUPP;
if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16)))
return -EFAULT;
max_len = 512;
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(max_len, GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
ptr = eeprom_buff;
if (eeprom->offset & 3) {
/* need read/modify/write of first changed EEPROM word */
/* only the second byte of the word is being modified */
if (!atl2_read_eeprom(hw, first_dword*4, &(eeprom_buff[0]))) {
ret_val = -EIO;
goto out;
}
ptr++;
}
if (((eeprom->offset + eeprom->len) & 3)) {
/*
* need read/modify/write of last changed EEPROM word
* only the first byte of the word is being modified
*/
if (!atl2_read_eeprom(hw, last_dword * 4,
&(eeprom_buff[last_dword - first_dword]))) {
ret_val = -EIO;
goto out;
}
}
/* Device's eeprom is always little-endian, word addressable */
memcpy(ptr, bytes, eeprom->len);
for (i = 0; i < last_dword - first_dword + 1; i++) {
if (!atl2_write_eeprom(hw, ((first_dword+i)*4), eeprom_buff[i])) {
ret_val = -EIO;
goto out;
}
}
out:
kfree(eeprom_buff);
return ret_val;
}
static void atl2_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
strlcpy(drvinfo->driver, atl2_driver_name, sizeof(drvinfo->driver));
strlcpy(drvinfo->version, atl2_driver_version,
sizeof(drvinfo->version));
strlcpy(drvinfo->fw_version, "L2", sizeof(drvinfo->fw_version));
strlcpy(drvinfo->bus_info, pci_name(adapter->pdev),
sizeof(drvinfo->bus_info));
drvinfo->n_stats = 0;
drvinfo->testinfo_len = 0;
drvinfo->regdump_len = atl2_get_regs_len(netdev);
drvinfo->eedump_len = atl2_get_eeprom_len(netdev);
}
static void atl2_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
wol->supported = WAKE_MAGIC;
wol->wolopts = 0;
if (adapter->wol & ATLX_WUFC_EX)
wol->wolopts |= WAKE_UCAST;
if (adapter->wol & ATLX_WUFC_MC)
wol->wolopts |= WAKE_MCAST;
if (adapter->wol & ATLX_WUFC_BC)
wol->wolopts |= WAKE_BCAST;
if (adapter->wol & ATLX_WUFC_MAG)
wol->wolopts |= WAKE_MAGIC;
if (adapter->wol & ATLX_WUFC_LNKC)
wol->wolopts |= WAKE_PHY;
}
static int atl2_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE))
return -EOPNOTSUPP;
if (wol->wolopts & (WAKE_UCAST | WAKE_BCAST | WAKE_MCAST))
return -EOPNOTSUPP;
/* these settings will always override what we currently have */
adapter->wol = 0;
if (wol->wolopts & WAKE_MAGIC)
adapter->wol |= ATLX_WUFC_MAG;
if (wol->wolopts & WAKE_PHY)
adapter->wol |= ATLX_WUFC_LNKC;
return 0;
}
static int atl2_nway_reset(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev))
atl2_reinit_locked(adapter);
return 0;
}
static const struct ethtool_ops atl2_ethtool_ops = {
.get_settings = atl2_get_settings,
.set_settings = atl2_set_settings,
.get_drvinfo = atl2_get_drvinfo,
.get_regs_len = atl2_get_regs_len,
.get_regs = atl2_get_regs,
.get_wol = atl2_get_wol,
.set_wol = atl2_set_wol,
.get_msglevel = atl2_get_msglevel,
.set_msglevel = atl2_set_msglevel,
.nway_reset = atl2_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = atl2_get_eeprom_len,
.get_eeprom = atl2_get_eeprom,
.set_eeprom = atl2_set_eeprom,
};
static void atl2_set_ethtool_ops(struct net_device *netdev)
{
SET_ETHTOOL_OPS(netdev, &atl2_ethtool_ops);
}
#define LBYTESWAP(a) ((((a) & 0x00ff00ff) << 8) | \
(((a) & 0xff00ff00) >> 8))
#define LONGSWAP(a) ((LBYTESWAP(a) << 16) | (LBYTESWAP(a) >> 16))
#define SHORTSWAP(a) (((a) << 8) | ((a) >> 8))
/*
* Reset the transmit and receive units; mask and clear all interrupts.
*
* hw - Struct containing variables accessed by shared code
* return : 0 or idle status (if error)
*/
static s32 atl2_reset_hw(struct atl2_hw *hw)
{
u32 icr;
u16 pci_cfg_cmd_word;
int i;
/* Workaround for PCI problem when BIOS sets MMRBC incorrectly. */
atl2_read_pci_cfg(hw, PCI_REG_COMMAND, &pci_cfg_cmd_word);
if ((pci_cfg_cmd_word &
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER)) !=
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER)) {
pci_cfg_cmd_word |=
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER);
atl2_write_pci_cfg(hw, PCI_REG_COMMAND, &pci_cfg_cmd_word);
}
/* Clear Interrupt mask to stop board from generating
* interrupts & Clear any pending interrupt events
*/
/* FIXME */
/* ATL2_WRITE_REG(hw, REG_IMR, 0); */
/* ATL2_WRITE_REG(hw, REG_ISR, 0xffffffff); */
/* Issue Soft Reset to the MAC. This will reset the chip's
* transmit, receive, DMA. It will not effect
* the current PCI configuration. The global reset bit is self-
* clearing, and should clear within a microsecond.
*/
ATL2_WRITE_REG(hw, REG_MASTER_CTRL, MASTER_CTRL_SOFT_RST);
wmb();
msleep(1); /* delay about 1ms */
/* Wait at least 10ms for All module to be Idle */
for (i = 0; i < 10; i++) {
icr = ATL2_READ_REG(hw, REG_IDLE_STATUS);
if (!icr)
break;
msleep(1); /* delay 1 ms */
cpu_relax();
}
if (icr)
return icr;
return 0;
}
#define CUSTOM_SPI_CS_SETUP 2
#define CUSTOM_SPI_CLK_HI 2
#define CUSTOM_SPI_CLK_LO 2
#define CUSTOM_SPI_CS_HOLD 2
#define CUSTOM_SPI_CS_HI 3
static struct atl2_spi_flash_dev flash_table[] =
{
/* MFR WRSR READ PROGRAM WREN WRDI RDSR RDID SECTOR_ERASE CHIP_ERASE */
{"Atmel", 0x0, 0x03, 0x02, 0x06, 0x04, 0x05, 0x15, 0x52, 0x62 },
{"SST", 0x01, 0x03, 0x02, 0x06, 0x04, 0x05, 0x90, 0x20, 0x60 },
{"ST", 0x01, 0x03, 0x02, 0x06, 0x04, 0x05, 0xAB, 0xD8, 0xC7 },
};
static bool atl2_spi_read(struct atl2_hw *hw, u32 addr, u32 *buf)
{
int i;
u32 value;
ATL2_WRITE_REG(hw, REG_SPI_DATA, 0);
ATL2_WRITE_REG(hw, REG_SPI_ADDR, addr);
value = SPI_FLASH_CTRL_WAIT_READY |
(CUSTOM_SPI_CS_SETUP & SPI_FLASH_CTRL_CS_SETUP_MASK) <<
SPI_FLASH_CTRL_CS_SETUP_SHIFT |
(CUSTOM_SPI_CLK_HI & SPI_FLASH_CTRL_CLK_HI_MASK) <<
SPI_FLASH_CTRL_CLK_HI_SHIFT |
(CUSTOM_SPI_CLK_LO & SPI_FLASH_CTRL_CLK_LO_MASK) <<
SPI_FLASH_CTRL_CLK_LO_SHIFT |
(CUSTOM_SPI_CS_HOLD & SPI_FLASH_CTRL_CS_HOLD_MASK) <<
SPI_FLASH_CTRL_CS_HOLD_SHIFT |
(CUSTOM_SPI_CS_HI & SPI_FLASH_CTRL_CS_HI_MASK) <<
SPI_FLASH_CTRL_CS_HI_SHIFT |
(0x1 & SPI_FLASH_CTRL_INS_MASK) << SPI_FLASH_CTRL_INS_SHIFT;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
value |= SPI_FLASH_CTRL_START;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
for (i = 0; i < 10; i++) {
msleep(1);
value = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
if (!(value & SPI_FLASH_CTRL_START))
break;
}
if (value & SPI_FLASH_CTRL_START)
return false;
*buf = ATL2_READ_REG(hw, REG_SPI_DATA);
return true;
}
/*
* get_permanent_address
* return 0 if get valid mac address,
*/
static int get_permanent_address(struct atl2_hw *hw)
{
u32 Addr[2];
u32 i, Control;
u16 Register;
u8 EthAddr[ETH_ALEN];
bool KeyValid;
if (is_valid_ether_addr(hw->perm_mac_addr))
return 0;
Addr[0] = 0;
Addr[1] = 0;
if (!atl2_check_eeprom_exist(hw)) { /* eeprom exists */
Register = 0;
KeyValid = false;
/* Read out all EEPROM content */
i = 0;
while (1) {
if (atl2_read_eeprom(hw, i + 0x100, &Control)) {
if (KeyValid) {
if (Register == REG_MAC_STA_ADDR)
Addr[0] = Control;
else if (Register ==
(REG_MAC_STA_ADDR + 4))
Addr[1] = Control;
KeyValid = false;
} else if ((Control & 0xff) == 0x5A) {
KeyValid = true;
Register = (u16) (Control >> 16);
} else {
/* assume data end while encount an invalid KEYWORD */
break;
}
} else {
break; /* read error */
}
i += 4;
}
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *) &Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, ETH_ALEN);
return 0;
}
return 1;
}
/* see if SPI flash exists? */
Addr[0] = 0;
Addr[1] = 0;
Register = 0;
KeyValid = false;
i = 0;
while (1) {
if (atl2_spi_read(hw, i + 0x1f000, &Control)) {
if (KeyValid) {
if (Register == REG_MAC_STA_ADDR)
Addr[0] = Control;
else if (Register == (REG_MAC_STA_ADDR + 4))
Addr[1] = Control;
KeyValid = false;
} else if ((Control & 0xff) == 0x5A) {
KeyValid = true;
Register = (u16) (Control >> 16);
} else {
break; /* data end */
}
} else {
break; /* read error */
}
i += 4;
}
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *)&Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, ETH_ALEN);
return 0;
}
/* maybe MAC-address is from BIOS */
Addr[0] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR);
Addr[1] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR + 4);
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *) &Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, ETH_ALEN);
return 0;
}
return 1;
}
/*
* Reads the adapter's MAC address from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*/
static s32 atl2_read_mac_addr(struct atl2_hw *hw)
{
if (get_permanent_address(hw)) {
/* for test */
/* FIXME: shouldn't we use random_ether_addr() here? */
hw->perm_mac_addr[0] = 0x00;
hw->perm_mac_addr[1] = 0x13;
hw->perm_mac_addr[2] = 0x74;
hw->perm_mac_addr[3] = 0x00;
hw->perm_mac_addr[4] = 0x5c;
hw->perm_mac_addr[5] = 0x38;
}
memcpy(hw->mac_addr, hw->perm_mac_addr, ETH_ALEN);
return 0;
}
/*
* Hashes an address to determine its location in the multicast table
*
* hw - Struct containing variables accessed by shared code
* mc_addr - the multicast address to hash
*
* atl2_hash_mc_addr
* purpose
* set hash value for a multicast address
* hash calcu processing :
* 1. calcu 32bit CRC for multicast address
* 2. reverse crc with MSB to LSB
*/
static u32 atl2_hash_mc_addr(struct atl2_hw *hw, u8 *mc_addr)
{
u32 crc32, value;
int i;
value = 0;
crc32 = ether_crc_le(6, mc_addr);
for (i = 0; i < 32; i++)
value |= (((crc32 >> i) & 1) << (31 - i));
return value;
}
/*
* Sets the bit in the multicast table corresponding to the hash value.
*
* hw - Struct containing variables accessed by shared code
* hash_value - Multicast address hash value
*/
static void atl2_hash_set(struct atl2_hw *hw, u32 hash_value)
{
u32 hash_bit, hash_reg;
u32 mta;
/* The HASH Table is a register array of 2 32-bit registers.
* It is treated like an array of 64 bits. We want to set
* bit BitArray[hash_value]. So we figure out what register
* the bit is in, read it, OR in the new bit, then write
* back the new value. The register is determined by the
* upper 7 bits of the hash value and the bit within that
* register are determined by the lower 5 bits of the value.
*/
hash_reg = (hash_value >> 31) & 0x1;
hash_bit = (hash_value >> 26) & 0x1F;
mta = ATL2_READ_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg);
mta |= (1 << hash_bit);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg, mta);
}
/*
* atl2_init_pcie - init PCIE module
*/
static void atl2_init_pcie(struct atl2_hw *hw)
{
u32 value;
value = LTSSM_TEST_MODE_DEF;
ATL2_WRITE_REG(hw, REG_LTSSM_TEST_MODE, value);
value = PCIE_DLL_TX_CTRL1_DEF;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, value);
}
static void atl2_init_flash_opcode(struct atl2_hw *hw)
{
if (hw->flash_vendor >= ARRAY_SIZE(flash_table))
hw->flash_vendor = 0; /* ATMEL */
/* Init OP table */
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_PROGRAM,
flash_table[hw->flash_vendor].cmdPROGRAM);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_SC_ERASE,
flash_table[hw->flash_vendor].cmdSECTOR_ERASE);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_CHIP_ERASE,
flash_table[hw->flash_vendor].cmdCHIP_ERASE);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_RDID,
flash_table[hw->flash_vendor].cmdRDID);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_WREN,
flash_table[hw->flash_vendor].cmdWREN);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_RDSR,
flash_table[hw->flash_vendor].cmdRDSR);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_WRSR,
flash_table[hw->flash_vendor].cmdWRSR);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_READ,
flash_table[hw->flash_vendor].cmdREAD);
}
/********************************************************************
* Performs basic configuration of the adapter.
*
* hw - Struct containing variables accessed by shared code
* Assumes that the controller has previously been reset and is in a
* post-reset uninitialized state. Initializes multicast table,
* and Calls routines to setup link
* Leaves the transmit and receive units disabled and uninitialized.
********************************************************************/
static s32 atl2_init_hw(struct atl2_hw *hw)
{
u32 ret_val = 0;
atl2_init_pcie(hw);
/* Zero out the Multicast HASH table */
/* clear the old settings from the multicast hash table */
ATL2_WRITE_REG(hw, REG_RX_HASH_TABLE, 0);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, 1, 0);
atl2_init_flash_opcode(hw);
ret_val = atl2_phy_init(hw);
return ret_val;
}
/*
* Detects the current speed and duplex settings of the hardware.
*
* hw - Struct containing variables accessed by shared code
* speed - Speed of the connection
* duplex - Duplex setting of the connection
*/
static s32 atl2_get_speed_and_duplex(struct atl2_hw *hw, u16 *speed,
u16 *duplex)
{
s32 ret_val;
u16 phy_data;
/* Read PHY Specific Status Register (17) */
ret_val = atl2_read_phy_reg(hw, MII_ATLX_PSSR, &phy_data);
if (ret_val)
return ret_val;
if (!(phy_data & MII_ATLX_PSSR_SPD_DPLX_RESOLVED))
return ATLX_ERR_PHY_RES;
switch (phy_data & MII_ATLX_PSSR_SPEED) {
case MII_ATLX_PSSR_100MBS:
*speed = SPEED_100;
break;
case MII_ATLX_PSSR_10MBS:
*speed = SPEED_10;
break;
default:
return ATLX_ERR_PHY_SPEED;
break;
}
if (phy_data & MII_ATLX_PSSR_DPLX)
*duplex = FULL_DUPLEX;
else
*duplex = HALF_DUPLEX;
return 0;
}
/*
* Reads the value from a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to read
*/
static s32 atl2_read_phy_reg(struct atl2_hw *hw, u16 reg_addr, u16 *phy_data)
{
u32 val;
int i;
val = ((u32)(reg_addr & MDIO_REG_ADDR_MASK)) << MDIO_REG_ADDR_SHIFT |
MDIO_START |
MDIO_SUP_PREAMBLE |
MDIO_RW |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
ATL2_WRITE_REG(hw, REG_MDIO_CTRL, val);
wmb();
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
wmb();
}
if (!(val & (MDIO_START | MDIO_BUSY))) {
*phy_data = (u16)val;
return 0;
}
return ATLX_ERR_PHY;
}
/*
* Writes a value to a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to write
* data - data to write to the PHY
*/
static s32 atl2_write_phy_reg(struct atl2_hw *hw, u32 reg_addr, u16 phy_data)
{
int i;
u32 val;
val = ((u32)(phy_data & MDIO_DATA_MASK)) << MDIO_DATA_SHIFT |
(reg_addr & MDIO_REG_ADDR_MASK) << MDIO_REG_ADDR_SHIFT |
MDIO_SUP_PREAMBLE |
MDIO_START |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
ATL2_WRITE_REG(hw, REG_MDIO_CTRL, val);
wmb();
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
wmb();
}
if (!(val & (MDIO_START | MDIO_BUSY)))
return 0;
return ATLX_ERR_PHY;
}
/*
* Configures PHY autoneg and flow control advertisement settings
*
* hw - Struct containing variables accessed by shared code
*/
static s32 atl2_phy_setup_autoneg_adv(struct atl2_hw *hw)
{
s32 ret_val;
s16 mii_autoneg_adv_reg;
/* Read the MII Auto-Neg Advertisement Register (Address 4). */
mii_autoneg_adv_reg = MII_AR_DEFAULT_CAP_MASK;
/* Need to parse autoneg_advertised and set up
* the appropriate PHY registers. First we will parse for
* autoneg_advertised software override. Since we can advertise
* a plethora of combinations, we need to check each bit
* individually.
*/
/* First we clear all the 10/100 mb speed bits in the Auto-Neg
* Advertisement Register (Address 4) and the 1000 mb speed bits in
* the 1000Base-T Control Register (Address 9). */
mii_autoneg_adv_reg &= ~MII_AR_SPEED_MASK;
/* Need to parse MediaType and setup the
* appropriate PHY registers. */
switch (hw->MediaType) {
case MEDIA_TYPE_AUTO_SENSOR:
mii_autoneg_adv_reg |=
(MII_AR_10T_HD_CAPS |
MII_AR_10T_FD_CAPS |
MII_AR_100TX_HD_CAPS|
MII_AR_100TX_FD_CAPS);
hw->autoneg_advertised =
ADVERTISE_10_HALF |
ADVERTISE_10_FULL |
ADVERTISE_100_HALF|
ADVERTISE_100_FULL;
break;
case MEDIA_TYPE_100M_FULL:
mii_autoneg_adv_reg |= MII_AR_100TX_FD_CAPS;
hw->autoneg_advertised = ADVERTISE_100_FULL;
break;
case MEDIA_TYPE_100M_HALF:
mii_autoneg_adv_reg |= MII_AR_100TX_HD_CAPS;
hw->autoneg_advertised = ADVERTISE_100_HALF;
break;
case MEDIA_TYPE_10M_FULL:
mii_autoneg_adv_reg |= MII_AR_10T_FD_CAPS;
hw->autoneg_advertised = ADVERTISE_10_FULL;
break;
default:
mii_autoneg_adv_reg |= MII_AR_10T_HD_CAPS;
hw->autoneg_advertised = ADVERTISE_10_HALF;
break;
}
/* flow control fixed to enable all */
mii_autoneg_adv_reg |= (MII_AR_ASM_DIR | MII_AR_PAUSE);
hw->mii_autoneg_adv_reg = mii_autoneg_adv_reg;
ret_val = atl2_write_phy_reg(hw, MII_ADVERTISE, mii_autoneg_adv_reg);
if (ret_val)
return ret_val;
return 0;
}
/*
* Resets the PHY and make all config validate
*
* hw - Struct containing variables accessed by shared code
*
* Sets bit 15 and 12 of the MII Control regiser (for F001 bug)
*/
static s32 atl2_phy_commit(struct atl2_hw *hw)
{
s32 ret_val;
u16 phy_data;
phy_data = MII_CR_RESET | MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
ret_val = atl2_write_phy_reg(hw, MII_BMCR, phy_data);
if (ret_val) {
u32 val;
int i;
/* pcie serdes link may be down ! */
for (i = 0; i < 25; i++) {
msleep(1);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
}
if (0 != (val & (MDIO_START | MDIO_BUSY))) {
printk(KERN_ERR "atl2: PCIe link down for at least 25ms !\n");
return ret_val;
}
}
return 0;
}
static s32 atl2_phy_init(struct atl2_hw *hw)
{
s32 ret_val;
u16 phy_val;
if (hw->phy_configured)
return 0;
/* Enable PHY */
ATL2_WRITE_REGW(hw, REG_PHY_ENABLE, 1);
ATL2_WRITE_FLUSH(hw);
msleep(1);
/* check if the PHY is in powersaving mode */
atl2_write_phy_reg(hw, MII_DBG_ADDR, 0);
atl2_read_phy_reg(hw, MII_DBG_DATA, &phy_val);
/* 024E / 124E 0r 0274 / 1274 ? */
if (phy_val & 0x1000) {
phy_val &= ~0x1000;
atl2_write_phy_reg(hw, MII_DBG_DATA, phy_val);
}
msleep(1);
/*Enable PHY LinkChange Interrupt */
ret_val = atl2_write_phy_reg(hw, 18, 0xC00);
if (ret_val)
return ret_val;
/* setup AutoNeg parameters */
ret_val = atl2_phy_setup_autoneg_adv(hw);
if (ret_val)
return ret_val;
/* SW.Reset & En-Auto-Neg to restart Auto-Neg */
ret_val = atl2_phy_commit(hw);
if (ret_val)
return ret_val;
hw->phy_configured = true;
return ret_val;
}
static void atl2_set_mac_addr(struct atl2_hw *hw)
{
u32 value;
/* 00-0B-6A-F6-00-DC
* 0: 6AF600DC 1: 000B
* low dword */
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5]));
ATL2_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 0, value);
/* hight dword */
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1]));
ATL2_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 1, value);
}
/*
* check_eeprom_exist
* return 0 if eeprom exist
*/
static int atl2_check_eeprom_exist(struct atl2_hw *hw)
{
u32 value;
value = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
if (value & SPI_FLASH_CTRL_EN_VPD) {
value &= ~SPI_FLASH_CTRL_EN_VPD;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
}
value = ATL2_READ_REGW(hw, REG_PCIE_CAP_LIST);
return ((value & 0xFF00) == 0x6C00) ? 0 : 1;
}
/* FIXME: This doesn't look right. -- CHS */
static bool atl2_write_eeprom(struct atl2_hw *hw, u32 offset, u32 value)
{
return true;
}
static bool atl2_read_eeprom(struct atl2_hw *hw, u32 Offset, u32 *pValue)
{
int i;
u32 Control;
if (Offset & 0x3)
return false; /* address do not align */
ATL2_WRITE_REG(hw, REG_VPD_DATA, 0);
Control = (Offset & VPD_CAP_VPD_ADDR_MASK) << VPD_CAP_VPD_ADDR_SHIFT;
ATL2_WRITE_REG(hw, REG_VPD_CAP, Control);
for (i = 0; i < 10; i++) {
msleep(2);
Control = ATL2_READ_REG(hw, REG_VPD_CAP);
if (Control & VPD_CAP_VPD_FLAG)
break;
}
if (Control & VPD_CAP_VPD_FLAG) {
*pValue = ATL2_READ_REG(hw, REG_VPD_DATA);
return true;
}
return false; /* timeout */
}
static void atl2_force_ps(struct atl2_hw *hw)
{
u16 phy_val;
atl2_write_phy_reg(hw, MII_DBG_ADDR, 0);
atl2_read_phy_reg(hw, MII_DBG_DATA, &phy_val);
atl2_write_phy_reg(hw, MII_DBG_DATA, phy_val | 0x1000);
atl2_write_phy_reg(hw, MII_DBG_ADDR, 2);
atl2_write_phy_reg(hw, MII_DBG_DATA, 0x3000);
atl2_write_phy_reg(hw, MII_DBG_ADDR, 3);
atl2_write_phy_reg(hw, MII_DBG_DATA, 0);
}
/* This is the only thing that needs to be changed to adjust the
* maximum number of ports that the driver can manage.
*/
#define ATL2_MAX_NIC 4
#define OPTION_UNSET -1
#define OPTION_DISABLED 0
#define OPTION_ENABLED 1
/* All parameters are treated the same, as an integer array of values.
* This macro just reduces the need to repeat the same declaration code
* over and over (plus this helps to avoid typo bugs).
*/
#define ATL2_PARAM_INIT {[0 ... ATL2_MAX_NIC] = OPTION_UNSET}
#ifndef module_param_array
/* Module Parameters are always initialized to -1, so that the driver
* can tell the difference between no user specified value or the
* user asking for the default value.
* The true default values are loaded in when atl2_check_options is called.
*
* This is a GCC extension to ANSI C.
* See the item "Labeled Elements in Initializers" in the section
* "Extensions to the C Language Family" of the GCC documentation.
*/
#define ATL2_PARAM(X, desc) \
static const int __devinitdata X[ATL2_MAX_NIC + 1] = ATL2_PARAM_INIT; \
MODULE_PARM(X, "1-" __MODULE_STRING(ATL2_MAX_NIC) "i"); \
MODULE_PARM_DESC(X, desc);
#else
#define ATL2_PARAM(X, desc) \
static int __devinitdata X[ATL2_MAX_NIC+1] = ATL2_PARAM_INIT; \
static unsigned int num_##X; \
module_param_array_named(X, X, int, &num_##X, 0); \
MODULE_PARM_DESC(X, desc);
#endif
/*
* Transmit Memory Size
* Valid Range: 64-2048
* Default Value: 128
*/
#define ATL2_MIN_TX_MEMSIZE 4 /* 4KB */
#define ATL2_MAX_TX_MEMSIZE 64 /* 64KB */
#define ATL2_DEFAULT_TX_MEMSIZE 8 /* 8KB */
ATL2_PARAM(TxMemSize, "Bytes of Transmit Memory");
/*
* Receive Memory Block Count
* Valid Range: 16-512
* Default Value: 128
*/
#define ATL2_MIN_RXD_COUNT 16
#define ATL2_MAX_RXD_COUNT 512
#define ATL2_DEFAULT_RXD_COUNT 64
ATL2_PARAM(RxMemBlock, "Number of receive memory block");
/*
* User Specified MediaType Override
*
* Valid Range: 0-5
* - 0 - auto-negotiate at all supported speeds
* - 1 - only link at 1000Mbps Full Duplex
* - 2 - only link at 100Mbps Full Duplex
* - 3 - only link at 100Mbps Half Duplex
* - 4 - only link at 10Mbps Full Duplex
* - 5 - only link at 10Mbps Half Duplex
* Default Value: 0
*/
ATL2_PARAM(MediaType, "MediaType Select");
/*
* Interrupt Moderate Timer in units of 2048 ns (~2 us)
* Valid Range: 10-65535
* Default Value: 45000(90ms)
*/
#define INT_MOD_DEFAULT_CNT 100 /* 200us */
#define INT_MOD_MAX_CNT 65000
#define INT_MOD_MIN_CNT 50
ATL2_PARAM(IntModTimer, "Interrupt Moderator Timer");
/*
* FlashVendor
* Valid Range: 0-2
* 0 - Atmel
* 1 - SST
* 2 - ST
*/
ATL2_PARAM(FlashVendor, "SPI Flash Vendor");
#define AUTONEG_ADV_DEFAULT 0x2F
#define AUTONEG_ADV_MASK 0x2F
#define FLOW_CONTROL_DEFAULT FLOW_CONTROL_FULL
#define FLASH_VENDOR_DEFAULT 0
#define FLASH_VENDOR_MIN 0
#define FLASH_VENDOR_MAX 2
struct atl2_option {
enum { enable_option, range_option, list_option } type;
char *name;
char *err;
int def;
union {
struct { /* range_option info */
int min;
int max;
} r;
struct { /* list_option info */
int nr;
struct atl2_opt_list { int i; char *str; } *p;
} l;
} arg;
};
static int __devinit atl2_validate_option(int *value, struct atl2_option *opt)
{
int i;
struct atl2_opt_list *ent;
if (*value == OPTION_UNSET) {
*value = opt->def;
return 0;
}
switch (opt->type) {
case enable_option:
switch (*value) {
case OPTION_ENABLED:
printk(KERN_INFO "%s Enabled\n", opt->name);
return 0;
break;
case OPTION_DISABLED:
printk(KERN_INFO "%s Disabled\n", opt->name);
return 0;
break;
}
break;
case range_option:
if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) {
printk(KERN_INFO "%s set to %i\n", opt->name, *value);
return 0;
}
break;
case list_option:
for (i = 0; i < opt->arg.l.nr; i++) {
ent = &opt->arg.l.p[i];
if (*value == ent->i) {
if (ent->str[0] != '\0')
printk(KERN_INFO "%s\n", ent->str);
return 0;
}
}
break;
default:
BUG();
}
printk(KERN_INFO "Invalid %s specified (%i) %s\n",
opt->name, *value, opt->err);
*value = opt->def;
return -1;
}
/*
* atl2_check_options - Range Checking for Command Line Parameters
* @adapter: board private structure
*
* This routine checks all command line parameters for valid user
* input. If an invalid value is given, or if no user specified
* value exists, a default value is used. The final value is stored
* in a variable in the adapter structure.
*/
static void __devinit atl2_check_options(struct atl2_adapter *adapter)
{
int val;
struct atl2_option opt;
int bd = adapter->bd_number;
if (bd >= ATL2_MAX_NIC) {
printk(KERN_NOTICE "Warning: no configuration for board #%i\n",
bd);
printk(KERN_NOTICE "Using defaults for all values\n");
#ifndef module_param_array
bd = ATL2_MAX_NIC;
#endif
}
/* Bytes of Transmit Memory */
opt.type = range_option;
opt.name = "Bytes of Transmit Memory";
opt.err = "using default of " __MODULE_STRING(ATL2_DEFAULT_TX_MEMSIZE);
opt.def = ATL2_DEFAULT_TX_MEMSIZE;
opt.arg.r.min = ATL2_MIN_TX_MEMSIZE;
opt.arg.r.max = ATL2_MAX_TX_MEMSIZE;
#ifdef module_param_array
if (num_TxMemSize > bd) {
#endif
val = TxMemSize[bd];
atl2_validate_option(&val, &opt);
adapter->txd_ring_size = ((u32) val) * 1024;
#ifdef module_param_array
} else
adapter->txd_ring_size = ((u32)opt.def) * 1024;
#endif
/* txs ring size: */
adapter->txs_ring_size = adapter->txd_ring_size / 128;
if (adapter->txs_ring_size > 160)
adapter->txs_ring_size = 160;
/* Receive Memory Block Count */
opt.type = range_option;
opt.name = "Number of receive memory block";
opt.err = "using default of " __MODULE_STRING(ATL2_DEFAULT_RXD_COUNT);
opt.def = ATL2_DEFAULT_RXD_COUNT;
opt.arg.r.min = ATL2_MIN_RXD_COUNT;
opt.arg.r.max = ATL2_MAX_RXD_COUNT;
#ifdef module_param_array
if (num_RxMemBlock > bd) {
#endif
val = RxMemBlock[bd];
atl2_validate_option(&val, &opt);
adapter->rxd_ring_size = (u32)val;
/* FIXME */
/* ((u16)val)&~1; */ /* even number */
#ifdef module_param_array
} else
adapter->rxd_ring_size = (u32)opt.def;
#endif
/* init RXD Flow control value */
adapter->hw.fc_rxd_hi = (adapter->rxd_ring_size / 8) * 7;
adapter->hw.fc_rxd_lo = (ATL2_MIN_RXD_COUNT / 8) >
(adapter->rxd_ring_size / 12) ? (ATL2_MIN_RXD_COUNT / 8) :
(adapter->rxd_ring_size / 12);
/* Interrupt Moderate Timer */
opt.type = range_option;
opt.name = "Interrupt Moderate Timer";
opt.err = "using default of " __MODULE_STRING(INT_MOD_DEFAULT_CNT);
opt.def = INT_MOD_DEFAULT_CNT;
opt.arg.r.min = INT_MOD_MIN_CNT;
opt.arg.r.max = INT_MOD_MAX_CNT;
#ifdef module_param_array
if (num_IntModTimer > bd) {
#endif
val = IntModTimer[bd];
atl2_validate_option(&val, &opt);
adapter->imt = (u16) val;
#ifdef module_param_array
} else
adapter->imt = (u16)(opt.def);
#endif
/* Flash Vendor */
opt.type = range_option;
opt.name = "SPI Flash Vendor";
opt.err = "using default of " __MODULE_STRING(FLASH_VENDOR_DEFAULT);
opt.def = FLASH_VENDOR_DEFAULT;
opt.arg.r.min = FLASH_VENDOR_MIN;
opt.arg.r.max = FLASH_VENDOR_MAX;
#ifdef module_param_array
if (num_FlashVendor > bd) {
#endif
val = FlashVendor[bd];
atl2_validate_option(&val, &opt);
adapter->hw.flash_vendor = (u8) val;
#ifdef module_param_array
} else
adapter->hw.flash_vendor = (u8)(opt.def);
#endif
/* MediaType */
opt.type = range_option;
opt.name = "Speed/Duplex Selection";
opt.err = "using default of " __MODULE_STRING(MEDIA_TYPE_AUTO_SENSOR);
opt.def = MEDIA_TYPE_AUTO_SENSOR;
opt.arg.r.min = MEDIA_TYPE_AUTO_SENSOR;
opt.arg.r.max = MEDIA_TYPE_10M_HALF;
#ifdef module_param_array
if (num_MediaType > bd) {
#endif
val = MediaType[bd];
atl2_validate_option(&val, &opt);
adapter->hw.MediaType = (u16) val;
#ifdef module_param_array
} else
adapter->hw.MediaType = (u16)(opt.def);
#endif
}
| gpl-2.0 |
DirtyDroidX/kernel_jactive | drivers/net/ethernet/3com/3c501.c | 4856 | 23842 | /* 3c501.c: A 3Com 3c501 Ethernet driver for Linux. */
/*
Written 1992,1993,1994 Donald Becker
Copyright 1993 United States Government as represented by the
Director, National Security Agency. This software may be used and
distributed according to the terms of the GNU General Public License,
incorporated herein by reference.
This is a device driver for the 3Com Etherlink 3c501.
Do not purchase this card, even as a joke. It's performance is horrible,
and it breaks in many ways.
The original author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
Fixed (again!) the missing interrupt locking on TX/RX shifting.
Alan Cox <alan@lxorguk.ukuu.org.uk>
Removed calls to init_etherdev since they are no longer needed, and
cleaned up modularization just a bit. The driver still allows only
the default address for cards when loaded as a module, but that's
really less braindead than anyone using a 3c501 board. :)
19950208 (invid@msen.com)
Added traps for interrupts hitting the window as we clear and TX load
the board. Now getting 150K/second FTP with a 3c501 card. Still playing
with a TX-TX optimisation to see if we can touch 180-200K/second as seems
theoretically maximum.
19950402 Alan Cox <alan@lxorguk.ukuu.org.uk>
Cleaned up for 2.3.x because we broke SMP now.
20000208 Alan Cox <alan@lxorguk.ukuu.org.uk>
Check up pass for 2.5. Nothing significant changed
20021009 Alan Cox <alan@lxorguk.ukuu.org.uk>
Fixed zero fill corner case
20030104 Alan Cox <alan@lxorguk.ukuu.org.uk>
For the avoidance of doubt the "preferred form" of this code is one which
is in an open non patent encumbered format. Where cryptographic key signing
forms part of the process of creating an executable the information
including keys needed to generate an equivalently functional executable
are deemed to be part of the source code.
*/
/**
* DOC: 3c501 Card Notes
*
* Some notes on this thing if you have to hack it. [Alan]
*
* Some documentation is available from 3Com. Due to the boards age
* standard responses when you ask for this will range from 'be serious'
* to 'give it to a museum'. The documentation is incomplete and mostly
* of historical interest anyway.
*
* The basic system is a single buffer which can be used to receive or
* transmit a packet. A third command mode exists when you are setting
* things up.
*
* If it's transmitting it's not receiving and vice versa. In fact the
* time to get the board back into useful state after an operation is
* quite large.
*
* The driver works by keeping the board in receive mode waiting for a
* packet to arrive. When one arrives it is copied out of the buffer
* and delivered to the kernel. The card is reloaded and off we go.
*
* When transmitting lp->txing is set and the card is reset (from
* receive mode) [possibly losing a packet just received] to command
* mode. A packet is loaded and transmit mode triggered. The interrupt
* handler runs different code for transmit interrupts and can handle
* returning to receive mode or retransmissions (yes you have to help
* out with those too).
*
* DOC: Problems
*
* There are a wide variety of undocumented error returns from the card
* and you basically have to kick the board and pray if they turn up. Most
* only occur under extreme load or if you do something the board doesn't
* like (eg touching a register at the wrong time).
*
* The driver is less efficient than it could be. It switches through
* receive mode even if more transmits are queued. If this worries you buy
* a real Ethernet card.
*
* The combination of slow receive restart and no real multicast
* filter makes the board unusable with a kernel compiled for IP
* multicasting in a real multicast environment. That's down to the board,
* but even with no multicast programs running a multicast IP kernel is
* in group 224.0.0.1 and you will therefore be listening to all multicasts.
* One nv conference running over that Ethernet and you can give up.
*
*/
#define DRV_NAME "3c501"
#define DRV_VERSION "2002/10/09"
static const char version[] =
DRV_NAME ".c: " DRV_VERSION " Alan Cox (alan@lxorguk.ukuu.org.uk).\n";
/*
* Braindamage remaining:
* The 3c501 board.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fcntl.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/delay.h>
#include <linux/bitops.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include "3c501.h"
/*
* The boilerplate probe code.
*/
static int io = 0x280;
static int irq = 5;
static int mem_start;
/**
* el1_probe: - probe for a 3c501
* @dev: The device structure passed in to probe.
*
* This can be called from two places. The network layer will probe using
* a device structure passed in with the probe information completed. For a
* modular driver we use #init_module to fill in our own structure and probe
* for it.
*
* Returns 0 on success. ENXIO if asked not to probe and ENODEV if asked to
* probe and failing to find anything.
*/
struct net_device * __init el1_probe(int unit)
{
struct net_device *dev = alloc_etherdev(sizeof(struct net_local));
static const unsigned ports[] = { 0x280, 0x300, 0};
const unsigned *port;
int err = 0;
if (!dev)
return ERR_PTR(-ENOMEM);
if (unit >= 0) {
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
io = dev->base_addr;
irq = dev->irq;
mem_start = dev->mem_start & 7;
}
if (io > 0x1ff) { /* Check a single specified location. */
err = el1_probe1(dev, io);
} else if (io != 0) {
err = -ENXIO; /* Don't probe at all. */
} else {
for (port = ports; *port && el1_probe1(dev, *port); port++)
;
if (!*port)
err = -ENODEV;
}
if (err)
goto out;
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
release_region(dev->base_addr, EL1_IO_EXTENT);
out:
free_netdev(dev);
return ERR_PTR(err);
}
static const struct net_device_ops el_netdev_ops = {
.ndo_open = el_open,
.ndo_stop = el1_close,
.ndo_start_xmit = el_start_xmit,
.ndo_tx_timeout = el_timeout,
.ndo_set_rx_mode = set_multicast_list,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/**
* el1_probe1:
* @dev: The device structure to use
* @ioaddr: An I/O address to probe at.
*
* The actual probe. This is iterated over by #el1_probe in order to
* check all the applicable device locations.
*
* Returns 0 for a success, in which case the device is activated,
* EAGAIN if the IRQ is in use by another driver, and ENODEV if the
* board cannot be found.
*/
static int __init el1_probe1(struct net_device *dev, int ioaddr)
{
struct net_local *lp;
const char *mname; /* Vendor name */
unsigned char station_addr[6];
int autoirq = 0;
int i;
/*
* Reserve I/O resource for exclusive use by this driver
*/
if (!request_region(ioaddr, EL1_IO_EXTENT, DRV_NAME))
return -ENODEV;
/*
* Read the station address PROM data from the special port.
*/
for (i = 0; i < 6; i++) {
outw(i, ioaddr + EL1_DATAPTR);
station_addr[i] = inb(ioaddr + EL1_SAPROM);
}
/*
* Check the first three octets of the S.A. for 3Com's prefix, or
* for the Sager NP943 prefix.
*/
if (station_addr[0] == 0x02 && station_addr[1] == 0x60 &&
station_addr[2] == 0x8c)
mname = "3c501";
else if (station_addr[0] == 0x00 && station_addr[1] == 0x80 &&
station_addr[2] == 0xC8)
mname = "NP943";
else {
release_region(ioaddr, EL1_IO_EXTENT);
return -ENODEV;
}
/*
* We auto-IRQ by shutting off the interrupt line and letting it
* float high.
*/
dev->irq = irq;
if (dev->irq < 2) {
unsigned long irq_mask;
irq_mask = probe_irq_on();
inb(RX_STATUS); /* Clear pending interrupts. */
inb(TX_STATUS);
outb(AX_LOOP + 1, AX_CMD);
outb(0x00, AX_CMD);
mdelay(20);
autoirq = probe_irq_off(irq_mask);
if (autoirq == 0) {
pr_warning("%s probe at %#x failed to detect IRQ line.\n",
mname, ioaddr);
release_region(ioaddr, EL1_IO_EXTENT);
return -EAGAIN;
}
}
outb(AX_RESET+AX_LOOP, AX_CMD); /* Loopback mode. */
dev->base_addr = ioaddr;
memcpy(dev->dev_addr, station_addr, ETH_ALEN);
if (mem_start & 0xf)
el_debug = mem_start & 0x7;
if (autoirq)
dev->irq = autoirq;
pr_info("%s: %s EtherLink at %#lx, using %sIRQ %d.\n",
dev->name, mname, dev->base_addr,
autoirq ? "auto":"assigned ", dev->irq);
#ifdef CONFIG_IP_MULTICAST
pr_warning("WARNING: Use of the 3c501 in a multicast kernel is NOT recommended.\n");
#endif
if (el_debug)
pr_debug("%s", version);
lp = netdev_priv(dev);
memset(lp, 0, sizeof(struct net_local));
spin_lock_init(&lp->lock);
/*
* The EL1-specific entries in the device structure.
*/
dev->netdev_ops = &el_netdev_ops;
dev->watchdog_timeo = HZ;
dev->ethtool_ops = &netdev_ethtool_ops;
return 0;
}
/**
* el1_open:
* @dev: device that is being opened
*
* When an ifconfig is issued which changes the device flags to include
* IFF_UP this function is called. It is only called when the change
* occurs, not when the interface remains up. #el1_close will be called
* when it goes down.
*
* Returns 0 for a successful open, or -EAGAIN if someone has run off
* with our interrupt line.
*/
static int el_open(struct net_device *dev)
{
int retval;
int ioaddr = dev->base_addr;
struct net_local *lp = netdev_priv(dev);
unsigned long flags;
if (el_debug > 2)
pr_debug("%s: Doing el_open()...\n", dev->name);
retval = request_irq(dev->irq, el_interrupt, 0, dev->name, dev);
if (retval)
return retval;
spin_lock_irqsave(&lp->lock, flags);
el_reset(dev);
spin_unlock_irqrestore(&lp->lock, flags);
lp->txing = 0; /* Board in RX mode */
outb(AX_RX, AX_CMD); /* Aux control, irq and receive enabled */
netif_start_queue(dev);
return 0;
}
/**
* el_timeout:
* @dev: The 3c501 card that has timed out
*
* Attempt to restart the board. This is basically a mixture of extreme
* violence and prayer
*
*/
static void el_timeout(struct net_device *dev)
{
struct net_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
if (el_debug)
pr_debug("%s: transmit timed out, txsr %#2x axsr=%02x rxsr=%02x.\n",
dev->name, inb(TX_STATUS),
inb(AX_STATUS), inb(RX_STATUS));
dev->stats.tx_errors++;
outb(TX_NORM, TX_CMD);
outb(RX_NORM, RX_CMD);
outb(AX_OFF, AX_CMD); /* Just trigger a false interrupt. */
outb(AX_RX, AX_CMD); /* Aux control, irq and receive enabled */
lp->txing = 0; /* Ripped back in to RX */
netif_wake_queue(dev);
}
/**
* el_start_xmit:
* @skb: The packet that is queued to be sent
* @dev: The 3c501 card we want to throw it down
*
* Attempt to send a packet to a 3c501 card. There are some interesting
* catches here because the 3c501 is an extremely old and therefore
* stupid piece of technology.
*
* If we are handling an interrupt on the other CPU we cannot load a packet
* as we may still be attempting to retrieve the last RX packet buffer.
*
* When a transmit times out we dump the card into control mode and just
* start again. It happens enough that it isn't worth logging.
*
* We avoid holding the spin locks when doing the packet load to the board.
* The device is very slow, and its DMA mode is even slower. If we held the
* lock while loading 1500 bytes onto the controller we would drop a lot of
* serial port characters. This requires we do extra locking, but we have
* no real choice.
*/
static netdev_tx_t el_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
unsigned long flags;
/*
* Avoid incoming interrupts between us flipping txing and flipping
* mode as the driver assumes txing is a faithful indicator of card
* state
*/
spin_lock_irqsave(&lp->lock, flags);
/*
* Avoid timer-based retransmission conflicts.
*/
netif_stop_queue(dev);
do {
int len = skb->len;
int pad = 0;
int gp_start;
unsigned char *buf = skb->data;
if (len < ETH_ZLEN)
pad = ETH_ZLEN - len;
gp_start = 0x800 - (len + pad);
lp->tx_pkt_start = gp_start;
lp->collisions = 0;
dev->stats.tx_bytes += skb->len;
/*
* Command mode with status cleared should [in theory]
* mean no more interrupts can be pending on the card.
*/
outb_p(AX_SYS, AX_CMD);
inb_p(RX_STATUS);
inb_p(TX_STATUS);
lp->loading = 1;
lp->txing = 1;
/*
* Turn interrupts back on while we spend a pleasant
* afternoon loading bytes into the board
*/
spin_unlock_irqrestore(&lp->lock, flags);
/* Set rx packet area to 0. */
outw(0x00, RX_BUF_CLR);
/* aim - packet will be loaded into buffer start */
outw(gp_start, GP_LOW);
/* load buffer (usual thing each byte increments the pointer) */
outsb(DATAPORT, buf, len);
if (pad) {
while (pad--) /* Zero fill buffer tail */
outb(0, DATAPORT);
}
/* the board reuses the same register */
outw(gp_start, GP_LOW);
if (lp->loading != 2) {
/* fire ... Trigger xmit. */
outb(AX_XMIT, AX_CMD);
lp->loading = 0;
if (el_debug > 2)
pr_debug(" queued xmit.\n");
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* A receive upset our load, despite our best efforts */
if (el_debug > 2)
pr_debug("%s: burped during tx load.\n", dev->name);
spin_lock_irqsave(&lp->lock, flags);
} while (1);
}
/**
* el_interrupt:
* @irq: Interrupt number
* @dev_id: The 3c501 that burped
*
* Handle the ether interface interrupts. The 3c501 needs a lot more
* hand holding than most cards. In particular we get a transmit interrupt
* with a collision error because the board firmware isn't capable of rewinding
* its own transmit buffer pointers. It can however count to 16 for us.
*
* On the receive side the card is also very dumb. It has no buffering to
* speak of. We simply pull the packet out of its PIO buffer (which is slow)
* and queue it for the kernel. Then we reset the card for the next packet.
*
* We sometimes get surprise interrupts late both because the SMP IRQ delivery
* is message passing and because the card sometimes seems to deliver late. I
* think if it is part way through a receive and the mode is changed it carries
* on receiving and sends us an interrupt. We have to band aid all these cases
* to get a sensible 150kBytes/second performance. Even then you want a small
* TCP window.
*/
static irqreturn_t el_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct net_local *lp;
int ioaddr;
int axsr; /* Aux. status reg. */
ioaddr = dev->base_addr;
lp = netdev_priv(dev);
spin_lock(&lp->lock);
/*
* What happened ?
*/
axsr = inb(AX_STATUS);
/*
* Log it
*/
if (el_debug > 3)
pr_debug("%s: el_interrupt() aux=%#02x\n", dev->name, axsr);
if (lp->loading == 1 && !lp->txing)
pr_warning("%s: Inconsistent state loading while not in tx\n",
dev->name);
if (lp->txing) {
/*
* Board in transmit mode. May be loading. If we are
* loading we shouldn't have got this.
*/
int txsr = inb(TX_STATUS);
if (lp->loading == 1) {
if (el_debug > 2)
pr_debug("%s: Interrupt while loading [txsr=%02x gp=%04x rp=%04x]\n",
dev->name, txsr, inw(GP_LOW), inw(RX_LOW));
/* Force a reload */
lp->loading = 2;
spin_unlock(&lp->lock);
goto out;
}
if (el_debug > 6)
pr_debug("%s: txsr=%02x gp=%04x rp=%04x\n", dev->name,
txsr, inw(GP_LOW), inw(RX_LOW));
if ((axsr & 0x80) && (txsr & TX_READY) == 0) {
/*
* FIXME: is there a logic to whether to keep
* on trying or reset immediately ?
*/
if (el_debug > 1)
pr_debug("%s: Unusual interrupt during Tx, txsr=%02x axsr=%02x gp=%03x rp=%03x.\n",
dev->name, txsr, axsr,
inw(ioaddr + EL1_DATAPTR),
inw(ioaddr + EL1_RXPTR));
lp->txing = 0;
netif_wake_queue(dev);
} else if (txsr & TX_16COLLISIONS) {
/*
* Timed out
*/
if (el_debug)
pr_debug("%s: Transmit failed 16 times, Ethernet jammed?\n", dev->name);
outb(AX_SYS, AX_CMD);
lp->txing = 0;
dev->stats.tx_aborted_errors++;
netif_wake_queue(dev);
} else if (txsr & TX_COLLISION) {
/*
* Retrigger xmit.
*/
if (el_debug > 6)
pr_debug("%s: retransmitting after a collision.\n", dev->name);
/*
* Poor little chip can't reset its own start
* pointer
*/
outb(AX_SYS, AX_CMD);
outw(lp->tx_pkt_start, GP_LOW);
outb(AX_XMIT, AX_CMD);
dev->stats.collisions++;
spin_unlock(&lp->lock);
goto out;
} else {
/*
* It worked.. we will now fall through and receive
*/
dev->stats.tx_packets++;
if (el_debug > 6)
pr_debug("%s: Tx succeeded %s\n", dev->name,
(txsr & TX_RDY) ? "." : "but tx is busy!");
/*
* This is safe the interrupt is atomic WRT itself.
*/
lp->txing = 0;
/* In case more to transmit */
netif_wake_queue(dev);
}
} else {
/*
* In receive mode.
*/
int rxsr = inb(RX_STATUS);
if (el_debug > 5)
pr_debug("%s: rxsr=%02x txsr=%02x rp=%04x\n",
dev->name, rxsr, inb(TX_STATUS), inw(RX_LOW));
/*
* Just reading rx_status fixes most errors.
*/
if (rxsr & RX_MISSED)
dev->stats.rx_missed_errors++;
else if (rxsr & RX_RUNT) {
/* Handled to avoid board lock-up. */
dev->stats.rx_length_errors++;
if (el_debug > 5)
pr_debug("%s: runt.\n", dev->name);
} else if (rxsr & RX_GOOD) {
/*
* Receive worked.
*/
el_receive(dev);
} else {
/*
* Nothing? Something is broken!
*/
if (el_debug > 2)
pr_debug("%s: No packet seen, rxsr=%02x **resetting 3c501***\n",
dev->name, rxsr);
el_reset(dev);
}
}
/*
* Move into receive mode
*/
outb(AX_RX, AX_CMD);
outw(0x00, RX_BUF_CLR);
inb(RX_STATUS); /* Be certain that interrupts are cleared. */
inb(TX_STATUS);
spin_unlock(&lp->lock);
out:
return IRQ_HANDLED;
}
/**
* el_receive:
* @dev: Device to pull the packets from
*
* We have a good packet. Well, not really "good", just mostly not broken.
* We must check everything to see if it is good. In particular we occasionally
* get wild packet sizes from the card. If the packet seems sane we PIO it
* off the card and queue it for the protocol layers.
*/
static void el_receive(struct net_device *dev)
{
int ioaddr = dev->base_addr;
int pkt_len;
struct sk_buff *skb;
pkt_len = inw(RX_LOW);
if (el_debug > 4)
pr_debug(" el_receive %d.\n", pkt_len);
if (pkt_len < 60 || pkt_len > 1536) {
if (el_debug)
pr_debug("%s: bogus packet, length=%d\n",
dev->name, pkt_len);
dev->stats.rx_over_errors++;
return;
}
/*
* Command mode so we can empty the buffer
*/
outb(AX_SYS, AX_CMD);
skb = netdev_alloc_skb(dev, pkt_len + 2);
/*
* Start of frame
*/
outw(0x00, GP_LOW);
if (skb == NULL) {
pr_info("%s: Memory squeeze, dropping packet.\n", dev->name);
dev->stats.rx_dropped++;
return;
} else {
skb_reserve(skb, 2); /* Force 16 byte alignment */
/*
* The read increments through the bytes. The interrupt
* handler will fix the pointer when it returns to
* receive mode.
*/
insb(DATAPORT, skb_put(skb, pkt_len), pkt_len);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
}
/**
* el_reset: Reset a 3c501 card
* @dev: The 3c501 card about to get zapped
*
* Even resetting a 3c501 isn't simple. When you activate reset it loses all
* its configuration. You must hold the lock when doing this. The function
* cannot take the lock itself as it is callable from the irq handler.
*/
static void el_reset(struct net_device *dev)
{
struct net_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
if (el_debug > 2)
pr_info("3c501 reset...\n");
outb(AX_RESET, AX_CMD); /* Reset the chip */
/* Aux control, irq and loopback enabled */
outb(AX_LOOP, AX_CMD);
{
int i;
for (i = 0; i < 6; i++) /* Set the station address. */
outb(dev->dev_addr[i], ioaddr + i);
}
outw(0, RX_BUF_CLR); /* Set rx packet area to 0. */
outb(TX_NORM, TX_CMD); /* tx irq on done, collision */
outb(RX_NORM, RX_CMD); /* Set Rx commands. */
inb(RX_STATUS); /* Clear status. */
inb(TX_STATUS);
lp->txing = 0;
}
/**
* el1_close:
* @dev: 3c501 card to shut down
*
* Close a 3c501 card. The IFF_UP flag has been cleared by the user via
* the SIOCSIFFLAGS ioctl. We stop any further transmissions being queued,
* and then disable the interrupts. Finally we reset the chip. The effects
* of the rest will be cleaned up by #el1_open. Always returns 0 indicating
* a success.
*/
static int el1_close(struct net_device *dev)
{
int ioaddr = dev->base_addr;
if (el_debug > 2)
pr_info("%s: Shutting down Ethernet card at %#x.\n",
dev->name, ioaddr);
netif_stop_queue(dev);
/*
* Free and disable the IRQ.
*/
free_irq(dev->irq, dev);
outb(AX_RESET, AX_CMD); /* Reset the chip */
return 0;
}
/**
* set_multicast_list:
* @dev: The device to adjust
*
* Set or clear the multicast filter for this adaptor to use the best-effort
* filtering supported. The 3c501 supports only three modes of filtering.
* It always receives broadcasts and packets for itself. You can choose to
* optionally receive all packets, or all multicast packets on top of this.
*/
static void set_multicast_list(struct net_device *dev)
{
int ioaddr = dev->base_addr;
if (dev->flags & IFF_PROMISC) {
outb(RX_PROM, RX_CMD);
inb(RX_STATUS);
} else if (!netdev_mc_empty(dev) || dev->flags & IFF_ALLMULTI) {
/* Multicast or all multicast is the same */
outb(RX_MULT, RX_CMD);
inb(RX_STATUS); /* Clear status. */
} else {
outb(RX_NORM, RX_CMD);
inb(RX_STATUS);
}
}
static void netdev_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
sprintf(info->bus_info, "ISA 0x%lx", dev->base_addr);
}
static u32 netdev_get_msglevel(struct net_device *dev)
{
return debug;
}
static void netdev_set_msglevel(struct net_device *dev, u32 level)
{
debug = level;
}
static const struct ethtool_ops netdev_ethtool_ops = {
.get_drvinfo = netdev_get_drvinfo,
.get_msglevel = netdev_get_msglevel,
.set_msglevel = netdev_set_msglevel,
};
#ifdef MODULE
static struct net_device *dev_3c501;
module_param(io, int, 0);
module_param(irq, int, 0);
MODULE_PARM_DESC(io, "EtherLink I/O base address");
MODULE_PARM_DESC(irq, "EtherLink IRQ number");
/**
* init_module:
*
* When the driver is loaded as a module this function is called. We fake up
* a device structure with the base I/O and interrupt set as if it were being
* called from Space.c. This minimises the extra code that would otherwise
* be required.
*
* Returns 0 for success or -EIO if a card is not found. Returning an error
* here also causes the module to be unloaded
*/
int __init init_module(void)
{
dev_3c501 = el1_probe(-1);
if (IS_ERR(dev_3c501))
return PTR_ERR(dev_3c501);
return 0;
}
/**
* cleanup_module:
*
* The module is being unloaded. We unhook our network device from the system
* and then free up the resources we took when the card was found.
*/
void __exit cleanup_module(void)
{
struct net_device *dev = dev_3c501;
unregister_netdev(dev);
release_region(dev->base_addr, EL1_IO_EXTENT);
free_netdev(dev);
}
#endif /* MODULE */
MODULE_AUTHOR("Donald Becker, Alan Cox");
MODULE_DESCRIPTION("Support for the ancient 3Com 3c501 ethernet card");
MODULE_LICENSE("GPL");
| gpl-2.0 |
SystemTera/SystemTera.Server-V-3.14-Kernel | drivers/net/wan/n2.c | 9464 | 13512 | /*
* SDL Inc. RISCom/N2 synchronous serial card driver for Linux
*
* Copyright (C) 1998-2003 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/>
*
* Note: integrated CSU/DSU/DDS are not supported by this driver
*
* Sources of information:
* Hitachi HD64570 SCA User's Manual
* SDL Inc. PPP/HDLC/CISCO driver
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#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 <asm/io.h>
#include "hd64570.h"
static const char* version = "SDL RISCom/N2 driver version: 1.15";
static const char* devname = "RISCom/N2";
#undef DEBUG_PKT
#define DEBUG_RINGS
#define USE_WINDOWSIZE 16384
#define USE_BUS16BITS 1
#define CLOCK_BASE 9830400 /* 9.8304 MHz */
#define MAX_PAGES 16 /* 16 RAM pages at max */
#define MAX_RAM_SIZE 0x80000 /* 512 KB */
#if MAX_RAM_SIZE > MAX_PAGES * USE_WINDOWSIZE
#undef MAX_RAM_SIZE
#define MAX_RAM_SIZE (MAX_PAGES * USE_WINDOWSIZE)
#endif
#define N2_IOPORTS 0x10
#define NEED_DETECT_RAM
#define NEED_SCA_MSCI_INTR
#define MAX_TX_BUFFERS 10
static char *hw; /* pointer to hw=xxx command line string */
/* RISCom/N2 Board Registers */
/* PC Control Register */
#define N2_PCR 0
#define PCR_RUNSCA 1 /* Run 64570 */
#define PCR_VPM 2 /* Enable VPM - needed if using RAM above 1 MB */
#define PCR_ENWIN 4 /* Open window */
#define PCR_BUS16 8 /* 16-bit bus */
/* Memory Base Address Register */
#define N2_BAR 2
/* Page Scan Register */
#define N2_PSR 4
#define WIN16K 0x00
#define WIN32K 0x20
#define WIN64K 0x40
#define PSR_WINBITS 0x60
#define PSR_DMAEN 0x80
#define PSR_PAGEBITS 0x0F
/* Modem Control Reg */
#define N2_MCR 6
#define CLOCK_OUT_PORT1 0x80
#define CLOCK_OUT_PORT0 0x40
#define TX422_PORT1 0x20
#define TX422_PORT0 0x10
#define DSR_PORT1 0x08
#define DSR_PORT0 0x04
#define DTR_PORT1 0x02
#define DTR_PORT0 0x01
typedef struct port_s {
struct net_device *dev;
struct card_s *card;
spinlock_t lock; /* TX lock */
sync_serial_settings settings;
int valid; /* port enabled */
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 phy_node; /* physical port # - 0 or 1 */
u8 log_node; /* logical port # */
}port_t;
typedef struct card_s {
u8 __iomem *winbase; /* ISA window base address */
u32 phy_winbase; /* ISA physical base address */
u32 ram_size; /* number of bytes */
u16 io; /* IO Base address */
u16 buff_offset; /* offset of first buffer of first channel */
u16 rx_ring_buffers; /* number of buffers in a ring */
u16 tx_ring_buffers;
u8 irq; /* IRQ (3-15) */
port_t ports[2];
struct card_s *next_card;
}card_t;
static card_t *first_card;
static card_t **new_card = &first_card;
#define sca_reg(reg, card) (0x8000 | (card)->io | \
((reg) & 0x0F) | (((reg) & 0xF0) << 6))
#define sca_in(reg, card) inb(sca_reg(reg, card))
#define sca_out(value, reg, card) outb(value, sca_reg(reg, card))
#define sca_inw(reg, card) inw(sca_reg(reg, card))
#define sca_outw(value, reg, card) outw(value, sca_reg(reg, card))
#define port_to_card(port) ((port)->card)
#define log_node(port) ((port)->log_node)
#define phy_node(port) ((port)->phy_node)
#define winsize(card) (USE_WINDOWSIZE)
#define winbase(card) ((card)->winbase)
#define get_port(card, port) ((card)->ports[port].valid ? \
&(card)->ports[port] : NULL)
static __inline__ u8 sca_get_page(card_t *card)
{
return inb(card->io + N2_PSR) & PSR_PAGEBITS;
}
static __inline__ void openwin(card_t *card, u8 page)
{
u8 psr = inb(card->io + N2_PSR);
outb((psr & ~PSR_PAGEBITS) | page, card->io + N2_PSR);
}
#include "hd64570.c"
static void n2_set_iface(port_t *port)
{
card_t *card = port->card;
int io = card->io;
u8 mcr = inb(io + N2_MCR);
u8 msci = get_msci(port);
u8 rxs = port->rxs & CLK_BRG_MASK;
u8 txs = port->txs & CLK_BRG_MASK;
switch(port->settings.clock_type) {
case CLOCK_INT:
mcr |= port->phy_node ? CLOCK_OUT_PORT1 : CLOCK_OUT_PORT0;
rxs |= CLK_BRG_RX; /* BRG output */
txs |= CLK_RXCLK_TX; /* RX clock */
break;
case CLOCK_TXINT:
mcr |= port->phy_node ? CLOCK_OUT_PORT1 : CLOCK_OUT_PORT0;
rxs |= CLK_LINE_RX; /* RXC input */
txs |= CLK_BRG_TX; /* BRG output */
break;
case CLOCK_TXFROMRX:
mcr |= port->phy_node ? CLOCK_OUT_PORT1 : CLOCK_OUT_PORT0;
rxs |= CLK_LINE_RX; /* RXC input */
txs |= CLK_RXCLK_TX; /* RX clock */
break;
default: /* Clock EXTernal */
mcr &= port->phy_node ? ~CLOCK_OUT_PORT1 : ~CLOCK_OUT_PORT0;
rxs |= CLK_LINE_RX; /* RXC input */
txs |= CLK_LINE_TX; /* TXC input */
}
outb(mcr, io + N2_MCR);
port->rxs = rxs;
port->txs = txs;
sca_out(rxs, msci + RXS, card);
sca_out(txs, msci + TXS, card);
sca_set_port(port);
}
static int n2_open(struct net_device *dev)
{
port_t *port = dev_to_port(dev);
int io = port->card->io;
u8 mcr = inb(io + N2_MCR) | (port->phy_node ? TX422_PORT1:TX422_PORT0);
int result;
result = hdlc_open(dev);
if (result)
return result;
mcr &= port->phy_node ? ~DTR_PORT1 : ~DTR_PORT0; /* set DTR ON */
outb(mcr, io + N2_MCR);
outb(inb(io + N2_PCR) | PCR_ENWIN, io + N2_PCR); /* open window */
outb(inb(io + N2_PSR) | PSR_DMAEN, io + N2_PSR); /* enable dma */
sca_open(dev);
n2_set_iface(port);
return 0;
}
static int n2_close(struct net_device *dev)
{
port_t *port = dev_to_port(dev);
int io = port->card->io;
u8 mcr = inb(io+N2_MCR) | (port->phy_node ? TX422_PORT1 : TX422_PORT0);
sca_close(dev);
mcr |= port->phy_node ? DTR_PORT1 : DTR_PORT0; /* set DTR OFF */
outb(mcr, io + N2_MCR);
hdlc_close(dev);
return 0;
}
static int n2_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_SYNC_SERIAL;
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_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 */
n2_set_iface(port);
return 0;
default:
return hdlc_ioctl(dev, ifr, cmd);
}
}
static void n2_destroy_card(card_t *card)
{
int cnt;
for (cnt = 0; cnt < 2; cnt++)
if (card->ports[cnt].card) {
struct net_device *dev = port_to_dev(&card->ports[cnt]);
unregister_hdlc_device(dev);
}
if (card->irq)
free_irq(card->irq, card);
if (card->winbase) {
iounmap(card->winbase);
release_mem_region(card->phy_winbase, USE_WINDOWSIZE);
}
if (card->io)
release_region(card->io, N2_IOPORTS);
if (card->ports[0].dev)
free_netdev(card->ports[0].dev);
if (card->ports[1].dev)
free_netdev(card->ports[1].dev);
kfree(card);
}
static const struct net_device_ops n2_ops = {
.ndo_open = n2_open,
.ndo_stop = n2_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = hdlc_start_xmit,
.ndo_do_ioctl = n2_ioctl,
};
static int __init n2_run(unsigned long io, unsigned long irq,
unsigned long winbase, long valid0, long valid1)
{
card_t *card;
u8 cnt, pcr;
int i;
if (io < 0x200 || io > 0x3FF || (io % N2_IOPORTS) != 0) {
pr_err("invalid I/O port value\n");
return -ENODEV;
}
if (irq < 3 || irq > 15 || irq == 6) /* FIXME */ {
pr_err("invalid IRQ value\n");
return -ENODEV;
}
if (winbase < 0xA0000 || winbase > 0xFFFFF || (winbase & 0xFFF) != 0) {
pr_err("invalid RAM value\n");
return -ENODEV;
}
card = kzalloc(sizeof(card_t), GFP_KERNEL);
if (card == NULL)
return -ENOBUFS;
card->ports[0].dev = alloc_hdlcdev(&card->ports[0]);
card->ports[1].dev = alloc_hdlcdev(&card->ports[1]);
if (!card->ports[0].dev || !card->ports[1].dev) {
pr_err("unable to allocate memory\n");
n2_destroy_card(card);
return -ENOMEM;
}
if (!request_region(io, N2_IOPORTS, devname)) {
pr_err("I/O port region in use\n");
n2_destroy_card(card);
return -EBUSY;
}
card->io = io;
if (request_irq(irq, sca_intr, 0, devname, card)) {
pr_err("could not allocate IRQ\n");
n2_destroy_card(card);
return -EBUSY;
}
card->irq = irq;
if (!request_mem_region(winbase, USE_WINDOWSIZE, devname)) {
pr_err("could not request RAM window\n");
n2_destroy_card(card);
return -EBUSY;
}
card->phy_winbase = winbase;
card->winbase = ioremap(winbase, USE_WINDOWSIZE);
if (!card->winbase) {
pr_err("ioremap() failed\n");
n2_destroy_card(card);
return -EFAULT;
}
outb(0, io + N2_PCR);
outb(winbase >> 12, io + N2_BAR);
switch (USE_WINDOWSIZE) {
case 16384:
outb(WIN16K, io + N2_PSR);
break;
case 32768:
outb(WIN32K, io + N2_PSR);
break;
case 65536:
outb(WIN64K, io + N2_PSR);
break;
default:
pr_err("invalid window size\n");
n2_destroy_card(card);
return -ENODEV;
}
pcr = PCR_ENWIN | PCR_VPM | (USE_BUS16BITS ? PCR_BUS16 : 0);
outb(pcr, io + N2_PCR);
card->ram_size = sca_detect_ram(card, card->winbase, MAX_RAM_SIZE);
/* number of TX + RX buffers for one port */
i = card->ram_size / ((valid0 + valid1) * (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 = (valid0 + valid1) * sizeof(pkt_desc) *
(card->tx_ring_buffers + card->rx_ring_buffers);
pr_info("RISCom/N2 %u KB RAM, IRQ%u, using %u TX + %u RX packets rings\n",
card->ram_size / 1024, card->irq,
card->tx_ring_buffers, card->rx_ring_buffers);
if (card->tx_ring_buffers < 1) {
pr_err("RAM test failed\n");
n2_destroy_card(card);
return -EIO;
}
pcr |= PCR_RUNSCA; /* run SCA */
outb(pcr, io + N2_PCR);
outb(0, io + N2_MCR);
sca_init(card, 0);
for (cnt = 0; cnt < 2; cnt++) {
port_t *port = &card->ports[cnt];
struct net_device *dev = port_to_dev(port);
hdlc_device *hdlc = dev_to_hdlc(dev);
if ((cnt == 0 && !valid0) || (cnt == 1 && !valid1))
continue;
port->phy_node = cnt;
port->valid = 1;
if ((cnt == 1) && valid0)
port->log_node = 1;
spin_lock_init(&port->lock);
dev->irq = irq;
dev->mem_start = winbase;
dev->mem_end = winbase + USE_WINDOWSIZE - 1;
dev->tx_queue_len = 50;
dev->netdev_ops = &n2_ops;
hdlc->attach = sca_attach;
hdlc->xmit = sca_xmit;
port->settings.clock_type = CLOCK_EXT;
port->card = card;
if (register_hdlc_device(dev)) {
pr_warn("unable to register hdlc device\n");
port->card = NULL;
n2_destroy_card(card);
return -ENOBUFS;
}
sca_init_port(port); /* Set up SCA memory */
netdev_info(dev, "RISCom/N2 node %d\n", port->phy_node);
}
*new_card = card;
new_card = &card->next_card;
return 0;
}
static int __init n2_init(void)
{
if (hw==NULL) {
#ifdef MODULE
pr_info("no card initialized\n");
#endif
return -EINVAL; /* no parameters specified, abort */
}
pr_info("%s\n", version);
do {
unsigned long io, irq, ram;
long valid[2] = { 0, 0 }; /* Default = both ports disabled */
io = simple_strtoul(hw, &hw, 0);
if (*hw++ != ',')
break;
irq = simple_strtoul(hw, &hw, 0);
if (*hw++ != ',')
break;
ram = simple_strtoul(hw, &hw, 0);
if (*hw++ != ',')
break;
while(1) {
if (*hw == '0' && !valid[0])
valid[0] = 1; /* Port 0 enabled */
else if (*hw == '1' && !valid[1])
valid[1] = 1; /* Port 1 enabled */
else
break;
hw++;
}
if (!valid[0] && !valid[1])
break; /* at least one port must be used */
if (*hw == ':' || *hw == '\x0')
n2_run(io, irq, ram, valid[0], valid[1]);
if (*hw == '\x0')
return first_card ? 0 : -EINVAL;
}while(*hw++ == ':');
pr_err("invalid hardware parameters\n");
return first_card ? 0 : -EINVAL;
}
static void __exit n2_cleanup(void)
{
card_t *card = first_card;
while (card) {
card_t *ptr = card;
card = card->next_card;
n2_destroy_card(ptr);
}
}
module_init(n2_init);
module_exit(n2_cleanup);
MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>");
MODULE_DESCRIPTION("RISCom/N2 serial port driver");
MODULE_LICENSE("GPL v2");
module_param(hw, charp, 0444);
MODULE_PARM_DESC(hw, "io,irq,ram,ports:io,irq,...");
| gpl-2.0 |
sunrunning/ok6410_linux | drivers/misc/sgi-xp/xpc_partition.c | 13304 | 14014 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (c) 2004-2008 Silicon Graphics, Inc. All Rights Reserved.
*/
/*
* Cross Partition Communication (XPC) partition support.
*
* This is the part of XPC that detects the presence/absence of
* other partitions. It provides a heartbeat and monitors the
* heartbeats of other partitions.
*
*/
#include <linux/device.h>
#include <linux/hardirq.h>
#include <linux/slab.h>
#include "xpc.h"
#include <asm/uv/uv_hub.h>
/* XPC is exiting flag */
int xpc_exiting;
/* this partition's reserved page pointers */
struct xpc_rsvd_page *xpc_rsvd_page;
static unsigned long *xpc_part_nasids;
unsigned long *xpc_mach_nasids;
static int xpc_nasid_mask_nbytes; /* #of bytes in nasid mask */
int xpc_nasid_mask_nlongs; /* #of longs in nasid mask */
struct xpc_partition *xpc_partitions;
/*
* Guarantee that the kmalloc'd memory is cacheline aligned.
*/
void *
xpc_kmalloc_cacheline_aligned(size_t size, gfp_t flags, void **base)
{
/* see if kmalloc will give us cachline aligned memory by default */
*base = kmalloc(size, flags);
if (*base == NULL)
return NULL;
if ((u64)*base == L1_CACHE_ALIGN((u64)*base))
return *base;
kfree(*base);
/* nope, we'll have to do it ourselves */
*base = kmalloc(size + L1_CACHE_BYTES, flags);
if (*base == NULL)
return NULL;
return (void *)L1_CACHE_ALIGN((u64)*base);
}
/*
* Given a nasid, get the physical address of the partition's reserved page
* for that nasid. This function returns 0 on any error.
*/
static unsigned long
xpc_get_rsvd_page_pa(int nasid)
{
enum xp_retval ret;
u64 cookie = 0;
unsigned long rp_pa = nasid; /* seed with nasid */
size_t len = 0;
size_t buf_len = 0;
void *buf = buf;
void *buf_base = NULL;
enum xp_retval (*get_partition_rsvd_page_pa)
(void *, u64 *, unsigned long *, size_t *) =
xpc_arch_ops.get_partition_rsvd_page_pa;
while (1) {
/* !!! rp_pa will need to be _gpa on UV.
* ??? So do we save it into the architecture specific parts
* ??? of the xpc_partition structure? Do we rename this
* ??? function or have two versions? Rename rp_pa for UV to
* ??? rp_gpa?
*/
ret = get_partition_rsvd_page_pa(buf, &cookie, &rp_pa, &len);
dev_dbg(xpc_part, "SAL returned with ret=%d, cookie=0x%016lx, "
"address=0x%016lx, len=0x%016lx\n", ret,
(unsigned long)cookie, rp_pa, len);
if (ret != xpNeedMoreInfo)
break;
/* !!! L1_CACHE_ALIGN() is only a sn2-bte_copy requirement */
if (is_shub())
len = L1_CACHE_ALIGN(len);
if (len > buf_len) {
if (buf_base != NULL)
kfree(buf_base);
buf_len = L1_CACHE_ALIGN(len);
buf = xpc_kmalloc_cacheline_aligned(buf_len, GFP_KERNEL,
&buf_base);
if (buf_base == NULL) {
dev_err(xpc_part, "unable to kmalloc "
"len=0x%016lx\n", buf_len);
ret = xpNoMemory;
break;
}
}
ret = xp_remote_memcpy(xp_pa(buf), rp_pa, len);
if (ret != xpSuccess) {
dev_dbg(xpc_part, "xp_remote_memcpy failed %d\n", ret);
break;
}
}
kfree(buf_base);
if (ret != xpSuccess)
rp_pa = 0;
dev_dbg(xpc_part, "reserved page at phys address 0x%016lx\n", rp_pa);
return rp_pa;
}
/*
* Fill the partition reserved page with the information needed by
* other partitions to discover we are alive and establish initial
* communications.
*/
int
xpc_setup_rsvd_page(void)
{
int ret;
struct xpc_rsvd_page *rp;
unsigned long rp_pa;
unsigned long new_ts_jiffies;
/* get the local reserved page's address */
preempt_disable();
rp_pa = xpc_get_rsvd_page_pa(xp_cpu_to_nasid(smp_processor_id()));
preempt_enable();
if (rp_pa == 0) {
dev_err(xpc_part, "SAL failed to locate the reserved page\n");
return -ESRCH;
}
rp = (struct xpc_rsvd_page *)__va(xp_socket_pa(rp_pa));
if (rp->SAL_version < 3) {
/* SAL_versions < 3 had a SAL_partid defined as a u8 */
rp->SAL_partid &= 0xff;
}
BUG_ON(rp->SAL_partid != xp_partition_id);
if (rp->SAL_partid < 0 || rp->SAL_partid >= xp_max_npartitions) {
dev_err(xpc_part, "the reserved page's partid of %d is outside "
"supported range (< 0 || >= %d)\n", rp->SAL_partid,
xp_max_npartitions);
return -EINVAL;
}
rp->version = XPC_RP_VERSION;
rp->max_npartitions = xp_max_npartitions;
/* establish the actual sizes of the nasid masks */
if (rp->SAL_version == 1) {
/* SAL_version 1 didn't set the nasids_size field */
rp->SAL_nasids_size = 128;
}
xpc_nasid_mask_nbytes = rp->SAL_nasids_size;
xpc_nasid_mask_nlongs = BITS_TO_LONGS(rp->SAL_nasids_size *
BITS_PER_BYTE);
/* setup the pointers to the various items in the reserved page */
xpc_part_nasids = XPC_RP_PART_NASIDS(rp);
xpc_mach_nasids = XPC_RP_MACH_NASIDS(rp);
ret = xpc_arch_ops.setup_rsvd_page(rp);
if (ret != 0)
return ret;
/*
* Set timestamp of when reserved page was setup by XPC.
* This signifies to the remote partition that our reserved
* page is initialized.
*/
new_ts_jiffies = jiffies;
if (new_ts_jiffies == 0 || new_ts_jiffies == rp->ts_jiffies)
new_ts_jiffies++;
rp->ts_jiffies = new_ts_jiffies;
xpc_rsvd_page = rp;
return 0;
}
void
xpc_teardown_rsvd_page(void)
{
/* a zero timestamp indicates our rsvd page is not initialized */
xpc_rsvd_page->ts_jiffies = 0;
}
/*
* Get a copy of a portion of the remote partition's rsvd page.
*
* remote_rp points to a buffer that is cacheline aligned for BTE copies and
* is large enough to contain a copy of their reserved page header and
* part_nasids mask.
*/
enum xp_retval
xpc_get_remote_rp(int nasid, unsigned long *discovered_nasids,
struct xpc_rsvd_page *remote_rp, unsigned long *remote_rp_pa)
{
int l;
enum xp_retval ret;
/* get the reserved page's physical address */
*remote_rp_pa = xpc_get_rsvd_page_pa(nasid);
if (*remote_rp_pa == 0)
return xpNoRsvdPageAddr;
/* pull over the reserved page header and part_nasids mask */
ret = xp_remote_memcpy(xp_pa(remote_rp), *remote_rp_pa,
XPC_RP_HEADER_SIZE + xpc_nasid_mask_nbytes);
if (ret != xpSuccess)
return ret;
if (discovered_nasids != NULL) {
unsigned long *remote_part_nasids =
XPC_RP_PART_NASIDS(remote_rp);
for (l = 0; l < xpc_nasid_mask_nlongs; l++)
discovered_nasids[l] |= remote_part_nasids[l];
}
/* zero timestamp indicates the reserved page has not been setup */
if (remote_rp->ts_jiffies == 0)
return xpRsvdPageNotSet;
if (XPC_VERSION_MAJOR(remote_rp->version) !=
XPC_VERSION_MAJOR(XPC_RP_VERSION)) {
return xpBadVersion;
}
/* check that both remote and local partids are valid for each side */
if (remote_rp->SAL_partid < 0 ||
remote_rp->SAL_partid >= xp_max_npartitions ||
remote_rp->max_npartitions <= xp_partition_id) {
return xpInvalidPartid;
}
if (remote_rp->SAL_partid == xp_partition_id)
return xpLocalPartid;
return xpSuccess;
}
/*
* See if the other side has responded to a partition deactivate request
* from us. Though we requested the remote partition to deactivate with regard
* to us, we really only need to wait for the other side to disengage from us.
*/
int
xpc_partition_disengaged(struct xpc_partition *part)
{
short partid = XPC_PARTID(part);
int disengaged;
disengaged = !xpc_arch_ops.partition_engaged(partid);
if (part->disengage_timeout) {
if (!disengaged) {
if (time_is_after_jiffies(part->disengage_timeout)) {
/* timelimit hasn't been reached yet */
return 0;
}
/*
* Other side hasn't responded to our deactivate
* request in a timely fashion, so assume it's dead.
*/
dev_info(xpc_part, "deactivate request to remote "
"partition %d timed out\n", partid);
xpc_disengage_timedout = 1;
xpc_arch_ops.assume_partition_disengaged(partid);
disengaged = 1;
}
part->disengage_timeout = 0;
/* cancel the timer function, provided it's not us */
if (!in_interrupt())
del_singleshot_timer_sync(&part->disengage_timer);
DBUG_ON(part->act_state != XPC_P_AS_DEACTIVATING &&
part->act_state != XPC_P_AS_INACTIVE);
if (part->act_state != XPC_P_AS_INACTIVE)
xpc_wakeup_channel_mgr(part);
xpc_arch_ops.cancel_partition_deactivation_request(part);
}
return disengaged;
}
/*
* Mark specified partition as active.
*/
enum xp_retval
xpc_mark_partition_active(struct xpc_partition *part)
{
unsigned long irq_flags;
enum xp_retval ret;
dev_dbg(xpc_part, "setting partition %d to ACTIVE\n", XPC_PARTID(part));
spin_lock_irqsave(&part->act_lock, irq_flags);
if (part->act_state == XPC_P_AS_ACTIVATING) {
part->act_state = XPC_P_AS_ACTIVE;
ret = xpSuccess;
} else {
DBUG_ON(part->reason == xpSuccess);
ret = part->reason;
}
spin_unlock_irqrestore(&part->act_lock, irq_flags);
return ret;
}
/*
* Start the process of deactivating the specified partition.
*/
void
xpc_deactivate_partition(const int line, struct xpc_partition *part,
enum xp_retval reason)
{
unsigned long irq_flags;
spin_lock_irqsave(&part->act_lock, irq_flags);
if (part->act_state == XPC_P_AS_INACTIVE) {
XPC_SET_REASON(part, reason, line);
spin_unlock_irqrestore(&part->act_lock, irq_flags);
if (reason == xpReactivating) {
/* we interrupt ourselves to reactivate partition */
xpc_arch_ops.request_partition_reactivation(part);
}
return;
}
if (part->act_state == XPC_P_AS_DEACTIVATING) {
if ((part->reason == xpUnloading && reason != xpUnloading) ||
reason == xpReactivating) {
XPC_SET_REASON(part, reason, line);
}
spin_unlock_irqrestore(&part->act_lock, irq_flags);
return;
}
part->act_state = XPC_P_AS_DEACTIVATING;
XPC_SET_REASON(part, reason, line);
spin_unlock_irqrestore(&part->act_lock, irq_flags);
/* ask remote partition to deactivate with regard to us */
xpc_arch_ops.request_partition_deactivation(part);
/* set a timelimit on the disengage phase of the deactivation request */
part->disengage_timeout = jiffies + (xpc_disengage_timelimit * HZ);
part->disengage_timer.expires = part->disengage_timeout;
add_timer(&part->disengage_timer);
dev_dbg(xpc_part, "bringing partition %d down, reason = %d\n",
XPC_PARTID(part), reason);
xpc_partition_going_down(part, reason);
}
/*
* Mark specified partition as inactive.
*/
void
xpc_mark_partition_inactive(struct xpc_partition *part)
{
unsigned long irq_flags;
dev_dbg(xpc_part, "setting partition %d to INACTIVE\n",
XPC_PARTID(part));
spin_lock_irqsave(&part->act_lock, irq_flags);
part->act_state = XPC_P_AS_INACTIVE;
spin_unlock_irqrestore(&part->act_lock, irq_flags);
part->remote_rp_pa = 0;
}
/*
* SAL has provided a partition and machine mask. The partition mask
* contains a bit for each even nasid in our partition. The machine
* mask contains a bit for each even nasid in the entire machine.
*
* Using those two bit arrays, we can determine which nasids are
* known in the machine. Each should also have a reserved page
* initialized if they are available for partitioning.
*/
void
xpc_discovery(void)
{
void *remote_rp_base;
struct xpc_rsvd_page *remote_rp;
unsigned long remote_rp_pa;
int region;
int region_size;
int max_regions;
int nasid;
struct xpc_rsvd_page *rp;
unsigned long *discovered_nasids;
enum xp_retval ret;
remote_rp = xpc_kmalloc_cacheline_aligned(XPC_RP_HEADER_SIZE +
xpc_nasid_mask_nbytes,
GFP_KERNEL, &remote_rp_base);
if (remote_rp == NULL)
return;
discovered_nasids = kzalloc(sizeof(long) * xpc_nasid_mask_nlongs,
GFP_KERNEL);
if (discovered_nasids == NULL) {
kfree(remote_rp_base);
return;
}
rp = (struct xpc_rsvd_page *)xpc_rsvd_page;
/*
* The term 'region' in this context refers to the minimum number of
* nodes that can comprise an access protection grouping. The access
* protection is in regards to memory, IOI and IPI.
*/
region_size = xp_region_size;
if (is_uv())
max_regions = 256;
else {
max_regions = 64;
switch (region_size) {
case 128:
max_regions *= 2;
case 64:
max_regions *= 2;
case 32:
max_regions *= 2;
region_size = 16;
DBUG_ON(!is_shub2());
}
}
for (region = 0; region < max_regions; region++) {
if (xpc_exiting)
break;
dev_dbg(xpc_part, "searching region %d\n", region);
for (nasid = (region * region_size * 2);
nasid < ((region + 1) * region_size * 2); nasid += 2) {
if (xpc_exiting)
break;
dev_dbg(xpc_part, "checking nasid %d\n", nasid);
if (test_bit(nasid / 2, xpc_part_nasids)) {
dev_dbg(xpc_part, "PROM indicates Nasid %d is "
"part of the local partition; skipping "
"region\n", nasid);
break;
}
if (!(test_bit(nasid / 2, xpc_mach_nasids))) {
dev_dbg(xpc_part, "PROM indicates Nasid %d was "
"not on Numa-Link network at reset\n",
nasid);
continue;
}
if (test_bit(nasid / 2, discovered_nasids)) {
dev_dbg(xpc_part, "Nasid %d is part of a "
"partition which was previously "
"discovered\n", nasid);
continue;
}
/* pull over the rsvd page header & part_nasids mask */
ret = xpc_get_remote_rp(nasid, discovered_nasids,
remote_rp, &remote_rp_pa);
if (ret != xpSuccess) {
dev_dbg(xpc_part, "unable to get reserved page "
"from nasid %d, reason=%d\n", nasid,
ret);
if (ret == xpLocalPartid)
break;
continue;
}
xpc_arch_ops.request_partition_activation(remote_rp,
remote_rp_pa, nasid);
}
}
kfree(discovered_nasids);
kfree(remote_rp_base);
}
/*
* Given a partid, get the nasids owned by that partition from the
* remote partition's reserved page.
*/
enum xp_retval
xpc_initiate_partid_to_nasids(short partid, void *nasid_mask)
{
struct xpc_partition *part;
unsigned long part_nasid_pa;
part = &xpc_partitions[partid];
if (part->remote_rp_pa == 0)
return xpPartitionDown;
memset(nasid_mask, 0, xpc_nasid_mask_nbytes);
part_nasid_pa = (unsigned long)XPC_RP_PART_NASIDS(part->remote_rp_pa);
return xp_remote_memcpy(xp_pa(nasid_mask), part_nasid_pa,
xpc_nasid_mask_nbytes);
}
| gpl-2.0 |
Nicklas373/Hana-Kernel_MSM8627-AOSP_7.0 | arch/cris/arch-v32/drivers/iop_fw_load.c | 13816 | 5989 | /*
* Firmware loader for ETRAX FS IO-Processor
*
* Copyright (C) 2004 Axis Communications AB
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/reg_map.h>
#include <hwregs/iop/iop_reg_space.h>
#include <hwregs/iop/iop_mpu_macros.h>
#include <hwregs/iop/iop_mpu_defs.h>
#include <hwregs/iop/iop_spu_defs.h>
#include <hwregs/iop/iop_sw_cpu_defs.h>
#define IOP_TIMEOUT 100
#error "This driver is broken with regard to its driver core usage."
#error "Please contact <greg@kroah.com> for details on how to fix it properly."
static struct device iop_spu_device[2] = {
{ .init_name = "iop-spu0", },
{ .init_name = "iop-spu1", },
};
static struct device iop_mpu_device = {
.init_name = "iop-mpu",
};
static int wait_mpu_idle(void)
{
reg_iop_mpu_r_stat mpu_stat;
unsigned int timeout = IOP_TIMEOUT;
do {
mpu_stat = REG_RD(iop_mpu, regi_iop_mpu, r_stat);
} while (mpu_stat.instr_reg_busy == regk_iop_mpu_yes && --timeout > 0);
if (timeout == 0) {
printk(KERN_ERR "Timeout waiting for MPU to be idle\n");
return -EBUSY;
}
return 0;
}
int iop_fw_load_spu(const unsigned char *fw_name, unsigned int spu_inst)
{
reg_iop_sw_cpu_rw_mc_ctrl mc_ctrl = {
.wr_spu0_mem = regk_iop_sw_cpu_no,
.wr_spu1_mem = regk_iop_sw_cpu_no,
.size = 4,
.cmd = regk_iop_sw_cpu_reg_copy,
.keep_owner = regk_iop_sw_cpu_yes
};
reg_iop_spu_rw_ctrl spu_ctrl = {
.en = regk_iop_spu_no,
.fsm = regk_iop_spu_no,
};
reg_iop_sw_cpu_r_mc_stat mc_stat;
const struct firmware *fw_entry;
u32 *data;
unsigned int timeout;
int retval, i;
if (spu_inst > 1)
return -ENODEV;
/* get firmware */
retval = request_firmware(&fw_entry,
fw_name,
&iop_spu_device[spu_inst]);
if (retval != 0)
{
printk(KERN_ERR
"iop_load_spu: Failed to load firmware \"%s\"\n",
fw_name);
return retval;
}
data = (u32 *) fw_entry->data;
/* acquire ownership of memory controller */
switch (spu_inst) {
case 0:
mc_ctrl.wr_spu0_mem = regk_iop_sw_cpu_yes;
REG_WR(iop_spu, regi_iop_spu0, rw_ctrl, spu_ctrl);
break;
case 1:
mc_ctrl.wr_spu1_mem = regk_iop_sw_cpu_yes;
REG_WR(iop_spu, regi_iop_spu1, rw_ctrl, spu_ctrl);
break;
}
timeout = IOP_TIMEOUT;
do {
REG_WR(iop_sw_cpu, regi_iop_sw_cpu, rw_mc_ctrl, mc_ctrl);
mc_stat = REG_RD(iop_sw_cpu, regi_iop_sw_cpu, r_mc_stat);
} while (mc_stat.owned_by_cpu == regk_iop_sw_cpu_no && --timeout > 0);
if (timeout == 0) {
printk(KERN_ERR "Timeout waiting to acquire MC\n");
retval = -EBUSY;
goto out;
}
/* write to SPU memory */
for (i = 0; i < (fw_entry->size/4); i++) {
switch (spu_inst) {
case 0:
REG_WR_INT(iop_spu, regi_iop_spu0, rw_seq_pc, (i*4));
break;
case 1:
REG_WR_INT(iop_spu, regi_iop_spu1, rw_seq_pc, (i*4));
break;
}
REG_WR_INT(iop_sw_cpu, regi_iop_sw_cpu, rw_mc_data, *data);
data++;
}
/* release ownership of memory controller */
(void) REG_RD(iop_sw_cpu, regi_iop_sw_cpu, rs_mc_data);
out:
release_firmware(fw_entry);
return retval;
}
int iop_fw_load_mpu(unsigned char *fw_name)
{
const unsigned int start_addr = 0;
reg_iop_mpu_rw_ctrl mpu_ctrl;
const struct firmware *fw_entry;
u32 *data;
int retval, i;
/* get firmware */
retval = request_firmware(&fw_entry, fw_name, &iop_mpu_device);
if (retval != 0)
{
printk(KERN_ERR
"iop_load_spu: Failed to load firmware \"%s\"\n",
fw_name);
return retval;
}
data = (u32 *) fw_entry->data;
/* disable MPU */
mpu_ctrl.en = regk_iop_mpu_no;
REG_WR(iop_mpu, regi_iop_mpu, rw_ctrl, mpu_ctrl);
/* put start address in R0 */
REG_WR_VECT(iop_mpu, regi_iop_mpu, rw_r, 0, start_addr);
/* write to memory by executing 'SWX i, 4, R0' for each word */
if ((retval = wait_mpu_idle()) != 0)
goto out;
REG_WR(iop_mpu, regi_iop_mpu, rw_instr, MPU_SWX_IIR_INSTR(0, 4, 0));
for (i = 0; i < (fw_entry->size / 4); i++) {
REG_WR_INT(iop_mpu, regi_iop_mpu, rw_immediate, *data);
if ((retval = wait_mpu_idle()) != 0)
goto out;
data++;
}
out:
release_firmware(fw_entry);
return retval;
}
int iop_start_mpu(unsigned int start_addr)
{
reg_iop_mpu_rw_ctrl mpu_ctrl = { .en = regk_iop_mpu_yes };
int retval;
/* disable MPU */
if ((retval = wait_mpu_idle()) != 0)
goto out;
REG_WR(iop_mpu, regi_iop_mpu, rw_instr, MPU_HALT());
if ((retval = wait_mpu_idle()) != 0)
goto out;
/* set PC and wait for it to bite */
if ((retval = wait_mpu_idle()) != 0)
goto out;
REG_WR_INT(iop_mpu, regi_iop_mpu, rw_instr, MPU_BA_I(start_addr));
if ((retval = wait_mpu_idle()) != 0)
goto out;
/* make sure the MPU starts executing with interrupts disabled */
REG_WR(iop_mpu, regi_iop_mpu, rw_instr, MPU_DI());
if ((retval = wait_mpu_idle()) != 0)
goto out;
/* enable MPU */
REG_WR(iop_mpu, regi_iop_mpu, rw_ctrl, mpu_ctrl);
out:
return retval;
}
static int __init iop_fw_load_init(void)
{
#if 0
/*
* static struct devices can not be added directly to sysfs by ignoring
* the driver model infrastructure. To fix this properly, please use
* the platform_bus to register these devices to be able to properly
* use the firmware infrastructure.
*/
device_initialize(&iop_spu_device[0]);
kobject_set_name(&iop_spu_device[0].kobj, "iop-spu0");
kobject_add(&iop_spu_device[0].kobj);
device_initialize(&iop_spu_device[1]);
kobject_set_name(&iop_spu_device[1].kobj, "iop-spu1");
kobject_add(&iop_spu_device[1].kobj);
device_initialize(&iop_mpu_device);
kobject_set_name(&iop_mpu_device.kobj, "iop-mpu");
kobject_add(&iop_mpu_device.kobj);
#endif
return 0;
}
static void __exit iop_fw_load_exit(void)
{
}
module_init(iop_fw_load_init);
module_exit(iop_fw_load_exit);
MODULE_DESCRIPTION("ETRAX FS IO-Processor Firmware Loader");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(iop_fw_load_spu);
EXPORT_SYMBOL(iop_fw_load_mpu);
EXPORT_SYMBOL(iop_start_mpu);
| gpl-2.0 |
yoctobsp/linux-yocto-3.14 | drivers/staging/lustre/lustre/ldlm/ldlm_resource.c | 249 | 39606 | /*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* 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 version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2010, 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*
* lustre/ldlm/ldlm_resource.c
*
* Author: Phil Schwan <phil@clusterfs.com>
* Author: Peter Braam <braam@clusterfs.com>
*/
#define DEBUG_SUBSYSTEM S_LDLM
# include <lustre_dlm.h>
#include <lustre_fid.h>
#include <obd_class.h>
#include "ldlm_internal.h"
struct kmem_cache *ldlm_resource_slab, *ldlm_lock_slab;
int ldlm_srv_namespace_nr = 0;
int ldlm_cli_namespace_nr = 0;
struct mutex ldlm_srv_namespace_lock;
LIST_HEAD(ldlm_srv_namespace_list);
struct mutex ldlm_cli_namespace_lock;
/* Client Namespaces that have active resources in them.
* Once all resources go away, ldlm_poold moves such namespaces to the
* inactive list */
LIST_HEAD(ldlm_cli_active_namespace_list);
/* Client namespaces that don't have any locks in them */
LIST_HEAD(ldlm_cli_inactive_namespace_list);
struct proc_dir_entry *ldlm_type_proc_dir = NULL;
struct proc_dir_entry *ldlm_ns_proc_dir = NULL;
struct proc_dir_entry *ldlm_svc_proc_dir = NULL;
extern unsigned int ldlm_cancel_unused_locks_before_replay;
/* during debug dump certain amount of granted locks for one resource to avoid
* DDOS. */
unsigned int ldlm_dump_granted_max = 256;
#ifdef LPROCFS
static ssize_t lprocfs_wr_dump_ns(struct file *file, const char *buffer,
size_t count, loff_t *off)
{
ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
return count;
}
LPROC_SEQ_FOPS_WR_ONLY(ldlm, dump_ns);
LPROC_SEQ_FOPS_RW_TYPE(ldlm_rw, uint);
LPROC_SEQ_FOPS_RO_TYPE(ldlm, uint);
int ldlm_proc_setup(void)
{
int rc;
struct lprocfs_vars list[] = {
{ "dump_namespaces", &ldlm_dump_ns_fops, 0, 0222 },
{ "dump_granted_max", &ldlm_rw_uint_fops,
&ldlm_dump_granted_max },
{ "cancel_unused_locks_before_replay", &ldlm_rw_uint_fops,
&ldlm_cancel_unused_locks_before_replay },
{ NULL }};
LASSERT(ldlm_ns_proc_dir == NULL);
ldlm_type_proc_dir = lprocfs_register(OBD_LDLM_DEVICENAME,
proc_lustre_root,
NULL, NULL);
if (IS_ERR(ldlm_type_proc_dir)) {
CERROR("LProcFS failed in ldlm-init\n");
rc = PTR_ERR(ldlm_type_proc_dir);
GOTO(err, rc);
}
ldlm_ns_proc_dir = lprocfs_register("namespaces",
ldlm_type_proc_dir,
NULL, NULL);
if (IS_ERR(ldlm_ns_proc_dir)) {
CERROR("LProcFS failed in ldlm-init\n");
rc = PTR_ERR(ldlm_ns_proc_dir);
GOTO(err_type, rc);
}
ldlm_svc_proc_dir = lprocfs_register("services",
ldlm_type_proc_dir,
NULL, NULL);
if (IS_ERR(ldlm_svc_proc_dir)) {
CERROR("LProcFS failed in ldlm-init\n");
rc = PTR_ERR(ldlm_svc_proc_dir);
GOTO(err_ns, rc);
}
rc = lprocfs_add_vars(ldlm_type_proc_dir, list, NULL);
return 0;
err_ns:
lprocfs_remove(&ldlm_ns_proc_dir);
err_type:
lprocfs_remove(&ldlm_type_proc_dir);
err:
ldlm_svc_proc_dir = NULL;
ldlm_type_proc_dir = NULL;
ldlm_ns_proc_dir = NULL;
return rc;
}
void ldlm_proc_cleanup(void)
{
if (ldlm_svc_proc_dir)
lprocfs_remove(&ldlm_svc_proc_dir);
if (ldlm_ns_proc_dir)
lprocfs_remove(&ldlm_ns_proc_dir);
if (ldlm_type_proc_dir)
lprocfs_remove(&ldlm_type_proc_dir);
ldlm_svc_proc_dir = NULL;
ldlm_type_proc_dir = NULL;
ldlm_ns_proc_dir = NULL;
}
static int lprocfs_ns_resources_seq_show(struct seq_file *m, void *v)
{
struct ldlm_namespace *ns = m->private;
__u64 res = 0;
struct cfs_hash_bd bd;
int i;
/* result is not strictly consistent */
cfs_hash_for_each_bucket(ns->ns_rs_hash, &bd, i)
res += cfs_hash_bd_count_get(&bd);
return lprocfs_rd_u64(m, &res);
}
LPROC_SEQ_FOPS_RO(lprocfs_ns_resources);
static int lprocfs_ns_locks_seq_show(struct seq_file *m, void *v)
{
struct ldlm_namespace *ns = m->private;
__u64 locks;
locks = lprocfs_stats_collector(ns->ns_stats, LDLM_NSS_LOCKS,
LPROCFS_FIELDS_FLAGS_SUM);
return lprocfs_rd_u64(m, &locks);
}
LPROC_SEQ_FOPS_RO(lprocfs_ns_locks);
static int lprocfs_lru_size_seq_show(struct seq_file *m, void *v)
{
struct ldlm_namespace *ns = m->private;
__u32 *nr = &ns->ns_max_unused;
if (ns_connect_lru_resize(ns))
nr = &ns->ns_nr_unused;
return lprocfs_rd_uint(m, nr);
}
static ssize_t lprocfs_lru_size_seq_write(struct file *file, const char *buffer,
size_t count, loff_t *off)
{
struct ldlm_namespace *ns = ((struct seq_file *)file->private_data)->private;
char dummy[MAX_STRING_SIZE + 1], *end;
unsigned long tmp;
int lru_resize;
dummy[MAX_STRING_SIZE] = '\0';
if (copy_from_user(dummy, buffer, MAX_STRING_SIZE))
return -EFAULT;
if (strncmp(dummy, "clear", 5) == 0) {
CDEBUG(D_DLMTRACE,
"dropping all unused locks from namespace %s\n",
ldlm_ns_name(ns));
if (ns_connect_lru_resize(ns)) {
int canceled, unused = ns->ns_nr_unused;
/* Try to cancel all @ns_nr_unused locks. */
canceled = ldlm_cancel_lru(ns, unused, 0,
LDLM_CANCEL_PASSED);
if (canceled < unused) {
CDEBUG(D_DLMTRACE,
"not all requested locks are canceled, "
"requested: %d, canceled: %d\n", unused,
canceled);
return -EINVAL;
}
} else {
tmp = ns->ns_max_unused;
ns->ns_max_unused = 0;
ldlm_cancel_lru(ns, 0, 0, LDLM_CANCEL_PASSED);
ns->ns_max_unused = tmp;
}
return count;
}
tmp = simple_strtoul(dummy, &end, 0);
if (dummy == end) {
CERROR("invalid value written\n");
return -EINVAL;
}
lru_resize = (tmp == 0);
if (ns_connect_lru_resize(ns)) {
if (!lru_resize)
ns->ns_max_unused = (unsigned int)tmp;
if (tmp > ns->ns_nr_unused)
tmp = ns->ns_nr_unused;
tmp = ns->ns_nr_unused - tmp;
CDEBUG(D_DLMTRACE,
"changing namespace %s unused locks from %u to %u\n",
ldlm_ns_name(ns), ns->ns_nr_unused,
(unsigned int)tmp);
ldlm_cancel_lru(ns, tmp, LCF_ASYNC, LDLM_CANCEL_PASSED);
if (!lru_resize) {
CDEBUG(D_DLMTRACE,
"disable lru_resize for namespace %s\n",
ldlm_ns_name(ns));
ns->ns_connect_flags &= ~OBD_CONNECT_LRU_RESIZE;
}
} else {
CDEBUG(D_DLMTRACE,
"changing namespace %s max_unused from %u to %u\n",
ldlm_ns_name(ns), ns->ns_max_unused,
(unsigned int)tmp);
ns->ns_max_unused = (unsigned int)tmp;
ldlm_cancel_lru(ns, 0, LCF_ASYNC, LDLM_CANCEL_PASSED);
/* Make sure that LRU resize was originally supported before
* turning it on here. */
if (lru_resize &&
(ns->ns_orig_connect_flags & OBD_CONNECT_LRU_RESIZE)) {
CDEBUG(D_DLMTRACE,
"enable lru_resize for namespace %s\n",
ldlm_ns_name(ns));
ns->ns_connect_flags |= OBD_CONNECT_LRU_RESIZE;
}
}
return count;
}
LPROC_SEQ_FOPS(lprocfs_lru_size);
static int lprocfs_elc_seq_show(struct seq_file *m, void *v)
{
struct ldlm_namespace *ns = m->private;
unsigned int supp = ns_connect_cancelset(ns);
return lprocfs_rd_uint(m, &supp);
}
static ssize_t lprocfs_elc_seq_write(struct file *file, const char *buffer,
size_t count, loff_t *off)
{
struct ldlm_namespace *ns = ((struct seq_file *)file->private_data)->private;
unsigned int supp = -1;
int rc;
rc = lprocfs_wr_uint(file, buffer, count, &supp);
if (rc < 0)
return rc;
if (supp == 0)
ns->ns_connect_flags &= ~OBD_CONNECT_CANCELSET;
else if (ns->ns_orig_connect_flags & OBD_CONNECT_CANCELSET)
ns->ns_connect_flags |= OBD_CONNECT_CANCELSET;
return count;
}
LPROC_SEQ_FOPS(lprocfs_elc);
void ldlm_namespace_proc_unregister(struct ldlm_namespace *ns)
{
if (ns->ns_proc_dir_entry == NULL)
CERROR("dlm namespace %s has no procfs dir?\n",
ldlm_ns_name(ns));
else
lprocfs_remove(&ns->ns_proc_dir_entry);
if (ns->ns_stats != NULL)
lprocfs_free_stats(&ns->ns_stats);
}
#define LDLM_NS_ADD_VAR(name, var, ops) \
do { \
snprintf(lock_name, MAX_STRING_SIZE, name); \
lock_vars[0].data = var; \
lock_vars[0].fops = ops; \
lprocfs_add_vars(ns_pde, lock_vars, 0); \
} while (0)
int ldlm_namespace_proc_register(struct ldlm_namespace *ns)
{
struct lprocfs_vars lock_vars[2];
char lock_name[MAX_STRING_SIZE + 1];
struct proc_dir_entry *ns_pde;
LASSERT(ns != NULL);
LASSERT(ns->ns_rs_hash != NULL);
if (ns->ns_proc_dir_entry != NULL) {
ns_pde = ns->ns_proc_dir_entry;
} else {
ns_pde = proc_mkdir(ldlm_ns_name(ns), ldlm_ns_proc_dir);
if (ns_pde == NULL)
return -ENOMEM;
ns->ns_proc_dir_entry = ns_pde;
}
ns->ns_stats = lprocfs_alloc_stats(LDLM_NSS_LAST, 0);
if (ns->ns_stats == NULL)
return -ENOMEM;
lprocfs_counter_init(ns->ns_stats, LDLM_NSS_LOCKS,
LPROCFS_CNTR_AVGMINMAX, "locks", "locks");
lock_name[MAX_STRING_SIZE] = '\0';
memset(lock_vars, 0, sizeof(lock_vars));
lock_vars[0].name = lock_name;
LDLM_NS_ADD_VAR("resource_count", ns, &lprocfs_ns_resources_fops);
LDLM_NS_ADD_VAR("lock_count", ns, &lprocfs_ns_locks_fops);
if (ns_is_client(ns)) {
LDLM_NS_ADD_VAR("lock_unused_count", &ns->ns_nr_unused,
&ldlm_uint_fops);
LDLM_NS_ADD_VAR("lru_size", ns, &lprocfs_lru_size_fops);
LDLM_NS_ADD_VAR("lru_max_age", &ns->ns_max_age,
&ldlm_rw_uint_fops);
LDLM_NS_ADD_VAR("early_lock_cancel", ns, &lprocfs_elc_fops);
} else {
LDLM_NS_ADD_VAR("ctime_age_limit", &ns->ns_ctime_age_limit,
&ldlm_rw_uint_fops);
LDLM_NS_ADD_VAR("lock_timeouts", &ns->ns_timeouts,
&ldlm_uint_fops);
LDLM_NS_ADD_VAR("max_nolock_bytes", &ns->ns_max_nolock_size,
&ldlm_rw_uint_fops);
LDLM_NS_ADD_VAR("contention_seconds", &ns->ns_contention_time,
&ldlm_rw_uint_fops);
LDLM_NS_ADD_VAR("contended_locks", &ns->ns_contended_locks,
&ldlm_rw_uint_fops);
LDLM_NS_ADD_VAR("max_parallel_ast", &ns->ns_max_parallel_ast,
&ldlm_rw_uint_fops);
}
return 0;
}
#undef MAX_STRING_SIZE
#else /* LPROCFS */
#define ldlm_namespace_proc_unregister(ns) ({;})
#define ldlm_namespace_proc_register(ns) ({0;})
#endif /* LPROCFS */
static unsigned ldlm_res_hop_hash(struct cfs_hash *hs,
const void *key, unsigned mask)
{
const struct ldlm_res_id *id = key;
unsigned val = 0;
unsigned i;
for (i = 0; i < RES_NAME_SIZE; i++)
val += id->name[i];
return val & mask;
}
static unsigned ldlm_res_hop_fid_hash(struct cfs_hash *hs,
const void *key, unsigned mask)
{
const struct ldlm_res_id *id = key;
struct lu_fid fid;
__u32 hash;
__u32 val;
fid.f_seq = id->name[LUSTRE_RES_ID_SEQ_OFF];
fid.f_oid = (__u32)id->name[LUSTRE_RES_ID_VER_OID_OFF];
fid.f_ver = (__u32)(id->name[LUSTRE_RES_ID_VER_OID_OFF] >> 32);
hash = fid_flatten32(&fid);
hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
if (id->name[LUSTRE_RES_ID_HSH_OFF] != 0) {
val = id->name[LUSTRE_RES_ID_HSH_OFF];
hash += (val >> 5) + (val << 11);
} else {
val = fid_oid(&fid);
}
hash = cfs_hash_long(hash, hs->hs_bkt_bits);
/* give me another random factor */
hash -= cfs_hash_long((unsigned long)hs, val % 11 + 3);
hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
hash |= ldlm_res_hop_hash(hs, key, CFS_HASH_NBKT(hs) - 1);
return hash & mask;
}
static void *ldlm_res_hop_key(struct hlist_node *hnode)
{
struct ldlm_resource *res;
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
return &res->lr_name;
}
static int ldlm_res_hop_keycmp(const void *key, struct hlist_node *hnode)
{
struct ldlm_resource *res;
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
return ldlm_res_eq((const struct ldlm_res_id *)key,
(const struct ldlm_res_id *)&res->lr_name);
}
static void *ldlm_res_hop_object(struct hlist_node *hnode)
{
return hlist_entry(hnode, struct ldlm_resource, lr_hash);
}
static void ldlm_res_hop_get_locked(struct cfs_hash *hs, struct hlist_node *hnode)
{
struct ldlm_resource *res;
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
ldlm_resource_getref(res);
}
static void ldlm_res_hop_put_locked(struct cfs_hash *hs, struct hlist_node *hnode)
{
struct ldlm_resource *res;
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
/* cfs_hash_for_each_nolock is the only chance we call it */
ldlm_resource_putref_locked(res);
}
static void ldlm_res_hop_put(struct cfs_hash *hs, struct hlist_node *hnode)
{
struct ldlm_resource *res;
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
ldlm_resource_putref(res);
}
cfs_hash_ops_t ldlm_ns_hash_ops = {
.hs_hash = ldlm_res_hop_hash,
.hs_key = ldlm_res_hop_key,
.hs_keycmp = ldlm_res_hop_keycmp,
.hs_keycpy = NULL,
.hs_object = ldlm_res_hop_object,
.hs_get = ldlm_res_hop_get_locked,
.hs_put_locked = ldlm_res_hop_put_locked,
.hs_put = ldlm_res_hop_put
};
cfs_hash_ops_t ldlm_ns_fid_hash_ops = {
.hs_hash = ldlm_res_hop_fid_hash,
.hs_key = ldlm_res_hop_key,
.hs_keycmp = ldlm_res_hop_keycmp,
.hs_keycpy = NULL,
.hs_object = ldlm_res_hop_object,
.hs_get = ldlm_res_hop_get_locked,
.hs_put_locked = ldlm_res_hop_put_locked,
.hs_put = ldlm_res_hop_put
};
typedef struct {
ldlm_ns_type_t nsd_type;
/** hash bucket bits */
unsigned nsd_bkt_bits;
/** hash bits */
unsigned nsd_all_bits;
/** hash operations */
cfs_hash_ops_t *nsd_hops;
} ldlm_ns_hash_def_t;
ldlm_ns_hash_def_t ldlm_ns_hash_defs[] =
{
{
.nsd_type = LDLM_NS_TYPE_MDC,
.nsd_bkt_bits = 11,
.nsd_all_bits = 16,
.nsd_hops = &ldlm_ns_fid_hash_ops,
},
{
.nsd_type = LDLM_NS_TYPE_MDT,
.nsd_bkt_bits = 14,
.nsd_all_bits = 21,
.nsd_hops = &ldlm_ns_fid_hash_ops,
},
{
.nsd_type = LDLM_NS_TYPE_OSC,
.nsd_bkt_bits = 8,
.nsd_all_bits = 12,
.nsd_hops = &ldlm_ns_hash_ops,
},
{
.nsd_type = LDLM_NS_TYPE_OST,
.nsd_bkt_bits = 11,
.nsd_all_bits = 17,
.nsd_hops = &ldlm_ns_hash_ops,
},
{
.nsd_type = LDLM_NS_TYPE_MGC,
.nsd_bkt_bits = 4,
.nsd_all_bits = 4,
.nsd_hops = &ldlm_ns_hash_ops,
},
{
.nsd_type = LDLM_NS_TYPE_MGT,
.nsd_bkt_bits = 4,
.nsd_all_bits = 4,
.nsd_hops = &ldlm_ns_hash_ops,
},
{
.nsd_type = LDLM_NS_TYPE_UNKNOWN,
},
};
/**
* Create and initialize new empty namespace.
*/
struct ldlm_namespace *ldlm_namespace_new(struct obd_device *obd, char *name,
ldlm_side_t client,
ldlm_appetite_t apt,
ldlm_ns_type_t ns_type)
{
struct ldlm_namespace *ns = NULL;
struct ldlm_ns_bucket *nsb;
ldlm_ns_hash_def_t *nsd;
struct cfs_hash_bd bd;
int idx;
int rc;
LASSERT(obd != NULL);
rc = ldlm_get_ref();
if (rc) {
CERROR("ldlm_get_ref failed: %d\n", rc);
return NULL;
}
for (idx = 0;;idx++) {
nsd = &ldlm_ns_hash_defs[idx];
if (nsd->nsd_type == LDLM_NS_TYPE_UNKNOWN) {
CERROR("Unknown type %d for ns %s\n", ns_type, name);
GOTO(out_ref, NULL);
}
if (nsd->nsd_type == ns_type)
break;
}
OBD_ALLOC_PTR(ns);
if (!ns)
GOTO(out_ref, NULL);
ns->ns_rs_hash = cfs_hash_create(name,
nsd->nsd_all_bits, nsd->nsd_all_bits,
nsd->nsd_bkt_bits, sizeof(*nsb),
CFS_HASH_MIN_THETA,
CFS_HASH_MAX_THETA,
nsd->nsd_hops,
CFS_HASH_DEPTH |
CFS_HASH_BIGNAME |
CFS_HASH_SPIN_BKTLOCK |
CFS_HASH_NO_ITEMREF);
if (ns->ns_rs_hash == NULL)
GOTO(out_ns, NULL);
cfs_hash_for_each_bucket(ns->ns_rs_hash, &bd, idx) {
nsb = cfs_hash_bd_extra_get(ns->ns_rs_hash, &bd);
at_init(&nsb->nsb_at_estimate, ldlm_enqueue_min, 0);
nsb->nsb_namespace = ns;
}
ns->ns_obd = obd;
ns->ns_appetite = apt;
ns->ns_client = client;
INIT_LIST_HEAD(&ns->ns_list_chain);
INIT_LIST_HEAD(&ns->ns_unused_list);
spin_lock_init(&ns->ns_lock);
atomic_set(&ns->ns_bref, 0);
init_waitqueue_head(&ns->ns_waitq);
ns->ns_max_nolock_size = NS_DEFAULT_MAX_NOLOCK_BYTES;
ns->ns_contention_time = NS_DEFAULT_CONTENTION_SECONDS;
ns->ns_contended_locks = NS_DEFAULT_CONTENDED_LOCKS;
ns->ns_max_parallel_ast = LDLM_DEFAULT_PARALLEL_AST_LIMIT;
ns->ns_nr_unused = 0;
ns->ns_max_unused = LDLM_DEFAULT_LRU_SIZE;
ns->ns_max_age = LDLM_DEFAULT_MAX_ALIVE;
ns->ns_ctime_age_limit = LDLM_CTIME_AGE_LIMIT;
ns->ns_timeouts = 0;
ns->ns_orig_connect_flags = 0;
ns->ns_connect_flags = 0;
ns->ns_stopping = 0;
rc = ldlm_namespace_proc_register(ns);
if (rc != 0) {
CERROR("Can't initialize ns proc, rc %d\n", rc);
GOTO(out_hash, rc);
}
idx = ldlm_namespace_nr_read(client);
rc = ldlm_pool_init(&ns->ns_pool, ns, idx, client);
if (rc) {
CERROR("Can't initialize lock pool, rc %d\n", rc);
GOTO(out_proc, rc);
}
ldlm_namespace_register(ns, client);
return ns;
out_proc:
ldlm_namespace_proc_unregister(ns);
ldlm_namespace_cleanup(ns, 0);
out_hash:
cfs_hash_putref(ns->ns_rs_hash);
out_ns:
OBD_FREE_PTR(ns);
out_ref:
ldlm_put_ref();
return NULL;
}
EXPORT_SYMBOL(ldlm_namespace_new);
extern struct ldlm_lock *ldlm_lock_get(struct ldlm_lock *lock);
/**
* Cancel and destroy all locks on a resource.
*
* If flags contains FL_LOCAL_ONLY, don't try to tell the server, just
* clean up. This is currently only used for recovery, and we make
* certain assumptions as a result--notably, that we shouldn't cancel
* locks with refs.
*/
static void cleanup_resource(struct ldlm_resource *res, struct list_head *q,
__u64 flags)
{
struct list_head *tmp;
int rc = 0, client = ns_is_client(ldlm_res_to_ns(res));
bool local_only = !!(flags & LDLM_FL_LOCAL_ONLY);
do {
struct ldlm_lock *lock = NULL;
/* First, we look for non-cleaned-yet lock
* all cleaned locks are marked by CLEANED flag. */
lock_res(res);
list_for_each(tmp, q) {
lock = list_entry(tmp, struct ldlm_lock,
l_res_link);
if (lock->l_flags & LDLM_FL_CLEANED) {
lock = NULL;
continue;
}
LDLM_LOCK_GET(lock);
lock->l_flags |= LDLM_FL_CLEANED;
break;
}
if (lock == NULL) {
unlock_res(res);
break;
}
/* Set CBPENDING so nothing in the cancellation path
* can match this lock. */
lock->l_flags |= LDLM_FL_CBPENDING;
lock->l_flags |= LDLM_FL_FAILED;
lock->l_flags |= flags;
/* ... without sending a CANCEL message for local_only. */
if (local_only)
lock->l_flags |= LDLM_FL_LOCAL_ONLY;
if (local_only && (lock->l_readers || lock->l_writers)) {
/* This is a little bit gross, but much better than the
* alternative: pretend that we got a blocking AST from
* the server, so that when the lock is decref'd, it
* will go away ... */
unlock_res(res);
LDLM_DEBUG(lock, "setting FL_LOCAL_ONLY");
if (lock->l_completion_ast)
lock->l_completion_ast(lock, 0, NULL);
LDLM_LOCK_RELEASE(lock);
continue;
}
if (client) {
struct lustre_handle lockh;
unlock_res(res);
ldlm_lock2handle(lock, &lockh);
rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
if (rc)
CERROR("ldlm_cli_cancel: %d\n", rc);
} else {
ldlm_resource_unlink_lock(lock);
unlock_res(res);
LDLM_DEBUG(lock, "Freeing a lock still held by a "
"client node");
ldlm_lock_destroy(lock);
}
LDLM_LOCK_RELEASE(lock);
} while (1);
}
static int ldlm_resource_clean(struct cfs_hash *hs, struct cfs_hash_bd *bd,
struct hlist_node *hnode, void *arg)
{
struct ldlm_resource *res = cfs_hash_object(hs, hnode);
__u64 flags = *(__u64 *)arg;
cleanup_resource(res, &res->lr_granted, flags);
cleanup_resource(res, &res->lr_converting, flags);
cleanup_resource(res, &res->lr_waiting, flags);
return 0;
}
static int ldlm_resource_complain(struct cfs_hash *hs, struct cfs_hash_bd *bd,
struct hlist_node *hnode, void *arg)
{
struct ldlm_resource *res = cfs_hash_object(hs, hnode);
lock_res(res);
CERROR("%s: namespace resource "DLDLMRES
" (%p) refcount nonzero (%d) after lock cleanup; forcing cleanup.\n",
ldlm_ns_name(ldlm_res_to_ns(res)), PLDLMRES(res), res,
atomic_read(&res->lr_refcount) - 1);
ldlm_resource_dump(D_ERROR, res);
unlock_res(res);
return 0;
}
/**
* Cancel and destroy all locks in the namespace.
*
* Typically used during evictions when server notified client that it was
* evicted and all of its state needs to be destroyed.
* Also used during shutdown.
*/
int ldlm_namespace_cleanup(struct ldlm_namespace *ns, __u64 flags)
{
if (ns == NULL) {
CDEBUG(D_INFO, "NULL ns, skipping cleanup\n");
return ELDLM_OK;
}
cfs_hash_for_each_nolock(ns->ns_rs_hash, ldlm_resource_clean, &flags);
cfs_hash_for_each_nolock(ns->ns_rs_hash, ldlm_resource_complain, NULL);
return ELDLM_OK;
}
EXPORT_SYMBOL(ldlm_namespace_cleanup);
/**
* Attempts to free namespace.
*
* Only used when namespace goes away, like during an unmount.
*/
static int __ldlm_namespace_free(struct ldlm_namespace *ns, int force)
{
/* At shutdown time, don't call the cancellation callback */
ldlm_namespace_cleanup(ns, force ? LDLM_FL_LOCAL_ONLY : 0);
if (atomic_read(&ns->ns_bref) > 0) {
struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
int rc;
CDEBUG(D_DLMTRACE,
"dlm namespace %s free waiting on refcount %d\n",
ldlm_ns_name(ns), atomic_read(&ns->ns_bref));
force_wait:
if (force)
lwi = LWI_TIMEOUT(obd_timeout * HZ / 4, NULL, NULL);
rc = l_wait_event(ns->ns_waitq,
atomic_read(&ns->ns_bref) == 0, &lwi);
/* Forced cleanups should be able to reclaim all references,
* so it's safe to wait forever... we can't leak locks... */
if (force && rc == -ETIMEDOUT) {
LCONSOLE_ERROR("Forced cleanup waiting for %s "
"namespace with %d resources in use, "
"(rc=%d)\n", ldlm_ns_name(ns),
atomic_read(&ns->ns_bref), rc);
GOTO(force_wait, rc);
}
if (atomic_read(&ns->ns_bref)) {
LCONSOLE_ERROR("Cleanup waiting for %s namespace "
"with %d resources in use, (rc=%d)\n",
ldlm_ns_name(ns),
atomic_read(&ns->ns_bref), rc);
return ELDLM_NAMESPACE_EXISTS;
}
CDEBUG(D_DLMTRACE, "dlm namespace %s free done waiting\n",
ldlm_ns_name(ns));
}
return ELDLM_OK;
}
/**
* Performs various cleanups for passed \a ns to make it drop refc and be
* ready for freeing. Waits for refc == 0.
*
* The following is done:
* (0) Unregister \a ns from its list to make inaccessible for potential
* users like pools thread and others;
* (1) Clear all locks in \a ns.
*/
void ldlm_namespace_free_prior(struct ldlm_namespace *ns,
struct obd_import *imp,
int force)
{
int rc;
if (!ns) {
return;
}
spin_lock(&ns->ns_lock);
ns->ns_stopping = 1;
spin_unlock(&ns->ns_lock);
/*
* Can fail with -EINTR when force == 0 in which case try harder.
*/
rc = __ldlm_namespace_free(ns, force);
if (rc != ELDLM_OK) {
if (imp) {
ptlrpc_disconnect_import(imp, 0);
ptlrpc_invalidate_import(imp);
}
/*
* With all requests dropped and the import inactive
* we are guaranteed all reference will be dropped.
*/
rc = __ldlm_namespace_free(ns, 1);
LASSERT(rc == 0);
}
}
/**
* Performs freeing memory structures related to \a ns. This is only done
* when ldlm_namespce_free_prior() successfully removed all resources
* referencing \a ns and its refc == 0.
*/
void ldlm_namespace_free_post(struct ldlm_namespace *ns)
{
if (!ns) {
return;
}
/* Make sure that nobody can find this ns in its list. */
ldlm_namespace_unregister(ns, ns->ns_client);
/* Fini pool _before_ parent proc dir is removed. This is important as
* ldlm_pool_fini() removes own proc dir which is child to @dir.
* Removing it after @dir may cause oops. */
ldlm_pool_fini(&ns->ns_pool);
ldlm_namespace_proc_unregister(ns);
cfs_hash_putref(ns->ns_rs_hash);
/* Namespace \a ns should be not on list at this time, otherwise
* this will cause issues related to using freed \a ns in poold
* thread. */
LASSERT(list_empty(&ns->ns_list_chain));
OBD_FREE_PTR(ns);
ldlm_put_ref();
}
/**
* Cleanup the resource, and free namespace.
* bug 12864:
* Deadlock issue:
* proc1: destroy import
* class_disconnect_export(grab cl_sem) ->
* -> ldlm_namespace_free ->
* -> lprocfs_remove(grab _lprocfs_lock).
* proc2: read proc info
* lprocfs_fops_read(grab _lprocfs_lock) ->
* -> osc_rd_active, etc(grab cl_sem).
*
* So that I have to split the ldlm_namespace_free into two parts - the first
* part ldlm_namespace_free_prior is used to cleanup the resource which is
* being used; the 2nd part ldlm_namespace_free_post is used to unregister the
* lprocfs entries, and then free memory. It will be called w/o cli->cl_sem
* held.
*/
void ldlm_namespace_free(struct ldlm_namespace *ns,
struct obd_import *imp,
int force)
{
ldlm_namespace_free_prior(ns, imp, force);
ldlm_namespace_free_post(ns);
}
EXPORT_SYMBOL(ldlm_namespace_free);
void ldlm_namespace_get(struct ldlm_namespace *ns)
{
atomic_inc(&ns->ns_bref);
}
EXPORT_SYMBOL(ldlm_namespace_get);
/* This is only for callers that care about refcount */
int ldlm_namespace_get_return(struct ldlm_namespace *ns)
{
return atomic_inc_return(&ns->ns_bref);
}
void ldlm_namespace_put(struct ldlm_namespace *ns)
{
if (atomic_dec_and_lock(&ns->ns_bref, &ns->ns_lock)) {
wake_up(&ns->ns_waitq);
spin_unlock(&ns->ns_lock);
}
}
EXPORT_SYMBOL(ldlm_namespace_put);
/** Register \a ns in the list of namespaces */
void ldlm_namespace_register(struct ldlm_namespace *ns, ldlm_side_t client)
{
mutex_lock(ldlm_namespace_lock(client));
LASSERT(list_empty(&ns->ns_list_chain));
list_add(&ns->ns_list_chain, ldlm_namespace_inactive_list(client));
ldlm_namespace_nr_inc(client);
mutex_unlock(ldlm_namespace_lock(client));
}
/** Unregister \a ns from the list of namespaces. */
void ldlm_namespace_unregister(struct ldlm_namespace *ns, ldlm_side_t client)
{
mutex_lock(ldlm_namespace_lock(client));
LASSERT(!list_empty(&ns->ns_list_chain));
/* Some asserts and possibly other parts of the code are still
* using list_empty(&ns->ns_list_chain). This is why it is
* important to use list_del_init() here. */
list_del_init(&ns->ns_list_chain);
ldlm_namespace_nr_dec(client);
mutex_unlock(ldlm_namespace_lock(client));
}
/** Should be called with ldlm_namespace_lock(client) taken. */
void ldlm_namespace_move_to_active_locked(struct ldlm_namespace *ns,
ldlm_side_t client)
{
LASSERT(!list_empty(&ns->ns_list_chain));
LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
list_move_tail(&ns->ns_list_chain, ldlm_namespace_list(client));
}
/** Should be called with ldlm_namespace_lock(client) taken. */
void ldlm_namespace_move_to_inactive_locked(struct ldlm_namespace *ns,
ldlm_side_t client)
{
LASSERT(!list_empty(&ns->ns_list_chain));
LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
list_move_tail(&ns->ns_list_chain,
ldlm_namespace_inactive_list(client));
}
/** Should be called with ldlm_namespace_lock(client) taken. */
struct ldlm_namespace *ldlm_namespace_first_locked(ldlm_side_t client)
{
LASSERT(mutex_is_locked(ldlm_namespace_lock(client)));
LASSERT(!list_empty(ldlm_namespace_list(client)));
return container_of(ldlm_namespace_list(client)->next,
struct ldlm_namespace, ns_list_chain);
}
/** Create and initialize new resource. */
static struct ldlm_resource *ldlm_resource_new(void)
{
struct ldlm_resource *res;
int idx;
OBD_SLAB_ALLOC_PTR_GFP(res, ldlm_resource_slab, __GFP_IO);
if (res == NULL)
return NULL;
INIT_LIST_HEAD(&res->lr_granted);
INIT_LIST_HEAD(&res->lr_converting);
INIT_LIST_HEAD(&res->lr_waiting);
/* Initialize interval trees for each lock mode. */
for (idx = 0; idx < LCK_MODE_NUM; idx++) {
res->lr_itree[idx].lit_size = 0;
res->lr_itree[idx].lit_mode = 1 << idx;
res->lr_itree[idx].lit_root = NULL;
}
atomic_set(&res->lr_refcount, 1);
spin_lock_init(&res->lr_lock);
lu_ref_init(&res->lr_reference);
/* The creator of the resource must unlock the mutex after LVB
* initialization. */
mutex_init(&res->lr_lvb_mutex);
mutex_lock(&res->lr_lvb_mutex);
return res;
}
/**
* Return a reference to resource with given name, creating it if necessary.
* Args: namespace with ns_lock unlocked
* Locks: takes and releases NS hash-lock and res->lr_lock
* Returns: referenced, unlocked ldlm_resource or NULL
*/
struct ldlm_resource *
ldlm_resource_get(struct ldlm_namespace *ns, struct ldlm_resource *parent,
const struct ldlm_res_id *name, ldlm_type_t type, int create)
{
struct hlist_node *hnode;
struct ldlm_resource *res;
struct cfs_hash_bd bd;
__u64 version;
int ns_refcount = 0;
LASSERT(ns != NULL);
LASSERT(parent == NULL);
LASSERT(ns->ns_rs_hash != NULL);
LASSERT(name->name[0] != 0);
cfs_hash_bd_get_and_lock(ns->ns_rs_hash, (void *)name, &bd, 0);
hnode = cfs_hash_bd_lookup_locked(ns->ns_rs_hash, &bd, (void *)name);
if (hnode != NULL) {
cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 0);
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
/* Synchronize with regard to resource creation. */
if (ns->ns_lvbo && ns->ns_lvbo->lvbo_init) {
mutex_lock(&res->lr_lvb_mutex);
mutex_unlock(&res->lr_lvb_mutex);
}
if (unlikely(res->lr_lvb_len < 0)) {
ldlm_resource_putref(res);
res = NULL;
}
return res;
}
version = cfs_hash_bd_version_get(&bd);
cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 0);
if (create == 0)
return NULL;
LASSERTF(type >= LDLM_MIN_TYPE && type < LDLM_MAX_TYPE,
"type: %d\n", type);
res = ldlm_resource_new();
if (!res)
return NULL;
res->lr_ns_bucket = cfs_hash_bd_extra_get(ns->ns_rs_hash, &bd);
res->lr_name = *name;
res->lr_type = type;
res->lr_most_restr = LCK_NL;
cfs_hash_bd_lock(ns->ns_rs_hash, &bd, 1);
hnode = (version == cfs_hash_bd_version_get(&bd)) ? NULL :
cfs_hash_bd_lookup_locked(ns->ns_rs_hash, &bd, (void *)name);
if (hnode != NULL) {
/* Someone won the race and already added the resource. */
cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
/* Clean lu_ref for failed resource. */
lu_ref_fini(&res->lr_reference);
/* We have taken lr_lvb_mutex. Drop it. */
mutex_unlock(&res->lr_lvb_mutex);
OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof(*res));
res = hlist_entry(hnode, struct ldlm_resource, lr_hash);
/* Synchronize with regard to resource creation. */
if (ns->ns_lvbo && ns->ns_lvbo->lvbo_init) {
mutex_lock(&res->lr_lvb_mutex);
mutex_unlock(&res->lr_lvb_mutex);
}
if (unlikely(res->lr_lvb_len < 0)) {
ldlm_resource_putref(res);
res = NULL;
}
return res;
}
/* We won! Let's add the resource. */
cfs_hash_bd_add_locked(ns->ns_rs_hash, &bd, &res->lr_hash);
if (cfs_hash_bd_count_get(&bd) == 1)
ns_refcount = ldlm_namespace_get_return(ns);
cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
if (ns->ns_lvbo && ns->ns_lvbo->lvbo_init) {
int rc;
OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_CREATE_RESOURCE, 2);
rc = ns->ns_lvbo->lvbo_init(res);
if (rc < 0) {
CERROR("%s: lvbo_init failed for resource "LPX64":"
LPX64": rc = %d\n", ns->ns_obd->obd_name,
name->name[0], name->name[1], rc);
if (res->lr_lvb_data) {
OBD_FREE(res->lr_lvb_data, res->lr_lvb_len);
res->lr_lvb_data = NULL;
}
res->lr_lvb_len = rc;
mutex_unlock(&res->lr_lvb_mutex);
ldlm_resource_putref(res);
return NULL;
}
}
/* We create resource with locked lr_lvb_mutex. */
mutex_unlock(&res->lr_lvb_mutex);
/* Let's see if we happened to be the very first resource in this
* namespace. If so, and this is a client namespace, we need to move
* the namespace into the active namespaces list to be patrolled by
* the ldlm_poold. */
if (ns_is_client(ns) && ns_refcount == 1) {
mutex_lock(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
ldlm_namespace_move_to_active_locked(ns, LDLM_NAMESPACE_CLIENT);
mutex_unlock(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
}
return res;
}
EXPORT_SYMBOL(ldlm_resource_get);
struct ldlm_resource *ldlm_resource_getref(struct ldlm_resource *res)
{
LASSERT(res != NULL);
LASSERT(res != LP_POISON);
atomic_inc(&res->lr_refcount);
CDEBUG(D_INFO, "getref res: %p count: %d\n", res,
atomic_read(&res->lr_refcount));
return res;
}
static void __ldlm_resource_putref_final(struct cfs_hash_bd *bd,
struct ldlm_resource *res)
{
struct ldlm_ns_bucket *nsb = res->lr_ns_bucket;
if (!list_empty(&res->lr_granted)) {
ldlm_resource_dump(D_ERROR, res);
LBUG();
}
if (!list_empty(&res->lr_converting)) {
ldlm_resource_dump(D_ERROR, res);
LBUG();
}
if (!list_empty(&res->lr_waiting)) {
ldlm_resource_dump(D_ERROR, res);
LBUG();
}
cfs_hash_bd_del_locked(nsb->nsb_namespace->ns_rs_hash,
bd, &res->lr_hash);
lu_ref_fini(&res->lr_reference);
if (cfs_hash_bd_count_get(bd) == 0)
ldlm_namespace_put(nsb->nsb_namespace);
}
/* Returns 1 if the resource was freed, 0 if it remains. */
int ldlm_resource_putref(struct ldlm_resource *res)
{
struct ldlm_namespace *ns = ldlm_res_to_ns(res);
struct cfs_hash_bd bd;
LASSERT_ATOMIC_GT_LT(&res->lr_refcount, 0, LI_POISON);
CDEBUG(D_INFO, "putref res: %p count: %d\n",
res, atomic_read(&res->lr_refcount) - 1);
cfs_hash_bd_get(ns->ns_rs_hash, &res->lr_name, &bd);
if (cfs_hash_bd_dec_and_lock(ns->ns_rs_hash, &bd, &res->lr_refcount)) {
__ldlm_resource_putref_final(&bd, res);
cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
if (ns->ns_lvbo && ns->ns_lvbo->lvbo_free)
ns->ns_lvbo->lvbo_free(res);
OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof(*res));
return 1;
}
return 0;
}
EXPORT_SYMBOL(ldlm_resource_putref);
/* Returns 1 if the resource was freed, 0 if it remains. */
int ldlm_resource_putref_locked(struct ldlm_resource *res)
{
struct ldlm_namespace *ns = ldlm_res_to_ns(res);
LASSERT_ATOMIC_GT_LT(&res->lr_refcount, 0, LI_POISON);
CDEBUG(D_INFO, "putref res: %p count: %d\n",
res, atomic_read(&res->lr_refcount) - 1);
if (atomic_dec_and_test(&res->lr_refcount)) {
struct cfs_hash_bd bd;
cfs_hash_bd_get(ldlm_res_to_ns(res)->ns_rs_hash,
&res->lr_name, &bd);
__ldlm_resource_putref_final(&bd, res);
cfs_hash_bd_unlock(ns->ns_rs_hash, &bd, 1);
/* NB: ns_rs_hash is created with CFS_HASH_NO_ITEMREF,
* so we should never be here while calling cfs_hash_del,
* cfs_hash_for_each_nolock is the only case we can get
* here, which is safe to release cfs_hash_bd_lock.
*/
if (ns->ns_lvbo && ns->ns_lvbo->lvbo_free)
ns->ns_lvbo->lvbo_free(res);
OBD_SLAB_FREE(res, ldlm_resource_slab, sizeof(*res));
cfs_hash_bd_lock(ns->ns_rs_hash, &bd, 1);
return 1;
}
return 0;
}
/**
* Add a lock into a given resource into specified lock list.
*/
void ldlm_resource_add_lock(struct ldlm_resource *res, struct list_head *head,
struct ldlm_lock *lock)
{
check_res_locked(res);
LDLM_DEBUG(lock, "About to add this lock:\n");
if (lock->l_flags & LDLM_FL_DESTROYED) {
CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
return;
}
LASSERT(list_empty(&lock->l_res_link));
list_add_tail(&lock->l_res_link, head);
}
/**
* Insert a lock into resource after specified lock.
*
* Obtain resource description from the lock we are inserting after.
*/
void ldlm_resource_insert_lock_after(struct ldlm_lock *original,
struct ldlm_lock *new)
{
struct ldlm_resource *res = original->l_resource;
check_res_locked(res);
ldlm_resource_dump(D_INFO, res);
LDLM_DEBUG(new, "About to insert this lock after %p:\n", original);
if (new->l_flags & LDLM_FL_DESTROYED) {
CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
goto out;
}
LASSERT(list_empty(&new->l_res_link));
list_add(&new->l_res_link, &original->l_res_link);
out:;
}
void ldlm_resource_unlink_lock(struct ldlm_lock *lock)
{
int type = lock->l_resource->lr_type;
check_res_locked(lock->l_resource);
if (type == LDLM_IBITS || type == LDLM_PLAIN)
ldlm_unlink_lock_skiplist(lock);
else if (type == LDLM_EXTENT)
ldlm_extent_unlink_lock(lock);
list_del_init(&lock->l_res_link);
}
EXPORT_SYMBOL(ldlm_resource_unlink_lock);
void ldlm_res2desc(struct ldlm_resource *res, struct ldlm_resource_desc *desc)
{
desc->lr_type = res->lr_type;
desc->lr_name = res->lr_name;
}
/**
* Print information about all locks in all namespaces on this node to debug
* log.
*/
void ldlm_dump_all_namespaces(ldlm_side_t client, int level)
{
struct list_head *tmp;
if (!((libcfs_debug | D_ERROR) & level))
return;
mutex_lock(ldlm_namespace_lock(client));
list_for_each(tmp, ldlm_namespace_list(client)) {
struct ldlm_namespace *ns;
ns = list_entry(tmp, struct ldlm_namespace, ns_list_chain);
ldlm_namespace_dump(level, ns);
}
mutex_unlock(ldlm_namespace_lock(client));
}
EXPORT_SYMBOL(ldlm_dump_all_namespaces);
static int ldlm_res_hash_dump(struct cfs_hash *hs, struct cfs_hash_bd *bd,
struct hlist_node *hnode, void *arg)
{
struct ldlm_resource *res = cfs_hash_object(hs, hnode);
int level = (int)(unsigned long)arg;
lock_res(res);
ldlm_resource_dump(level, res);
unlock_res(res);
return 0;
}
/**
* Print information about all locks in this namespace on this node to debug
* log.
*/
void ldlm_namespace_dump(int level, struct ldlm_namespace *ns)
{
if (!((libcfs_debug | D_ERROR) & level))
return;
CDEBUG(level, "--- Namespace: %s (rc: %d, side: %s)\n",
ldlm_ns_name(ns), atomic_read(&ns->ns_bref),
ns_is_client(ns) ? "client" : "server");
if (cfs_time_before(cfs_time_current(), ns->ns_next_dump))
return;
cfs_hash_for_each_nolock(ns->ns_rs_hash,
ldlm_res_hash_dump,
(void *)(unsigned long)level);
spin_lock(&ns->ns_lock);
ns->ns_next_dump = cfs_time_shift(10);
spin_unlock(&ns->ns_lock);
}
EXPORT_SYMBOL(ldlm_namespace_dump);
/**
* Print information about all locks in this resource to debug log.
*/
void ldlm_resource_dump(int level, struct ldlm_resource *res)
{
struct ldlm_lock *lock;
unsigned int granted = 0;
CLASSERT(RES_NAME_SIZE == 4);
if (!((libcfs_debug | D_ERROR) & level))
return;
CDEBUG(level, "--- Resource: "DLDLMRES" (%p) refcount = %d\n",
PLDLMRES(res), res, atomic_read(&res->lr_refcount));
if (!list_empty(&res->lr_granted)) {
CDEBUG(level, "Granted locks (in reverse order):\n");
list_for_each_entry_reverse(lock, &res->lr_granted,
l_res_link) {
LDLM_DEBUG_LIMIT(level, lock, "###");
if (!(level & D_CANTMASK) &&
++granted > ldlm_dump_granted_max) {
CDEBUG(level, "only dump %d granted locks to "
"avoid DDOS.\n", granted);
break;
}
}
}
if (!list_empty(&res->lr_converting)) {
CDEBUG(level, "Converting locks:\n");
list_for_each_entry(lock, &res->lr_converting, l_res_link)
LDLM_DEBUG_LIMIT(level, lock, "###");
}
if (!list_empty(&res->lr_waiting)) {
CDEBUG(level, "Waiting locks:\n");
list_for_each_entry(lock, &res->lr_waiting, l_res_link)
LDLM_DEBUG_LIMIT(level, lock, "###");
}
}
| gpl-2.0 |
DerRomtester/android_kernel_oneplus_bacon-3.10 | fs/jbd2/transaction.c | 249 | 72598 | /*
* linux/fs/jbd2/transaction.c
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1998
*
* Copyright 1998 Red Hat corp --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Generic filesystem transaction handling code; part of the ext2fs
* journaling system.
*
* This file manages transactions (compound commits managed by the
* journaling code) and handles (individual atomic operations by the
* filesystem).
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/hrtimer.h>
#include <linux/backing-dev.h>
#include <linux/bug.h>
#include <linux/module.h>
#include <trace/events/jbd2.h>
static void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh);
static void __jbd2_journal_unfile_buffer(struct journal_head *jh);
static struct kmem_cache *transaction_cache;
int __init jbd2_journal_init_transaction_cache(void)
{
J_ASSERT(!transaction_cache);
transaction_cache = kmem_cache_create("jbd2_transaction_s",
sizeof(transaction_t),
0,
SLAB_HWCACHE_ALIGN|SLAB_TEMPORARY,
NULL);
if (transaction_cache)
return 0;
return -ENOMEM;
}
void jbd2_journal_destroy_transaction_cache(void)
{
if (transaction_cache) {
kmem_cache_destroy(transaction_cache);
transaction_cache = NULL;
}
}
void jbd2_journal_free_transaction(transaction_t *transaction)
{
if (unlikely(ZERO_OR_NULL_PTR(transaction)))
return;
kmem_cache_free(transaction_cache, transaction);
}
/*
* jbd2_get_transaction: obtain a new transaction_t object.
*
* Simply allocate and initialise a new transaction. Create it in
* RUNNING state and add it to the current journal (which should not
* have an existing running transaction: we only make a new transaction
* once we have started to commit the old one).
*
* Preconditions:
* The journal MUST be locked. We don't perform atomic mallocs on the
* new transaction and we can't block without protecting against other
* processes trying to touch the journal while it is in transition.
*
*/
static transaction_t *
jbd2_get_transaction(journal_t *journal, transaction_t *transaction)
{
transaction->t_journal = journal;
transaction->t_state = T_RUNNING;
transaction->t_start_time = ktime_get();
transaction->t_tid = journal->j_transaction_sequence++;
transaction->t_expires = jiffies + journal->j_commit_interval;
spin_lock_init(&transaction->t_handle_lock);
atomic_set(&transaction->t_updates, 0);
atomic_set(&transaction->t_outstanding_credits, 0);
atomic_set(&transaction->t_handle_count, 0);
INIT_LIST_HEAD(&transaction->t_inode_list);
INIT_LIST_HEAD(&transaction->t_private_list);
/* Set up the commit timer for the new transaction. */
journal->j_commit_timer.expires = round_jiffies_up(transaction->t_expires);
add_timer(&journal->j_commit_timer);
J_ASSERT(journal->j_running_transaction == NULL);
journal->j_running_transaction = transaction;
transaction->t_max_wait = 0;
transaction->t_start = jiffies;
transaction->t_requested = 0;
return transaction;
}
/*
* Handle management.
*
* A handle_t is an object which represents a single atomic update to a
* filesystem, and which tracks all of the modifications which form part
* of that one update.
*/
/*
* Update transaction's maximum wait time, if debugging is enabled.
*
* In order for t_max_wait to be reliable, it must be protected by a
* lock. But doing so will mean that start_this_handle() can not be
* run in parallel on SMP systems, which limits our scalability. So
* unless debugging is enabled, we no longer update t_max_wait, which
* means that maximum wait time reported by the jbd2_run_stats
* tracepoint will always be zero.
*/
static inline void update_t_max_wait(transaction_t *transaction,
unsigned long ts)
{
#ifdef CONFIG_JBD2_DEBUG
if (jbd2_journal_enable_debug &&
time_after(transaction->t_start, ts)) {
ts = jbd2_time_diff(ts, transaction->t_start);
spin_lock(&transaction->t_handle_lock);
if (ts > transaction->t_max_wait)
transaction->t_max_wait = ts;
spin_unlock(&transaction->t_handle_lock);
}
#endif
}
/*
* start_this_handle: Given a handle, deal with any locking or stalling
* needed to make sure that there is enough journal space for the handle
* to begin. Attach the handle to a transaction and set up the
* transaction's buffer credits.
*/
static int start_this_handle(journal_t *journal, handle_t *handle,
gfp_t gfp_mask)
{
transaction_t *transaction, *new_transaction = NULL;
tid_t tid;
int needed, need_to_start;
int nblocks = handle->h_buffer_credits;
unsigned long ts = jiffies;
if (nblocks > journal->j_max_transaction_buffers) {
printk(KERN_ERR "JBD2: %s wants too many credits (%d > %d)\n",
current->comm, nblocks,
journal->j_max_transaction_buffers);
return -ENOSPC;
}
alloc_transaction:
if (!journal->j_running_transaction) {
new_transaction = kmem_cache_zalloc(transaction_cache,
gfp_mask);
if (!new_transaction) {
/*
* If __GFP_FS is not present, then we may be
* being called from inside the fs writeback
* layer, so we MUST NOT fail. Since
* __GFP_NOFAIL is going away, we will arrange
* to retry the allocation ourselves.
*/
if ((gfp_mask & __GFP_FS) == 0) {
congestion_wait(BLK_RW_ASYNC, HZ/50);
goto alloc_transaction;
}
return -ENOMEM;
}
}
jbd_debug(3, "New handle %p going live.\n", handle);
/*
* We need to hold j_state_lock until t_updates has been incremented,
* for proper journal barrier handling
*/
repeat:
read_lock(&journal->j_state_lock);
BUG_ON(journal->j_flags & JBD2_UNMOUNT);
if (is_journal_aborted(journal) ||
(journal->j_errno != 0 && !(journal->j_flags & JBD2_ACK_ERR))) {
read_unlock(&journal->j_state_lock);
jbd2_journal_free_transaction(new_transaction);
return -EROFS;
}
/* Wait on the journal's transaction barrier if necessary */
if (journal->j_barrier_count) {
read_unlock(&journal->j_state_lock);
wait_event(journal->j_wait_transaction_locked,
journal->j_barrier_count == 0);
goto repeat;
}
if (!journal->j_running_transaction) {
read_unlock(&journal->j_state_lock);
if (!new_transaction)
goto alloc_transaction;
write_lock(&journal->j_state_lock);
if (!journal->j_running_transaction &&
!journal->j_barrier_count) {
jbd2_get_transaction(journal, new_transaction);
new_transaction = NULL;
}
write_unlock(&journal->j_state_lock);
goto repeat;
}
transaction = journal->j_running_transaction;
/*
* If the current transaction is locked down for commit, wait for the
* lock to be released.
*/
if (transaction->t_state == T_LOCKED) {
DEFINE_WAIT(wait);
prepare_to_wait(&journal->j_wait_transaction_locked,
&wait, TASK_UNINTERRUPTIBLE);
read_unlock(&journal->j_state_lock);
schedule();
finish_wait(&journal->j_wait_transaction_locked, &wait);
goto repeat;
}
/*
* If there is not enough space left in the log to write all potential
* buffers requested by this operation, we need to stall pending a log
* checkpoint to free some more log space.
*/
needed = atomic_add_return(nblocks,
&transaction->t_outstanding_credits);
if (needed > journal->j_max_transaction_buffers) {
/*
* If the current transaction is already too large, then start
* to commit it: we can then go back and attach this handle to
* a new transaction.
*/
DEFINE_WAIT(wait);
jbd_debug(2, "Handle %p starting new commit...\n", handle);
atomic_sub(nblocks, &transaction->t_outstanding_credits);
prepare_to_wait(&journal->j_wait_transaction_locked, &wait,
TASK_UNINTERRUPTIBLE);
tid = transaction->t_tid;
need_to_start = !tid_geq(journal->j_commit_request, tid);
read_unlock(&journal->j_state_lock);
if (need_to_start)
jbd2_log_start_commit(journal, tid);
schedule();
finish_wait(&journal->j_wait_transaction_locked, &wait);
goto repeat;
}
/*
* The commit code assumes that it can get enough log space
* without forcing a checkpoint. This is *critical* for
* correctness: a checkpoint of a buffer which is also
* associated with a committing transaction creates a deadlock,
* so commit simply cannot force through checkpoints.
*
* We must therefore ensure the necessary space in the journal
* *before* starting to dirty potentially checkpointed buffers
* in the new transaction.
*
* The worst part is, any transaction currently committing can
* reduce the free space arbitrarily. Be careful to account for
* those buffers when checkpointing.
*/
/*
* @@@ AKPM: This seems rather over-defensive. We're giving commit
* a _lot_ of headroom: 1/4 of the journal plus the size of
* the committing transaction. Really, we only need to give it
* committing_transaction->t_outstanding_credits plus "enough" for
* the log control blocks.
* Also, this test is inconsistent with the matching one in
* jbd2_journal_extend().
*/
if (__jbd2_log_space_left(journal) < jbd_space_needed(journal)) {
jbd_debug(2, "Handle %p waiting for checkpoint...\n", handle);
atomic_sub(nblocks, &transaction->t_outstanding_credits);
read_unlock(&journal->j_state_lock);
write_lock(&journal->j_state_lock);
if (__jbd2_log_space_left(journal) < jbd_space_needed(journal))
__jbd2_log_wait_for_space(journal);
write_unlock(&journal->j_state_lock);
goto repeat;
}
/* OK, account for the buffers that this operation expects to
* use and add the handle to the running transaction.
*/
update_t_max_wait(transaction, ts);
handle->h_transaction = transaction;
handle->h_requested_credits = nblocks;
handle->h_start_jiffies = jiffies;
atomic_inc(&transaction->t_updates);
atomic_inc(&transaction->t_handle_count);
jbd_debug(4, "Handle %p given %d credits (total %d, free %d)\n",
handle, nblocks,
atomic_read(&transaction->t_outstanding_credits),
__jbd2_log_space_left(journal));
read_unlock(&journal->j_state_lock);
lock_map_acquire(&handle->h_lockdep_map);
jbd2_journal_free_transaction(new_transaction);
return 0;
}
static struct lock_class_key jbd2_handle_key;
/* Allocate a new handle. This should probably be in a slab... */
static handle_t *new_handle(int nblocks)
{
handle_t *handle = jbd2_alloc_handle(GFP_NOFS);
if (!handle)
return NULL;
handle->h_buffer_credits = nblocks;
handle->h_ref = 1;
lockdep_init_map(&handle->h_lockdep_map, "jbd2_handle",
&jbd2_handle_key, 0);
return handle;
}
/**
* handle_t *jbd2_journal_start() - Obtain a new handle.
* @journal: Journal to start transaction on.
* @nblocks: number of block buffer we might modify
*
* We make sure that the transaction can guarantee at least nblocks of
* modified buffers in the log. We block until the log can guarantee
* that much space.
*
* This function is visible to journal users (like ext3fs), so is not
* called with the journal already locked.
*
* Return a pointer to a newly allocated handle, or an ERR_PTR() value
* on failure.
*/
handle_t *jbd2__journal_start(journal_t *journal, int nblocks, gfp_t gfp_mask,
unsigned int type, unsigned int line_no)
{
handle_t *handle = journal_current_handle();
int err;
if (!journal)
return ERR_PTR(-EROFS);
if (handle) {
J_ASSERT(handle->h_transaction->t_journal == journal);
handle->h_ref++;
return handle;
}
handle = new_handle(nblocks);
if (!handle)
return ERR_PTR(-ENOMEM);
current->journal_info = handle;
err = start_this_handle(journal, handle, gfp_mask);
if (err < 0) {
jbd2_free_handle(handle);
current->journal_info = NULL;
return ERR_PTR(err);
}
handle->h_type = type;
handle->h_line_no = line_no;
trace_jbd2_handle_start(journal->j_fs_dev->bd_dev,
handle->h_transaction->t_tid, type,
line_no, nblocks);
return handle;
}
EXPORT_SYMBOL(jbd2__journal_start);
handle_t *jbd2_journal_start(journal_t *journal, int nblocks)
{
return jbd2__journal_start(journal, nblocks, GFP_NOFS, 0, 0);
}
EXPORT_SYMBOL(jbd2_journal_start);
/**
* int jbd2_journal_extend() - extend buffer credits.
* @handle: handle to 'extend'
* @nblocks: nr blocks to try to extend by.
*
* Some transactions, such as large extends and truncates, can be done
* atomically all at once or in several stages. The operation requests
* a credit for a number of buffer modications in advance, but can
* extend its credit if it needs more.
*
* jbd2_journal_extend tries to give the running handle more buffer credits.
* It does not guarantee that allocation - this is a best-effort only.
* The calling process MUST be able to deal cleanly with a failure to
* extend here.
*
* Return 0 on success, non-zero on failure.
*
* return code < 0 implies an error
* return code > 0 implies normal transaction-full status.
*/
int jbd2_journal_extend(handle_t *handle, int nblocks)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
int result;
int wanted;
result = -EIO;
if (is_handle_aborted(handle))
goto out;
result = 1;
read_lock(&journal->j_state_lock);
/* Don't extend a locked-down transaction! */
if (handle->h_transaction->t_state != T_RUNNING) {
jbd_debug(3, "denied handle %p %d blocks: "
"transaction not running\n", handle, nblocks);
goto error_out;
}
spin_lock(&transaction->t_handle_lock);
wanted = atomic_read(&transaction->t_outstanding_credits) + nblocks;
if (wanted > journal->j_max_transaction_buffers) {
jbd_debug(3, "denied handle %p %d blocks: "
"transaction too large\n", handle, nblocks);
goto unlock;
}
if (wanted > __jbd2_log_space_left(journal)) {
jbd_debug(3, "denied handle %p %d blocks: "
"insufficient log space\n", handle, nblocks);
goto unlock;
}
trace_jbd2_handle_extend(journal->j_fs_dev->bd_dev,
handle->h_transaction->t_tid,
handle->h_type, handle->h_line_no,
handle->h_buffer_credits,
nblocks);
handle->h_buffer_credits += nblocks;
handle->h_requested_credits += nblocks;
atomic_add(nblocks, &transaction->t_outstanding_credits);
result = 0;
jbd_debug(3, "extended handle %p by %d\n", handle, nblocks);
unlock:
spin_unlock(&transaction->t_handle_lock);
error_out:
read_unlock(&journal->j_state_lock);
out:
return result;
}
/**
* int jbd2_journal_restart() - restart a handle .
* @handle: handle to restart
* @nblocks: nr credits requested
*
* Restart a handle for a multi-transaction filesystem
* operation.
*
* If the jbd2_journal_extend() call above fails to grant new buffer credits
* to a running handle, a call to jbd2_journal_restart will commit the
* handle's transaction so far and reattach the handle to a new
* transaction capabable of guaranteeing the requested number of
* credits.
*/
int jbd2__journal_restart(handle_t *handle, int nblocks, gfp_t gfp_mask)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
tid_t tid;
int need_to_start, ret;
/* If we've had an abort of any type, don't even think about
* actually doing the restart! */
if (is_handle_aborted(handle))
return 0;
/*
* First unlink the handle from its current transaction, and start the
* commit on that.
*/
J_ASSERT(atomic_read(&transaction->t_updates) > 0);
J_ASSERT(journal_current_handle() == handle);
read_lock(&journal->j_state_lock);
spin_lock(&transaction->t_handle_lock);
atomic_sub(handle->h_buffer_credits,
&transaction->t_outstanding_credits);
if (atomic_dec_and_test(&transaction->t_updates))
wake_up(&journal->j_wait_updates);
tid = transaction->t_tid;
spin_unlock(&transaction->t_handle_lock);
jbd_debug(2, "restarting handle %p\n", handle);
need_to_start = !tid_geq(journal->j_commit_request, tid);
read_unlock(&journal->j_state_lock);
if (need_to_start)
jbd2_log_start_commit(journal, tid);
lock_map_release(&handle->h_lockdep_map);
handle->h_buffer_credits = nblocks;
ret = start_this_handle(journal, handle, gfp_mask);
return ret;
}
EXPORT_SYMBOL(jbd2__journal_restart);
int jbd2_journal_restart(handle_t *handle, int nblocks)
{
return jbd2__journal_restart(handle, nblocks, GFP_NOFS);
}
EXPORT_SYMBOL(jbd2_journal_restart);
/**
* void jbd2_journal_lock_updates () - establish a transaction barrier.
* @journal: Journal to establish a barrier on.
*
* This locks out any further updates from being started, and blocks
* until all existing updates have completed, returning only once the
* journal is in a quiescent state with no updates running.
*
* The journal lock should not be held on entry.
*/
void jbd2_journal_lock_updates(journal_t *journal)
{
DEFINE_WAIT(wait);
write_lock(&journal->j_state_lock);
++journal->j_barrier_count;
/* Wait until there are no running updates */
while (1) {
transaction_t *transaction = journal->j_running_transaction;
if (!transaction)
break;
spin_lock(&transaction->t_handle_lock);
prepare_to_wait(&journal->j_wait_updates, &wait,
TASK_UNINTERRUPTIBLE);
if (!atomic_read(&transaction->t_updates)) {
spin_unlock(&transaction->t_handle_lock);
finish_wait(&journal->j_wait_updates, &wait);
break;
}
spin_unlock(&transaction->t_handle_lock);
write_unlock(&journal->j_state_lock);
schedule();
finish_wait(&journal->j_wait_updates, &wait);
write_lock(&journal->j_state_lock);
}
write_unlock(&journal->j_state_lock);
/*
* We have now established a barrier against other normal updates, but
* we also need to barrier against other jbd2_journal_lock_updates() calls
* to make sure that we serialise special journal-locked operations
* too.
*/
mutex_lock(&journal->j_barrier);
}
/**
* void jbd2_journal_unlock_updates (journal_t* journal) - release barrier
* @journal: Journal to release the barrier on.
*
* Release a transaction barrier obtained with jbd2_journal_lock_updates().
*
* Should be called without the journal lock held.
*/
void jbd2_journal_unlock_updates (journal_t *journal)
{
J_ASSERT(journal->j_barrier_count != 0);
mutex_unlock(&journal->j_barrier);
write_lock(&journal->j_state_lock);
--journal->j_barrier_count;
write_unlock(&journal->j_state_lock);
wake_up(&journal->j_wait_transaction_locked);
}
static void warn_dirty_buffer(struct buffer_head *bh)
{
char b[BDEVNAME_SIZE];
printk(KERN_WARNING
"JBD2: Spotted dirty metadata buffer (dev = %s, blocknr = %llu). "
"There's a risk of filesystem corruption in case of system "
"crash.\n",
bdevname(bh->b_bdev, b), (unsigned long long)bh->b_blocknr);
}
/*
* If the buffer is already part of the current transaction, then there
* is nothing we need to do. If it is already part of a prior
* transaction which we are still committing to disk, then we need to
* make sure that we do not overwrite the old copy: we do copy-out to
* preserve the copy going to disk. We also account the buffer against
* the handle's metadata buffer credits (unless the buffer is already
* part of the transaction, that is).
*
*/
static int
do_get_write_access(handle_t *handle, struct journal_head *jh,
int force_copy)
{
struct buffer_head *bh;
transaction_t *transaction;
journal_t *journal;
int error;
char *frozen_buffer = NULL;
int need_copy = 0;
unsigned long start_lock, time_lock;
if (is_handle_aborted(handle))
return -EROFS;
transaction = handle->h_transaction;
journal = transaction->t_journal;
jbd_debug(5, "journal_head %p, force_copy %d\n", jh, force_copy);
JBUFFER_TRACE(jh, "entry");
repeat:
bh = jh2bh(jh);
/* @@@ Need to check for errors here at some point. */
start_lock = jiffies;
lock_buffer(bh);
jbd_lock_bh_state(bh);
/* If it takes too long to lock the buffer, trace it */
time_lock = jbd2_time_diff(start_lock, jiffies);
if (time_lock > HZ/10)
trace_jbd2_lock_buffer_stall(bh->b_bdev->bd_dev,
jiffies_to_msecs(time_lock));
/* We now hold the buffer lock so it is safe to query the buffer
* state. Is the buffer dirty?
*
* If so, there are two possibilities. The buffer may be
* non-journaled, and undergoing a quite legitimate writeback.
* Otherwise, it is journaled, and we don't expect dirty buffers
* in that state (the buffers should be marked JBD_Dirty
* instead.) So either the IO is being done under our own
* control and this is a bug, or it's a third party IO such as
* dump(8) (which may leave the buffer scheduled for read ---
* ie. locked but not dirty) or tune2fs (which may actually have
* the buffer dirtied, ugh.) */
if (buffer_dirty(bh)) {
/*
* First question: is this buffer already part of the current
* transaction or the existing committing transaction?
*/
if (jh->b_transaction) {
J_ASSERT_JH(jh,
jh->b_transaction == transaction ||
jh->b_transaction ==
journal->j_committing_transaction);
if (jh->b_next_transaction)
J_ASSERT_JH(jh, jh->b_next_transaction ==
transaction);
warn_dirty_buffer(bh);
}
/*
* In any case we need to clean the dirty flag and we must
* do it under the buffer lock to be sure we don't race
* with running write-out.
*/
JBUFFER_TRACE(jh, "Journalling dirty buffer");
clear_buffer_dirty(bh);
set_buffer_jbddirty(bh);
}
unlock_buffer(bh);
error = -EROFS;
if (is_handle_aborted(handle)) {
jbd_unlock_bh_state(bh);
goto out;
}
error = 0;
/*
* The buffer is already part of this transaction if b_transaction or
* b_next_transaction points to it
*/
if (jh->b_transaction == transaction ||
jh->b_next_transaction == transaction)
goto done;
/*
* this is the first time this transaction is touching this buffer,
* reset the modified flag
*/
jh->b_modified = 0;
/*
* If there is already a copy-out version of this buffer, then we don't
* need to make another one
*/
if (jh->b_frozen_data) {
JBUFFER_TRACE(jh, "has frozen data");
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
jh->b_next_transaction = transaction;
goto done;
}
/* Is there data here we need to preserve? */
if (jh->b_transaction && jh->b_transaction != transaction) {
JBUFFER_TRACE(jh, "owned by older transaction");
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
J_ASSERT_JH(jh, jh->b_transaction ==
journal->j_committing_transaction);
/* There is one case we have to be very careful about.
* If the committing transaction is currently writing
* this buffer out to disk and has NOT made a copy-out,
* then we cannot modify the buffer contents at all
* right now. The essence of copy-out is that it is the
* extra copy, not the primary copy, which gets
* journaled. If the primary copy is already going to
* disk then we cannot do copy-out here. */
if (jh->b_jlist == BJ_Shadow) {
DEFINE_WAIT_BIT(wait, &bh->b_state, BH_Unshadow);
wait_queue_head_t *wqh;
wqh = bit_waitqueue(&bh->b_state, BH_Unshadow);
JBUFFER_TRACE(jh, "on shadow: sleep");
jbd_unlock_bh_state(bh);
/* commit wakes up all shadow buffers after IO */
for ( ; ; ) {
prepare_to_wait(wqh, &wait.wait,
TASK_UNINTERRUPTIBLE);
if (jh->b_jlist != BJ_Shadow)
break;
schedule();
}
finish_wait(wqh, &wait.wait);
goto repeat;
}
/* Only do the copy if the currently-owning transaction
* still needs it. If it is on the Forget list, the
* committing transaction is past that stage. The
* buffer had better remain locked during the kmalloc,
* but that should be true --- we hold the journal lock
* still and the buffer is already on the BUF_JOURNAL
* list so won't be flushed.
*
* Subtle point, though: if this is a get_undo_access,
* then we will be relying on the frozen_data to contain
* the new value of the committed_data record after the
* transaction, so we HAVE to force the frozen_data copy
* in that case. */
if (jh->b_jlist != BJ_Forget || force_copy) {
JBUFFER_TRACE(jh, "generate frozen data");
if (!frozen_buffer) {
JBUFFER_TRACE(jh, "allocate memory for buffer");
jbd_unlock_bh_state(bh);
frozen_buffer =
jbd2_alloc(jh2bh(jh)->b_size,
GFP_NOFS);
if (!frozen_buffer) {
printk(KERN_EMERG
"%s: OOM for frozen_buffer\n",
__func__);
JBUFFER_TRACE(jh, "oom!");
error = -ENOMEM;
jbd_lock_bh_state(bh);
goto done;
}
goto repeat;
}
jh->b_frozen_data = frozen_buffer;
frozen_buffer = NULL;
need_copy = 1;
}
jh->b_next_transaction = transaction;
}
/*
* Finally, if the buffer is not journaled right now, we need to make
* sure it doesn't get written to disk before the caller actually
* commits the new data
*/
if (!jh->b_transaction) {
JBUFFER_TRACE(jh, "no transaction");
J_ASSERT_JH(jh, !jh->b_next_transaction);
JBUFFER_TRACE(jh, "file as BJ_Reserved");
spin_lock(&journal->j_list_lock);
__jbd2_journal_file_buffer(jh, transaction, BJ_Reserved);
spin_unlock(&journal->j_list_lock);
}
done:
if (need_copy) {
struct page *page;
int offset;
char *source;
J_EXPECT_JH(jh, buffer_uptodate(jh2bh(jh)),
"Possible IO failure.\n");
page = jh2bh(jh)->b_page;
offset = offset_in_page(jh2bh(jh)->b_data);
source = kmap_atomic(page);
/* Fire data frozen trigger just before we copy the data */
jbd2_buffer_frozen_trigger(jh, source + offset,
jh->b_triggers);
memcpy(jh->b_frozen_data, source+offset, jh2bh(jh)->b_size);
kunmap_atomic(source);
/*
* Now that the frozen data is saved off, we need to store
* any matching triggers.
*/
jh->b_frozen_triggers = jh->b_triggers;
}
jbd_unlock_bh_state(bh);
/*
* If we are about to journal a buffer, then any revoke pending on it is
* no longer valid
*/
jbd2_journal_cancel_revoke(handle, jh);
out:
if (unlikely(frozen_buffer)) /* It's usually NULL */
jbd2_free(frozen_buffer, bh->b_size);
JBUFFER_TRACE(jh, "exit");
return error;
}
/**
* int jbd2_journal_get_write_access() - notify intent to modify a buffer for metadata (not data) update.
* @handle: transaction to add buffer modifications to
* @bh: bh to be used for metadata writes
*
* Returns an error code or 0 on success.
*
* In full data journalling mode the buffer may be of type BJ_AsyncData,
* because we're write()ing a buffer which is also part of a shared mapping.
*/
int jbd2_journal_get_write_access(handle_t *handle, struct buffer_head *bh)
{
struct journal_head *jh = jbd2_journal_add_journal_head(bh);
int rc;
/* We do not want to get caught playing with fields which the
* log thread also manipulates. Make sure that the buffer
* completes any outstanding IO before proceeding. */
rc = do_get_write_access(handle, jh, 0);
jbd2_journal_put_journal_head(jh);
return rc;
}
/*
* When the user wants to journal a newly created buffer_head
* (ie. getblk() returned a new buffer and we are going to populate it
* manually rather than reading off disk), then we need to keep the
* buffer_head locked until it has been completely filled with new
* data. In this case, we should be able to make the assertion that
* the bh is not already part of an existing transaction.
*
* The buffer should already be locked by the caller by this point.
* There is no lock ranking violation: it was a newly created,
* unlocked buffer beforehand. */
/**
* int jbd2_journal_get_create_access () - notify intent to use newly created bh
* @handle: transaction to new buffer to
* @bh: new buffer.
*
* Call this if you create a new bh.
*/
int jbd2_journal_get_create_access(handle_t *handle, struct buffer_head *bh)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
struct journal_head *jh = jbd2_journal_add_journal_head(bh);
int err;
jbd_debug(5, "journal_head %p\n", jh);
err = -EROFS;
if (is_handle_aborted(handle))
goto out;
err = 0;
JBUFFER_TRACE(jh, "entry");
/*
* The buffer may already belong to this transaction due to pre-zeroing
* in the filesystem's new_block code. It may also be on the previous,
* committing transaction's lists, but it HAS to be in Forget state in
* that case: the transaction must have deleted the buffer for it to be
* reused here.
*/
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
J_ASSERT_JH(jh, (jh->b_transaction == transaction ||
jh->b_transaction == NULL ||
(jh->b_transaction == journal->j_committing_transaction &&
jh->b_jlist == BJ_Forget)));
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
J_ASSERT_JH(jh, buffer_locked(jh2bh(jh)));
if (jh->b_transaction == NULL) {
/*
* Previous jbd2_journal_forget() could have left the buffer
* with jbddirty bit set because it was being committed. When
* the commit finished, we've filed the buffer for
* checkpointing and marked it dirty. Now we are reallocating
* the buffer so the transaction freeing it must have
* committed and so it's safe to clear the dirty bit.
*/
clear_buffer_dirty(jh2bh(jh));
/* first access by this transaction */
jh->b_modified = 0;
JBUFFER_TRACE(jh, "file as BJ_Reserved");
__jbd2_journal_file_buffer(jh, transaction, BJ_Reserved);
} else if (jh->b_transaction == journal->j_committing_transaction) {
/* first access by this transaction */
jh->b_modified = 0;
JBUFFER_TRACE(jh, "set next transaction");
jh->b_next_transaction = transaction;
}
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
/*
* akpm: I added this. ext3_alloc_branch can pick up new indirect
* blocks which contain freed but then revoked metadata. We need
* to cancel the revoke in case we end up freeing it yet again
* and the reallocating as data - this would cause a second revoke,
* which hits an assertion error.
*/
JBUFFER_TRACE(jh, "cancelling revoke");
jbd2_journal_cancel_revoke(handle, jh);
out:
jbd2_journal_put_journal_head(jh);
return err;
}
/**
* int jbd2_journal_get_undo_access() - Notify intent to modify metadata with
* non-rewindable consequences
* @handle: transaction
* @bh: buffer to undo
*
* Sometimes there is a need to distinguish between metadata which has
* been committed to disk and that which has not. The ext3fs code uses
* this for freeing and allocating space, we have to make sure that we
* do not reuse freed space until the deallocation has been committed,
* since if we overwrote that space we would make the delete
* un-rewindable in case of a crash.
*
* To deal with that, jbd2_journal_get_undo_access requests write access to a
* buffer for parts of non-rewindable operations such as delete
* operations on the bitmaps. The journaling code must keep a copy of
* the buffer's contents prior to the undo_access call until such time
* as we know that the buffer has definitely been committed to disk.
*
* We never need to know which transaction the committed data is part
* of, buffers touched here are guaranteed to be dirtied later and so
* will be committed to a new transaction in due course, at which point
* we can discard the old committed data pointer.
*
* Returns error number or 0 on success.
*/
int jbd2_journal_get_undo_access(handle_t *handle, struct buffer_head *bh)
{
int err;
struct journal_head *jh = jbd2_journal_add_journal_head(bh);
char *committed_data = NULL;
JBUFFER_TRACE(jh, "entry");
/*
* Do this first --- it can drop the journal lock, so we want to
* make sure that obtaining the committed_data is done
* atomically wrt. completion of any outstanding commits.
*/
err = do_get_write_access(handle, jh, 1);
if (err)
goto out;
repeat:
if (!jh->b_committed_data) {
committed_data = jbd2_alloc(jh2bh(jh)->b_size, GFP_NOFS);
if (!committed_data) {
printk(KERN_EMERG "%s: No memory for committed data\n",
__func__);
err = -ENOMEM;
goto out;
}
}
jbd_lock_bh_state(bh);
if (!jh->b_committed_data) {
/* Copy out the current buffer contents into the
* preserved, committed copy. */
JBUFFER_TRACE(jh, "generate b_committed data");
if (!committed_data) {
jbd_unlock_bh_state(bh);
goto repeat;
}
jh->b_committed_data = committed_data;
committed_data = NULL;
memcpy(jh->b_committed_data, bh->b_data, bh->b_size);
}
jbd_unlock_bh_state(bh);
out:
jbd2_journal_put_journal_head(jh);
if (unlikely(committed_data))
jbd2_free(committed_data, bh->b_size);
return err;
}
/**
* void jbd2_journal_set_triggers() - Add triggers for commit writeout
* @bh: buffer to trigger on
* @type: struct jbd2_buffer_trigger_type containing the trigger(s).
*
* Set any triggers on this journal_head. This is always safe, because
* triggers for a committing buffer will be saved off, and triggers for
* a running transaction will match the buffer in that transaction.
*
* Call with NULL to clear the triggers.
*/
void jbd2_journal_set_triggers(struct buffer_head *bh,
struct jbd2_buffer_trigger_type *type)
{
struct journal_head *jh = jbd2_journal_grab_journal_head(bh);
if (WARN_ON(!jh))
return;
jh->b_triggers = type;
jbd2_journal_put_journal_head(jh);
}
void jbd2_buffer_frozen_trigger(struct journal_head *jh, void *mapped_data,
struct jbd2_buffer_trigger_type *triggers)
{
struct buffer_head *bh = jh2bh(jh);
if (!triggers || !triggers->t_frozen)
return;
triggers->t_frozen(triggers, bh, mapped_data, bh->b_size);
}
void jbd2_buffer_abort_trigger(struct journal_head *jh,
struct jbd2_buffer_trigger_type *triggers)
{
if (!triggers || !triggers->t_abort)
return;
triggers->t_abort(triggers, jh2bh(jh));
}
/**
* int jbd2_journal_dirty_metadata() - mark a buffer as containing dirty metadata
* @handle: transaction to add buffer to.
* @bh: buffer to mark
*
* mark dirty metadata which needs to be journaled as part of the current
* transaction.
*
* The buffer must have previously had jbd2_journal_get_write_access()
* called so that it has a valid journal_head attached to the buffer
* head.
*
* The buffer is placed on the transaction's metadata list and is marked
* as belonging to the transaction.
*
* Returns error number or 0 on success.
*
* Special care needs to be taken if the buffer already belongs to the
* current committing transaction (in which case we should have frozen
* data present for that commit). In that case, we don't relink the
* buffer: that only gets done when the old transaction finally
* completes its commit.
*/
int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
struct journal_head *jh;
int ret = 0;
if (is_handle_aborted(handle))
goto out;
jh = jbd2_journal_grab_journal_head(bh);
if (!jh) {
ret = -EUCLEAN;
goto out;
}
jbd_debug(5, "journal_head %p\n", jh);
JBUFFER_TRACE(jh, "entry");
jbd_lock_bh_state(bh);
if (jh->b_modified == 0) {
/*
* This buffer's got modified and becoming part
* of the transaction. This needs to be done
* once a transaction -bzzz
*/
jh->b_modified = 1;
if (handle->h_buffer_credits <= 0) {
ret = -ENOSPC;
goto out_unlock_bh;
}
handle->h_buffer_credits--;
}
/*
* fastpath, to avoid expensive locking. If this buffer is already
* on the running transaction's metadata list there is nothing to do.
* Nobody can take it off again because there is a handle open.
* I _think_ we're OK here with SMP barriers - a mistaken decision will
* result in this test being false, so we go in and take the locks.
*/
if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) {
JBUFFER_TRACE(jh, "fastpath");
if (unlikely(jh->b_transaction !=
journal->j_running_transaction)) {
printk(KERN_EMERG "JBD: %s: "
"jh->b_transaction (%llu, %p, %u) != "
"journal->j_running_transaction (%p, %u)",
journal->j_devname,
(unsigned long long) bh->b_blocknr,
jh->b_transaction,
jh->b_transaction ? jh->b_transaction->t_tid : 0,
journal->j_running_transaction,
journal->j_running_transaction ?
journal->j_running_transaction->t_tid : 0);
ret = -EINVAL;
}
goto out_unlock_bh;
}
set_buffer_jbddirty(bh);
/*
* Metadata already on the current transaction list doesn't
* need to be filed. Metadata on another transaction's list must
* be committing, and will be refiled once the commit completes:
* leave it alone for now.
*/
if (jh->b_transaction != transaction) {
JBUFFER_TRACE(jh, "already on other transaction");
if (unlikely(jh->b_transaction !=
journal->j_committing_transaction)) {
printk(KERN_EMERG "JBD: %s: "
"jh->b_transaction (%llu, %p, %u) != "
"journal->j_committing_transaction (%p, %u)",
journal->j_devname,
(unsigned long long) bh->b_blocknr,
jh->b_transaction,
jh->b_transaction ? jh->b_transaction->t_tid : 0,
journal->j_committing_transaction,
journal->j_committing_transaction ?
journal->j_committing_transaction->t_tid : 0);
ret = -EINVAL;
}
if (unlikely(jh->b_next_transaction != transaction)) {
printk(KERN_EMERG "JBD: %s: "
"jh->b_next_transaction (%llu, %p, %u) != "
"transaction (%p, %u)",
journal->j_devname,
(unsigned long long) bh->b_blocknr,
jh->b_next_transaction,
jh->b_next_transaction ?
jh->b_next_transaction->t_tid : 0,
transaction, transaction->t_tid);
ret = -EINVAL;
}
/* And this case is illegal: we can't reuse another
* transaction's data buffer, ever. */
goto out_unlock_bh;
}
/* That test should have eliminated the following case: */
J_ASSERT_JH(jh, jh->b_frozen_data == NULL);
JBUFFER_TRACE(jh, "file as BJ_Metadata");
spin_lock(&journal->j_list_lock);
__jbd2_journal_file_buffer(jh, handle->h_transaction, BJ_Metadata);
spin_unlock(&journal->j_list_lock);
out_unlock_bh:
jbd_unlock_bh_state(bh);
jbd2_journal_put_journal_head(jh);
out:
JBUFFER_TRACE(jh, "exit");
return ret;
}
/**
* void jbd2_journal_forget() - bforget() for potentially-journaled buffers.
* @handle: transaction handle
* @bh: bh to 'forget'
*
* We can only do the bforget if there are no commits pending against the
* buffer. If the buffer is dirty in the current running transaction we
* can safely unlink it.
*
* bh may not be a journalled buffer at all - it may be a non-JBD
* buffer which came off the hashtable. Check for this.
*
* Decrements bh->b_count by one.
*
* Allow this call even if the handle has aborted --- it may be part of
* the caller's cleanup after an abort.
*/
int jbd2_journal_forget (handle_t *handle, struct buffer_head *bh)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
struct journal_head *jh;
int drop_reserve = 0;
int err = 0;
int was_modified = 0;
BUFFER_TRACE(bh, "entry");
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
if (!buffer_jbd(bh))
goto not_jbd;
jh = bh2jh(bh);
/* Critical error: attempting to delete a bitmap buffer, maybe?
* Don't do any jbd operations, and return an error. */
if (!J_EXPECT_JH(jh, !jh->b_committed_data,
"inconsistent data on disk")) {
err = -EIO;
goto not_jbd;
}
/* keep track of whether or not this transaction modified us */
was_modified = jh->b_modified;
/*
* The buffer's going from the transaction, we must drop
* all references -bzzz
*/
jh->b_modified = 0;
if (jh->b_transaction == handle->h_transaction) {
J_ASSERT_JH(jh, !jh->b_frozen_data);
/* If we are forgetting a buffer which is already part
* of this transaction, then we can just drop it from
* the transaction immediately. */
clear_buffer_dirty(bh);
clear_buffer_jbddirty(bh);
JBUFFER_TRACE(jh, "belongs to current transaction: unfile");
/*
* we only want to drop a reference if this transaction
* modified the buffer
*/
if (was_modified)
drop_reserve = 1;
/*
* We are no longer going to journal this buffer.
* However, the commit of this transaction is still
* important to the buffer: the delete that we are now
* processing might obsolete an old log entry, so by
* committing, we can satisfy the buffer's checkpoint.
*
* So, if we have a checkpoint on the buffer, we should
* now refile the buffer on our BJ_Forget list so that
* we know to remove the checkpoint after we commit.
*/
if (jh->b_cp_transaction) {
__jbd2_journal_temp_unlink_buffer(jh);
__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
} else {
__jbd2_journal_unfile_buffer(jh);
if (!buffer_jbd(bh)) {
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
__bforget(bh);
goto drop;
}
}
} else if (jh->b_transaction) {
J_ASSERT_JH(jh, (jh->b_transaction ==
journal->j_committing_transaction));
/* However, if the buffer is still owned by a prior
* (committing) transaction, we can't drop it yet... */
JBUFFER_TRACE(jh, "belongs to older transaction");
/* ... but we CAN drop it from the new transaction if we
* have also modified it since the original commit. */
if (jh->b_next_transaction) {
J_ASSERT(jh->b_next_transaction == transaction);
jh->b_next_transaction = NULL;
/*
* only drop a reference if this transaction modified
* the buffer
*/
if (was_modified)
drop_reserve = 1;
}
}
not_jbd:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
__brelse(bh);
drop:
if (drop_reserve) {
/* no need to reserve log space for this block -bzzz */
handle->h_buffer_credits++;
}
return err;
}
/**
* int jbd2_journal_stop() - complete a transaction
* @handle: tranaction to complete.
*
* All done for a particular handle.
*
* There is not much action needed here. We just return any remaining
* buffer credits to the transaction and remove the handle. The only
* complication is that we need to start a commit operation if the
* filesystem is marked for synchronous update.
*
* jbd2_journal_stop itself will not usually return an error, but it may
* do so in unusual circumstances. In particular, expect it to
* return -EIO if a jbd2_journal_abort has been executed since the
* transaction began.
*/
int jbd2_journal_stop(handle_t *handle)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
int err, wait_for_commit = 0;
tid_t tid;
pid_t pid;
J_ASSERT(journal_current_handle() == handle);
if (is_handle_aborted(handle))
err = -EIO;
else {
J_ASSERT(atomic_read(&transaction->t_updates) > 0);
err = 0;
}
if (--handle->h_ref > 0) {
jbd_debug(4, "h_ref %d -> %d\n", handle->h_ref + 1,
handle->h_ref);
return err;
}
jbd_debug(4, "Handle %p going down\n", handle);
trace_jbd2_handle_stats(journal->j_fs_dev->bd_dev,
handle->h_transaction->t_tid,
handle->h_type, handle->h_line_no,
jiffies - handle->h_start_jiffies,
handle->h_sync, handle->h_requested_credits,
(handle->h_requested_credits -
handle->h_buffer_credits));
/*
* Implement synchronous transaction batching. If the handle
* was synchronous, don't force a commit immediately. Let's
* yield and let another thread piggyback onto this
* transaction. Keep doing that while new threads continue to
* arrive. It doesn't cost much - we're about to run a commit
* and sleep on IO anyway. Speeds up many-threaded, many-dir
* operations by 30x or more...
*
* We try and optimize the sleep time against what the
* underlying disk can do, instead of having a static sleep
* time. This is useful for the case where our storage is so
* fast that it is more optimal to go ahead and force a flush
* and wait for the transaction to be committed than it is to
* wait for an arbitrary amount of time for new writers to
* join the transaction. We achieve this by measuring how
* long it takes to commit a transaction, and compare it with
* how long this transaction has been running, and if run time
* < commit time then we sleep for the delta and commit. This
* greatly helps super fast disks that would see slowdowns as
* more threads started doing fsyncs.
*
* But don't do this if this process was the most recent one
* to perform a synchronous write. We do this to detect the
* case where a single process is doing a stream of sync
* writes. No point in waiting for joiners in that case.
*/
pid = current->pid;
if (handle->h_sync && journal->j_last_sync_writer != pid) {
u64 commit_time, trans_time;
journal->j_last_sync_writer = pid;
read_lock(&journal->j_state_lock);
commit_time = journal->j_average_commit_time;
read_unlock(&journal->j_state_lock);
trans_time = ktime_to_ns(ktime_sub(ktime_get(),
transaction->t_start_time));
commit_time = max_t(u64, commit_time,
1000*journal->j_min_batch_time);
commit_time = min_t(u64, commit_time,
1000*journal->j_max_batch_time);
if (trans_time < commit_time) {
ktime_t expires = ktime_add_ns(ktime_get(),
commit_time);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
}
}
if (handle->h_sync)
transaction->t_synchronous_commit = 1;
current->journal_info = NULL;
atomic_sub(handle->h_buffer_credits,
&transaction->t_outstanding_credits);
/*
* If the handle is marked SYNC, we need to set another commit
* going! We also want to force a commit if the current
* transaction is occupying too much of the log, or if the
* transaction is too old now.
*/
if (handle->h_sync ||
(atomic_read(&transaction->t_outstanding_credits) >
journal->j_max_transaction_buffers) ||
time_after_eq(jiffies, transaction->t_expires)) {
/* Do this even for aborted journals: an abort still
* completes the commit thread, it just doesn't write
* anything to disk. */
jbd_debug(2, "transaction too old, requesting commit for "
"handle %p\n", handle);
/* This is non-blocking */
jbd2_log_start_commit(journal, transaction->t_tid);
/*
* Special case: JBD2_SYNC synchronous updates require us
* to wait for the commit to complete.
*/
if (handle->h_sync && !(current->flags & PF_MEMALLOC))
wait_for_commit = 1;
}
/*
* Once we drop t_updates, if it goes to zero the transaction
* could start committing on us and eventually disappear. So
* once we do this, we must not dereference transaction
* pointer again.
*/
tid = transaction->t_tid;
if (atomic_dec_and_test(&transaction->t_updates)) {
wake_up(&journal->j_wait_updates);
if (journal->j_barrier_count)
wake_up(&journal->j_wait_transaction_locked);
}
if (wait_for_commit)
err = jbd2_log_wait_commit(journal, tid);
lock_map_release(&handle->h_lockdep_map);
jbd2_free_handle(handle);
return err;
}
/**
* int jbd2_journal_force_commit() - force any uncommitted transactions
* @journal: journal to force
*
* For synchronous operations: force any uncommitted transactions
* to disk. May seem kludgy, but it reuses all the handle batching
* code in a very simple manner.
*/
int jbd2_journal_force_commit(journal_t *journal)
{
handle_t *handle;
int ret;
handle = jbd2_journal_start(journal, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
} else {
handle->h_sync = 1;
ret = jbd2_journal_stop(handle);
}
return ret;
}
/*
*
* List management code snippets: various functions for manipulating the
* transaction buffer lists.
*
*/
/*
* Append a buffer to a transaction list, given the transaction's list head
* pointer.
*
* j_list_lock is held.
*
* jbd_lock_bh_state(jh2bh(jh)) is held.
*/
static inline void
__blist_add_buffer(struct journal_head **list, struct journal_head *jh)
{
if (!*list) {
jh->b_tnext = jh->b_tprev = jh;
*list = jh;
} else {
/* Insert at the tail of the list to preserve order */
struct journal_head *first = *list, *last = first->b_tprev;
jh->b_tprev = last;
jh->b_tnext = first;
last->b_tnext = first->b_tprev = jh;
}
}
/*
* Remove a buffer from a transaction list, given the transaction's list
* head pointer.
*
* Called with j_list_lock held, and the journal may not be locked.
*
* jbd_lock_bh_state(jh2bh(jh)) is held.
*/
static inline void
__blist_del_buffer(struct journal_head **list, struct journal_head *jh)
{
if (*list == jh) {
*list = jh->b_tnext;
if (*list == jh)
*list = NULL;
}
jh->b_tprev->b_tnext = jh->b_tnext;
jh->b_tnext->b_tprev = jh->b_tprev;
}
/*
* Remove a buffer from the appropriate transaction list.
*
* Note that this function can *change* the value of
* bh->b_transaction->t_buffers, t_forget, t_iobuf_list, t_shadow_list,
* t_log_list or t_reserved_list. If the caller is holding onto a copy of one
* of these pointers, it could go bad. Generally the caller needs to re-read
* the pointer from the transaction_t.
*
* Called under j_list_lock.
*/
static void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh)
{
struct journal_head **list = NULL;
transaction_t *transaction;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
transaction = jh->b_transaction;
if (transaction)
assert_spin_locked(&transaction->t_journal->j_list_lock);
J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
if (jh->b_jlist != BJ_None)
J_ASSERT_JH(jh, transaction != NULL);
switch (jh->b_jlist) {
case BJ_None:
return;
case BJ_Metadata:
transaction->t_nr_buffers--;
J_ASSERT_JH(jh, transaction->t_nr_buffers >= 0);
list = &transaction->t_buffers;
break;
case BJ_Forget:
list = &transaction->t_forget;
break;
case BJ_IO:
list = &transaction->t_iobuf_list;
break;
case BJ_Shadow:
list = &transaction->t_shadow_list;
break;
case BJ_LogCtl:
list = &transaction->t_log_list;
break;
case BJ_Reserved:
list = &transaction->t_reserved_list;
break;
}
__blist_del_buffer(list, jh);
jh->b_jlist = BJ_None;
if (test_clear_buffer_jbddirty(bh))
mark_buffer_dirty(bh); /* Expose it to the VM */
}
/*
* Remove buffer from all transactions.
*
* Called with bh_state lock and j_list_lock
*
* jh and bh may be already freed when this function returns.
*/
static void __jbd2_journal_unfile_buffer(struct journal_head *jh)
{
__jbd2_journal_temp_unlink_buffer(jh);
jh->b_transaction = NULL;
jbd2_journal_put_journal_head(jh);
}
void jbd2_journal_unfile_buffer(journal_t *journal, struct journal_head *jh)
{
struct buffer_head *bh = jh2bh(jh);
/* Get reference so that buffer cannot be freed before we unlock it */
get_bh(bh);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
__jbd2_journal_unfile_buffer(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
__brelse(bh);
}
/*
* Called from jbd2_journal_try_to_free_buffers().
*
* Called under jbd_lock_bh_state(bh)
*/
static void
__journal_try_to_free_buffer(journal_t *journal, struct buffer_head *bh)
{
struct journal_head *jh;
jh = bh2jh(bh);
if (buffer_locked(bh) || buffer_dirty(bh))
goto out;
if (jh->b_next_transaction != NULL)
goto out;
spin_lock(&journal->j_list_lock);
if (jh->b_cp_transaction != NULL && jh->b_transaction == NULL) {
/* written-back checkpointed metadata buffer */
JBUFFER_TRACE(jh, "remove from checkpoint list");
__jbd2_journal_remove_checkpoint(jh);
}
spin_unlock(&journal->j_list_lock);
out:
return;
}
/**
* int jbd2_journal_try_to_free_buffers() - try to free page buffers.
* @journal: journal for operation
* @page: to try and free
* @gfp_mask: we use the mask to detect how hard should we try to release
* buffers. If __GFP_WAIT and __GFP_FS is set, we wait for commit code to
* release the buffers.
*
*
* For all the buffers on this page,
* if they are fully written out ordered data, move them onto BUF_CLEAN
* so try_to_free_buffers() can reap them.
*
* This function returns non-zero if we wish try_to_free_buffers()
* to be called. We do this if the page is releasable by try_to_free_buffers().
* We also do it if the page has locked or dirty buffers and the caller wants
* us to perform sync or async writeout.
*
* This complicates JBD locking somewhat. We aren't protected by the
* BKL here. We wish to remove the buffer from its committing or
* running transaction's ->t_datalist via __jbd2_journal_unfile_buffer.
*
* This may *change* the value of transaction_t->t_datalist, so anyone
* who looks at t_datalist needs to lock against this function.
*
* Even worse, someone may be doing a jbd2_journal_dirty_data on this
* buffer. So we need to lock against that. jbd2_journal_dirty_data()
* will come out of the lock with the buffer dirty, which makes it
* ineligible for release here.
*
* Who else is affected by this? hmm... Really the only contender
* is do_get_write_access() - it could be looking at the buffer while
* journal_try_to_free_buffer() is changing its state. But that
* cannot happen because we never reallocate freed data as metadata
* while the data is part of a transaction. Yes?
*
* Return 0 on failure, 1 on success
*/
int jbd2_journal_try_to_free_buffers(journal_t *journal,
struct page *page, gfp_t gfp_mask)
{
struct buffer_head *head;
struct buffer_head *bh;
int ret = 0;
J_ASSERT(PageLocked(page));
head = page_buffers(page);
bh = head;
do {
struct journal_head *jh;
/*
* We take our own ref against the journal_head here to avoid
* having to add tons of locking around each instance of
* jbd2_journal_put_journal_head().
*/
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
continue;
jbd_lock_bh_state(bh);
__journal_try_to_free_buffer(journal, bh);
jbd2_journal_put_journal_head(jh);
jbd_unlock_bh_state(bh);
if (buffer_jbd(bh))
goto busy;
} while ((bh = bh->b_this_page) != head);
ret = try_to_free_buffers(page);
busy:
return ret;
}
/*
* This buffer is no longer needed. If it is on an older transaction's
* checkpoint list we need to record it on this transaction's forget list
* to pin this buffer (and hence its checkpointing transaction) down until
* this transaction commits. If the buffer isn't on a checkpoint list, we
* release it.
* Returns non-zero if JBD no longer has an interest in the buffer.
*
* Called under j_list_lock.
*
* Called under jbd_lock_bh_state(bh).
*/
static int __dispose_buffer(struct journal_head *jh, transaction_t *transaction)
{
int may_free = 1;
struct buffer_head *bh = jh2bh(jh);
if (jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "on running+cp transaction");
__jbd2_journal_temp_unlink_buffer(jh);
/*
* We don't want to write the buffer anymore, clear the
* bit so that we don't confuse checks in
* __journal_file_buffer
*/
clear_buffer_dirty(bh);
__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
may_free = 0;
} else {
JBUFFER_TRACE(jh, "on running transaction");
__jbd2_journal_unfile_buffer(jh);
}
return may_free;
}
/*
* jbd2_journal_invalidatepage
*
* This code is tricky. It has a number of cases to deal with.
*
* There are two invariants which this code relies on:
*
* i_size must be updated on disk before we start calling invalidatepage on the
* data.
*
* This is done in ext3 by defining an ext3_setattr method which
* updates i_size before truncate gets going. By maintaining this
* invariant, we can be sure that it is safe to throw away any buffers
* attached to the current transaction: once the transaction commits,
* we know that the data will not be needed.
*
* Note however that we can *not* throw away data belonging to the
* previous, committing transaction!
*
* Any disk blocks which *are* part of the previous, committing
* transaction (and which therefore cannot be discarded immediately) are
* not going to be reused in the new running transaction
*
* The bitmap committed_data images guarantee this: any block which is
* allocated in one transaction and removed in the next will be marked
* as in-use in the committed_data bitmap, so cannot be reused until
* the next transaction to delete the block commits. This means that
* leaving committing buffers dirty is quite safe: the disk blocks
* cannot be reallocated to a different file and so buffer aliasing is
* not possible.
*
*
* The above applies mainly to ordered data mode. In writeback mode we
* don't make guarantees about the order in which data hits disk --- in
* particular we don't guarantee that new dirty data is flushed before
* transaction commit --- so it is always safe just to discard data
* immediately in that mode. --sct
*/
/*
* The journal_unmap_buffer helper function returns zero if the buffer
* concerned remains pinned as an anonymous buffer belonging to an older
* transaction.
*
* We're outside-transaction here. Either or both of j_running_transaction
* and j_committing_transaction may be NULL.
*/
static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh,
int partial_page)
{
transaction_t *transaction;
struct journal_head *jh;
int may_free = 1;
BUFFER_TRACE(bh, "entry");
/*
* It is safe to proceed here without the j_list_lock because the
* buffers cannot be stolen by try_to_free_buffers as long as we are
* holding the page lock. --sct
*/
if (!buffer_jbd(bh))
goto zap_buffer_unlocked;
/* OK, we have data buffer in journaled mode */
write_lock(&journal->j_state_lock);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
goto zap_buffer_no_jh;
/*
* We cannot remove the buffer from checkpoint lists until the
* transaction adding inode to orphan list (let's call it T)
* is committed. Otherwise if the transaction changing the
* buffer would be cleaned from the journal before T is
* committed, a crash will cause that the correct contents of
* the buffer will be lost. On the other hand we have to
* clear the buffer dirty bit at latest at the moment when the
* transaction marking the buffer as freed in the filesystem
* structures is committed because from that moment on the
* block can be reallocated and used by a different page.
* Since the block hasn't been freed yet but the inode has
* already been added to orphan list, it is safe for us to add
* the buffer to BJ_Forget list of the newest transaction.
*
* Also we have to clear buffer_mapped flag of a truncated buffer
* because the buffer_head may be attached to the page straddling
* i_size (can happen only when blocksize < pagesize) and thus the
* buffer_head can be reused when the file is extended again. So we end
* up keeping around invalidated buffers attached to transactions'
* BJ_Forget list just to stop checkpointing code from cleaning up
* the transaction this buffer was modified in.
*/
transaction = jh->b_transaction;
if (transaction == NULL) {
/* First case: not on any transaction. If it
* has no checkpoint link, then we can zap it:
* it's a writeback-mode buffer so we don't care
* if it hits disk safely. */
if (!jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "not on any transaction: zap");
goto zap_buffer;
}
if (!buffer_dirty(bh)) {
/* bdflush has written it. We can drop it now */
goto zap_buffer;
}
/* OK, it must be in the journal but still not
* written fully to disk: it's metadata or
* journaled data... */
if (journal->j_running_transaction) {
/* ... and once the current transaction has
* committed, the buffer won't be needed any
* longer. */
JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
may_free = __dispose_buffer(jh,
journal->j_running_transaction);
goto zap_buffer;
} else {
/* There is no currently-running transaction. So the
* orphan record which we wrote for this file must have
* passed into commit. We must attach this buffer to
* the committing transaction, if it exists. */
if (journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "give to committing trans");
may_free = __dispose_buffer(jh,
journal->j_committing_transaction);
goto zap_buffer;
} else {
/* The orphan record's transaction has
* committed. We can cleanse this buffer */
clear_buffer_jbddirty(bh);
goto zap_buffer;
}
}
} else if (transaction == journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "on committing transaction");
/*
* The buffer is committing, we simply cannot touch
* it. If the page is straddling i_size we have to wait
* for commit and try again.
*/
if (partial_page) {
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return -EBUSY;
}
/*
* OK, buffer won't be reachable after truncate. We just set
* j_next_transaction to the running transaction (if there is
* one) and mark buffer as freed so that commit code knows it
* should clear dirty bits when it is done with the buffer.
*/
set_buffer_freed(bh);
if (journal->j_running_transaction && buffer_jbddirty(bh))
jh->b_next_transaction = journal->j_running_transaction;
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return 0;
} else {
/* Good, the buffer belongs to the running transaction.
* We are writing our own transaction's data, not any
* previous one's, so it is safe to throw it away
* (remember that we expect the filesystem to have set
* i_size already for this truncate so recovery will not
* expose the disk blocks we are discarding here.) */
J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
JBUFFER_TRACE(jh, "on running transaction");
may_free = __dispose_buffer(jh, transaction);
}
zap_buffer:
/*
* This is tricky. Although the buffer is truncated, it may be reused
* if blocksize < pagesize and it is attached to the page straddling
* EOF. Since the buffer might have been added to BJ_Forget list of the
* running transaction, journal_get_write_access() won't clear
* b_modified and credit accounting gets confused. So clear b_modified
* here.
*/
jh->b_modified = 0;
jbd2_journal_put_journal_head(jh);
zap_buffer_no_jh:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
zap_buffer_unlocked:
clear_buffer_dirty(bh);
J_ASSERT_BH(bh, !buffer_jbddirty(bh));
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
clear_buffer_delay(bh);
clear_buffer_unwritten(bh);
bh->b_bdev = NULL;
return may_free;
}
/**
* void jbd2_journal_invalidatepage()
* @journal: journal to use for flush...
* @page: page to flush
* @offset: length of page to invalidate.
*
* Reap page buffers containing data after offset in page. Can return -EBUSY
* if buffers are part of the committing transaction and the page is straddling
* i_size. Caller then has to wait for current commit and try again.
*/
int jbd2_journal_invalidatepage(journal_t *journal,
struct page *page,
unsigned long offset)
{
struct buffer_head *head, *bh, *next;
unsigned int curr_off = 0;
int may_free = 1;
int ret = 0;
if (!PageLocked(page))
BUG();
if (!page_has_buffers(page))
return 0;
/* We will potentially be playing with lists other than just the
* data lists (especially for journaled data mode), so be
* cautious in our locking. */
head = bh = page_buffers(page);
do {
unsigned int next_off = curr_off + bh->b_size;
next = bh->b_this_page;
if (offset <= curr_off) {
/* This block is wholly outside the truncation point */
lock_buffer(bh);
ret = journal_unmap_buffer(journal, bh, offset > 0);
unlock_buffer(bh);
if (ret < 0)
return ret;
may_free &= ret;
}
curr_off = next_off;
bh = next;
} while (bh != head);
if (!offset) {
if (may_free && try_to_free_buffers(page))
J_ASSERT(!page_has_buffers(page));
}
return 0;
}
/*
* File a buffer on the given transaction list.
*/
void __jbd2_journal_file_buffer(struct journal_head *jh,
transaction_t *transaction, int jlist)
{
struct journal_head **list = NULL;
int was_dirty = 0;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
assert_spin_locked(&transaction->t_journal->j_list_lock);
J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
J_ASSERT_JH(jh, jh->b_transaction == transaction ||
jh->b_transaction == NULL);
if (jh->b_transaction && jh->b_jlist == jlist)
return;
if (jlist == BJ_Metadata || jlist == BJ_Reserved ||
jlist == BJ_Shadow || jlist == BJ_Forget) {
/*
* For metadata buffers, we track dirty bit in buffer_jbddirty
* instead of buffer_dirty. We should not see a dirty bit set
* here because we clear it in do_get_write_access but e.g.
* tune2fs can modify the sb and set the dirty bit at any time
* so we try to gracefully handle that.
*/
if (buffer_dirty(bh))
warn_dirty_buffer(bh);
if (test_clear_buffer_dirty(bh) ||
test_clear_buffer_jbddirty(bh))
was_dirty = 1;
}
if (jh->b_transaction)
__jbd2_journal_temp_unlink_buffer(jh);
else
jbd2_journal_grab_journal_head(bh);
jh->b_transaction = transaction;
switch (jlist) {
case BJ_None:
J_ASSERT_JH(jh, !jh->b_committed_data);
J_ASSERT_JH(jh, !jh->b_frozen_data);
return;
case BJ_Metadata:
transaction->t_nr_buffers++;
list = &transaction->t_buffers;
break;
case BJ_Forget:
list = &transaction->t_forget;
break;
case BJ_IO:
list = &transaction->t_iobuf_list;
break;
case BJ_Shadow:
list = &transaction->t_shadow_list;
break;
case BJ_LogCtl:
list = &transaction->t_log_list;
break;
case BJ_Reserved:
list = &transaction->t_reserved_list;
break;
}
__blist_add_buffer(list, jh);
jh->b_jlist = jlist;
if (was_dirty)
set_buffer_jbddirty(bh);
}
void jbd2_journal_file_buffer(struct journal_head *jh,
transaction_t *transaction, int jlist)
{
jbd_lock_bh_state(jh2bh(jh));
spin_lock(&transaction->t_journal->j_list_lock);
__jbd2_journal_file_buffer(jh, transaction, jlist);
spin_unlock(&transaction->t_journal->j_list_lock);
jbd_unlock_bh_state(jh2bh(jh));
}
/*
* Remove a buffer from its current buffer list in preparation for
* dropping it from its current transaction entirely. If the buffer has
* already started to be used by a subsequent transaction, refile the
* buffer on that transaction's metadata list.
*
* Called under j_list_lock
* Called under jbd_lock_bh_state(jh2bh(jh))
*
* jh and bh may be already free when this function returns
*/
void __jbd2_journal_refile_buffer(struct journal_head *jh)
{
int was_dirty, jlist;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
if (jh->b_transaction)
assert_spin_locked(&jh->b_transaction->t_journal->j_list_lock);
/* If the buffer is now unused, just drop it. */
if (jh->b_next_transaction == NULL) {
__jbd2_journal_unfile_buffer(jh);
return;
}
/*
* It has been modified by a later transaction: add it to the new
* transaction's metadata list.
*/
was_dirty = test_clear_buffer_jbddirty(bh);
__jbd2_journal_temp_unlink_buffer(jh);
/*
* We set b_transaction here because b_next_transaction will inherit
* our jh reference and thus __jbd2_journal_file_buffer() must not
* take a new one.
*/
jh->b_transaction = jh->b_next_transaction;
jh->b_next_transaction = NULL;
if (buffer_freed(bh))
jlist = BJ_Forget;
else if (jh->b_modified)
jlist = BJ_Metadata;
else
jlist = BJ_Reserved;
__jbd2_journal_file_buffer(jh, jh->b_transaction, jlist);
J_ASSERT_JH(jh, jh->b_transaction->t_state == T_RUNNING);
if (was_dirty)
set_buffer_jbddirty(bh);
}
/*
* __jbd2_journal_refile_buffer() with necessary locking added. We take our
* bh reference so that we can safely unlock bh.
*
* The jh and bh may be freed by this call.
*/
void jbd2_journal_refile_buffer(journal_t *journal, struct journal_head *jh)
{
struct buffer_head *bh = jh2bh(jh);
/* Get reference so that buffer cannot be freed before we unlock it */
get_bh(bh);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
__jbd2_journal_refile_buffer(jh);
jbd_unlock_bh_state(bh);
spin_unlock(&journal->j_list_lock);
__brelse(bh);
}
/*
* File inode in the inode list of the handle's transaction
*/
int jbd2_journal_file_inode(handle_t *handle, struct jbd2_inode *jinode)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
if (is_handle_aborted(handle))
return -EIO;
jbd_debug(4, "Adding inode %lu, tid:%d\n", jinode->i_vfs_inode->i_ino,
transaction->t_tid);
/*
* First check whether inode isn't already on the transaction's
* lists without taking the lock. Note that this check is safe
* without the lock as we cannot race with somebody removing inode
* from the transaction. The reason is that we remove inode from the
* transaction only in journal_release_jbd_inode() and when we commit
* the transaction. We are guarded from the first case by holding
* a reference to the inode. We are safe against the second case
* because if jinode->i_transaction == transaction, commit code
* cannot touch the transaction because we hold reference to it,
* and if jinode->i_next_transaction == transaction, commit code
* will only file the inode where we want it.
*/
if (jinode->i_transaction == transaction ||
jinode->i_next_transaction == transaction)
return 0;
spin_lock(&journal->j_list_lock);
if (jinode->i_transaction == transaction ||
jinode->i_next_transaction == transaction)
goto done;
/*
* We only ever set this variable to 1 so the test is safe. Since
* t_need_data_flush is likely to be set, we do the test to save some
* cacheline bouncing
*/
if (!transaction->t_need_data_flush)
transaction->t_need_data_flush = 1;
/* On some different transaction's list - should be
* the committing one */
if (jinode->i_transaction) {
J_ASSERT(jinode->i_next_transaction == NULL);
J_ASSERT(jinode->i_transaction ==
journal->j_committing_transaction);
jinode->i_next_transaction = transaction;
goto done;
}
/* Not on any transaction list... */
J_ASSERT(!jinode->i_next_transaction);
jinode->i_transaction = transaction;
list_add(&jinode->i_list, &transaction->t_inode_list);
done:
spin_unlock(&journal->j_list_lock);
return 0;
}
/*
* File truncate and transaction commit interact with each other in a
* non-trivial way. If a transaction writing data block A is
* committing, we cannot discard the data by truncate until we have
* written them. Otherwise if we crashed after the transaction with
* write has committed but before the transaction with truncate has
* committed, we could see stale data in block A. This function is a
* helper to solve this problem. It starts writeout of the truncated
* part in case it is in the committing transaction.
*
* Filesystem code must call this function when inode is journaled in
* ordered mode before truncation happens and after the inode has been
* placed on orphan list with the new inode size. The second condition
* avoids the race that someone writes new data and we start
* committing the transaction after this function has been called but
* before a transaction for truncate is started (and furthermore it
* allows us to optimize the case where the addition to orphan list
* happens in the same transaction as write --- we don't have to write
* any data in such case).
*/
int jbd2_journal_begin_ordered_truncate(journal_t *journal,
struct jbd2_inode *jinode,
loff_t new_size)
{
transaction_t *inode_trans, *commit_trans;
int ret = 0;
/* This is a quick check to avoid locking if not necessary */
if (!jinode->i_transaction)
goto out;
/* Locks are here just to force reading of recent values, it is
* enough that the transaction was not committing before we started
* a transaction adding the inode to orphan list */
read_lock(&journal->j_state_lock);
commit_trans = journal->j_committing_transaction;
read_unlock(&journal->j_state_lock);
spin_lock(&journal->j_list_lock);
inode_trans = jinode->i_transaction;
spin_unlock(&journal->j_list_lock);
if (inode_trans == commit_trans) {
ret = filemap_fdatawrite_range(jinode->i_vfs_inode->i_mapping,
new_size, LLONG_MAX);
if (ret)
jbd2_journal_abort(journal, ret);
}
out:
return ret;
}
| gpl-2.0 |
pershoot/gtab-2632 | drivers/hwmon/dme1737.c | 505 | 75410 | /*
* dme1737.c - Driver for the SMSC DME1737, Asus A8000, SMSC SCH311x and
* SCH5027 Super-I/O chips integrated hardware monitoring features.
* Copyright (c) 2007, 2008 Juerg Haefliger <juergh@gmail.com>
*
* This driver is an I2C/ISA hybrid, meaning that it uses the I2C bus to access
* the chip registers if a DME1737, A8000, or SCH5027 is found and the ISA bus
* if a SCH311x chip is found. Both types of chips have very similar hardware
* monitoring capabilities but differ in the way they can be accessed.
*
* 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/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/acpi.h>
#include <linux/io.h>
/* ISA device, if found */
static struct platform_device *pdev;
/* Module load parameters */
static int force_start;
module_param(force_start, bool, 0);
MODULE_PARM_DESC(force_start, "Force the chip to start monitoring inputs");
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
static int probe_all_addr;
module_param(probe_all_addr, bool, 0);
MODULE_PARM_DESC(probe_all_addr, "Include probing of non-standard LPC "
"addresses");
/* Addresses to scan */
static const unsigned short normal_i2c[] = {0x2c, 0x2d, 0x2e, I2C_CLIENT_END};
/* Insmod parameters */
I2C_CLIENT_INSMOD_2(dme1737, sch5027);
/* ISA chip types */
enum isa_chips { sch311x = sch5027 + 1 };
/* ---------------------------------------------------------------------
* Registers
*
* The sensors are defined as follows:
*
* Voltages Temperatures
* -------- ------------
* in0 +5VTR (+5V stdby) temp1 Remote diode 1
* in1 Vccp (proc core) temp2 Internal temp
* in2 VCC (internal +3.3V) temp3 Remote diode 2
* in3 +5V
* in4 +12V
* in5 VTR (+3.3V stby)
* in6 Vbat
*
* --------------------------------------------------------------------- */
/* Voltages (in) numbered 0-6 (ix) */
#define DME1737_REG_IN(ix) ((ix) < 5 ? 0x20 + (ix) \
: 0x94 + (ix))
#define DME1737_REG_IN_MIN(ix) ((ix) < 5 ? 0x44 + (ix) * 2 \
: 0x91 + (ix) * 2)
#define DME1737_REG_IN_MAX(ix) ((ix) < 5 ? 0x45 + (ix) * 2 \
: 0x92 + (ix) * 2)
/* Temperatures (temp) numbered 0-2 (ix) */
#define DME1737_REG_TEMP(ix) (0x25 + (ix))
#define DME1737_REG_TEMP_MIN(ix) (0x4e + (ix) * 2)
#define DME1737_REG_TEMP_MAX(ix) (0x4f + (ix) * 2)
#define DME1737_REG_TEMP_OFFSET(ix) ((ix) == 0 ? 0x1f \
: 0x1c + (ix))
/* Voltage and temperature LSBs
* The LSBs (4 bits each) are stored in 5 registers with the following layouts:
* IN_TEMP_LSB(0) = [in5, in6]
* IN_TEMP_LSB(1) = [temp3, temp1]
* IN_TEMP_LSB(2) = [in4, temp2]
* IN_TEMP_LSB(3) = [in3, in0]
* IN_TEMP_LSB(4) = [in2, in1] */
#define DME1737_REG_IN_TEMP_LSB(ix) (0x84 + (ix))
static const u8 DME1737_REG_IN_LSB[] = {3, 4, 4, 3, 2, 0, 0};
static const u8 DME1737_REG_IN_LSB_SHL[] = {4, 4, 0, 0, 0, 0, 4};
static const u8 DME1737_REG_TEMP_LSB[] = {1, 2, 1};
static const u8 DME1737_REG_TEMP_LSB_SHL[] = {4, 4, 0};
/* Fans numbered 0-5 (ix) */
#define DME1737_REG_FAN(ix) ((ix) < 4 ? 0x28 + (ix) * 2 \
: 0xa1 + (ix) * 2)
#define DME1737_REG_FAN_MIN(ix) ((ix) < 4 ? 0x54 + (ix) * 2 \
: 0xa5 + (ix) * 2)
#define DME1737_REG_FAN_OPT(ix) ((ix) < 4 ? 0x90 + (ix) \
: 0xb2 + (ix))
#define DME1737_REG_FAN_MAX(ix) (0xb4 + (ix)) /* only for fan[4-5] */
/* PWMs numbered 0-2, 4-5 (ix) */
#define DME1737_REG_PWM(ix) ((ix) < 3 ? 0x30 + (ix) \
: 0xa1 + (ix))
#define DME1737_REG_PWM_CONFIG(ix) (0x5c + (ix)) /* only for pwm[0-2] */
#define DME1737_REG_PWM_MIN(ix) (0x64 + (ix)) /* only for pwm[0-2] */
#define DME1737_REG_PWM_FREQ(ix) ((ix) < 3 ? 0x5f + (ix) \
: 0xa3 + (ix))
/* The layout of the ramp rate registers is different from the other pwm
* registers. The bits for the 3 PWMs are stored in 2 registers:
* PWM_RR(0) = [OFF3, OFF2, OFF1, RES, RR1E, RR1-2, RR1-1, RR1-0]
* PWM_RR(1) = [RR2E, RR2-2, RR2-1, RR2-0, RR3E, RR3-2, RR3-1, RR3-0] */
#define DME1737_REG_PWM_RR(ix) (0x62 + (ix)) /* only for pwm[0-2] */
/* Thermal zones 0-2 */
#define DME1737_REG_ZONE_LOW(ix) (0x67 + (ix))
#define DME1737_REG_ZONE_ABS(ix) (0x6a + (ix))
/* The layout of the hysteresis registers is different from the other zone
* registers. The bits for the 3 zones are stored in 2 registers:
* ZONE_HYST(0) = [H1-3, H1-2, H1-1, H1-0, H2-3, H2-2, H2-1, H2-0]
* ZONE_HYST(1) = [H3-3, H3-2, H3-1, H3-0, RES, RES, RES, RES] */
#define DME1737_REG_ZONE_HYST(ix) (0x6d + (ix))
/* Alarm registers and bit mapping
* The 3 8-bit alarm registers will be concatenated to a single 32-bit
* alarm value [0, ALARM3, ALARM2, ALARM1]. */
#define DME1737_REG_ALARM1 0x41
#define DME1737_REG_ALARM2 0x42
#define DME1737_REG_ALARM3 0x83
static const u8 DME1737_BIT_ALARM_IN[] = {0, 1, 2, 3, 8, 16, 17};
static const u8 DME1737_BIT_ALARM_TEMP[] = {4, 5, 6};
static const u8 DME1737_BIT_ALARM_FAN[] = {10, 11, 12, 13, 22, 23};
/* Miscellaneous registers */
#define DME1737_REG_DEVICE 0x3d
#define DME1737_REG_COMPANY 0x3e
#define DME1737_REG_VERSTEP 0x3f
#define DME1737_REG_CONFIG 0x40
#define DME1737_REG_CONFIG2 0x7f
#define DME1737_REG_VID 0x43
#define DME1737_REG_TACH_PWM 0x81
/* ---------------------------------------------------------------------
* Misc defines
* --------------------------------------------------------------------- */
/* Chip identification */
#define DME1737_COMPANY_SMSC 0x5c
#define DME1737_VERSTEP 0x88
#define DME1737_VERSTEP_MASK 0xf8
#define SCH311X_DEVICE 0x8c
#define SCH5027_VERSTEP 0x69
/* Length of ISA address segment */
#define DME1737_EXTENT 2
/* ---------------------------------------------------------------------
* Data structures and manipulation thereof
* --------------------------------------------------------------------- */
struct dme1737_data {
struct i2c_client *client; /* for I2C devices only */
struct device *hwmon_dev;
const char *name;
unsigned int addr; /* for ISA devices only */
struct mutex update_lock;
int valid; /* !=0 if following fields are valid */
unsigned long last_update; /* in jiffies */
unsigned long last_vbat; /* in jiffies */
enum chips type;
const int *in_nominal; /* pointer to IN_NOMINAL array */
u8 vid;
u8 pwm_rr_en;
u8 has_pwm;
u8 has_fan;
/* Register values */
u16 in[7];
u8 in_min[7];
u8 in_max[7];
s16 temp[3];
s8 temp_min[3];
s8 temp_max[3];
s8 temp_offset[3];
u8 config;
u8 config2;
u8 vrm;
u16 fan[6];
u16 fan_min[6];
u8 fan_max[2];
u8 fan_opt[6];
u8 pwm[6];
u8 pwm_min[3];
u8 pwm_config[3];
u8 pwm_acz[3];
u8 pwm_freq[6];
u8 pwm_rr[2];
u8 zone_low[3];
u8 zone_abs[3];
u8 zone_hyst[2];
u32 alarms;
};
/* Nominal voltage values */
static const int IN_NOMINAL_DME1737[] = {5000, 2250, 3300, 5000, 12000, 3300,
3300};
static const int IN_NOMINAL_SCH311x[] = {2500, 1500, 3300, 5000, 12000, 3300,
3300};
static const int IN_NOMINAL_SCH5027[] = {5000, 2250, 3300, 1125, 1125, 3300,
3300};
#define IN_NOMINAL(type) ((type) == sch311x ? IN_NOMINAL_SCH311x : \
(type) == sch5027 ? IN_NOMINAL_SCH5027 : \
IN_NOMINAL_DME1737)
/* Voltage input
* Voltage inputs have 16 bits resolution, limit values have 8 bits
* resolution. */
static inline int IN_FROM_REG(int reg, int nominal, int res)
{
return (reg * nominal + (3 << (res - 3))) / (3 << (res - 2));
}
static inline int IN_TO_REG(int val, int nominal)
{
return SENSORS_LIMIT((val * 192 + nominal / 2) / nominal, 0, 255);
}
/* Temperature input
* The register values represent temperatures in 2's complement notation from
* -127 degrees C to +127 degrees C. Temp inputs have 16 bits resolution, limit
* values have 8 bits resolution. */
static inline int TEMP_FROM_REG(int reg, int res)
{
return (reg * 1000) >> (res - 8);
}
static inline int TEMP_TO_REG(int val)
{
return SENSORS_LIMIT((val < 0 ? val - 500 : val + 500) / 1000,
-128, 127);
}
/* Temperature range */
static const int TEMP_RANGE[] = {2000, 2500, 3333, 4000, 5000, 6666, 8000,
10000, 13333, 16000, 20000, 26666, 32000,
40000, 53333, 80000};
static inline int TEMP_RANGE_FROM_REG(int reg)
{
return TEMP_RANGE[(reg >> 4) & 0x0f];
}
static int TEMP_RANGE_TO_REG(int val, int reg)
{
int i;
for (i = 15; i > 0; i--) {
if (val > (TEMP_RANGE[i] + TEMP_RANGE[i - 1] + 1) / 2) {
break;
}
}
return (reg & 0x0f) | (i << 4);
}
/* Temperature hysteresis
* Register layout:
* reg[0] = [H1-3, H1-2, H1-1, H1-0, H2-3, H2-2, H2-1, H2-0]
* reg[1] = [H3-3, H3-2, H3-1, H3-0, xxxx, xxxx, xxxx, xxxx] */
static inline int TEMP_HYST_FROM_REG(int reg, int ix)
{
return (((ix == 1) ? reg : reg >> 4) & 0x0f) * 1000;
}
static inline int TEMP_HYST_TO_REG(int val, int ix, int reg)
{
int hyst = SENSORS_LIMIT((val + 500) / 1000, 0, 15);
return (ix == 1) ? (reg & 0xf0) | hyst : (reg & 0x0f) | (hyst << 4);
}
/* Fan input RPM */
static inline int FAN_FROM_REG(int reg, int tpc)
{
if (tpc) {
return tpc * reg;
} else {
return (reg == 0 || reg == 0xffff) ? 0 : 90000 * 60 / reg;
}
}
static inline int FAN_TO_REG(int val, int tpc)
{
if (tpc) {
return SENSORS_LIMIT(val / tpc, 0, 0xffff);
} else {
return (val <= 0) ? 0xffff :
SENSORS_LIMIT(90000 * 60 / val, 0, 0xfffe);
}
}
/* Fan TPC (tach pulse count)
* Converts a register value to a TPC multiplier or returns 0 if the tachometer
* is configured in legacy (non-tpc) mode */
static inline int FAN_TPC_FROM_REG(int reg)
{
return (reg & 0x20) ? 0 : 60 >> (reg & 0x03);
}
/* Fan type
* The type of a fan is expressed in number of pulses-per-revolution that it
* emits */
static inline int FAN_TYPE_FROM_REG(int reg)
{
int edge = (reg >> 1) & 0x03;
return (edge > 0) ? 1 << (edge - 1) : 0;
}
static inline int FAN_TYPE_TO_REG(int val, int reg)
{
int edge = (val == 4) ? 3 : val;
return (reg & 0xf9) | (edge << 1);
}
/* Fan max RPM */
static const int FAN_MAX[] = {0x54, 0x38, 0x2a, 0x21, 0x1c, 0x18, 0x15, 0x12,
0x11, 0x0f, 0x0e};
static int FAN_MAX_FROM_REG(int reg)
{
int i;
for (i = 10; i > 0; i--) {
if (reg == FAN_MAX[i]) {
break;
}
}
return 1000 + i * 500;
}
static int FAN_MAX_TO_REG(int val)
{
int i;
for (i = 10; i > 0; i--) {
if (val > (1000 + (i - 1) * 500)) {
break;
}
}
return FAN_MAX[i];
}
/* PWM enable
* Register to enable mapping:
* 000: 2 fan on zone 1 auto
* 001: 2 fan on zone 2 auto
* 010: 2 fan on zone 3 auto
* 011: 0 fan full on
* 100: -1 fan disabled
* 101: 2 fan on hottest of zones 2,3 auto
* 110: 2 fan on hottest of zones 1,2,3 auto
* 111: 1 fan in manual mode */
static inline int PWM_EN_FROM_REG(int reg)
{
static const int en[] = {2, 2, 2, 0, -1, 2, 2, 1};
return en[(reg >> 5) & 0x07];
}
static inline int PWM_EN_TO_REG(int val, int reg)
{
int en = (val == 1) ? 7 : 3;
return (reg & 0x1f) | ((en & 0x07) << 5);
}
/* PWM auto channels zone
* Register to auto channels zone mapping (ACZ is a bitfield with bit x
* corresponding to zone x+1):
* 000: 001 fan on zone 1 auto
* 001: 010 fan on zone 2 auto
* 010: 100 fan on zone 3 auto
* 011: 000 fan full on
* 100: 000 fan disabled
* 101: 110 fan on hottest of zones 2,3 auto
* 110: 111 fan on hottest of zones 1,2,3 auto
* 111: 000 fan in manual mode */
static inline int PWM_ACZ_FROM_REG(int reg)
{
static const int acz[] = {1, 2, 4, 0, 0, 6, 7, 0};
return acz[(reg >> 5) & 0x07];
}
static inline int PWM_ACZ_TO_REG(int val, int reg)
{
int acz = (val == 4) ? 2 : val - 1;
return (reg & 0x1f) | ((acz & 0x07) << 5);
}
/* PWM frequency */
static const int PWM_FREQ[] = {11, 15, 22, 29, 35, 44, 59, 88,
15000, 20000, 30000, 25000, 0, 0, 0, 0};
static inline int PWM_FREQ_FROM_REG(int reg)
{
return PWM_FREQ[reg & 0x0f];
}
static int PWM_FREQ_TO_REG(int val, int reg)
{
int i;
/* the first two cases are special - stupid chip design! */
if (val > 27500) {
i = 10;
} else if (val > 22500) {
i = 11;
} else {
for (i = 9; i > 0; i--) {
if (val > (PWM_FREQ[i] + PWM_FREQ[i - 1] + 1) / 2) {
break;
}
}
}
return (reg & 0xf0) | i;
}
/* PWM ramp rate
* Register layout:
* reg[0] = [OFF3, OFF2, OFF1, RES, RR1-E, RR1-2, RR1-1, RR1-0]
* reg[1] = [RR2-E, RR2-2, RR2-1, RR2-0, RR3-E, RR3-2, RR3-1, RR3-0] */
static const u8 PWM_RR[] = {206, 104, 69, 41, 26, 18, 10, 5};
static inline int PWM_RR_FROM_REG(int reg, int ix)
{
int rr = (ix == 1) ? reg >> 4 : reg;
return (rr & 0x08) ? PWM_RR[rr & 0x07] : 0;
}
static int PWM_RR_TO_REG(int val, int ix, int reg)
{
int i;
for (i = 0; i < 7; i++) {
if (val > (PWM_RR[i] + PWM_RR[i + 1] + 1) / 2) {
break;
}
}
return (ix == 1) ? (reg & 0x8f) | (i << 4) : (reg & 0xf8) | i;
}
/* PWM ramp rate enable */
static inline int PWM_RR_EN_FROM_REG(int reg, int ix)
{
return PWM_RR_FROM_REG(reg, ix) ? 1 : 0;
}
static inline int PWM_RR_EN_TO_REG(int val, int ix, int reg)
{
int en = (ix == 1) ? 0x80 : 0x08;
return val ? reg | en : reg & ~en;
}
/* PWM min/off
* The PWM min/off bits are part of the PMW ramp rate register 0 (see above for
* the register layout). */
static inline int PWM_OFF_FROM_REG(int reg, int ix)
{
return (reg >> (ix + 5)) & 0x01;
}
static inline int PWM_OFF_TO_REG(int val, int ix, int reg)
{
return (reg & ~(1 << (ix + 5))) | ((val & 0x01) << (ix + 5));
}
/* ---------------------------------------------------------------------
* Device I/O access
*
* ISA access is performed through an index/data register pair and needs to
* be protected by a mutex during runtime (not required for initialization).
* We use data->update_lock for this and need to ensure that we acquire it
* before calling dme1737_read or dme1737_write.
* --------------------------------------------------------------------- */
static u8 dme1737_read(const struct dme1737_data *data, u8 reg)
{
struct i2c_client *client = data->client;
s32 val;
if (client) { /* I2C device */
val = i2c_smbus_read_byte_data(client, reg);
if (val < 0) {
dev_warn(&client->dev, "Read from register "
"0x%02x failed! Please report to the driver "
"maintainer.\n", reg);
}
} else { /* ISA device */
outb(reg, data->addr);
val = inb(data->addr + 1);
}
return val;
}
static s32 dme1737_write(const struct dme1737_data *data, u8 reg, u8 val)
{
struct i2c_client *client = data->client;
s32 res = 0;
if (client) { /* I2C device */
res = i2c_smbus_write_byte_data(client, reg, val);
if (res < 0) {
dev_warn(&client->dev, "Write to register "
"0x%02x failed! Please report to the driver "
"maintainer.\n", reg);
}
} else { /* ISA device */
outb(reg, data->addr);
outb(val, data->addr + 1);
}
return res;
}
static struct dme1737_data *dme1737_update_device(struct device *dev)
{
struct dme1737_data *data = dev_get_drvdata(dev);
int ix;
u8 lsb[5];
mutex_lock(&data->update_lock);
/* Enable a Vbat monitoring cycle every 10 mins */
if (time_after(jiffies, data->last_vbat + 600 * HZ) || !data->valid) {
dme1737_write(data, DME1737_REG_CONFIG, dme1737_read(data,
DME1737_REG_CONFIG) | 0x10);
data->last_vbat = jiffies;
}
/* Sample register contents every 1 sec */
if (time_after(jiffies, data->last_update + HZ) || !data->valid) {
if (data->type == dme1737) {
data->vid = dme1737_read(data, DME1737_REG_VID) &
0x3f;
}
/* In (voltage) registers */
for (ix = 0; ix < ARRAY_SIZE(data->in); ix++) {
/* Voltage inputs are stored as 16 bit values even
* though they have only 12 bits resolution. This is
* to make it consistent with the temp inputs. */
data->in[ix] = dme1737_read(data,
DME1737_REG_IN(ix)) << 8;
data->in_min[ix] = dme1737_read(data,
DME1737_REG_IN_MIN(ix));
data->in_max[ix] = dme1737_read(data,
DME1737_REG_IN_MAX(ix));
}
/* Temp registers */
for (ix = 0; ix < ARRAY_SIZE(data->temp); ix++) {
/* Temp inputs are stored as 16 bit values even
* though they have only 12 bits resolution. This is
* to take advantage of implicit conversions between
* register values (2's complement) and temp values
* (signed decimal). */
data->temp[ix] = dme1737_read(data,
DME1737_REG_TEMP(ix)) << 8;
data->temp_min[ix] = dme1737_read(data,
DME1737_REG_TEMP_MIN(ix));
data->temp_max[ix] = dme1737_read(data,
DME1737_REG_TEMP_MAX(ix));
if (data->type != sch5027) {
data->temp_offset[ix] = dme1737_read(data,
DME1737_REG_TEMP_OFFSET(ix));
}
}
/* In and temp LSB registers
* The LSBs are latched when the MSBs are read, so the order in
* which the registers are read (MSB first, then LSB) is
* important! */
for (ix = 0; ix < ARRAY_SIZE(lsb); ix++) {
lsb[ix] = dme1737_read(data,
DME1737_REG_IN_TEMP_LSB(ix));
}
for (ix = 0; ix < ARRAY_SIZE(data->in); ix++) {
data->in[ix] |= (lsb[DME1737_REG_IN_LSB[ix]] <<
DME1737_REG_IN_LSB_SHL[ix]) & 0xf0;
}
for (ix = 0; ix < ARRAY_SIZE(data->temp); ix++) {
data->temp[ix] |= (lsb[DME1737_REG_TEMP_LSB[ix]] <<
DME1737_REG_TEMP_LSB_SHL[ix]) & 0xf0;
}
/* Fan registers */
for (ix = 0; ix < ARRAY_SIZE(data->fan); ix++) {
/* Skip reading registers if optional fans are not
* present */
if (!(data->has_fan & (1 << ix))) {
continue;
}
data->fan[ix] = dme1737_read(data,
DME1737_REG_FAN(ix));
data->fan[ix] |= dme1737_read(data,
DME1737_REG_FAN(ix) + 1) << 8;
data->fan_min[ix] = dme1737_read(data,
DME1737_REG_FAN_MIN(ix));
data->fan_min[ix] |= dme1737_read(data,
DME1737_REG_FAN_MIN(ix) + 1) << 8;
data->fan_opt[ix] = dme1737_read(data,
DME1737_REG_FAN_OPT(ix));
/* fan_max exists only for fan[5-6] */
if (ix > 3) {
data->fan_max[ix - 4] = dme1737_read(data,
DME1737_REG_FAN_MAX(ix));
}
}
/* PWM registers */
for (ix = 0; ix < ARRAY_SIZE(data->pwm); ix++) {
/* Skip reading registers if optional PWMs are not
* present */
if (!(data->has_pwm & (1 << ix))) {
continue;
}
data->pwm[ix] = dme1737_read(data,
DME1737_REG_PWM(ix));
data->pwm_freq[ix] = dme1737_read(data,
DME1737_REG_PWM_FREQ(ix));
/* pwm_config and pwm_min exist only for pwm[1-3] */
if (ix < 3) {
data->pwm_config[ix] = dme1737_read(data,
DME1737_REG_PWM_CONFIG(ix));
data->pwm_min[ix] = dme1737_read(data,
DME1737_REG_PWM_MIN(ix));
}
}
for (ix = 0; ix < ARRAY_SIZE(data->pwm_rr); ix++) {
data->pwm_rr[ix] = dme1737_read(data,
DME1737_REG_PWM_RR(ix));
}
/* Thermal zone registers */
for (ix = 0; ix < ARRAY_SIZE(data->zone_low); ix++) {
data->zone_low[ix] = dme1737_read(data,
DME1737_REG_ZONE_LOW(ix));
data->zone_abs[ix] = dme1737_read(data,
DME1737_REG_ZONE_ABS(ix));
}
if (data->type != sch5027) {
for (ix = 0; ix < ARRAY_SIZE(data->zone_hyst); ix++) {
data->zone_hyst[ix] = dme1737_read(data,
DME1737_REG_ZONE_HYST(ix));
}
}
/* Alarm registers */
data->alarms = dme1737_read(data,
DME1737_REG_ALARM1);
/* Bit 7 tells us if the other alarm registers are non-zero and
* therefore also need to be read */
if (data->alarms & 0x80) {
data->alarms |= dme1737_read(data,
DME1737_REG_ALARM2) << 8;
data->alarms |= dme1737_read(data,
DME1737_REG_ALARM3) << 16;
}
/* The ISA chips require explicit clearing of alarm bits.
* Don't worry, an alarm will come back if the condition
* that causes it still exists */
if (!data->client) {
if (data->alarms & 0xff0000) {
dme1737_write(data, DME1737_REG_ALARM3,
0xff);
}
if (data->alarms & 0xff00) {
dme1737_write(data, DME1737_REG_ALARM2,
0xff);
}
if (data->alarms & 0xff) {
dme1737_write(data, DME1737_REG_ALARM1,
0xff);
}
}
data->last_update = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
/* ---------------------------------------------------------------------
* Voltage sysfs attributes
* ix = [0-5]
* --------------------------------------------------------------------- */
#define SYS_IN_INPUT 0
#define SYS_IN_MIN 1
#define SYS_IN_MAX 2
#define SYS_IN_ALARM 3
static ssize_t show_in(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dme1737_update_device(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
int res;
switch (fn) {
case SYS_IN_INPUT:
res = IN_FROM_REG(data->in[ix], data->in_nominal[ix], 16);
break;
case SYS_IN_MIN:
res = IN_FROM_REG(data->in_min[ix], data->in_nominal[ix], 8);
break;
case SYS_IN_MAX:
res = IN_FROM_REG(data->in_max[ix], data->in_nominal[ix], 8);
break;
case SYS_IN_ALARM:
res = (data->alarms >> DME1737_BIT_ALARM_IN[ix]) & 0x01;
break;
default:
res = 0;
dev_dbg(dev, "Unknown function %d.\n", fn);
}
return sprintf(buf, "%d\n", res);
}
static ssize_t set_in(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct dme1737_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
switch (fn) {
case SYS_IN_MIN:
data->in_min[ix] = IN_TO_REG(val, data->in_nominal[ix]);
dme1737_write(data, DME1737_REG_IN_MIN(ix),
data->in_min[ix]);
break;
case SYS_IN_MAX:
data->in_max[ix] = IN_TO_REG(val, data->in_nominal[ix]);
dme1737_write(data, DME1737_REG_IN_MAX(ix),
data->in_max[ix]);
break;
default:
dev_dbg(dev, "Unknown function %d.\n", fn);
}
mutex_unlock(&data->update_lock);
return count;
}
/* ---------------------------------------------------------------------
* Temperature sysfs attributes
* ix = [0-2]
* --------------------------------------------------------------------- */
#define SYS_TEMP_INPUT 0
#define SYS_TEMP_MIN 1
#define SYS_TEMP_MAX 2
#define SYS_TEMP_OFFSET 3
#define SYS_TEMP_ALARM 4
#define SYS_TEMP_FAULT 5
static ssize_t show_temp(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dme1737_update_device(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
int res;
switch (fn) {
case SYS_TEMP_INPUT:
res = TEMP_FROM_REG(data->temp[ix], 16);
break;
case SYS_TEMP_MIN:
res = TEMP_FROM_REG(data->temp_min[ix], 8);
break;
case SYS_TEMP_MAX:
res = TEMP_FROM_REG(data->temp_max[ix], 8);
break;
case SYS_TEMP_OFFSET:
res = TEMP_FROM_REG(data->temp_offset[ix], 8);
break;
case SYS_TEMP_ALARM:
res = (data->alarms >> DME1737_BIT_ALARM_TEMP[ix]) & 0x01;
break;
case SYS_TEMP_FAULT:
res = (((u16)data->temp[ix] & 0xff00) == 0x8000);
break;
default:
res = 0;
dev_dbg(dev, "Unknown function %d.\n", fn);
}
return sprintf(buf, "%d\n", res);
}
static ssize_t set_temp(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct dme1737_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
switch (fn) {
case SYS_TEMP_MIN:
data->temp_min[ix] = TEMP_TO_REG(val);
dme1737_write(data, DME1737_REG_TEMP_MIN(ix),
data->temp_min[ix]);
break;
case SYS_TEMP_MAX:
data->temp_max[ix] = TEMP_TO_REG(val);
dme1737_write(data, DME1737_REG_TEMP_MAX(ix),
data->temp_max[ix]);
break;
case SYS_TEMP_OFFSET:
data->temp_offset[ix] = TEMP_TO_REG(val);
dme1737_write(data, DME1737_REG_TEMP_OFFSET(ix),
data->temp_offset[ix]);
break;
default:
dev_dbg(dev, "Unknown function %d.\n", fn);
}
mutex_unlock(&data->update_lock);
return count;
}
/* ---------------------------------------------------------------------
* Zone sysfs attributes
* ix = [0-2]
* --------------------------------------------------------------------- */
#define SYS_ZONE_AUTO_CHANNELS_TEMP 0
#define SYS_ZONE_AUTO_POINT1_TEMP_HYST 1
#define SYS_ZONE_AUTO_POINT1_TEMP 2
#define SYS_ZONE_AUTO_POINT2_TEMP 3
#define SYS_ZONE_AUTO_POINT3_TEMP 4
static ssize_t show_zone(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dme1737_update_device(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
int res;
switch (fn) {
case SYS_ZONE_AUTO_CHANNELS_TEMP:
/* check config2 for non-standard temp-to-zone mapping */
if ((ix == 1) && (data->config2 & 0x02)) {
res = 4;
} else {
res = 1 << ix;
}
break;
case SYS_ZONE_AUTO_POINT1_TEMP_HYST:
res = TEMP_FROM_REG(data->zone_low[ix], 8) -
TEMP_HYST_FROM_REG(data->zone_hyst[ix == 2], ix);
break;
case SYS_ZONE_AUTO_POINT1_TEMP:
res = TEMP_FROM_REG(data->zone_low[ix], 8);
break;
case SYS_ZONE_AUTO_POINT2_TEMP:
/* pwm_freq holds the temp range bits in the upper nibble */
res = TEMP_FROM_REG(data->zone_low[ix], 8) +
TEMP_RANGE_FROM_REG(data->pwm_freq[ix]);
break;
case SYS_ZONE_AUTO_POINT3_TEMP:
res = TEMP_FROM_REG(data->zone_abs[ix], 8);
break;
default:
res = 0;
dev_dbg(dev, "Unknown function %d.\n", fn);
}
return sprintf(buf, "%d\n", res);
}
static ssize_t set_zone(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct dme1737_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
switch (fn) {
case SYS_ZONE_AUTO_POINT1_TEMP_HYST:
/* Refresh the cache */
data->zone_low[ix] = dme1737_read(data,
DME1737_REG_ZONE_LOW(ix));
/* Modify the temp hyst value */
data->zone_hyst[ix == 2] = TEMP_HYST_TO_REG(
TEMP_FROM_REG(data->zone_low[ix], 8) -
val, ix, dme1737_read(data,
DME1737_REG_ZONE_HYST(ix == 2)));
dme1737_write(data, DME1737_REG_ZONE_HYST(ix == 2),
data->zone_hyst[ix == 2]);
break;
case SYS_ZONE_AUTO_POINT1_TEMP:
data->zone_low[ix] = TEMP_TO_REG(val);
dme1737_write(data, DME1737_REG_ZONE_LOW(ix),
data->zone_low[ix]);
break;
case SYS_ZONE_AUTO_POINT2_TEMP:
/* Refresh the cache */
data->zone_low[ix] = dme1737_read(data,
DME1737_REG_ZONE_LOW(ix));
/* Modify the temp range value (which is stored in the upper
* nibble of the pwm_freq register) */
data->pwm_freq[ix] = TEMP_RANGE_TO_REG(val -
TEMP_FROM_REG(data->zone_low[ix], 8),
dme1737_read(data,
DME1737_REG_PWM_FREQ(ix)));
dme1737_write(data, DME1737_REG_PWM_FREQ(ix),
data->pwm_freq[ix]);
break;
case SYS_ZONE_AUTO_POINT3_TEMP:
data->zone_abs[ix] = TEMP_TO_REG(val);
dme1737_write(data, DME1737_REG_ZONE_ABS(ix),
data->zone_abs[ix]);
break;
default:
dev_dbg(dev, "Unknown function %d.\n", fn);
}
mutex_unlock(&data->update_lock);
return count;
}
/* ---------------------------------------------------------------------
* Fan sysfs attributes
* ix = [0-5]
* --------------------------------------------------------------------- */
#define SYS_FAN_INPUT 0
#define SYS_FAN_MIN 1
#define SYS_FAN_MAX 2
#define SYS_FAN_ALARM 3
#define SYS_FAN_TYPE 4
static ssize_t show_fan(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dme1737_update_device(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
int res;
switch (fn) {
case SYS_FAN_INPUT:
res = FAN_FROM_REG(data->fan[ix],
ix < 4 ? 0 :
FAN_TPC_FROM_REG(data->fan_opt[ix]));
break;
case SYS_FAN_MIN:
res = FAN_FROM_REG(data->fan_min[ix],
ix < 4 ? 0 :
FAN_TPC_FROM_REG(data->fan_opt[ix]));
break;
case SYS_FAN_MAX:
/* only valid for fan[5-6] */
res = FAN_MAX_FROM_REG(data->fan_max[ix - 4]);
break;
case SYS_FAN_ALARM:
res = (data->alarms >> DME1737_BIT_ALARM_FAN[ix]) & 0x01;
break;
case SYS_FAN_TYPE:
/* only valid for fan[1-4] */
res = FAN_TYPE_FROM_REG(data->fan_opt[ix]);
break;
default:
res = 0;
dev_dbg(dev, "Unknown function %d.\n", fn);
}
return sprintf(buf, "%d\n", res);
}
static ssize_t set_fan(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct dme1737_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
switch (fn) {
case SYS_FAN_MIN:
if (ix < 4) {
data->fan_min[ix] = FAN_TO_REG(val, 0);
} else {
/* Refresh the cache */
data->fan_opt[ix] = dme1737_read(data,
DME1737_REG_FAN_OPT(ix));
/* Modify the fan min value */
data->fan_min[ix] = FAN_TO_REG(val,
FAN_TPC_FROM_REG(data->fan_opt[ix]));
}
dme1737_write(data, DME1737_REG_FAN_MIN(ix),
data->fan_min[ix] & 0xff);
dme1737_write(data, DME1737_REG_FAN_MIN(ix) + 1,
data->fan_min[ix] >> 8);
break;
case SYS_FAN_MAX:
/* Only valid for fan[5-6] */
data->fan_max[ix - 4] = FAN_MAX_TO_REG(val);
dme1737_write(data, DME1737_REG_FAN_MAX(ix),
data->fan_max[ix - 4]);
break;
case SYS_FAN_TYPE:
/* Only valid for fan[1-4] */
if (!(val == 1 || val == 2 || val == 4)) {
count = -EINVAL;
dev_warn(dev, "Fan type value %ld not "
"supported. Choose one of 1, 2, or 4.\n",
val);
goto exit;
}
data->fan_opt[ix] = FAN_TYPE_TO_REG(val, dme1737_read(data,
DME1737_REG_FAN_OPT(ix)));
dme1737_write(data, DME1737_REG_FAN_OPT(ix),
data->fan_opt[ix]);
break;
default:
dev_dbg(dev, "Unknown function %d.\n", fn);
}
exit:
mutex_unlock(&data->update_lock);
return count;
}
/* ---------------------------------------------------------------------
* PWM sysfs attributes
* ix = [0-4]
* --------------------------------------------------------------------- */
#define SYS_PWM 0
#define SYS_PWM_FREQ 1
#define SYS_PWM_ENABLE 2
#define SYS_PWM_RAMP_RATE 3
#define SYS_PWM_AUTO_CHANNELS_ZONE 4
#define SYS_PWM_AUTO_PWM_MIN 5
#define SYS_PWM_AUTO_POINT1_PWM 6
#define SYS_PWM_AUTO_POINT2_PWM 7
static ssize_t show_pwm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dme1737_update_device(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
int res;
switch (fn) {
case SYS_PWM:
if (PWM_EN_FROM_REG(data->pwm_config[ix]) == 0) {
res = 255;
} else {
res = data->pwm[ix];
}
break;
case SYS_PWM_FREQ:
res = PWM_FREQ_FROM_REG(data->pwm_freq[ix]);
break;
case SYS_PWM_ENABLE:
if (ix >= 3) {
res = 1; /* pwm[5-6] hard-wired to manual mode */
} else {
res = PWM_EN_FROM_REG(data->pwm_config[ix]);
}
break;
case SYS_PWM_RAMP_RATE:
/* Only valid for pwm[1-3] */
res = PWM_RR_FROM_REG(data->pwm_rr[ix > 0], ix);
break;
case SYS_PWM_AUTO_CHANNELS_ZONE:
/* Only valid for pwm[1-3] */
if (PWM_EN_FROM_REG(data->pwm_config[ix]) == 2) {
res = PWM_ACZ_FROM_REG(data->pwm_config[ix]);
} else {
res = data->pwm_acz[ix];
}
break;
case SYS_PWM_AUTO_PWM_MIN:
/* Only valid for pwm[1-3] */
if (PWM_OFF_FROM_REG(data->pwm_rr[0], ix)) {
res = data->pwm_min[ix];
} else {
res = 0;
}
break;
case SYS_PWM_AUTO_POINT1_PWM:
/* Only valid for pwm[1-3] */
res = data->pwm_min[ix];
break;
case SYS_PWM_AUTO_POINT2_PWM:
/* Only valid for pwm[1-3] */
res = 255; /* hard-wired */
break;
default:
res = 0;
dev_dbg(dev, "Unknown function %d.\n", fn);
}
return sprintf(buf, "%d\n", res);
}
static struct attribute *dme1737_pwm_chmod_attr[];
static void dme1737_chmod_file(struct device*, struct attribute*, mode_t);
static ssize_t set_pwm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct dme1737_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute_2
*sensor_attr_2 = to_sensor_dev_attr_2(attr);
int ix = sensor_attr_2->index;
int fn = sensor_attr_2->nr;
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
switch (fn) {
case SYS_PWM:
data->pwm[ix] = SENSORS_LIMIT(val, 0, 255);
dme1737_write(data, DME1737_REG_PWM(ix), data->pwm[ix]);
break;
case SYS_PWM_FREQ:
data->pwm_freq[ix] = PWM_FREQ_TO_REG(val, dme1737_read(data,
DME1737_REG_PWM_FREQ(ix)));
dme1737_write(data, DME1737_REG_PWM_FREQ(ix),
data->pwm_freq[ix]);
break;
case SYS_PWM_ENABLE:
/* Only valid for pwm[1-3] */
if (val < 0 || val > 2) {
count = -EINVAL;
dev_warn(dev, "PWM enable %ld not "
"supported. Choose one of 0, 1, or 2.\n",
val);
goto exit;
}
/* Refresh the cache */
data->pwm_config[ix] = dme1737_read(data,
DME1737_REG_PWM_CONFIG(ix));
if (val == PWM_EN_FROM_REG(data->pwm_config[ix])) {
/* Bail out if no change */
goto exit;
}
/* Do some housekeeping if we are currently in auto mode */
if (PWM_EN_FROM_REG(data->pwm_config[ix]) == 2) {
/* Save the current zone channel assignment */
data->pwm_acz[ix] = PWM_ACZ_FROM_REG(
data->pwm_config[ix]);
/* Save the current ramp rate state and disable it */
data->pwm_rr[ix > 0] = dme1737_read(data,
DME1737_REG_PWM_RR(ix > 0));
data->pwm_rr_en &= ~(1 << ix);
if (PWM_RR_EN_FROM_REG(data->pwm_rr[ix > 0], ix)) {
data->pwm_rr_en |= (1 << ix);
data->pwm_rr[ix > 0] = PWM_RR_EN_TO_REG(0, ix,
data->pwm_rr[ix > 0]);
dme1737_write(data,
DME1737_REG_PWM_RR(ix > 0),
data->pwm_rr[ix > 0]);
}
}
/* Set the new PWM mode */
switch (val) {
case 0:
/* Change permissions of pwm[ix] to read-only */
dme1737_chmod_file(dev, dme1737_pwm_chmod_attr[ix],
S_IRUGO);
/* Turn fan fully on */
data->pwm_config[ix] = PWM_EN_TO_REG(0,
data->pwm_config[ix]);
dme1737_write(data, DME1737_REG_PWM_CONFIG(ix),
data->pwm_config[ix]);
break;
case 1:
/* Turn on manual mode */
data->pwm_config[ix] = PWM_EN_TO_REG(1,
data->pwm_config[ix]);
dme1737_write(data, DME1737_REG_PWM_CONFIG(ix),
data->pwm_config[ix]);
/* Change permissions of pwm[ix] to read-writeable */
dme1737_chmod_file(dev, dme1737_pwm_chmod_attr[ix],
S_IRUGO | S_IWUSR);
break;
case 2:
/* Change permissions of pwm[ix] to read-only */
dme1737_chmod_file(dev, dme1737_pwm_chmod_attr[ix],
S_IRUGO);
/* Turn on auto mode using the saved zone channel
* assignment */
data->pwm_config[ix] = PWM_ACZ_TO_REG(
data->pwm_acz[ix],
data->pwm_config[ix]);
dme1737_write(data, DME1737_REG_PWM_CONFIG(ix),
data->pwm_config[ix]);
/* Enable PWM ramp rate if previously enabled */
if (data->pwm_rr_en & (1 << ix)) {
data->pwm_rr[ix > 0] = PWM_RR_EN_TO_REG(1, ix,
dme1737_read(data,
DME1737_REG_PWM_RR(ix > 0)));
dme1737_write(data,
DME1737_REG_PWM_RR(ix > 0),
data->pwm_rr[ix > 0]);
}
break;
}
break;
case SYS_PWM_RAMP_RATE:
/* Only valid for pwm[1-3] */
/* Refresh the cache */
data->pwm_config[ix] = dme1737_read(data,
DME1737_REG_PWM_CONFIG(ix));
data->pwm_rr[ix > 0] = dme1737_read(data,
DME1737_REG_PWM_RR(ix > 0));
/* Set the ramp rate value */
if (val > 0) {
data->pwm_rr[ix > 0] = PWM_RR_TO_REG(val, ix,
data->pwm_rr[ix > 0]);
}
/* Enable/disable the feature only if the associated PWM
* output is in automatic mode. */
if (PWM_EN_FROM_REG(data->pwm_config[ix]) == 2) {
data->pwm_rr[ix > 0] = PWM_RR_EN_TO_REG(val > 0, ix,
data->pwm_rr[ix > 0]);
}
dme1737_write(data, DME1737_REG_PWM_RR(ix > 0),
data->pwm_rr[ix > 0]);
break;
case SYS_PWM_AUTO_CHANNELS_ZONE:
/* Only valid for pwm[1-3] */
if (!(val == 1 || val == 2 || val == 4 ||
val == 6 || val == 7)) {
count = -EINVAL;
dev_warn(dev, "PWM auto channels zone %ld "
"not supported. Choose one of 1, 2, 4, 6, "
"or 7.\n", val);
goto exit;
}
/* Refresh the cache */
data->pwm_config[ix] = dme1737_read(data,
DME1737_REG_PWM_CONFIG(ix));
if (PWM_EN_FROM_REG(data->pwm_config[ix]) == 2) {
/* PWM is already in auto mode so update the temp
* channel assignment */
data->pwm_config[ix] = PWM_ACZ_TO_REG(val,
data->pwm_config[ix]);
dme1737_write(data, DME1737_REG_PWM_CONFIG(ix),
data->pwm_config[ix]);
} else {
/* PWM is not in auto mode so we save the temp
* channel assignment for later use */
data->pwm_acz[ix] = val;
}
break;
case SYS_PWM_AUTO_PWM_MIN:
/* Only valid for pwm[1-3] */
/* Refresh the cache */
data->pwm_min[ix] = dme1737_read(data,
DME1737_REG_PWM_MIN(ix));
/* There are only 2 values supported for the auto_pwm_min
* value: 0 or auto_point1_pwm. So if the temperature drops
* below the auto_point1_temp_hyst value, the fan either turns
* off or runs at auto_point1_pwm duty-cycle. */
if (val > ((data->pwm_min[ix] + 1) / 2)) {
data->pwm_rr[0] = PWM_OFF_TO_REG(1, ix,
dme1737_read(data,
DME1737_REG_PWM_RR(0)));
} else {
data->pwm_rr[0] = PWM_OFF_TO_REG(0, ix,
dme1737_read(data,
DME1737_REG_PWM_RR(0)));
}
dme1737_write(data, DME1737_REG_PWM_RR(0),
data->pwm_rr[0]);
break;
case SYS_PWM_AUTO_POINT1_PWM:
/* Only valid for pwm[1-3] */
data->pwm_min[ix] = SENSORS_LIMIT(val, 0, 255);
dme1737_write(data, DME1737_REG_PWM_MIN(ix),
data->pwm_min[ix]);
break;
default:
dev_dbg(dev, "Unknown function %d.\n", fn);
}
exit:
mutex_unlock(&data->update_lock);
return count;
}
/* ---------------------------------------------------------------------
* Miscellaneous sysfs attributes
* --------------------------------------------------------------------- */
static ssize_t show_vrm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct dme1737_data *data = i2c_get_clientdata(client);
return sprintf(buf, "%d\n", data->vrm);
}
static ssize_t set_vrm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct dme1737_data *data = dev_get_drvdata(dev);
long val = simple_strtol(buf, NULL, 10);
data->vrm = val;
return count;
}
static ssize_t show_vid(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dme1737_update_device(dev);
return sprintf(buf, "%d\n", vid_from_reg(data->vid, data->vrm));
}
static ssize_t show_name(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct dme1737_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
/* ---------------------------------------------------------------------
* Sysfs device attribute defines and structs
* --------------------------------------------------------------------- */
/* Voltages 0-6 */
#define SENSOR_DEVICE_ATTR_IN(ix) \
static SENSOR_DEVICE_ATTR_2(in##ix##_input, S_IRUGO, \
show_in, NULL, SYS_IN_INPUT, ix); \
static SENSOR_DEVICE_ATTR_2(in##ix##_min, S_IRUGO | S_IWUSR, \
show_in, set_in, SYS_IN_MIN, ix); \
static SENSOR_DEVICE_ATTR_2(in##ix##_max, S_IRUGO | S_IWUSR, \
show_in, set_in, SYS_IN_MAX, ix); \
static SENSOR_DEVICE_ATTR_2(in##ix##_alarm, S_IRUGO, \
show_in, NULL, SYS_IN_ALARM, ix)
SENSOR_DEVICE_ATTR_IN(0);
SENSOR_DEVICE_ATTR_IN(1);
SENSOR_DEVICE_ATTR_IN(2);
SENSOR_DEVICE_ATTR_IN(3);
SENSOR_DEVICE_ATTR_IN(4);
SENSOR_DEVICE_ATTR_IN(5);
SENSOR_DEVICE_ATTR_IN(6);
/* Temperatures 1-3 */
#define SENSOR_DEVICE_ATTR_TEMP(ix) \
static SENSOR_DEVICE_ATTR_2(temp##ix##_input, S_IRUGO, \
show_temp, NULL, SYS_TEMP_INPUT, ix-1); \
static SENSOR_DEVICE_ATTR_2(temp##ix##_min, S_IRUGO | S_IWUSR, \
show_temp, set_temp, SYS_TEMP_MIN, ix-1); \
static SENSOR_DEVICE_ATTR_2(temp##ix##_max, S_IRUGO | S_IWUSR, \
show_temp, set_temp, SYS_TEMP_MAX, ix-1); \
static SENSOR_DEVICE_ATTR_2(temp##ix##_offset, S_IRUGO, \
show_temp, set_temp, SYS_TEMP_OFFSET, ix-1); \
static SENSOR_DEVICE_ATTR_2(temp##ix##_alarm, S_IRUGO, \
show_temp, NULL, SYS_TEMP_ALARM, ix-1); \
static SENSOR_DEVICE_ATTR_2(temp##ix##_fault, S_IRUGO, \
show_temp, NULL, SYS_TEMP_FAULT, ix-1)
SENSOR_DEVICE_ATTR_TEMP(1);
SENSOR_DEVICE_ATTR_TEMP(2);
SENSOR_DEVICE_ATTR_TEMP(3);
/* Zones 1-3 */
#define SENSOR_DEVICE_ATTR_ZONE(ix) \
static SENSOR_DEVICE_ATTR_2(zone##ix##_auto_channels_temp, S_IRUGO, \
show_zone, NULL, SYS_ZONE_AUTO_CHANNELS_TEMP, ix-1); \
static SENSOR_DEVICE_ATTR_2(zone##ix##_auto_point1_temp_hyst, S_IRUGO, \
show_zone, set_zone, SYS_ZONE_AUTO_POINT1_TEMP_HYST, ix-1); \
static SENSOR_DEVICE_ATTR_2(zone##ix##_auto_point1_temp, S_IRUGO, \
show_zone, set_zone, SYS_ZONE_AUTO_POINT1_TEMP, ix-1); \
static SENSOR_DEVICE_ATTR_2(zone##ix##_auto_point2_temp, S_IRUGO, \
show_zone, set_zone, SYS_ZONE_AUTO_POINT2_TEMP, ix-1); \
static SENSOR_DEVICE_ATTR_2(zone##ix##_auto_point3_temp, S_IRUGO, \
show_zone, set_zone, SYS_ZONE_AUTO_POINT3_TEMP, ix-1)
SENSOR_DEVICE_ATTR_ZONE(1);
SENSOR_DEVICE_ATTR_ZONE(2);
SENSOR_DEVICE_ATTR_ZONE(3);
/* Fans 1-4 */
#define SENSOR_DEVICE_ATTR_FAN_1TO4(ix) \
static SENSOR_DEVICE_ATTR_2(fan##ix##_input, S_IRUGO, \
show_fan, NULL, SYS_FAN_INPUT, ix-1); \
static SENSOR_DEVICE_ATTR_2(fan##ix##_min, S_IRUGO | S_IWUSR, \
show_fan, set_fan, SYS_FAN_MIN, ix-1); \
static SENSOR_DEVICE_ATTR_2(fan##ix##_alarm, S_IRUGO, \
show_fan, NULL, SYS_FAN_ALARM, ix-1); \
static SENSOR_DEVICE_ATTR_2(fan##ix##_type, S_IRUGO | S_IWUSR, \
show_fan, set_fan, SYS_FAN_TYPE, ix-1)
SENSOR_DEVICE_ATTR_FAN_1TO4(1);
SENSOR_DEVICE_ATTR_FAN_1TO4(2);
SENSOR_DEVICE_ATTR_FAN_1TO4(3);
SENSOR_DEVICE_ATTR_FAN_1TO4(4);
/* Fans 5-6 */
#define SENSOR_DEVICE_ATTR_FAN_5TO6(ix) \
static SENSOR_DEVICE_ATTR_2(fan##ix##_input, S_IRUGO, \
show_fan, NULL, SYS_FAN_INPUT, ix-1); \
static SENSOR_DEVICE_ATTR_2(fan##ix##_min, S_IRUGO | S_IWUSR, \
show_fan, set_fan, SYS_FAN_MIN, ix-1); \
static SENSOR_DEVICE_ATTR_2(fan##ix##_alarm, S_IRUGO, \
show_fan, NULL, SYS_FAN_ALARM, ix-1); \
static SENSOR_DEVICE_ATTR_2(fan##ix##_max, S_IRUGO | S_IWUSR, \
show_fan, set_fan, SYS_FAN_MAX, ix-1)
SENSOR_DEVICE_ATTR_FAN_5TO6(5);
SENSOR_DEVICE_ATTR_FAN_5TO6(6);
/* PWMs 1-3 */
#define SENSOR_DEVICE_ATTR_PWM_1TO3(ix) \
static SENSOR_DEVICE_ATTR_2(pwm##ix, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_freq, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_FREQ, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_enable, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_ENABLE, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_ramp_rate, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_RAMP_RATE, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_auto_channels_zone, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_AUTO_CHANNELS_ZONE, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_auto_pwm_min, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_AUTO_PWM_MIN, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_auto_point1_pwm, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_AUTO_POINT1_PWM, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_auto_point2_pwm, S_IRUGO, \
show_pwm, NULL, SYS_PWM_AUTO_POINT2_PWM, ix-1)
SENSOR_DEVICE_ATTR_PWM_1TO3(1);
SENSOR_DEVICE_ATTR_PWM_1TO3(2);
SENSOR_DEVICE_ATTR_PWM_1TO3(3);
/* PWMs 5-6 */
#define SENSOR_DEVICE_ATTR_PWM_5TO6(ix) \
static SENSOR_DEVICE_ATTR_2(pwm##ix, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_freq, S_IRUGO, \
show_pwm, set_pwm, SYS_PWM_FREQ, ix-1); \
static SENSOR_DEVICE_ATTR_2(pwm##ix##_enable, S_IRUGO, \
show_pwm, NULL, SYS_PWM_ENABLE, ix-1)
SENSOR_DEVICE_ATTR_PWM_5TO6(5);
SENSOR_DEVICE_ATTR_PWM_5TO6(6);
/* Misc */
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm, set_vrm);
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid, NULL);
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL); /* for ISA devices */
/* This struct holds all the attributes that are always present and need to be
* created unconditionally. The attributes that need modification of their
* permissions are created read-only and write permissions are added or removed
* on the fly when required */
static struct attribute *dme1737_attr[] ={
/* Voltages */
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_min.dev_attr.attr,
&sensor_dev_attr_in0_max.dev_attr.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_min.dev_attr.attr,
&sensor_dev_attr_in1_max.dev_attr.attr,
&sensor_dev_attr_in1_alarm.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_min.dev_attr.attr,
&sensor_dev_attr_in2_max.dev_attr.attr,
&sensor_dev_attr_in2_alarm.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in3_min.dev_attr.attr,
&sensor_dev_attr_in3_max.dev_attr.attr,
&sensor_dev_attr_in3_alarm.dev_attr.attr,
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in4_min.dev_attr.attr,
&sensor_dev_attr_in4_max.dev_attr.attr,
&sensor_dev_attr_in4_alarm.dev_attr.attr,
&sensor_dev_attr_in5_input.dev_attr.attr,
&sensor_dev_attr_in5_min.dev_attr.attr,
&sensor_dev_attr_in5_max.dev_attr.attr,
&sensor_dev_attr_in5_alarm.dev_attr.attr,
&sensor_dev_attr_in6_input.dev_attr.attr,
&sensor_dev_attr_in6_min.dev_attr.attr,
&sensor_dev_attr_in6_max.dev_attr.attr,
&sensor_dev_attr_in6_alarm.dev_attr.attr,
/* Temperatures */
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_fault.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
/* Zones */
&sensor_dev_attr_zone1_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_zone1_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_zone1_auto_point3_temp.dev_attr.attr,
&sensor_dev_attr_zone1_auto_channels_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point3_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_channels_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point3_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_channels_temp.dev_attr.attr,
NULL
};
static const struct attribute_group dme1737_group = {
.attrs = dme1737_attr,
};
/* The following struct holds misc attributes, which are not available in all
* chips. Their creation depends on the chip type which is determined during
* module load. */
static struct attribute *dme1737_misc_attr[] = {
/* Temperatures */
&sensor_dev_attr_temp1_offset.dev_attr.attr,
&sensor_dev_attr_temp2_offset.dev_attr.attr,
&sensor_dev_attr_temp3_offset.dev_attr.attr,
/* Zones */
&sensor_dev_attr_zone1_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point1_temp_hyst.dev_attr.attr,
NULL
};
static const struct attribute_group dme1737_misc_group = {
.attrs = dme1737_misc_attr,
};
/* The following struct holds VID-related attributes. Their creation
depends on the chip type which is determined during module load. */
static struct attribute *dme1737_vid_attr[] = {
&dev_attr_vrm.attr,
&dev_attr_cpu0_vid.attr,
NULL
};
static const struct attribute_group dme1737_vid_group = {
.attrs = dme1737_vid_attr,
};
/* The following structs hold the PWM attributes, some of which are optional.
* Their creation depends on the chip configuration which is determined during
* module load. */
static struct attribute *dme1737_pwm1_attr[] = {
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_pwm1_freq.dev_attr.attr,
&sensor_dev_attr_pwm1_enable.dev_attr.attr,
&sensor_dev_attr_pwm1_ramp_rate.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_channels_zone.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point2_pwm.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm2_attr[] = {
&sensor_dev_attr_pwm2.dev_attr.attr,
&sensor_dev_attr_pwm2_freq.dev_attr.attr,
&sensor_dev_attr_pwm2_enable.dev_attr.attr,
&sensor_dev_attr_pwm2_ramp_rate.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_channels_zone.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point2_pwm.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm3_attr[] = {
&sensor_dev_attr_pwm3.dev_attr.attr,
&sensor_dev_attr_pwm3_freq.dev_attr.attr,
&sensor_dev_attr_pwm3_enable.dev_attr.attr,
&sensor_dev_attr_pwm3_ramp_rate.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_channels_zone.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point2_pwm.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm5_attr[] = {
&sensor_dev_attr_pwm5.dev_attr.attr,
&sensor_dev_attr_pwm5_freq.dev_attr.attr,
&sensor_dev_attr_pwm5_enable.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm6_attr[] = {
&sensor_dev_attr_pwm6.dev_attr.attr,
&sensor_dev_attr_pwm6_freq.dev_attr.attr,
&sensor_dev_attr_pwm6_enable.dev_attr.attr,
NULL
};
static const struct attribute_group dme1737_pwm_group[] = {
{ .attrs = dme1737_pwm1_attr },
{ .attrs = dme1737_pwm2_attr },
{ .attrs = dme1737_pwm3_attr },
{ .attrs = NULL },
{ .attrs = dme1737_pwm5_attr },
{ .attrs = dme1737_pwm6_attr },
};
/* The following struct holds misc PWM attributes, which are not available in
* all chips. Their creation depends on the chip type which is determined
* during module load. */
static struct attribute *dme1737_pwm_misc_attr[] = {
&sensor_dev_attr_pwm1_auto_pwm_min.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_pwm_min.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_pwm_min.dev_attr.attr,
};
/* The following structs hold the fan attributes, some of which are optional.
* Their creation depends on the chip configuration which is determined during
* module load. */
static struct attribute *dme1737_fan1_attr[] = {
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_type.dev_attr.attr,
NULL
};
static struct attribute *dme1737_fan2_attr[] = {
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_type.dev_attr.attr,
NULL
};
static struct attribute *dme1737_fan3_attr[] = {
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan3_alarm.dev_attr.attr,
&sensor_dev_attr_fan3_type.dev_attr.attr,
NULL
};
static struct attribute *dme1737_fan4_attr[] = {
&sensor_dev_attr_fan4_input.dev_attr.attr,
&sensor_dev_attr_fan4_min.dev_attr.attr,
&sensor_dev_attr_fan4_alarm.dev_attr.attr,
&sensor_dev_attr_fan4_type.dev_attr.attr,
NULL
};
static struct attribute *dme1737_fan5_attr[] = {
&sensor_dev_attr_fan5_input.dev_attr.attr,
&sensor_dev_attr_fan5_min.dev_attr.attr,
&sensor_dev_attr_fan5_alarm.dev_attr.attr,
&sensor_dev_attr_fan5_max.dev_attr.attr,
NULL
};
static struct attribute *dme1737_fan6_attr[] = {
&sensor_dev_attr_fan6_input.dev_attr.attr,
&sensor_dev_attr_fan6_min.dev_attr.attr,
&sensor_dev_attr_fan6_alarm.dev_attr.attr,
&sensor_dev_attr_fan6_max.dev_attr.attr,
NULL
};
static const struct attribute_group dme1737_fan_group[] = {
{ .attrs = dme1737_fan1_attr },
{ .attrs = dme1737_fan2_attr },
{ .attrs = dme1737_fan3_attr },
{ .attrs = dme1737_fan4_attr },
{ .attrs = dme1737_fan5_attr },
{ .attrs = dme1737_fan6_attr },
};
/* The permissions of the following zone attributes are changed to read-
* writeable if the chip is *not* locked. Otherwise they stay read-only. */
static struct attribute *dme1737_zone_chmod_attr[] = {
&sensor_dev_attr_zone1_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_zone1_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_zone1_auto_point3_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_zone2_auto_point3_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_zone3_auto_point3_temp.dev_attr.attr,
NULL
};
static const struct attribute_group dme1737_zone_chmod_group = {
.attrs = dme1737_zone_chmod_attr,
};
/* The permissions of the following PWM attributes are changed to read-
* writeable if the chip is *not* locked and the respective PWM is available.
* Otherwise they stay read-only. */
static struct attribute *dme1737_pwm1_chmod_attr[] = {
&sensor_dev_attr_pwm1_freq.dev_attr.attr,
&sensor_dev_attr_pwm1_enable.dev_attr.attr,
&sensor_dev_attr_pwm1_ramp_rate.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_channels_zone.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point1_pwm.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm2_chmod_attr[] = {
&sensor_dev_attr_pwm2_freq.dev_attr.attr,
&sensor_dev_attr_pwm2_enable.dev_attr.attr,
&sensor_dev_attr_pwm2_ramp_rate.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_channels_zone.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point1_pwm.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm3_chmod_attr[] = {
&sensor_dev_attr_pwm3_freq.dev_attr.attr,
&sensor_dev_attr_pwm3_enable.dev_attr.attr,
&sensor_dev_attr_pwm3_ramp_rate.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_channels_zone.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point1_pwm.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm5_chmod_attr[] = {
&sensor_dev_attr_pwm5.dev_attr.attr,
&sensor_dev_attr_pwm5_freq.dev_attr.attr,
NULL
};
static struct attribute *dme1737_pwm6_chmod_attr[] = {
&sensor_dev_attr_pwm6.dev_attr.attr,
&sensor_dev_attr_pwm6_freq.dev_attr.attr,
NULL
};
static const struct attribute_group dme1737_pwm_chmod_group[] = {
{ .attrs = dme1737_pwm1_chmod_attr },
{ .attrs = dme1737_pwm2_chmod_attr },
{ .attrs = dme1737_pwm3_chmod_attr },
{ .attrs = NULL },
{ .attrs = dme1737_pwm5_chmod_attr },
{ .attrs = dme1737_pwm6_chmod_attr },
};
/* Pwm[1-3] are read-writeable if the associated pwm is in manual mode and the
* chip is not locked. Otherwise they are read-only. */
static struct attribute *dme1737_pwm_chmod_attr[] = {
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_pwm2.dev_attr.attr,
&sensor_dev_attr_pwm3.dev_attr.attr,
};
/* ---------------------------------------------------------------------
* Super-IO functions
* --------------------------------------------------------------------- */
static inline void dme1737_sio_enter(int sio_cip)
{
outb(0x55, sio_cip);
}
static inline void dme1737_sio_exit(int sio_cip)
{
outb(0xaa, sio_cip);
}
static inline int dme1737_sio_inb(int sio_cip, int reg)
{
outb(reg, sio_cip);
return inb(sio_cip + 1);
}
static inline void dme1737_sio_outb(int sio_cip, int reg, int val)
{
outb(reg, sio_cip);
outb(val, sio_cip + 1);
}
/* ---------------------------------------------------------------------
* Device initialization
* --------------------------------------------------------------------- */
static int dme1737_i2c_get_features(int, struct dme1737_data*);
static void dme1737_chmod_file(struct device *dev,
struct attribute *attr, mode_t mode)
{
if (sysfs_chmod_file(&dev->kobj, attr, mode)) {
dev_warn(dev, "Failed to change permissions of %s.\n",
attr->name);
}
}
static void dme1737_chmod_group(struct device *dev,
const struct attribute_group *group,
mode_t mode)
{
struct attribute **attr;
for (attr = group->attrs; *attr; attr++) {
dme1737_chmod_file(dev, *attr, mode);
}
}
static void dme1737_remove_files(struct device *dev)
{
struct dme1737_data *data = dev_get_drvdata(dev);
int ix;
for (ix = 0; ix < ARRAY_SIZE(dme1737_fan_group); ix++) {
if (data->has_fan & (1 << ix)) {
sysfs_remove_group(&dev->kobj,
&dme1737_fan_group[ix]);
}
}
for (ix = 0; ix < ARRAY_SIZE(dme1737_pwm_group); ix++) {
if (data->has_pwm & (1 << ix)) {
sysfs_remove_group(&dev->kobj,
&dme1737_pwm_group[ix]);
if (data->type != sch5027 && ix < 3) {
sysfs_remove_file(&dev->kobj,
dme1737_pwm_misc_attr[ix]);
}
}
}
if (data->type != sch5027) {
sysfs_remove_group(&dev->kobj, &dme1737_misc_group);
}
if (data->type == dme1737) {
sysfs_remove_group(&dev->kobj, &dme1737_vid_group);
}
sysfs_remove_group(&dev->kobj, &dme1737_group);
if (!data->client) {
sysfs_remove_file(&dev->kobj, &dev_attr_name.attr);
}
}
static int dme1737_create_files(struct device *dev)
{
struct dme1737_data *data = dev_get_drvdata(dev);
int err, ix;
/* Create a name attribute for ISA devices */
if (!data->client &&
(err = sysfs_create_file(&dev->kobj, &dev_attr_name.attr))) {
goto exit;
}
/* Create standard sysfs attributes */
if ((err = sysfs_create_group(&dev->kobj, &dme1737_group))) {
goto exit_remove;
}
/* Create misc sysfs attributes */
if ((data->type != sch5027) &&
(err = sysfs_create_group(&dev->kobj,
&dme1737_misc_group))) {
goto exit_remove;
}
/* Create VID-related sysfs attributes */
if ((data->type == dme1737) &&
(err = sysfs_create_group(&dev->kobj,
&dme1737_vid_group))) {
goto exit_remove;
}
/* Create fan sysfs attributes */
for (ix = 0; ix < ARRAY_SIZE(dme1737_fan_group); ix++) {
if (data->has_fan & (1 << ix)) {
if ((err = sysfs_create_group(&dev->kobj,
&dme1737_fan_group[ix]))) {
goto exit_remove;
}
}
}
/* Create PWM sysfs attributes */
for (ix = 0; ix < ARRAY_SIZE(dme1737_pwm_group); ix++) {
if (data->has_pwm & (1 << ix)) {
if ((err = sysfs_create_group(&dev->kobj,
&dme1737_pwm_group[ix]))) {
goto exit_remove;
}
if (data->type != sch5027 && ix < 3 &&
(err = sysfs_create_file(&dev->kobj,
dme1737_pwm_misc_attr[ix]))) {
goto exit_remove;
}
}
}
/* Inform if the device is locked. Otherwise change the permissions of
* selected attributes from read-only to read-writeable. */
if (data->config & 0x02) {
dev_info(dev, "Device is locked. Some attributes "
"will be read-only.\n");
} else {
/* Change permissions of zone sysfs attributes */
dme1737_chmod_group(dev, &dme1737_zone_chmod_group,
S_IRUGO | S_IWUSR);
/* Change permissions of misc sysfs attributes */
if (data->type != sch5027) {
dme1737_chmod_group(dev, &dme1737_misc_group,
S_IRUGO | S_IWUSR);
}
/* Change permissions of PWM sysfs attributes */
for (ix = 0; ix < ARRAY_SIZE(dme1737_pwm_chmod_group); ix++) {
if (data->has_pwm & (1 << ix)) {
dme1737_chmod_group(dev,
&dme1737_pwm_chmod_group[ix],
S_IRUGO | S_IWUSR);
if (data->type != sch5027 && ix < 3) {
dme1737_chmod_file(dev,
dme1737_pwm_misc_attr[ix],
S_IRUGO | S_IWUSR);
}
}
}
/* Change permissions of pwm[1-3] if in manual mode */
for (ix = 0; ix < 3; ix++) {
if ((data->has_pwm & (1 << ix)) &&
(PWM_EN_FROM_REG(data->pwm_config[ix]) == 1)) {
dme1737_chmod_file(dev,
dme1737_pwm_chmod_attr[ix],
S_IRUGO | S_IWUSR);
}
}
}
return 0;
exit_remove:
dme1737_remove_files(dev);
exit:
return err;
}
static int dme1737_init_device(struct device *dev)
{
struct dme1737_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
int ix;
u8 reg;
/* Point to the right nominal voltages array */
data->in_nominal = IN_NOMINAL(data->type);
data->config = dme1737_read(data, DME1737_REG_CONFIG);
/* Inform if part is not monitoring/started */
if (!(data->config & 0x01)) {
if (!force_start) {
dev_err(dev, "Device is not monitoring. "
"Use the force_start load parameter to "
"override.\n");
return -EFAULT;
}
/* Force monitoring */
data->config |= 0x01;
dme1737_write(data, DME1737_REG_CONFIG, data->config);
}
/* Inform if part is not ready */
if (!(data->config & 0x04)) {
dev_err(dev, "Device is not ready.\n");
return -EFAULT;
}
/* Determine which optional fan and pwm features are enabled/present */
if (client) { /* I2C chip */
data->config2 = dme1737_read(data, DME1737_REG_CONFIG2);
/* Check if optional fan3 input is enabled */
if (data->config2 & 0x04) {
data->has_fan |= (1 << 2);
}
/* Fan4 and pwm3 are only available if the client's I2C address
* is the default 0x2e. Otherwise the I/Os associated with
* these functions are used for addr enable/select. */
if (client->addr == 0x2e) {
data->has_fan |= (1 << 3);
data->has_pwm |= (1 << 2);
}
/* Determine which of the optional fan[5-6] and pwm[5-6]
* features are enabled. For this, we need to query the runtime
* registers through the Super-IO LPC interface. Try both
* config ports 0x2e and 0x4e. */
if (dme1737_i2c_get_features(0x2e, data) &&
dme1737_i2c_get_features(0x4e, data)) {
dev_warn(dev, "Failed to query Super-IO for optional "
"features.\n");
}
} else { /* ISA chip */
/* Fan3 and pwm3 are always available. Fan[4-5] and pwm[5-6]
* don't exist in the ISA chip. */
data->has_fan |= (1 << 2);
data->has_pwm |= (1 << 2);
}
/* Fan1, fan2, pwm1, and pwm2 are always present */
data->has_fan |= 0x03;
data->has_pwm |= 0x03;
dev_info(dev, "Optional features: pwm3=%s, pwm5=%s, pwm6=%s, "
"fan3=%s, fan4=%s, fan5=%s, fan6=%s.\n",
(data->has_pwm & (1 << 2)) ? "yes" : "no",
(data->has_pwm & (1 << 4)) ? "yes" : "no",
(data->has_pwm & (1 << 5)) ? "yes" : "no",
(data->has_fan & (1 << 2)) ? "yes" : "no",
(data->has_fan & (1 << 3)) ? "yes" : "no",
(data->has_fan & (1 << 4)) ? "yes" : "no",
(data->has_fan & (1 << 5)) ? "yes" : "no");
reg = dme1737_read(data, DME1737_REG_TACH_PWM);
/* Inform if fan-to-pwm mapping differs from the default */
if (client && reg != 0xa4) { /* I2C chip */
dev_warn(dev, "Non-standard fan to pwm mapping: "
"fan1->pwm%d, fan2->pwm%d, fan3->pwm%d, "
"fan4->pwm%d. Please report to the driver "
"maintainer.\n",
(reg & 0x03) + 1, ((reg >> 2) & 0x03) + 1,
((reg >> 4) & 0x03) + 1, ((reg >> 6) & 0x03) + 1);
} else if (!client && reg != 0x24) { /* ISA chip */
dev_warn(dev, "Non-standard fan to pwm mapping: "
"fan1->pwm%d, fan2->pwm%d, fan3->pwm%d. "
"Please report to the driver maintainer.\n",
(reg & 0x03) + 1, ((reg >> 2) & 0x03) + 1,
((reg >> 4) & 0x03) + 1);
}
/* Switch pwm[1-3] to manual mode if they are currently disabled and
* set the duty-cycles to 0% (which is identical to the PWMs being
* disabled). */
if (!(data->config & 0x02)) {
for (ix = 0; ix < 3; ix++) {
data->pwm_config[ix] = dme1737_read(data,
DME1737_REG_PWM_CONFIG(ix));
if ((data->has_pwm & (1 << ix)) &&
(PWM_EN_FROM_REG(data->pwm_config[ix]) == -1)) {
dev_info(dev, "Switching pwm%d to "
"manual mode.\n", ix + 1);
data->pwm_config[ix] = PWM_EN_TO_REG(1,
data->pwm_config[ix]);
dme1737_write(data, DME1737_REG_PWM(ix), 0);
dme1737_write(data,
DME1737_REG_PWM_CONFIG(ix),
data->pwm_config[ix]);
}
}
}
/* Initialize the default PWM auto channels zone (acz) assignments */
data->pwm_acz[0] = 1; /* pwm1 -> zone1 */
data->pwm_acz[1] = 2; /* pwm2 -> zone2 */
data->pwm_acz[2] = 4; /* pwm3 -> zone3 */
/* Set VRM */
if (data->type == dme1737) {
data->vrm = vid_which_vrm();
}
return 0;
}
/* ---------------------------------------------------------------------
* I2C device detection and registration
* --------------------------------------------------------------------- */
static struct i2c_driver dme1737_i2c_driver;
static int dme1737_i2c_get_features(int sio_cip, struct dme1737_data *data)
{
int err = 0, reg;
u16 addr;
dme1737_sio_enter(sio_cip);
/* Check device ID
* The DME1737 can return either 0x78 or 0x77 as its device ID.
* The SCH5027 returns 0x89 as its device ID. */
reg = force_id ? force_id : dme1737_sio_inb(sio_cip, 0x20);
if (!(reg == 0x77 || reg == 0x78 || reg == 0x89)) {
err = -ENODEV;
goto exit;
}
/* Select logical device A (runtime registers) */
dme1737_sio_outb(sio_cip, 0x07, 0x0a);
/* Get the base address of the runtime registers */
if (!(addr = (dme1737_sio_inb(sio_cip, 0x60) << 8) |
dme1737_sio_inb(sio_cip, 0x61))) {
err = -ENODEV;
goto exit;
}
/* Read the runtime registers to determine which optional features
* are enabled and available. Bits [3:2] of registers 0x43-0x46 are set
* to '10' if the respective feature is enabled. */
if ((inb(addr + 0x43) & 0x0c) == 0x08) { /* fan6 */
data->has_fan |= (1 << 5);
}
if ((inb(addr + 0x44) & 0x0c) == 0x08) { /* pwm6 */
data->has_pwm |= (1 << 5);
}
if ((inb(addr + 0x45) & 0x0c) == 0x08) { /* fan5 */
data->has_fan |= (1 << 4);
}
if ((inb(addr + 0x46) & 0x0c) == 0x08) { /* pwm5 */
data->has_pwm |= (1 << 4);
}
exit:
dme1737_sio_exit(sio_cip);
return err;
}
/* Return 0 if detection is successful, -ENODEV otherwise */
static int dme1737_i2c_detect(struct i2c_client *client, int kind,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
struct device *dev = &adapter->dev;
u8 company, verstep = 0;
const char *name;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
return -ENODEV;
}
/* A negative kind means that the driver was loaded with no force
* parameter (default), so we must identify the chip. */
if (kind < 0) {
company = i2c_smbus_read_byte_data(client, DME1737_REG_COMPANY);
verstep = i2c_smbus_read_byte_data(client, DME1737_REG_VERSTEP);
if (company == DME1737_COMPANY_SMSC &&
(verstep & DME1737_VERSTEP_MASK) == DME1737_VERSTEP) {
kind = dme1737;
} else if (company == DME1737_COMPANY_SMSC &&
verstep == SCH5027_VERSTEP) {
kind = sch5027;
} else {
return -ENODEV;
}
}
if (kind == sch5027) {
name = "sch5027";
} else {
kind = dme1737;
name = "dme1737";
}
dev_info(dev, "Found a %s chip at 0x%02x (rev 0x%02x).\n",
kind == sch5027 ? "SCH5027" : "DME1737", client->addr,
verstep);
strlcpy(info->type, name, I2C_NAME_SIZE);
return 0;
}
static int dme1737_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct dme1737_data *data;
struct device *dev = &client->dev;
int err;
data = kzalloc(sizeof(struct dme1737_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(client, data);
data->type = id->driver_data;
data->client = client;
data->name = client->name;
mutex_init(&data->update_lock);
/* Initialize the DME1737 chip */
if ((err = dme1737_init_device(dev))) {
dev_err(dev, "Failed to initialize device.\n");
goto exit_kfree;
}
/* Create sysfs files */
if ((err = dme1737_create_files(dev))) {
dev_err(dev, "Failed to create sysfs files.\n");
goto exit_kfree;
}
/* Register device */
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
dev_err(dev, "Failed to register device.\n");
err = PTR_ERR(data->hwmon_dev);
goto exit_remove;
}
return 0;
exit_remove:
dme1737_remove_files(dev);
exit_kfree:
kfree(data);
exit:
return err;
}
static int dme1737_i2c_remove(struct i2c_client *client)
{
struct dme1737_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
dme1737_remove_files(&client->dev);
kfree(data);
return 0;
}
static const struct i2c_device_id dme1737_id[] = {
{ "dme1737", dme1737 },
{ "sch5027", sch5027 },
{ }
};
MODULE_DEVICE_TABLE(i2c, dme1737_id);
static struct i2c_driver dme1737_i2c_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "dme1737",
},
.probe = dme1737_i2c_probe,
.remove = dme1737_i2c_remove,
.id_table = dme1737_id,
.detect = dme1737_i2c_detect,
.address_data = &addr_data,
};
/* ---------------------------------------------------------------------
* ISA device detection and registration
* --------------------------------------------------------------------- */
static int __init dme1737_isa_detect(int sio_cip, unsigned short *addr)
{
int err = 0, reg;
unsigned short base_addr;
dme1737_sio_enter(sio_cip);
/* Check device ID
* We currently know about SCH3112 (0x7c), SCH3114 (0x7d), and
* SCH3116 (0x7f). */
reg = force_id ? force_id : dme1737_sio_inb(sio_cip, 0x20);
if (!(reg == 0x7c || reg == 0x7d || reg == 0x7f)) {
err = -ENODEV;
goto exit;
}
/* Select logical device A (runtime registers) */
dme1737_sio_outb(sio_cip, 0x07, 0x0a);
/* Get the base address of the runtime registers */
if (!(base_addr = (dme1737_sio_inb(sio_cip, 0x60) << 8) |
dme1737_sio_inb(sio_cip, 0x61))) {
printk(KERN_ERR "dme1737: Base address not set.\n");
err = -ENODEV;
goto exit;
}
/* Access to the hwmon registers is through an index/data register
* pair located at offset 0x70/0x71. */
*addr = base_addr + 0x70;
exit:
dme1737_sio_exit(sio_cip);
return err;
}
static int __init dme1737_isa_device_add(unsigned short addr)
{
struct resource res = {
.start = addr,
.end = addr + DME1737_EXTENT - 1,
.name = "dme1737",
.flags = IORESOURCE_IO,
};
int err;
err = acpi_check_resource_conflict(&res);
if (err)
goto exit;
if (!(pdev = platform_device_alloc("dme1737", addr))) {
printk(KERN_ERR "dme1737: Failed to allocate device.\n");
err = -ENOMEM;
goto exit;
}
if ((err = platform_device_add_resources(pdev, &res, 1))) {
printk(KERN_ERR "dme1737: Failed to add device resource "
"(err = %d).\n", err);
goto exit_device_put;
}
if ((err = platform_device_add(pdev))) {
printk(KERN_ERR "dme1737: Failed to add device (err = %d).\n",
err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
pdev = NULL;
exit:
return err;
}
static int __devinit dme1737_isa_probe(struct platform_device *pdev)
{
u8 company, device;
struct resource *res;
struct dme1737_data *data;
struct device *dev = &pdev->dev;
int err;
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!request_region(res->start, DME1737_EXTENT, "dme1737")) {
dev_err(dev, "Failed to request region 0x%04x-0x%04x.\n",
(unsigned short)res->start,
(unsigned short)res->start + DME1737_EXTENT - 1);
err = -EBUSY;
goto exit;
}
if (!(data = kzalloc(sizeof(struct dme1737_data), GFP_KERNEL))) {
err = -ENOMEM;
goto exit_release_region;
}
data->addr = res->start;
platform_set_drvdata(pdev, data);
/* Skip chip detection if module is loaded with force_id parameter */
if (!force_id) {
company = dme1737_read(data, DME1737_REG_COMPANY);
device = dme1737_read(data, DME1737_REG_DEVICE);
if (!((company == DME1737_COMPANY_SMSC) &&
(device == SCH311X_DEVICE))) {
err = -ENODEV;
goto exit_kfree;
}
}
data->type = sch311x;
/* Fill in the remaining client fields and initialize the mutex */
data->name = "sch311x";
mutex_init(&data->update_lock);
dev_info(dev, "Found a SCH311x chip at 0x%04x\n", data->addr);
/* Initialize the chip */
if ((err = dme1737_init_device(dev))) {
dev_err(dev, "Failed to initialize device.\n");
goto exit_kfree;
}
/* Create sysfs files */
if ((err = dme1737_create_files(dev))) {
dev_err(dev, "Failed to create sysfs files.\n");
goto exit_kfree;
}
/* Register device */
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
dev_err(dev, "Failed to register device.\n");
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
dme1737_remove_files(dev);
exit_kfree:
platform_set_drvdata(pdev, NULL);
kfree(data);
exit_release_region:
release_region(res->start, DME1737_EXTENT);
exit:
return err;
}
static int __devexit dme1737_isa_remove(struct platform_device *pdev)
{
struct dme1737_data *data = platform_get_drvdata(pdev);
hwmon_device_unregister(data->hwmon_dev);
dme1737_remove_files(&pdev->dev);
release_region(data->addr, DME1737_EXTENT);
platform_set_drvdata(pdev, NULL);
kfree(data);
return 0;
}
static struct platform_driver dme1737_isa_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "dme1737",
},
.probe = dme1737_isa_probe,
.remove = __devexit_p(dme1737_isa_remove),
};
/* ---------------------------------------------------------------------
* Module initialization and cleanup
* --------------------------------------------------------------------- */
static int __init dme1737_init(void)
{
int err;
unsigned short addr;
if ((err = i2c_add_driver(&dme1737_i2c_driver))) {
goto exit;
}
if (dme1737_isa_detect(0x2e, &addr) &&
dme1737_isa_detect(0x4e, &addr) &&
(!probe_all_addr ||
(dme1737_isa_detect(0x162e, &addr) &&
dme1737_isa_detect(0x164e, &addr)))) {
/* Return 0 if we didn't find an ISA device */
return 0;
}
if ((err = platform_driver_register(&dme1737_isa_driver))) {
goto exit_del_i2c_driver;
}
/* Sets global pdev as a side effect */
if ((err = dme1737_isa_device_add(addr))) {
goto exit_del_isa_driver;
}
return 0;
exit_del_isa_driver:
platform_driver_unregister(&dme1737_isa_driver);
exit_del_i2c_driver:
i2c_del_driver(&dme1737_i2c_driver);
exit:
return err;
}
static void __exit dme1737_exit(void)
{
if (pdev) {
platform_device_unregister(pdev);
platform_driver_unregister(&dme1737_isa_driver);
}
i2c_del_driver(&dme1737_i2c_driver);
}
MODULE_AUTHOR("Juerg Haefliger <juergh@gmail.com>");
MODULE_DESCRIPTION("DME1737 sensors");
MODULE_LICENSE("GPL");
module_init(dme1737_init);
module_exit(dme1737_exit);
| gpl-2.0 |
sxwzhw/iproj | drivers/net/wireless/bcmdhd/src/dhd/sys/dhd_cfg80211.c | 505 | 18098 | /*
* Linux cfg80211 driver - Dongle Host Driver (DHD) related
*
* Copyright (C) 1999-2012, 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: wl_cfg80211.c,v 1.1.4.1.2.14 2011/02/09 01:40:07 Exp $
*/
#include <net/rtnetlink.h>
#include <bcmutils.h>
#include <wldev_common.h>
#include <wl_cfg80211.h>
#include <dhd_cfg80211.h>
#ifdef PKT_FILTER_SUPPORT
#include <dngl_stats.h>
#include <dhd.h>
#endif
extern struct wl_priv *wlcfg_drv_priv;
#ifdef PKT_FILTER_SUPPORT
extern uint dhd_pkt_filter_enable;
extern uint dhd_master_mode;
extern void dhd_pktfilter_offload_enable(dhd_pub_t * dhd, char *arg, int enable, int master_mode);
#endif
static int dhd_dongle_up = FALSE;
#include <dngl_stats.h>
#include <dhd.h>
#include <dhdioctl.h>
#include <wlioctl.h>
#include <dhd_cfg80211.h>
static s32 wl_dongle_up(struct net_device *ndev, u32 up);
/**
* Function implementations
*/
s32 dhd_cfg80211_init(struct wl_priv *wl)
{
dhd_dongle_up = FALSE;
return 0;
}
s32 dhd_cfg80211_deinit(struct wl_priv *wl)
{
dhd_dongle_up = FALSE;
return 0;
}
s32 dhd_cfg80211_down(struct wl_priv *wl)
{
dhd_dongle_up = FALSE;
return 0;
}
s32 dhd_cfg80211_set_p2p_info(struct wl_priv *wl, int val)
{
dhd_pub_t *dhd = (dhd_pub_t *)(wl->pub);
dhd->op_mode |= val;
WL_ERR(("Set : op_mode=0x%04x\n", dhd->op_mode));
#ifdef ARP_OFFLOAD_SUPPORT
if (dhd->arp_version == 1) {
/* IF P2P is enabled, disable arpoe */
dhd_arp_offload_set(dhd, 0);
dhd_arp_offload_enable(dhd, false);
}
#endif /* ARP_OFFLOAD_SUPPORT */
return 0;
}
s32 dhd_cfg80211_clean_p2p_info(struct wl_priv *wl)
{
dhd_pub_t *dhd = (dhd_pub_t *)(wl->pub);
dhd->op_mode &= ~(DHD_FLAG_P2P_GC_MODE | DHD_FLAG_P2P_GO_MODE);
WL_ERR(("Clean : op_mode=0x%04x\n", dhd->op_mode));
#ifdef ARP_OFFLOAD_SUPPORT
if (dhd->arp_version == 1) {
/* IF P2P is disabled, enable arpoe back for STA mode. */
dhd_arp_offload_set(dhd, dhd_arp_mode);
dhd_arp_offload_enable(dhd, true);
}
#endif /* ARP_OFFLOAD_SUPPORT */
return 0;
}
static s32 wl_dongle_up(struct net_device *ndev, u32 up)
{
s32 err = 0;
err = wldev_ioctl(ndev, WLC_UP, &up, sizeof(up), true);
if (unlikely(err)) {
WL_ERR(("WLC_UP error (%d)\n", err));
}
return err;
}
s32 dhd_config_dongle(struct wl_priv *wl, bool need_lock)
{
#ifndef DHD_SDALIGN
#define DHD_SDALIGN 32
#endif
struct net_device *ndev;
s32 err = 0;
WL_TRACE(("In\n"));
if (dhd_dongle_up) {
WL_ERR(("Dongle is already up\n"));
return err;
}
ndev = wl_to_prmry_ndev(wl);
if (need_lock)
rtnl_lock();
err = wl_dongle_up(ndev, 0);
if (unlikely(err)) {
WL_ERR(("wl_dongle_up failed\n"));
goto default_conf_out;
}
dhd_dongle_up = true;
default_conf_out:
if (need_lock)
rtnl_unlock();
return err;
}
/* TODO: clean up the BT-Coex code, it still have some legacy ioctl/iovar functions */
#define COEX_DHCP
#if defined(COEX_DHCP)
/* use New SCO/eSCO smart YG suppression */
#define BT_DHCP_eSCO_FIX
/* this flag boost wifi pkt priority to max, caution: -not fair to sco */
#define BT_DHCP_USE_FLAGS
/* T1 start SCO/ESCo priority suppression */
#define BT_DHCP_OPPR_WIN_TIME 2500
/* T2 turn off SCO/SCO supperesion is (timeout) */
#define BT_DHCP_FLAG_FORCE_TIME 5500
enum wl_cfg80211_btcoex_status {
BT_DHCP_IDLE,
BT_DHCP_START,
BT_DHCP_OPPR_WIN,
BT_DHCP_FLAG_FORCE_TIMEOUT
};
/*
* get named driver variable to uint register value and return error indication
* calling example: dev_wlc_intvar_get_reg(dev, "btc_params",66, ®_value)
*/
static int
dev_wlc_intvar_get_reg(struct net_device *dev, char *name,
uint reg, int *retval)
{
union {
char buf[WLC_IOCTL_SMLEN];
int val;
} var;
int error;
bcm_mkiovar(name, (char *)(®), sizeof(reg),
(char *)(&var), sizeof(var.buf));
error = wldev_ioctl(dev, WLC_GET_VAR, (char *)(&var), sizeof(var.buf), false);
*retval = dtoh32(var.val);
return (error);
}
static int
dev_wlc_bufvar_set(struct net_device *dev, char *name, char *buf, int len)
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31)
char ioctlbuf_local[1024];
#else
static char ioctlbuf_local[1024];
#endif /* LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31) */
bcm_mkiovar(name, buf, len, ioctlbuf_local, sizeof(ioctlbuf_local));
return (wldev_ioctl(dev, WLC_SET_VAR, ioctlbuf_local, sizeof(ioctlbuf_local), true));
}
/*
get named driver variable to uint register value and return error indication
calling example: dev_wlc_intvar_set_reg(dev, "btc_params",66, value)
*/
static int
dev_wlc_intvar_set_reg(struct net_device *dev, char *name, char *addr, char * val)
{
char reg_addr[8];
memset(reg_addr, 0, sizeof(reg_addr));
memcpy((char *)®_addr[0], (char *)addr, 4);
memcpy((char *)®_addr[4], (char *)val, 4);
return (dev_wlc_bufvar_set(dev, name, (char *)®_addr[0], sizeof(reg_addr)));
}
static bool btcoex_is_sco_active(struct net_device *dev)
{
int ioc_res = 0;
bool res = FALSE;
int sco_id_cnt = 0;
int param27;
int i;
for (i = 0; i < 12; i++) {
ioc_res = dev_wlc_intvar_get_reg(dev, "btc_params", 27, ¶m27);
WL_TRACE(("%s, sample[%d], btc params: 27:%x\n",
__FUNCTION__, i, param27));
if (ioc_res < 0) {
WL_ERR(("%s ioc read btc params error\n", __FUNCTION__));
break;
}
if ((param27 & 0x6) == 2) { /* count both sco & esco */
sco_id_cnt++;
}
if (sco_id_cnt > 2) {
WL_TRACE(("%s, sco/esco detected, pkt id_cnt:%d samples:%d\n",
__FUNCTION__, sco_id_cnt, i));
res = TRUE;
break;
}
msleep(5);
}
return res;
}
#if defined(BT_DHCP_eSCO_FIX)
/* Enhanced BT COEX settings for eSCO compatibility during DHCP window */
static int set_btc_esco_params(struct net_device *dev, bool trump_sco)
{
static bool saved_status = FALSE;
char buf_reg50va_dhcp_on[8] =
{ 50, 00, 00, 00, 0x22, 0x80, 0x00, 0x00 };
char buf_reg51va_dhcp_on[8] =
{ 51, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 };
char buf_reg64va_dhcp_on[8] =
{ 64, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 };
char buf_reg65va_dhcp_on[8] =
{ 65, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 };
char buf_reg71va_dhcp_on[8] =
{ 71, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 };
uint32 regaddr;
static uint32 saved_reg50;
static uint32 saved_reg51;
static uint32 saved_reg64;
static uint32 saved_reg65;
static uint32 saved_reg71;
if (trump_sco) {
/* this should reduce eSCO agressive retransmit
* w/o breaking it
*/
/* 1st save current */
WL_TRACE(("Do new SCO/eSCO coex algo {save &"
"override}\n"));
if ((!dev_wlc_intvar_get_reg(dev, "btc_params", 50, &saved_reg50)) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 51, &saved_reg51)) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 64, &saved_reg64)) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 65, &saved_reg65)) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 71, &saved_reg71))) {
saved_status = TRUE;
WL_TRACE(("%s saved bt_params[50,51,64,65,71]:"
"0x%x 0x%x 0x%x 0x%x 0x%x\n",
__FUNCTION__, saved_reg50, saved_reg51,
saved_reg64, saved_reg65, saved_reg71));
} else {
WL_ERR((":%s: save btc_params failed\n",
__FUNCTION__));
saved_status = FALSE;
return -1;
}
WL_TRACE(("override with [50,51,64,65,71]:"
"0x%x 0x%x 0x%x 0x%x 0x%x\n",
*(u32 *)(buf_reg50va_dhcp_on+4),
*(u32 *)(buf_reg51va_dhcp_on+4),
*(u32 *)(buf_reg64va_dhcp_on+4),
*(u32 *)(buf_reg65va_dhcp_on+4),
*(u32 *)(buf_reg71va_dhcp_on+4)));
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg50va_dhcp_on[0], 8);
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg51va_dhcp_on[0], 8);
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg64va_dhcp_on[0], 8);
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg65va_dhcp_on[0], 8);
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg71va_dhcp_on[0], 8);
saved_status = TRUE;
} else if (saved_status) {
/* restore previously saved bt params */
WL_TRACE(("Do new SCO/eSCO coex algo {save &"
"override}\n"));
regaddr = 50;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg50);
regaddr = 51;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg51);
regaddr = 64;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg64);
regaddr = 65;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg65);
regaddr = 71;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg71);
WL_TRACE(("restore bt_params[50,51,64,65,71]:"
"0x%x 0x%x 0x%x 0x%x 0x%x\n",
saved_reg50, saved_reg51, saved_reg64,
saved_reg65, saved_reg71));
saved_status = FALSE;
} else {
WL_ERR((":%s att to restore not saved BTCOEX params\n",
__FUNCTION__));
return -1;
}
return 0;
}
#endif /* BT_DHCP_eSCO_FIX */
static void
wl_cfg80211_bt_setflag(struct net_device *dev, bool set)
{
#if defined(BT_DHCP_USE_FLAGS)
char buf_flag7_dhcp_on[8] = { 7, 00, 00, 00, 0x1, 0x0, 0x00, 0x00 };
char buf_flag7_default[8] = { 7, 00, 00, 00, 0x0, 0x00, 0x00, 0x00};
#endif
#if defined(BT_DHCP_eSCO_FIX)
/* set = 1, save & turn on 0 - off & restore prev settings */
set_btc_esco_params(dev, set);
#endif
#if defined(BT_DHCP_USE_FLAGS)
WL_TRACE(("WI-FI priority boost via bt flags, set:%d\n", set));
if (set == TRUE)
/* Forcing bt_flag7 */
dev_wlc_bufvar_set(dev, "btc_flags",
(char *)&buf_flag7_dhcp_on[0],
sizeof(buf_flag7_dhcp_on));
else
/* Restoring default bt flag7 */
dev_wlc_bufvar_set(dev, "btc_flags",
(char *)&buf_flag7_default[0],
sizeof(buf_flag7_default));
#endif
}
static void wl_cfg80211_bt_timerfunc(ulong data)
{
struct btcoex_info *bt_local = (struct btcoex_info *)data;
WL_TRACE(("%s\n", __FUNCTION__));
bt_local->timer_on = 0;
schedule_work(&bt_local->work);
}
static void wl_cfg80211_bt_handler(struct work_struct *work)
{
struct btcoex_info *btcx_inf;
btcx_inf = container_of(work, struct btcoex_info, work);
if (btcx_inf->timer_on) {
btcx_inf->timer_on = 0;
del_timer_sync(&btcx_inf->timer);
}
switch (btcx_inf->bt_state) {
case BT_DHCP_START:
/* DHCP started
* provide OPPORTUNITY window to get DHCP address
*/
WL_TRACE(("%s bt_dhcp stm: started \n",
__FUNCTION__));
btcx_inf->bt_state = BT_DHCP_OPPR_WIN;
mod_timer(&btcx_inf->timer,
jiffies + msecs_to_jiffies(BT_DHCP_OPPR_WIN_TIME));
btcx_inf->timer_on = 1;
break;
case BT_DHCP_OPPR_WIN:
if (btcx_inf->dhcp_done) {
WL_TRACE(("%s DHCP Done before T1 expiration\n",
__FUNCTION__));
goto btc_coex_idle;
}
/* DHCP is not over yet, start lowering BT priority
* enforce btc_params + flags if necessary
*/
WL_TRACE(("%s DHCP T1:%d expired\n", __FUNCTION__,
BT_DHCP_OPPR_WIN_TIME));
if (btcx_inf->dev)
wl_cfg80211_bt_setflag(btcx_inf->dev, TRUE);
btcx_inf->bt_state = BT_DHCP_FLAG_FORCE_TIMEOUT;
mod_timer(&btcx_inf->timer,
jiffies + msecs_to_jiffies(BT_DHCP_FLAG_FORCE_TIME));
btcx_inf->timer_on = 1;
break;
case BT_DHCP_FLAG_FORCE_TIMEOUT:
if (btcx_inf->dhcp_done) {
WL_TRACE(("%s DHCP Done before T2 expiration\n",
__FUNCTION__));
} else {
/* Noo dhcp during T1+T2, restore BT priority */
WL_TRACE(("%s DHCP wait interval T2:%d"
"msec expired\n", __FUNCTION__,
BT_DHCP_FLAG_FORCE_TIME));
}
/* Restoring default bt priority */
if (btcx_inf->dev)
wl_cfg80211_bt_setflag(btcx_inf->dev, FALSE);
btc_coex_idle:
btcx_inf->bt_state = BT_DHCP_IDLE;
btcx_inf->timer_on = 0;
break;
default:
WL_ERR(("%s error g_status=%d !!!\n", __FUNCTION__,
btcx_inf->bt_state));
if (btcx_inf->dev)
wl_cfg80211_bt_setflag(btcx_inf->dev, FALSE);
btcx_inf->bt_state = BT_DHCP_IDLE;
btcx_inf->timer_on = 0;
break;
}
net_os_wake_unlock(btcx_inf->dev);
}
int wl_cfg80211_btcoex_init(struct wl_priv *wl)
{
struct btcoex_info *btco_inf = NULL;
btco_inf = kmalloc(sizeof(struct btcoex_info), GFP_KERNEL);
if (!btco_inf)
return -ENOMEM;
btco_inf->bt_state = BT_DHCP_IDLE;
btco_inf->ts_dhcp_start = 0;
btco_inf->ts_dhcp_ok = 0;
/* Set up timer for BT */
btco_inf->timer_ms = 10;
init_timer(&btco_inf->timer);
btco_inf->timer.data = (ulong)btco_inf;
btco_inf->timer.function = wl_cfg80211_bt_timerfunc;
btco_inf->dev = wl->wdev->netdev;
INIT_WORK(&btco_inf->work, wl_cfg80211_bt_handler);
wl->btcoex_info = btco_inf;
return 0;
}
void wl_cfg80211_btcoex_deinit(struct wl_priv *wl)
{
if (!wl->btcoex_info)
return;
if (wl->btcoex_info->timer_on) {
wl->btcoex_info->timer_on = 0;
del_timer_sync(&wl->btcoex_info->timer);
}
cancel_work_sync(&wl->btcoex_info->work);
kfree(wl->btcoex_info);
wl->btcoex_info = NULL;
}
#endif
int wl_cfg80211_set_btcoex_dhcp(struct net_device *dev, char *command)
{
struct wl_priv *wl = wlcfg_drv_priv;
char powermode_val = 0;
char buf_reg66va_dhcp_on[8] = { 66, 00, 00, 00, 0x10, 0x27, 0x00, 0x00 };
char buf_reg41va_dhcp_on[8] = { 41, 00, 00, 00, 0x33, 0x00, 0x00, 0x00 };
char buf_reg68va_dhcp_on[8] = { 68, 00, 00, 00, 0x90, 0x01, 0x00, 0x00 };
uint32 regaddr;
static uint32 saved_reg66;
static uint32 saved_reg41;
static uint32 saved_reg68;
static bool saved_status = FALSE;
#ifdef COEX_DHCP
char buf_flag7_default[8] = { 7, 00, 00, 00, 0x0, 0x00, 0x00, 0x00};
struct btcoex_info *btco_inf = wl->btcoex_info;
#endif /* COEX_DHCP */
#ifdef PKT_FILTER_SUPPORT
dhd_pub_t *dhd = (dhd_pub_t *)(wl->pub);
#endif
/* Figure out powermode 1 or o command */
strncpy((char *)&powermode_val, command + strlen("BTCOEXMODE") +1, 1);
if (strnicmp((char *)&powermode_val, "1", strlen("1")) == 0) {
WL_TRACE_HW4(("%s: DHCP session starts\n", __FUNCTION__));
#ifdef PKT_FILTER_SUPPORT
dhd->dhcp_in_progress = 1;
if (dhd->early_suspended) {
WL_TRACE_HW4(("DHCP in progressing , disable packet filter!!!\n"));
dhd_enable_packet_filter(0, dhd);
}
#endif
/* Retrieve and saved orig regs value */
if ((saved_status == FALSE) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 66, &saved_reg66)) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 41, &saved_reg41)) &&
(!dev_wlc_intvar_get_reg(dev, "btc_params", 68, &saved_reg68))) {
saved_status = TRUE;
WL_TRACE(("Saved 0x%x 0x%x 0x%x\n",
saved_reg66, saved_reg41, saved_reg68));
/* Disable PM mode during dhpc session */
/* Disable PM mode during dhpc session */
#ifdef COEX_DHCP
/* Start BT timer only for SCO connection */
if (btcoex_is_sco_active(dev)) {
/* btc_params 66 */
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg66va_dhcp_on[0],
sizeof(buf_reg66va_dhcp_on));
/* btc_params 41 0x33 */
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg41va_dhcp_on[0],
sizeof(buf_reg41va_dhcp_on));
/* btc_params 68 0x190 */
dev_wlc_bufvar_set(dev, "btc_params",
(char *)&buf_reg68va_dhcp_on[0],
sizeof(buf_reg68va_dhcp_on));
saved_status = TRUE;
btco_inf->bt_state = BT_DHCP_START;
btco_inf->timer_on = 1;
mod_timer(&btco_inf->timer, btco_inf->timer.expires);
WL_TRACE(("%s enable BT DHCP Timer\n",
__FUNCTION__));
}
#endif /* COEX_DHCP */
}
else if (saved_status == TRUE) {
WL_ERR(("%s was called w/o DHCP OFF. Continue\n", __FUNCTION__));
}
}
else if (strnicmp((char *)&powermode_val, "2", strlen("2")) == 0) {
#ifdef PKT_FILTER_SUPPORT
dhd->dhcp_in_progress = 0;
WL_TRACE_HW4(("%s: DHCP is complete \n", __FUNCTION__));
/* Enable packet filtering */
if (dhd->early_suspended) {
WL_TRACE_HW4(("DHCP is complete , enable packet filter!!!\n"));
dhd_enable_packet_filter(1, dhd);
}
#endif
/* Restoring PM mode */
#ifdef COEX_DHCP
/* Stop any bt timer because DHCP session is done */
WL_TRACE(("%s disable BT DHCP Timer\n", __FUNCTION__));
if (btco_inf->timer_on) {
btco_inf->timer_on = 0;
del_timer_sync(&btco_inf->timer);
if (btco_inf->bt_state != BT_DHCP_IDLE) {
/* need to restore original btc flags & extra btc params */
WL_TRACE(("%s bt->bt_state:%d\n",
__FUNCTION__, btco_inf->bt_state));
/* wake up btcoex thread to restore btlags+params */
schedule_work(&btco_inf->work);
}
}
/* Restoring btc_flag paramter anyway */
if (saved_status == TRUE)
dev_wlc_bufvar_set(dev, "btc_flags",
(char *)&buf_flag7_default[0], sizeof(buf_flag7_default));
#endif /* COEX_DHCP */
/* Restore original values */
if (saved_status == TRUE) {
regaddr = 66;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg66);
regaddr = 41;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg41);
regaddr = 68;
dev_wlc_intvar_set_reg(dev, "btc_params",
(char *)®addr, (char *)&saved_reg68);
WL_TRACE(("restore regs {66,41,68} <- 0x%x 0x%x 0x%x\n",
saved_reg66, saved_reg41, saved_reg68));
}
saved_status = FALSE;
}
else {
WL_ERR(("%s Unkwown yet power setting, ignored\n",
__FUNCTION__));
}
snprintf(command, 3, "OK");
return (strlen("OK"));
}
| gpl-2.0 |
liquidware/liquidware_beagleboard_linux | drivers/staging/rtl8192e/ieee80211/ieee80211_softmac.c | 761 | 104871 | /* IEEE 802.11 SoftMAC layer
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* Mostly extracted from the rtl8180-sa2400 driver for the
* in-kernel generic ieee802.11 stack.
*
* Few lines might be stolen from other part of the ieee80211
* stack. Copyright who own it's copyright
*
* WPA code stolen from the ipw2200 driver.
* Copyright who own it's copyright.
*
* released under the GPL
*/
#include "ieee80211.h"
#include <linux/random.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <asm/uaccess.h>
#ifdef ENABLE_DOT11D
#include "dot11d.h"
#endif
u8 rsn_authen_cipher_suite[16][4] = {
{0x00,0x0F,0xAC,0x00}, //Use group key, //Reserved
{0x00,0x0F,0xAC,0x01}, //WEP-40 //RSNA default
{0x00,0x0F,0xAC,0x02}, //TKIP //NONE //{used just as default}
{0x00,0x0F,0xAC,0x03}, //WRAP-historical
{0x00,0x0F,0xAC,0x04}, //CCMP
{0x00,0x0F,0xAC,0x05}, //WEP-104
};
short ieee80211_is_54g(struct ieee80211_network net)
{
return ((net.rates_ex_len > 0) || (net.rates_len > 4));
}
short ieee80211_is_shortslot(struct ieee80211_network net)
{
return (net.capability & WLAN_CAPABILITY_SHORT_SLOT);
}
/* returns the total length needed for pleacing the RATE MFIE
* tag and the EXTENDED RATE MFIE tag if needed.
* It encludes two bytes per tag for the tag itself and its len
*/
unsigned int ieee80211_MFIE_rate_len(struct ieee80211_device *ieee)
{
unsigned int rate_len = 0;
if (ieee->modulation & IEEE80211_CCK_MODULATION)
rate_len = IEEE80211_CCK_RATE_LEN + 2;
if (ieee->modulation & IEEE80211_OFDM_MODULATION)
rate_len += IEEE80211_OFDM_RATE_LEN + 2;
return rate_len;
}
/* pleace the MFIE rate, tag to the memory (double) poined.
* Then it updates the pointer so that
* it points after the new MFIE tag added.
*/
void ieee80211_MFIE_Brate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_CCK_MODULATION){
*tag++ = MFIE_TYPE_RATES;
*tag++ = 4;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_MFIE_Grate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_OFDM_MODULATION){
*tag++ = MFIE_TYPE_RATES_EX;
*tag++ = 8;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_WMM_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0x50;
*tag++ = 0xf2;
*tag++ = 0x02;//5
*tag++ = 0x00;
*tag++ = 0x01;
#ifdef SUPPORT_USPD
if(ieee->current_network.wmm_info & 0x80) {
*tag++ = 0x0f|MAX_SP_Len;
} else {
*tag++ = MAX_SP_Len;
}
#else
*tag++ = MAX_SP_Len;
#endif
*tag_p = tag;
}
#ifdef THOMAS_TURBO
void ieee80211_TURBO_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0xe0;
*tag++ = 0x4c;
*tag++ = 0x01;//5
*tag++ = 0x02;
*tag++ = 0x11;
*tag++ = 0x00;
*tag_p = tag;
printk(KERN_ALERT "This is enable turbo mode IE process\n");
}
#endif
void enqueue_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb)
{
int nh;
nh = (ieee->mgmt_queue_head +1) % MGMT_QUEUE_NUM;
/*
* if the queue is full but we have newer frames then
* just overwrites the oldest.
*
* if (nh == ieee->mgmt_queue_tail)
* return -1;
*/
ieee->mgmt_queue_head = nh;
ieee->mgmt_queue_ring[nh] = skb;
//return 0;
}
struct sk_buff *dequeue_mgmt(struct ieee80211_device *ieee)
{
struct sk_buff *ret;
if(ieee->mgmt_queue_tail == ieee->mgmt_queue_head)
return NULL;
ret = ieee->mgmt_queue_ring[ieee->mgmt_queue_tail];
ieee->mgmt_queue_tail =
(ieee->mgmt_queue_tail+1) % MGMT_QUEUE_NUM;
return ret;
}
void init_mgmt_queue(struct ieee80211_device *ieee)
{
ieee->mgmt_queue_tail = ieee->mgmt_queue_head = 0;
}
u8 MgntQuery_MgntFrameTxRate(struct ieee80211_device *ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8 rate;
// 2008/01/25 MH For broadcom, MGNT frame set as OFDM 6M.
if(pHTInfo->IOTAction & HT_IOT_ACT_MGNT_USE_CCK_6M)
rate = 0x0c;
else
rate = ieee->basic_rate & 0x7f;
if(rate == 0){
// 2005.01.26, by rcnjko.
if(ieee->mode == IEEE_A||
ieee->mode== IEEE_N_5G||
(ieee->mode== IEEE_N_24G&&!pHTInfo->bCurSuppCCK))
rate = 0x0c;
else
rate = 0x02;
}
/*
// Data rate of ProbeReq is already decided. Annie, 2005-03-31
if( pMgntInfo->bScanInProgress || (pMgntInfo->bDualModeScanStep!=0) )
{
if(pMgntInfo->dot11CurrentWirelessMode==WIRELESS_MODE_A)
rate = 0x0c;
else
rate = 0x02;
}
*/
return rate;
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl);
inline void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
unsigned long flags;
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header=
(struct ieee80211_hdr_3addr *) skb->data;
cb_desc *tcb_desc = (cb_desc *)(skb->cb + 8);
spin_lock_irqsave(&ieee->lock, flags);
/* called with 2nd param 0, no mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
tcb_desc->queue_index = MGNT_QUEUE;
tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
tcb_desc->RATRIndex = 7;
tcb_desc->bTxDisableRateFallBack = 1;
tcb_desc->bTxUseDriverAssingedRate = 1;
if(single){
if(ieee->queue_stop){
enqueue_mgmt(ieee,skb);
}else{
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0]<<4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
// ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
//dev_kfree_skb_any(skb);//edit by thomas
}
spin_unlock_irqrestore(&ieee->lock, flags);
}else{
spin_unlock_irqrestore(&ieee->lock, flags);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags);
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* check wether the managed packet queued greater than 5 */
if(!ieee->check_nic_enough_desc(ieee->dev,tcb_desc->queue_index)||\
(skb_queue_len(&ieee->skb_waitQ[tcb_desc->queue_index]) != 0)||\
(ieee->queue_stop) ) {
/* insert the skb packet to the management queue */
/* as for the completion function, it does not need
* to check it any more.
* */
//printk("%s():insert to waitqueue!\n",__FUNCTION__);
skb_queue_tail(&ieee->skb_waitQ[tcb_desc->queue_index], skb);
} else {
//printk("TX packet!\n");
ieee->softmac_hard_start_xmit(skb,ieee->dev);
//dev_kfree_skb_any(skb);//edit by thomas
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags);
}
}
inline void softmac_ps_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
cb_desc *tcb_desc = (cb_desc *)(skb->cb + 8);
tcb_desc->queue_index = MGNT_QUEUE;
tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
tcb_desc->RATRIndex = 7;
tcb_desc->bTxDisableRateFallBack = 1;
tcb_desc->bTxUseDriverAssingedRate = 1;
//printk("=============>%s()\n", __FUNCTION__);
if(single){
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
// ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
}else{
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_hard_start_xmit(skb,ieee->dev);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
inline struct sk_buff *ieee80211_probe_req(struct ieee80211_device *ieee)
{
unsigned int len,rate_len;
u8 *tag;
struct sk_buff *skb;
struct ieee80211_probe_request *req;
len = ieee->current_network.ssid_len;
rate_len = ieee80211_MFIE_rate_len(ieee);
skb = dev_alloc_skb(sizeof(struct ieee80211_probe_request) +
2 + len + rate_len + ieee->tx_headroom);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
req = (struct ieee80211_probe_request *) skb_put(skb,sizeof(struct ieee80211_probe_request));
req->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
req->header.duration_id = 0; //FIXME: is this OK ?
memset(req->header.addr1, 0xff, ETH_ALEN);
memcpy(req->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memset(req->header.addr3, 0xff, ETH_ALEN);
tag = (u8 *) skb_put(skb,len+2+rate_len);
*tag++ = MFIE_TYPE_SSID;
*tag++ = len;
memcpy(tag, ieee->current_network.ssid, len);
tag += len;
ieee80211_MFIE_Brate(ieee,&tag);
ieee80211_MFIE_Grate(ieee,&tag);
return skb;
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee);
void ieee80211_send_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
if(!ieee->ieee_up)
return;
//unsigned long flags;
skb = ieee80211_get_beacon_(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_beacons++;
//dev_kfree_skb_any(skb);//edit by thomas
}
// ieee->beacon_timer.expires = jiffies +
// (MSECS( ieee->current_network.beacon_interval -5));
//spin_lock_irqsave(&ieee->beacon_lock,flags);
if(ieee->beacon_txing && ieee->ieee_up){
// if(!timer_pending(&ieee->beacon_timer))
// add_timer(&ieee->beacon_timer);
mod_timer(&ieee->beacon_timer,jiffies+(MSECS(ieee->current_network.beacon_interval-5)));
}
//spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_send_beacon_cb(unsigned long _ieee)
{
struct ieee80211_device *ieee =
(struct ieee80211_device *) _ieee;
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
void ieee80211_send_probe(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
skb = ieee80211_probe_req(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_probe_rq++;
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_send_probe_requests(struct ieee80211_device *ieee)
{
if (ieee->active_scan && (ieee->softmac_features & IEEE_SOFTMAC_PROBERQ)){
ieee80211_send_probe(ieee);
ieee80211_send_probe(ieee);
}
}
/* this performs syncro scan blocking the caller until all channels
* in the allowed channel map has been checked.
*/
void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee)
{
short ch = 0;
#ifdef ENABLE_DOT11D
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
#endif
down(&ieee->scan_sem);
while(1)
{
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
goto out; /* scan completed */
#ifdef ENABLE_DOT11D
}while(!channel_map[ch]);
#else
}while(!ieee->channel_map[ch]);
#endif
/* this fuction can be called in two situations
* 1- We have switched to ad-hoc mode and we are
* performing a complete syncro scan before conclude
* there are no interesting cell and to create a
* new one. In this case the link state is
* IEEE80211_NOLINK until we found an interesting cell.
* If so the ieee8021_new_net, called by the RX path
* will set the state to IEEE80211_LINKED, so we stop
* scanning
* 2- We are linked and the root uses run iwlist scan.
* So we switch to IEEE80211_LINKED_SCANNING to remember
* that we are still logically linked (not interested in
* new network events, despite for updating the net list,
* but we are temporarly 'unlinked' as the driver shall
* not filter RX frames and the channel is changing.
* So the only situation in witch are interested is to check
* if the state become LINKED because of the #1 situation
*/
if (ieee->state == IEEE80211_LINKED)
goto out;
ieee->set_chan(ieee->dev, ch);
#ifdef ENABLE_DOT11D
if(channel_map[ch] == 1)
#endif
ieee80211_send_probe_requests(ieee);
/* this prevent excessive time wait when we
* need to wait for a syncro scan to end..
*/
if(ieee->state < IEEE80211_LINKED)
;
else
if (ieee->sync_scan_hurryup)
goto out;
msleep_interruptible_rsl(IEEE80211_SOFTMAC_SCAN_TIME);
}
out:
if(ieee->state < IEEE80211_LINKED){
ieee->actscanning = false;
up(&ieee->scan_sem);
}
else{
ieee->sync_scan_hurryup = 0;
#ifdef ENABLE_DOT11D
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
#endif
up(&ieee->scan_sem);
}
}
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
/* called both by wq with ieee->lock held */
void ieee80211_softmac_scan(struct ieee80211_device *ieee)
{
#if 0
short watchdog = 0;
do{
ieee->current_network.channel =
(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
if (watchdog++ > MAX_CHANNEL_NUMBER)
return; /* no good chans */
}while(!ieee->channel_map[ieee->current_network.channel]);
#endif
schedule_task(&ieee->softmac_scan_wq);
}
#endif
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
void ieee80211_softmac_scan_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, softmac_scan_wq);
#else
void ieee80211_softmac_scan_wq(struct ieee80211_device *ieee)
{
#endif
static short watchdog = 0;
u8 last_channel = ieee->current_network.channel;
#ifdef ENABLE_DOT11D
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
#endif
if(!ieee->ieee_up)
return;
down(&ieee->scan_sem);
do{
ieee->current_network.channel =
(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
if (watchdog++ > MAX_CHANNEL_NUMBER)
{
//if current channel is not in channel map, set to default channel.
#ifdef ENABLE_DOT11D
if (!channel_map[ieee->current_network.channel]);
#else
if (!ieee->channel_map[ieee->current_network.channel]);
#endif
ieee->current_network.channel = 6;
goto out; /* no good chans */
}
#ifdef ENABLE_DOT11D
}while(!channel_map[ieee->current_network.channel]);
#else
}while(!ieee->channel_map[ieee->current_network.channel]);
#endif
if (ieee->scanning == 0 )
goto out;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
#ifdef ENABLE_DOT11D
if(channel_map[ieee->current_network.channel] == 1)
#endif
ieee80211_send_probe_requests(ieee);
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, IEEE80211_SOFTMAC_SCAN_TIME);
#else
//ieee->scan_timer.expires = jiffies + MSECS(IEEE80211_SOFTMAC_SCAN_TIME);
if (ieee->scanning == 1)
mod_timer(&ieee->scan_timer,(jiffies + MSECS(IEEE80211_SOFTMAC_SCAN_TIME)));
#endif
up(&ieee->scan_sem);
return;
out:
#ifdef ENABLE_DOT11D
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
#endif
ieee->current_network.channel = last_channel;
ieee->actscanning = false;
watchdog = 0;
ieee->scanning = 0;
up(&ieee->scan_sem);
}
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
void ieee80211_softmac_scan_cb(unsigned long _dev)
{
unsigned long flags;
struct ieee80211_device *ieee = (struct ieee80211_device *)_dev;
spin_lock_irqsave(&ieee->lock, flags);
ieee80211_softmac_scan(ieee);
spin_unlock_irqrestore(&ieee->lock, flags);
}
#endif
void ieee80211_beacons_start(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 1;
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_beacons_stop(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 0;
del_timer_sync(&ieee->beacon_timer);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_stop_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->stop_send_beacons)
ieee->stop_send_beacons(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_stop(ieee);
}
void ieee80211_start_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->start_send_beacons)
ieee->start_send_beacons(ieee->dev);
if(ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_start(ieee);
}
void ieee80211_softmac_stop_scan(struct ieee80211_device *ieee)
{
// unsigned long flags;
//ieee->sync_scan_hurryup = 1;
down(&ieee->scan_sem);
// spin_lock_irqsave(&ieee->lock, flags);
if (ieee->scanning == 1){
ieee->scanning = 0;
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
cancel_delayed_work(&ieee->softmac_scan_wq);
#else
del_timer_sync(&ieee->scan_timer);
#endif
}
// spin_unlock_irqrestore(&ieee->lock, flags);
up(&ieee->scan_sem);
}
void ieee80211_stop_scan(struct ieee80211_device *ieee)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_stop_scan(ieee);
else
ieee->stop_scan(ieee->dev);
}
/* called with ieee->lock held */
void ieee80211_rtl_start_scan(struct ieee80211_device *ieee)
{
#ifdef ENABLE_IPS
if(ieee->ieee80211_ips_leave_wq != NULL)
ieee->ieee80211_ips_leave_wq(ieee->dev);
#endif
#ifdef ENABLE_DOT11D
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
#endif
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN){
if (ieee->scanning == 0){
ieee->scanning = 1;
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, 0);
#else
queue_work(ieee->wq, &ieee->softmac_scan_wq);
#endif
#else
ieee80211_softmac_scan(ieee);
#endif
}
}else
ieee->start_scan(ieee->dev);
}
/* called with wx_sem held */
void ieee80211_start_scan_syncro(struct ieee80211_device *ieee)
{
#ifdef ENABLE_DOT11D
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
#endif
ieee->sync_scan_hurryup = 0;
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_scan_syncro(ieee);
else
ieee->scan_syncro(ieee->dev);
}
inline struct sk_buff *ieee80211_authentication_req(struct ieee80211_network *beacon,
struct ieee80211_device *ieee, int challengelen)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
int len = sizeof(struct ieee80211_authentication) + challengelen + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb) return NULL;
skb_reserve(skb, ieee->tx_headroom);
auth = (struct ieee80211_authentication *)
skb_put(skb, sizeof(struct ieee80211_authentication));
auth->header.frame_ctl = IEEE80211_STYPE_AUTH;
if (challengelen) auth->header.frame_ctl |= IEEE80211_FCTL_WEP;
auth->header.duration_id = 0x013a; //FIXME
memcpy(auth->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr3, beacon->bssid, ETH_ALEN);
//auth->algorithm = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
if(ieee->auth_mode == 0)
auth->algorithm = WLAN_AUTH_OPEN;
else if(ieee->auth_mode == 1)
auth->algorithm = WLAN_AUTH_SHARED_KEY;
else if(ieee->auth_mode == 2)
auth->algorithm = WLAN_AUTH_OPEN;//0x80;
printk("=================>%s():auth->algorithm is %d\n",__FUNCTION__,auth->algorithm);
auth->transaction = cpu_to_le16(ieee->associate_seq);
ieee->associate_seq++;
auth->status = cpu_to_le16(WLAN_STATUS_SUCCESS);
return skb;
}
static struct sk_buff* ieee80211_probe_resp(struct ieee80211_device *ieee, u8 *dest)
{
u8 *tag;
int beacon_size;
struct ieee80211_probe_response *beacon_buf;
struct sk_buff *skb = NULL;
int encrypt;
int atim_len,erp_len;
struct ieee80211_crypt_data* crypt;
char *ssid = ieee->current_network.ssid;
int ssid_len = ieee->current_network.ssid_len;
int rate_len = ieee->current_network.rates_len+2;
int rate_ex_len = ieee->current_network.rates_ex_len;
int wpa_ie_len = ieee->wpa_ie_len;
u8 erpinfo_content = 0;
u8* tmp_ht_cap_buf;
u8 tmp_ht_cap_len=0;
u8* tmp_ht_info_buf;
u8 tmp_ht_info_len=0;
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8* tmp_generic_ie_buf=NULL;
u8 tmp_generic_ie_len=0;
if(rate_ex_len > 0) rate_ex_len+=2;
if(ieee->current_network.capability & WLAN_CAPABILITY_IBSS)
atim_len = 4;
else
atim_len = 0;
#if 1
if(ieee80211_is_54g(ieee->current_network))
erp_len = 3;
else
erp_len = 0;
#else
if((ieee->current_network.mode == IEEE_G)
||( ieee->current_network.mode == IEEE_N_24G && ieee->pHTInfo->bCurSuppCCK)) {
erp_len = 3;
erpinfo_content = 0;
if(ieee->current_network.buseprotection)
erpinfo_content |= ERP_UseProtection;
}
else
erp_len = 0;
#endif
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
((0 == strcmp(crypt->ops->name, "WEP") || wpa_ie_len));
//HT ralated element
#if 1
tmp_ht_cap_buf =(u8*) &(ieee->pHTInfo->SelfHTCap);
tmp_ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
tmp_ht_info_buf =(u8*) &(ieee->pHTInfo->SelfHTInfo);
tmp_ht_info_len = sizeof(ieee->pHTInfo->SelfHTInfo);
HTConstructCapabilityElement(ieee, tmp_ht_cap_buf, &tmp_ht_cap_len,encrypt);
HTConstructInfoElement(ieee,tmp_ht_info_buf,&tmp_ht_info_len, encrypt);
if(pHTInfo->bRegRT2RTAggregation)
{
tmp_generic_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
tmp_generic_ie_len = sizeof(ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, tmp_generic_ie_buf, &tmp_generic_ie_len);
}
// printk("===============>tmp_ht_cap_len is %d,tmp_ht_info_len is %d, tmp_generic_ie_len is %d\n",tmp_ht_cap_len,tmp_ht_info_len,tmp_generic_ie_len);
#endif
beacon_size = sizeof(struct ieee80211_probe_response)+2+
ssid_len
+3 //channel
+rate_len
+rate_ex_len
+atim_len
+erp_len
+wpa_ie_len
// +tmp_ht_cap_len
// +tmp_ht_info_len
// +tmp_generic_ie_len
// +wmm_len+2
+ieee->tx_headroom;
skb = dev_alloc_skb(beacon_size);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
beacon_buf = (struct ieee80211_probe_response*) skb_put(skb, (beacon_size - ieee->tx_headroom));
memcpy (beacon_buf->header.addr1, dest,ETH_ALEN);
memcpy (beacon_buf->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy (beacon_buf->header.addr3, ieee->current_network.bssid, ETH_ALEN);
beacon_buf->header.duration_id = 0; //FIXME
beacon_buf->beacon_interval =
cpu_to_le16(ieee->current_network.beacon_interval);
beacon_buf->capability =
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_IBSS);
beacon_buf->capability |=
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_SHORT_PREAMBLE); //add short preamble here
if(ieee->short_slot && (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_SLOT))
cpu_to_le16((beacon_buf->capability |= WLAN_CAPABILITY_SHORT_SLOT));
crypt = ieee->crypt[ieee->tx_keyidx];
#if 0
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
(0 == strcmp(crypt->ops->name, "WEP"));
#endif
if (encrypt)
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
beacon_buf->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_RESP);
beacon_buf->info_element[0].id = MFIE_TYPE_SSID;
beacon_buf->info_element[0].len = ssid_len;
tag = (u8*) beacon_buf->info_element[0].data;
memcpy(tag, ssid, ssid_len);
tag += ssid_len;
*(tag++) = MFIE_TYPE_RATES;
*(tag++) = rate_len-2;
memcpy(tag,ieee->current_network.rates,rate_len-2);
tag+=rate_len-2;
*(tag++) = MFIE_TYPE_DS_SET;
*(tag++) = 1;
*(tag++) = ieee->current_network.channel;
if(atim_len){
u16 val16;
*(tag++) = MFIE_TYPE_IBSS_SET;
*(tag++) = 2;
//*((u16*)(tag)) = cpu_to_le16(ieee->current_network.atim_window);
val16 = cpu_to_le16(ieee->current_network.atim_window);
memcpy((u8 *)tag, (u8 *)&val16, 2);
tag+=2;
}
if(erp_len){
*(tag++) = MFIE_TYPE_ERP;
*(tag++) = 1;
*(tag++) = erpinfo_content;
}
#if 0
//Include High Throuput capability
*(tag++) = MFIE_TYPE_HT_CAP;
*(tag++) = tmp_ht_cap_len - 2;
memcpy(tag, tmp_ht_cap_buf, tmp_ht_cap_len - 2);
tag += tmp_ht_cap_len - 2;
#endif
if(rate_ex_len){
*(tag++) = MFIE_TYPE_RATES_EX;
*(tag++) = rate_ex_len-2;
memcpy(tag,ieee->current_network.rates_ex,rate_ex_len-2);
tag+=rate_ex_len-2;
}
#if 0
//Include High Throuput info
*(tag++) = MFIE_TYPE_HT_INFO;
*(tag++) = tmp_ht_info_len - 2;
memcpy(tag, tmp_ht_info_buf, tmp_ht_info_len -2);
tag += tmp_ht_info_len - 2;
#endif
if (wpa_ie_len)
{
if (ieee->iw_mode == IW_MODE_ADHOC)
{//as Windows will set pairwise key same as the group key which is not allowed in Linux, so set this for IOT issue. WB 2008.07.07
memcpy(&ieee->wpa_ie[14], &ieee->wpa_ie[8], 4);
}
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
tag += wpa_ie_len;
}
#if 0
//
// Construct Realtek Proprietary Aggregation mode (Set AMPDU Factor to 2, 32k)
//
if(pHTInfo->bRegRT2RTAggregation)
{
(*tag++) = 0xdd;
(*tag++) = tmp_generic_ie_len - 2;
memcpy(tag,tmp_generic_ie_buf,tmp_generic_ie_len -2);
tag += tmp_generic_ie_len -2;
}
#endif
#if 0
if(ieee->qos_support)
{
(*tag++) = 0xdd;
(*tag++) = wmm_len;
memcpy(tag,QosOui,wmm_len);
tag += wmm_len;
}
#endif
//skb->dev = ieee->dev;
return skb;
}
struct sk_buff* ieee80211_assoc_resp(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *skb;
u8* tag;
struct ieee80211_crypt_data* crypt;
struct ieee80211_assoc_response_frame *assoc;
short encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
int len = sizeof(struct ieee80211_assoc_response_frame) + rate_len + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
assoc = (struct ieee80211_assoc_response_frame *)
skb_put(skb,sizeof(struct ieee80211_assoc_response_frame));
assoc->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP);
memcpy(assoc->header.addr1, dest,ETH_ALEN);
memcpy(assoc->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(assoc->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
assoc->capability = cpu_to_le16(ieee->iw_mode == IW_MODE_MASTER ?
WLAN_CAPABILITY_BSS : WLAN_CAPABILITY_IBSS);
if(ieee->short_slot)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (ieee->host_encrypt)
crypt = ieee->crypt[ieee->tx_keyidx];
else crypt = NULL;
encrypt = ( crypt && crypt->ops);
if (encrypt)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
assoc->status = 0;
assoc->aid = cpu_to_le16(ieee->assoc_id);
if (ieee->assoc_id == 0x2007) ieee->assoc_id=0;
else ieee->assoc_id++;
tag = (u8*) skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
return skb;
}
struct sk_buff* ieee80211_auth_resp(struct ieee80211_device *ieee,int status, u8 *dest)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
int len = ieee->tx_headroom + sizeof(struct ieee80211_authentication)+1;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb->len = sizeof(struct ieee80211_authentication);
auth = (struct ieee80211_authentication *)skb->data;
auth->status = cpu_to_le16(status);
auth->transaction = cpu_to_le16(2);
auth->algorithm = cpu_to_le16(WLAN_AUTH_OPEN);
memcpy(auth->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr1, dest, ETH_ALEN);
auth->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_AUTH);
return skb;
}
struct sk_buff* ieee80211_null_func(struct ieee80211_device *ieee,short pwr)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr* hdr;
skb = dev_alloc_skb(sizeof(struct ieee80211_hdr_3addr));
if (!skb)
return NULL;
hdr = (struct ieee80211_hdr_3addr*)skb_put(skb,sizeof(struct ieee80211_hdr_3addr));
memcpy(hdr->addr1, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->addr3, ieee->current_network.bssid, ETH_ALEN);
hdr->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS |
(pwr ? IEEE80211_FCTL_PM:0));
return skb;
}
struct sk_buff* ieee80211_pspoll_func(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
struct ieee80211_pspoll_hdr* hdr;
#ifdef USB_USE_ALIGNMENT
u32 Tmpaddr=0;
int alignment=0;
skb = dev_alloc_skb(sizeof(struct ieee80211_pspoll_hdr) + ieee->tx_headroom + USB_512B_ALIGNMENT_SIZE);
#else
skb = dev_alloc_skb(sizeof(struct ieee80211_pspoll_hdr)+ieee->tx_headroom);
#endif
if (!skb)
return NULL;
#ifdef USB_USE_ALIGNMENT
Tmpaddr = (u32)skb->data;
alignment = Tmpaddr & 0x1ff;
skb_reserve(skb,(USB_512B_ALIGNMENT_SIZE - alignment));
#endif
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct ieee80211_pspoll_hdr*)skb_put(skb,sizeof(struct ieee80211_pspoll_hdr));
memcpy(hdr->bssid, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->ta, ieee->dev->dev_addr, ETH_ALEN);
hdr->aid = cpu_to_le16(ieee->assoc_id | 0xc000);
hdr->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_CTL |IEEE80211_STYPE_PSPOLL | IEEE80211_FCTL_PM);
return skb;
}
void ieee80211_resp_to_assoc_rq(struct ieee80211_device *ieee, u8* dest)
{
struct sk_buff *buf = ieee80211_assoc_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
void ieee80211_resp_to_auth(struct ieee80211_device *ieee, int s, u8* dest)
{
struct sk_buff *buf = ieee80211_auth_resp(ieee, s, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
void ieee80211_resp_to_probe(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *buf = ieee80211_probe_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
inline struct sk_buff *ieee80211_association_req(struct ieee80211_network *beacon,struct ieee80211_device *ieee)
{
struct sk_buff *skb;
//unsigned long flags;
struct ieee80211_assoc_request_frame *hdr;
u8 *tag;//,*rsn_ie;
//short info_addr = 0;
//int i;
//u16 suite_count = 0;
//u8 suit_select = 0;
//unsigned int wpa_len = beacon->wpa_ie_len;
//for HT
u8* ht_cap_buf = NULL;
u8 ht_cap_len=0;
u8* realtek_ie_buf=NULL;
u8 realtek_ie_len=0;
int wpa_ie_len= ieee->wpa_ie_len;
unsigned int ckip_ie_len=0;
unsigned int ccxrm_ie_len=0;
unsigned int cxvernum_ie_len=0;
struct ieee80211_crypt_data* crypt;
int encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
unsigned int wmm_info_len = beacon->qos_data.supported?9:0;
#ifdef THOMAS_TURBO
unsigned int turbo_info_len = beacon->Turbo_Enable?9:0;
#endif
int len = 0;
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops && ((0 == strcmp(crypt->ops->name,"WEP") || wpa_ie_len));
//Include High Throuput capability && Realtek proprietary
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
{
ht_cap_buf = (u8*)&(ieee->pHTInfo->SelfHTCap);
ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
HTConstructCapabilityElement(ieee, ht_cap_buf, &ht_cap_len, encrypt);
if(ieee->pHTInfo->bCurrentRT2RTAggregation)
{
realtek_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
realtek_ie_len = sizeof( ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, realtek_ie_buf, &realtek_ie_len);
}
}
if(ieee->qos_support){
wmm_info_len = beacon->qos_data.supported?9:0;
}
if(beacon->bCkipSupported)
{
ckip_ie_len = 30+2;
}
if(beacon->bCcxRmEnable)
{
ccxrm_ie_len = 6+2;
}
if( beacon->BssCcxVerNumber >= 2 )
{
cxvernum_ie_len = 5+2;
}
#ifdef THOMAS_TURBO
len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_ie_len
+ wmm_info_len
+ turbo_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
#else
len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_ie_len
+ wmm_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
#endif
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct ieee80211_assoc_request_frame *)
skb_put(skb, sizeof(struct ieee80211_assoc_request_frame)+2);
hdr->header.frame_ctl = IEEE80211_STYPE_ASSOC_REQ;
hdr->header.duration_id= 37; //FIXME
memcpy(hdr->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(hdr->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->header.addr3, beacon->bssid, ETH_ALEN);
memcpy(ieee->ap_mac_addr, beacon->bssid, ETH_ALEN);//for HW security, John
hdr->capability = cpu_to_le16(WLAN_CAPABILITY_BSS);
if (beacon->capability & WLAN_CAPABILITY_PRIVACY )
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
if (beacon->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE); //add short_preamble here
if(ieee->short_slot)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (wmm_info_len) //QOS
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_QOS);
hdr->listen_interval = 0xa; //FIXME
hdr->info_element[0].id = MFIE_TYPE_SSID;
hdr->info_element[0].len = beacon->ssid_len;
tag = skb_put(skb, beacon->ssid_len);
memcpy(tag, beacon->ssid, beacon->ssid_len);
tag = skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
// For CCX 1 S13, CKIP. Added by Annie, 2006-08-14.
if( beacon->bCkipSupported )
{
static u8 AironetIeOui[] = {0x00, 0x01, 0x66}; // "4500-client"
u8 CcxAironetBuf[30];
OCTET_STRING osCcxAironetIE;
memset(CcxAironetBuf, 0,30);
osCcxAironetIE.Octet = CcxAironetBuf;
osCcxAironetIE.Length = sizeof(CcxAironetBuf);
//
// Ref. CCX test plan v3.61, 3.2.3.1 step 13.
// We want to make the device type as "4500-client". 060926, by CCW.
//
memcpy(osCcxAironetIE.Octet, AironetIeOui, sizeof(AironetIeOui));
// CCX1 spec V1.13, A01.1 CKIP Negotiation (page23):
// "The CKIP negotiation is started with the associate request from the client to the access point,
// containing an Aironet element with both the MIC and KP bits set."
osCcxAironetIE.Octet[IE_CISCO_FLAG_POSITION] |= (SUPPORT_CKIP_PK|SUPPORT_CKIP_MIC) ;
tag = skb_put(skb, ckip_ie_len);
*tag++ = MFIE_TYPE_AIRONET;
*tag++ = osCcxAironetIE.Length;
memcpy(tag,osCcxAironetIE.Octet,osCcxAironetIE.Length);
tag += osCcxAironetIE.Length;
}
if(beacon->bCcxRmEnable)
{
static u8 CcxRmCapBuf[] = {0x00, 0x40, 0x96, 0x01, 0x01, 0x00};
OCTET_STRING osCcxRmCap;
osCcxRmCap.Octet = CcxRmCapBuf;
osCcxRmCap.Length = sizeof(CcxRmCapBuf);
tag = skb_put(skb,ccxrm_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxRmCap.Length;
memcpy(tag,osCcxRmCap.Octet,osCcxRmCap.Length);
tag += osCcxRmCap.Length;
}
if( beacon->BssCcxVerNumber >= 2 )
{
u8 CcxVerNumBuf[] = {0x00, 0x40, 0x96, 0x03, 0x00};
OCTET_STRING osCcxVerNum;
CcxVerNumBuf[4] = beacon->BssCcxVerNumber;
osCcxVerNum.Octet = CcxVerNumBuf;
osCcxVerNum.Length = sizeof(CcxVerNumBuf);
tag = skb_put(skb,cxvernum_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxVerNum.Length;
memcpy(tag,osCcxVerNum.Octet,osCcxVerNum.Length);
tag += osCcxVerNum.Length;
}
//HT cap element
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
if(ieee->pHTInfo->ePeerHTSpecVer != HT_SPEC_VER_EWC)
{
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_HT_CAP;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf,ht_cap_len -2);
tag += ht_cap_len -2;
}
}
//choose what wpa_supplicant gives to associate.
tag = skb_put(skb, wpa_ie_len);
if (wpa_ie_len){
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
}
tag = skb_put(skb,wmm_info_len);
if(wmm_info_len) {
ieee80211_WMM_Info(ieee, &tag);
}
#ifdef THOMAS_TURBO
tag = skb_put(skb,turbo_info_len);
if(turbo_info_len) {
ieee80211_TURBO_Info(ieee, &tag);
}
#endif
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
if(ieee->pHTInfo->ePeerHTSpecVer == HT_SPEC_VER_EWC)
{
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf,ht_cap_len - 2);
tag += ht_cap_len -2;
}
if(ieee->pHTInfo->bCurrentRT2RTAggregation){
tag = skb_put(skb, realtek_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = realtek_ie_len - 2;
memcpy(tag, realtek_ie_buf,realtek_ie_len -2 );
}
}
// printk("<=====%s(), %p, %p\n", __FUNCTION__, ieee->dev, ieee->dev->dev_addr);
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
return skb;
}
void ieee80211_associate_abort(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock, flags);
ieee->associate_seq++;
/* don't scan, and avoid to have the RX path possibily
* try again to associate. Even do not react to AUTH or
* ASSOC response. Just wait for the retry wq to be scheduled.
* Here we will check if there are good nets to associate
* with, so we retry or just get back to NO_LINK and scanning
*/
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING){
IEEE80211_DEBUG_MGMT("Authentication failed\n");
ieee->softmac_stats.no_auth_rs++;
}else{
IEEE80211_DEBUG_MGMT("Association failed\n");
ieee->softmac_stats.no_ass_rs++;
}
ieee->state = IEEE80211_ASSOCIATING_RETRY;
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_delayed_work(ieee->wq, &ieee->associate_retry_wq, \
IEEE80211_SOFTMAC_ASSOC_RETRY_TIME);
#else
schedule_task(&ieee->associate_retry_wq);
#endif
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_associate_abort_cb(unsigned long dev)
{
ieee80211_associate_abort((struct ieee80211_device *) dev);
}
void ieee80211_associate_step1(struct ieee80211_device *ieee)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
IEEE80211_DEBUG_MGMT("Stopping scan\n");
ieee->softmac_stats.tx_auth_rq++;
skb=ieee80211_authentication_req(beacon, ieee, 0);
if (!skb)
ieee80211_associate_abort(ieee);
else{
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATING ;
IEEE80211_DEBUG_MGMT("Sending authentication request\n");
//printk(KERN_WARNING "Sending authentication request\n");
softmac_mgmt_xmit(skb, ieee);
//BUGON when you try to add_timer twice, using mod_timer may be better, john0709
if(!timer_pending(&ieee->associate_timer)){
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_rtl_auth_challenge(struct ieee80211_device *ieee, u8 *challenge, int chlen)
{
u8 *c;
struct sk_buff *skb;
struct ieee80211_network *beacon = &ieee->current_network;
// int hlen = sizeof(struct ieee80211_authentication);
ieee->associate_seq++;
ieee->softmac_stats.tx_auth_rq++;
skb = ieee80211_authentication_req(beacon, ieee, chlen+2);
if (!skb)
ieee80211_associate_abort(ieee);
else{
c = skb_put(skb, chlen+2);
*(c++) = MFIE_TYPE_CHALLENGE;
*(c++) = chlen;
memcpy(c, challenge, chlen);
IEEE80211_DEBUG_MGMT("Sending authentication challenge response\n");
ieee80211_encrypt_fragment(ieee, skb, sizeof(struct ieee80211_hdr_3addr ));
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
#if 0
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
#endif
//dev_kfree_skb_any(skb);//edit by thomas
}
kfree(challenge);
}
void ieee80211_associate_step2(struct ieee80211_device *ieee)
{
struct sk_buff* skb;
struct ieee80211_network *beacon = &ieee->current_network;
del_timer_sync(&ieee->associate_timer);
IEEE80211_DEBUG_MGMT("Sending association request\n");
ieee->softmac_stats.tx_ass_rq++;
skb=ieee80211_association_req(beacon, ieee);
if (!skb)
ieee80211_associate_abort(ieee);
else{
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
#if 0
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
#endif
//dev_kfree_skb_any(skb);//edit by thomas
}
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
void ieee80211_associate_complete_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_complete_wq);
#else
void ieee80211_associate_complete_wq(struct ieee80211_device *ieee)
{
#endif
printk(KERN_INFO "Associated successfully\n");
ieee->is_roaming = false;
if(ieee80211_is_54g(ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 108;
printk(KERN_INFO"Using G rates:%d\n", ieee->rate);
}else{
ieee->rate = 22;
printk(KERN_INFO"Using B rates:%d\n", ieee->rate);
}
if (ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
{
printk("Successfully associated, ht enabled\n");
HTOnAssocRsp(ieee);
}
else
{
printk("Successfully associated, ht not enabled(%d, %d)\n", ieee->pHTInfo->bCurrentHTSupport, ieee->pHTInfo->bEnableHT);
memset(ieee->dot11HTOperationalRateSet, 0, 16);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
}
ieee->LinkDetectInfo.SlotNum = 2 * (1 + ieee->current_network.beacon_interval/500);
// To prevent the immediately calling watch_dog after association.
if(ieee->LinkDetectInfo.NumRecvBcnInPeriod==0||ieee->LinkDetectInfo.NumRecvDataInPeriod==0 )
{
ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
ieee->LinkDetectInfo.NumRecvDataInPeriod= 1;
}
ieee->link_change(ieee->dev);
if(ieee->is_silent_reset == 0){
printk("============>normal associate\n");
notify_wx_assoc_event(ieee);
}
else if(ieee->is_silent_reset == 1)
{
printk("==================>silent reset associate\n");
ieee->is_silent_reset = 0;
}
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_associate_complete(struct ieee80211_device *ieee)
{
// int i;
// struct net_device* dev = ieee->dev;
del_timer_sync(&ieee->associate_timer);
#if 0
for(i = 0; i < 6; i++) {
ieee->seq_ctrl[i] = 0;
}
#endif
ieee->state = IEEE80211_LINKED;
#if 0
if (ieee->pHTInfo->bCurrentHTSupport)
{
printk("Successfully associated, ht enabled\n");
queue_work(ieee->wq, &ieee->ht_onAssRsp);
}
else
{
printk("Successfully associated, ht not enabled\n");
memset(ieee->dot11HTOperationalRateSet, 0, 16);
HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
}
#endif
//ieee->UpdateHalRATRTableHandler(dev, ieee->dot11HTOperationalRateSet);
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_work(ieee->wq, &ieee->associate_complete_wq);
#else
schedule_task(&ieee->associate_complete_wq);
#endif
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
void ieee80211_associate_procedure_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_procedure_wq);
#else
void ieee80211_associate_procedure_wq(struct ieee80211_device *ieee)
{
#endif
ieee->sync_scan_hurryup = 1;
#ifdef ENABLE_IPS
if(ieee->ieee80211_ips_leave != NULL)
ieee->ieee80211_ips_leave(ieee->dev);
#endif
down(&ieee->wx_sem);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
ieee80211_stop_scan(ieee);
printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
//ieee->set_chan(ieee->dev, ieee->current_network.channel);
HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
#ifdef ENABLE_IPS
if(ieee->eRFPowerState == eRfOff)
{
if(ieee->ieee80211_ips_leave_wq != NULL)
ieee->ieee80211_ips_leave_wq(ieee->dev);
up(&ieee->wx_sem);
return;
}
#endif
ieee->associate_seq = 1;
ieee80211_associate_step1(ieee);
up(&ieee->wx_sem);
}
inline void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net)
{
u8 tmp_ssid[IW_ESSID_MAX_SIZE+1];
int tmp_ssid_len = 0;
short apset,ssidset,ssidbroad,apmatch,ssidmatch;
/* we are interested in new new only if we are not associated
* and we are not associating / authenticating
*/
if (ieee->state != IEEE80211_NOLINK)
return;
if ((ieee->iw_mode == IW_MODE_INFRA) && !(net->capability & WLAN_CAPABILITY_BSS))
return;
if ((ieee->iw_mode == IW_MODE_ADHOC) && !(net->capability & WLAN_CAPABILITY_IBSS))
return;
if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC){
/* if the user specified the AP MAC, we need also the essid
* This could be obtained by beacons or, if the network does not
* broadcast it, it can be put manually.
*/
apset = ieee->wap_set;//(memcmp(ieee->current_network.bssid, zero,ETH_ALEN)!=0 );
ssidset = ieee->ssid_set;//ieee->current_network.ssid[0] != '\0';
ssidbroad = !(net->ssid_len == 0 || net->ssid[0]== '\0');
apmatch = (memcmp(ieee->current_network.bssid, net->bssid, ETH_ALEN)==0);
ssidmatch = (ieee->current_network.ssid_len == net->ssid_len)&&\
(!strncmp(ieee->current_network.ssid, net->ssid, net->ssid_len));
if ( /* if the user set the AP check if match.
* if the network does not broadcast essid we check the user supplyed ANY essid
* if the network does broadcast and the user does not set essid it is OK
* if the network does broadcast and the user did set essid chech if essid match
*/
( apset && apmatch &&
((ssidset && ssidbroad && ssidmatch) || (ssidbroad && !ssidset) || (!ssidbroad && ssidset)) ) ||
/* if the ap is not set, check that the user set the bssid
* and the network does bradcast and that those two bssid matches
*/
(!apset && ssidset && ssidbroad && ssidmatch)
){
/* if the essid is hidden replace it with the
* essid provided by the user.
*/
if (!ssidbroad){
strncpy(tmp_ssid, ieee->current_network.ssid, IW_ESSID_MAX_SIZE);
tmp_ssid_len = ieee->current_network.ssid_len;
}
memcpy(&ieee->current_network, net, sizeof(struct ieee80211_network));
if (!ssidbroad){
strncpy(ieee->current_network.ssid, tmp_ssid, IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = tmp_ssid_len;
}
printk(KERN_INFO"Linking with %s,channel:%d, qos:%d, myHT:%d, networkHT:%d\n",ieee->current_network.ssid,ieee->current_network.channel, ieee->current_network.qos_data.supported, ieee->pHTInfo->bEnableHT, ieee->current_network.bssht.bdSupportHT);
//ieee->pHTInfo->IOTAction = 0;
HTResetIOTSetting(ieee->pHTInfo);
if (ieee->iw_mode == IW_MODE_INFRA){
/* Join the network for the first time */
ieee->AsocRetryCount = 0;
//for HT by amy 080514
if((ieee->current_network.qos_data.supported == 1) &&
// (ieee->pHTInfo->bEnableHT && ieee->current_network.bssht.bdSupportHT))
ieee->current_network.bssht.bdSupportHT)
/*WB, 2008.09.09:bCurrentHTSupport and bEnableHT two flags are going to put together to check whether we are in HT now, so needn't to check bEnableHT flags here. That's is to say we will set to HT support whenever joined AP has the ability to support HT. And whether we are in HT or not, please check bCurrentHTSupport&&bEnableHT now please.*/
{
// ieee->pHTInfo->bCurrentHTSupport = true;
HTResetSelfAndSavePeerSetting(ieee, &(ieee->current_network));
}
else
{
ieee->pHTInfo->bCurrentHTSupport = false;
}
ieee->state = IEEE80211_ASSOCIATING;
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_work(ieee->wq, &ieee->associate_procedure_wq);
#else
schedule_task(&ieee->associate_procedure_wq);
#endif
}else{
if(ieee80211_is_54g(ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 108;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
printk(KERN_INFO"Using G rates\n");
}else{
ieee->rate = 22;
ieee->SetWirelessMode(ieee->dev, IEEE_B);
printk(KERN_INFO"Using B rates\n");
}
memset(ieee->dot11HTOperationalRateSet, 0, 16);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
ieee->state = IEEE80211_LINKED;
}
}
}
}
void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee)
{
unsigned long flags;
struct ieee80211_network *target;
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(target, &ieee->network_list, list) {
/* if the state become different that NOLINK means
* we had found what we are searching for
*/
if (ieee->state != IEEE80211_NOLINK)
break;
if (ieee->scan_age == 0 || time_after(target->last_scanned + ieee->scan_age, jiffies))
ieee80211_softmac_new_net(ieee, target);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
static inline u16 auth_parse(struct sk_buff *skb, u8** challenge, int *chlen)
{
struct ieee80211_authentication *a;
u8 *t;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n",skb->len);
return 0xcafe;
}
*challenge = NULL;
a = (struct ieee80211_authentication*) skb->data;
if(skb->len > (sizeof(struct ieee80211_authentication) +3)){
t = skb->data + sizeof(struct ieee80211_authentication);
if(*(t++) == MFIE_TYPE_CHALLENGE){
*chlen = *(t++);
*challenge = kmalloc(*chlen, GFP_ATOMIC);
memcpy(*challenge, t, *chlen);
}
}
return cpu_to_le16(a->status);
}
int auth_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_authentication *a;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth request: %d\n",skb->len);
return -1;
}
a = (struct ieee80211_authentication*) skb->data;
memcpy(dest,a->header.addr2, ETH_ALEN);
if (le16_to_cpu(a->algorithm) != WLAN_AUTH_OPEN)
return WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
return WLAN_STATUS_SUCCESS;
}
static short probe_rq_parse(struct ieee80211_device *ieee, struct sk_buff *skb, u8 *src)
{
u8 *tag;
u8 *skbend;
u8 *ssid=NULL;
u8 ssidlen = 0;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if (skb->len < sizeof (struct ieee80211_hdr_3addr ))
return -1; /* corrupted */
memcpy(src,header->addr2, ETH_ALEN);
skbend = (u8*)skb->data + skb->len;
tag = skb->data + sizeof (struct ieee80211_hdr_3addr );
while (tag+1 < skbend){
if (*tag == 0){
ssid = tag+2;
ssidlen = *(tag+1);
break;
}
tag++; /* point to the len field */
tag = tag + *(tag); /* point to the last data byte of the tag */
tag++; /* point to the next tag */
}
//IEEE80211DMESG("Card MAC address is "MACSTR, MAC2STR(src));
if (ssidlen == 0) return 1;
if (!ssid) return 1; /* ssid not found in tagged param */
return (!strncmp(ssid, ieee->current_network.ssid, ssidlen));
}
int assoc_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_assoc_request_frame *a;
if (skb->len < (sizeof(struct ieee80211_assoc_request_frame) -
sizeof(struct ieee80211_info_element))) {
IEEE80211_DEBUG_MGMT("invalid len in auth request:%d \n", skb->len);
return -1;
}
a = (struct ieee80211_assoc_request_frame*) skb->data;
memcpy(dest,a->header.addr2,ETH_ALEN);
return 0;
}
static inline u16 assoc_parse(struct ieee80211_device *ieee, struct sk_buff *skb, int *aid)
{
struct ieee80211_assoc_response_frame *response_head;
u16 status_code;
if (skb->len < sizeof(struct ieee80211_assoc_response_frame)){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
return 0xcafe;
}
response_head = (struct ieee80211_assoc_response_frame*) skb->data;
*aid = le16_to_cpu(response_head->aid) & 0x3fff;
status_code = le16_to_cpu(response_head->status);
if((status_code==WLAN_STATUS_ASSOC_DENIED_RATES || \
status_code==WLAN_STATUS_CAPS_UNSUPPORTED)&&
((ieee->mode == IEEE_G) &&
(ieee->current_network.mode == IEEE_N_24G) &&
(ieee->AsocRetryCount++ < (RT_ASOC_RETRY_LIMIT-1)))) {
ieee->pHTInfo->IOTAction |= HT_IOT_ACT_PURE_N_MODE;
}else {
ieee->AsocRetryCount = 0;
}
return le16_to_cpu(response_head->status);
}
static inline void
ieee80211_rx_probe_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_probe_rq++;
//DMESG("Dest is "MACSTR, MAC2STR(dest));
if (probe_rq_parse(ieee, skb, dest)){
//IEEE80211DMESG("Was for me!");
ieee->softmac_stats.tx_probe_rs++;
ieee80211_resp_to_probe(ieee, dest);
}
}
static inline void
ieee80211_rx_auth_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
int status;
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_auth_rq++;
status = auth_rq_parse(skb, dest);
if (status != -1) {
ieee80211_resp_to_auth(ieee, status, dest);
}
//DMESG("Dest is "MACSTR, MAC2STR(dest));
}
static inline void
ieee80211_rx_assoc_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//unsigned long flags;
ieee->softmac_stats.rx_ass_rq++;
if (assoc_rq_parse(skb,dest) != -1){
ieee80211_resp_to_assoc_rq(ieee, dest);
}
printk(KERN_INFO"New client associated: %pM\n", dest);
//FIXME
#if 0
spin_lock_irqsave(&ieee->lock,flags);
add_associate(ieee,dest);
spin_unlock_irqrestore(&ieee->lock,flags);
#endif
}
void ieee80211_sta_ps_send_null_frame(struct ieee80211_device *ieee, short pwr)
{
struct sk_buff *buf = ieee80211_null_func(ieee, pwr);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
void ieee80211_sta_ps_send_pspoll_frame(struct ieee80211_device *ieee)
{
struct sk_buff *buf = ieee80211_pspoll_func(ieee);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
short ieee80211_sta_ps_sleep(struct ieee80211_device *ieee, u32 *time_h, u32 *time_l)
{
int timeout = ieee->ps_timeout;
u8 dtim;
PRT_POWER_SAVE_CONTROL pPSC = (PRT_POWER_SAVE_CONTROL)(&(ieee->PowerSaveControl));
if(ieee->LPSDelayCnt)
{
//printk("===============>Delay enter LPS for DHCP and ARP packets...\n");
ieee->LPSDelayCnt --;
return 0;
}
dtim = ieee->current_network.dtim_data;
// printk("%s():DTIM:%d\n",__FUNCTION__,dtim);
if(!(dtim & IEEE80211_DTIM_VALID))
return 0;
timeout = ieee->current_network.beacon_interval; //should we use ps_timeout value or beacon_interval
//printk("VALID\n");
ieee->current_network.dtim_data = IEEE80211_DTIM_INVALID;
/* there's no need to nofity AP that I find you buffered with broadcast packet */
if(dtim & (IEEE80211_DTIM_UCAST & ieee->ps))
return 2;
if(!time_after(jiffies, ieee->dev->trans_start + MSECS(timeout))){
// printk("%s():111Oh Oh ,it is not time out return 0\n",__FUNCTION__);
return 0;
}
if(!time_after(jiffies, ieee->last_rx_ps_time + MSECS(timeout))){
// printk("%s():222Oh Oh ,it is not time out return 0\n",__FUNCTION__);
return 0;
}
if((ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE ) &&
(ieee->mgmt_queue_tail != ieee->mgmt_queue_head))
return 0;
if(time_l){
if(ieee->bAwakePktSent == true) {
pPSC->LPSAwakeIntvl = 1;//tx wake one beacon
} else {
u8 MaxPeriod = 1;
if(pPSC->LPSAwakeIntvl == 0)
pPSC->LPSAwakeIntvl = 1;
//pNdisCommon->RegLPSMaxIntvl /// 0x0 - eFastPs, 0xFF -DTIM, 0xNN - 0xNN * BeaconIntvl
if(pPSC->RegMaxLPSAwakeIntvl == 0) // Default (0x0 - eFastPs, 0xFF -DTIM, 0xNN - 0xNN * BeaconIntvl)
MaxPeriod = 1; // 1 Beacon interval
else if(pPSC->RegMaxLPSAwakeIntvl == 0xFF) // DTIM
MaxPeriod = ieee->current_network.dtim_period;
else
MaxPeriod = pPSC->RegMaxLPSAwakeIntvl;
pPSC->LPSAwakeIntvl = (pPSC->LPSAwakeIntvl >= MaxPeriod) ? MaxPeriod : (pPSC->LPSAwakeIntvl + 1);
}
{
u8 LPSAwakeIntvl_tmp = 0;
u8 period = ieee->current_network.dtim_period;
u8 count = ieee->current_network.tim.tim_count;
if(count == 0 ) {
if(pPSC->LPSAwakeIntvl > period)
LPSAwakeIntvl_tmp = period + (pPSC->LPSAwakeIntvl - period) -((pPSC->LPSAwakeIntvl-period)%period);
else
LPSAwakeIntvl_tmp = pPSC->LPSAwakeIntvl;
} else {
if(pPSC->LPSAwakeIntvl > ieee->current_network.tim.tim_count)
LPSAwakeIntvl_tmp = count + (pPSC->LPSAwakeIntvl - count) -((pPSC->LPSAwakeIntvl-count)%period);
else
LPSAwakeIntvl_tmp = pPSC->LPSAwakeIntvl;//ieee->current_network.tim.tim_count;//pPSC->LPSAwakeIntvl;
}
//printk("=========>%s()assoc_id:%d(%#x),bAwakePktSent:%d,DTIM:%d, sleep interval:%d, LPSAwakeIntvl_tmp:%d, count:%d\n",__func__,ieee->assoc_id,cpu_to_le16(ieee->assoc_id),ieee->bAwakePktSent,ieee->current_network.dtim_period,pPSC->LPSAwakeIntvl,LPSAwakeIntvl_tmp,count);
*time_l = ieee->current_network.last_dtim_sta_time[0]
+ MSECS(ieee->current_network.beacon_interval * LPSAwakeIntvl_tmp);
// * ieee->current_network.dtim_period) * 1000;
}
}
if(time_h){
*time_h = ieee->current_network.last_dtim_sta_time[1];
if(time_l && *time_l < ieee->current_network.last_dtim_sta_time[0])
*time_h += 1;
}
return 1;
}
inline void ieee80211_sta_ps(struct ieee80211_device *ieee)
{
u32 th,tl;
short sleep;
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if((ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)){
// #warning CHECK_LOCK_HERE
printk("=====>%s(): no need to ps,wake up!! ieee->ps is %d,ieee->iw_mode is %d,ieee->state is %d\n",
__FUNCTION__,ieee->ps,ieee->iw_mode,ieee->state);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_wakeup(ieee, 1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
sleep = ieee80211_sta_ps_sleep(ieee,&th, &tl);
/* 2 wake, 1 sleep, 0 do nothing */
if(sleep == 0)//it is not time out or dtim is not valid
{
//printk("===========>sleep is 0,do nothing\n");
goto out;
}
if(sleep == 1){
//printk("===========>sleep is 1,to sleep\n");
if(ieee->sta_sleep == 1){
//printk("%s(1): sta_sleep = 1, sleep again ++++++++++ \n", __func__);
ieee->enter_sleep_state(ieee->dev,th,tl);
}
else if(ieee->sta_sleep == 0){
// printk("send null 1\n");
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
if(ieee->ps_is_queue_empty(ieee->dev)){
ieee->sta_sleep = 2;
ieee->ack_tx_to_ieee = 1;
//printk("%s(2): sta_sleep = 0, notify AP we will sleeped ++++++++++ SendNullFunctionData\n", __func__);
ieee80211_sta_ps_send_null_frame(ieee,1);
ieee->ps_th = th;
ieee->ps_tl = tl;
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
ieee->bAwakePktSent = false;//after null to power save we set it to false. not listen every beacon.
}else if(sleep == 2){
//printk("==========>sleep is 2,to wakeup\n");
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
//printk("%s(3): pkt buffered in ap will awake ++++++++++ ieee80211_sta_wakeup\n", __func__);
ieee80211_sta_wakeup(ieee,1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
out:
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl)
{
if(ieee->sta_sleep == 0){
if(nl){
if(ieee->pHTInfo->IOTAction & HT_IOT_ACT_NULL_DATA_POWER_SAVING)
{
//printk("%s(1): notify AP we are awaked ++++++++++ SendNullFunctionData\n", __func__);
//printk("Warning: driver is probably failing to report TX ps error\n");
ieee->ack_tx_to_ieee = 1;
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
else
{
ieee->ack_tx_to_ieee = 1;
//printk("%s(2): notify AP we are awaked ++++++++++ Send PS-Poll\n", __func__);
ieee80211_sta_ps_send_pspoll_frame(ieee);
}
}
return;
}
if(ieee->sta_sleep == 1)
ieee->sta_wake_up(ieee->dev);
if(nl){
if(ieee->pHTInfo->IOTAction & HT_IOT_ACT_NULL_DATA_POWER_SAVING)
{
//printk("%s(3): notify AP we are awaked ++++++++++ SendNullFunctionData\n", __func__);
//printk("Warning: driver is probably failing to report TX ps error\n");
ieee->ack_tx_to_ieee = 1;
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
else
{
ieee->ack_tx_to_ieee = 1;
ieee->polling = true;
//printk("%s(4): notify AP we are awaked ++++++++++ Send PS-Poll\n", __func__);
//ieee80211_sta_ps_send_null_frame(ieee, 0);
ieee80211_sta_ps_send_pspoll_frame(ieee);
}
} else {
ieee->sta_sleep = 0;
ieee->polling = false;
}
}
void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success)
{
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->sta_sleep == 2){
/* Null frame with PS bit set */
if(success){
ieee->sta_sleep = 1;
//printk("notify AP we will sleep and send null ok, so sleep now++++++++++ enter_sleep_state\n");
ieee->enter_sleep_state(ieee->dev,ieee->ps_th,ieee->ps_tl);
}
} else {/* 21112005 - tx again null without PS bit if lost */
if((ieee->sta_sleep == 0) && !success){
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
//ieee80211_sta_ps_send_null_frame(ieee, 0);
if(ieee->pHTInfo->IOTAction & HT_IOT_ACT_NULL_DATA_POWER_SAVING)
{
//printk("notify AP we will sleep but send bull failed, so resend++++++++++ SendNullFunctionData\n");
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
else
{
//printk("notify AP we are awaked but send pspoll failed, so resend++++++++++ Send PS-Poll\n");
ieee80211_sta_ps_send_pspoll_frame(ieee);
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_process_action(struct ieee80211_device* ieee, struct sk_buff* skb)
{
struct ieee80211_hdr* header = (struct ieee80211_hdr*)skb->data;
u8* act = ieee80211_get_payload(header);
u8 tmp = 0;
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
if (act == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "error to get payload of action frame\n");
return;
}
tmp = *act;
act ++;
switch (tmp)
{
case ACT_CAT_BA:
if (*act == ACT_ADDBAREQ)
ieee80211_rx_ADDBAReq(ieee, skb);
else if (*act == ACT_ADDBARSP)
ieee80211_rx_ADDBARsp(ieee, skb);
else if (*act == ACT_DELBA)
ieee80211_rx_DELBA(ieee, skb);
break;
default:
// if (net_ratelimit())
// IEEE80211_DEBUG(IEEE80211_DL_BA, "unknown action frame(%d)\n", tmp);
break;
}
return;
}
inline int
ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
struct ieee80211_rx_stats *rx_stats, u16 type,
u16 stype)
{
struct ieee80211_hdr_3addr *header = (struct ieee80211_hdr_3addr *) skb->data;
u16 errcode;
u8* challenge;
int chlen=0;
int aid;
struct ieee80211_assoc_response_frame *assoc_resp;
// struct ieee80211_info_element *info_element;
bool bSupportNmode = true, bHalfSupportNmode = false; //default support N mode, disable halfNmode
if(!ieee->proto_started)
return 0;
#if 0
printk("%d, %d, %d, %d\n", ieee->sta_sleep, ieee->ps, ieee->iw_mode, ieee->state);
if(ieee->sta_sleep || (ieee->ps != IEEE80211_PS_DISABLED &&
ieee->iw_mode == IW_MODE_INFRA &&
ieee->state == IEEE80211_LINKED))
tasklet_schedule(&ieee->ps_task);
if(WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_PROBE_RESP &&
WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_BEACON)
ieee->last_rx_ps_time = jiffies;
#endif
switch (WLAN_FC_GET_STYPE(header->frame_ctl)) {
case IEEE80211_STYPE_ASSOC_RESP:
case IEEE80211_STYPE_REASSOC_RESP:
IEEE80211_DEBUG_MGMT("received [RE]ASSOCIATION RESPONSE (%d)\n",
WLAN_FC_GET_STYPE(header->frame_ctl));
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATED &&
ieee->iw_mode == IW_MODE_INFRA){
struct ieee80211_network network_resp;
struct ieee80211_network *network = &network_resp;
if (0 == (errcode=assoc_parse(ieee,skb, &aid))){
ieee->state=IEEE80211_LINKED;
ieee->assoc_id = aid;
ieee->softmac_stats.rx_ass_ok++;
/* station support qos */
/* Let the register setting defaultly with Legacy station */
if(ieee->qos_support) {
assoc_resp = (struct ieee80211_assoc_response_frame*)skb->data;
memset(network, 0, sizeof(*network));
if (ieee80211_parse_info_param(ieee,assoc_resp->info_element,\
rx_stats->len - sizeof(*assoc_resp),\
network,rx_stats)){
return 1;
}
else
{ //filling the PeerHTCap. //maybe not neccesary as we can get its info from current_network.
memcpy(ieee->pHTInfo->PeerHTCapBuf, network->bssht.bdHTCapBuf, network->bssht.bdHTCapLen);
memcpy(ieee->pHTInfo->PeerHTInfoBuf, network->bssht.bdHTInfoBuf, network->bssht.bdHTInfoLen);
}
if (ieee->handle_assoc_response != NULL)
ieee->handle_assoc_response(ieee->dev, (struct ieee80211_assoc_response_frame*)header, network);
}
ieee80211_associate_complete(ieee);
} else {
/* aid could not been allocated */
ieee->softmac_stats.rx_ass_err++;
printk(
"Association response status code 0x%x\n",
errcode);
IEEE80211_DEBUG_MGMT(
"Association response status code 0x%x\n",
errcode);
if(ieee->AsocRetryCount < RT_ASOC_RETRY_LIMIT) {
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_work(ieee->wq, &ieee->associate_procedure_wq);
#else
schedule_task(&ieee->associate_procedure_wq);
#endif
} else {
ieee80211_associate_abort(ieee);
}
}
}
break;
case IEEE80211_STYPE_ASSOC_REQ:
case IEEE80211_STYPE_REASSOC_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->iw_mode == IW_MODE_MASTER)
ieee80211_rx_assoc_rq(ieee, skb);
break;
case IEEE80211_STYPE_AUTH:
if (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE){
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING &&
ieee->iw_mode == IW_MODE_INFRA){
IEEE80211_DEBUG_MGMT("Received authentication response");
if (0 == (errcode=auth_parse(skb, &challenge, &chlen))){
if(ieee->open_wep || !challenge){
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATED;
ieee->softmac_stats.rx_auth_rs_ok++;
if(!(ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE))
{
if (!ieee->GetNmodeSupportBySecCfg(ieee->dev))
{
// WEP or TKIP encryption
if(IsHTHalfNmodeAPs(ieee))
{
bSupportNmode = true;
bHalfSupportNmode = true;
}
else
{
bSupportNmode = false;
bHalfSupportNmode = false;
}
printk("==========>to link with AP using SEC(%d, %d)\n", bSupportNmode, bHalfSupportNmode);
}
}
/* Dummy wirless mode setting to avoid encryption issue */
if(bSupportNmode) {
//N mode setting
ieee->SetWirelessMode(ieee->dev, \
ieee->current_network.mode);
}else{
//b/g mode setting
/*TODO*/
ieee->SetWirelessMode(ieee->dev, IEEE_G);
}
if (ieee->current_network.mode == IEEE_N_24G && bHalfSupportNmode == true)
{
printk("===============>entern half N mode\n");
ieee->bHalfWirelessN24GMode = true;
}
else
ieee->bHalfWirelessN24GMode = false;
ieee80211_associate_step2(ieee);
}else{
ieee80211_rtl_auth_challenge(ieee, challenge, chlen);
}
}else{
ieee->softmac_stats.rx_auth_rs_err++;
IEEE80211_DEBUG_MGMT("Authentication respose status code 0x%x",errcode);
printk("Authentication respose status code 0x%x",errcode);
ieee80211_associate_abort(ieee);
}
}else if (ieee->iw_mode == IW_MODE_MASTER){
ieee80211_rx_auth_rq(ieee, skb);
}
}
break;
case IEEE80211_STYPE_PROBE_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_PROBERS) &&
((ieee->iw_mode == IW_MODE_ADHOC ||
ieee->iw_mode == IW_MODE_MASTER) &&
ieee->state == IEEE80211_LINKED)){
ieee80211_rx_probe_rq(ieee, skb);
}
break;
case IEEE80211_STYPE_DISASSOC:
case IEEE80211_STYPE_DEAUTH:
/* FIXME for now repeat all the association procedure
* both for disassociation and deauthentication
*/
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_LINKED &&
ieee->iw_mode == IW_MODE_INFRA){
ieee->state = IEEE80211_ASSOCIATING;
ieee->softmac_stats.reassoc++;
ieee->is_roaming = true;
ieee80211_disassociate(ieee);
// notify_wx_assoc_event(ieee);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
RemovePeerTS(ieee, header->addr2);
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_work(ieee->wq, &ieee->associate_procedure_wq);
#else
schedule_task(&ieee->associate_procedure_wq);
#endif
}
break;
case IEEE80211_STYPE_MANAGE_ACT:
ieee80211_process_action(ieee,skb);
break;
default:
return -1;
break;
}
//dev_kfree_skb_any(skb);
return 0;
}
/* following are for a simplier TX queue management.
* Instead of using netif_[stop/wake]_queue the driver
* will uses these two function (plus a reset one), that
* will internally uses the kernel netif_* and takes
* care of the ieee802.11 fragmentation.
* So the driver receives a fragment per time and might
* call the stop function when it want without take care
* to have enough room to TX an entire packet.
* This might be useful if each fragment need it's own
* descriptor, thus just keep a total free memory > than
* the max fragmentation threshold is not enough.. If the
* ieee802.11 stack passed a TXB struct then you needed
* to keep N free descriptors where
* N = MAX_PACKET_SIZE / MIN_FRAG_TRESHOLD
* In this way you need just one and the 802.11 stack
* will take care of buffering fragments and pass them to
* to the driver later, when it wakes the queue.
*/
void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee)
{
unsigned int queue_index = txb->queue_index;
unsigned long flags;
int i;
cb_desc *tcb_desc = NULL;
spin_lock_irqsave(&ieee->lock,flags);
/* called with 2nd parm 0, no tx mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
/* update the tx status */
// ieee->stats.tx_bytes += txb->payload_size;
// ieee->stats.tx_packets++;
tcb_desc = (cb_desc *)(txb->fragments[0]->cb + MAX_DEV_ADDR_SIZE);
if(tcb_desc->bMulticast) {
ieee->stats.multicast++;
}
#if 1
/* if xmit available, just xmit it immediately, else just insert it to the wait queue */
for(i = 0; i < txb->nr_frags; i++) {
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
if ((skb_queue_len(&ieee->skb_drv_aggQ[queue_index]) != 0) ||
#else
if ((skb_queue_len(&ieee->skb_waitQ[queue_index]) != 0) ||
#endif
(!ieee->check_nic_enough_desc(ieee->dev,queue_index))||\
(ieee->queue_stop)) {
/* insert the skb packet to the wait queue */
/* as for the completion function, it does not need
* to check it any more.
* */
//printk("error:no descriptor left@queue_index %d\n", queue_index);
//ieee80211_rtl_stop_queue(ieee);
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
skb_queue_tail(&ieee->skb_drv_aggQ[queue_index], txb->fragments[i]);
#else
skb_queue_tail(&ieee->skb_waitQ[queue_index], txb->fragments[i]);
#endif
}else{
ieee->softmac_data_hard_start_xmit(
txb->fragments[i],
ieee->dev,ieee->rate);
//ieee->stats.tx_packets++;
//ieee->stats.tx_bytes += txb->fragments[i]->len;
//ieee->dev->trans_start = jiffies;
}
}
#endif
ieee80211_txb_free(txb);
//exit:
spin_unlock_irqrestore(&ieee->lock,flags);
}
/* called with ieee->lock acquired */
void ieee80211_resume_tx(struct ieee80211_device *ieee)
{
int i;
for(i = ieee->tx_pending.frag; i < ieee->tx_pending.txb->nr_frags; i++) {
if (ieee->queue_stop){
ieee->tx_pending.frag = i;
return;
}else{
ieee->softmac_data_hard_start_xmit(
ieee->tx_pending.txb->fragments[i],
ieee->dev,ieee->rate);
//(i+1)<ieee->tx_pending.txb->nr_frags);
ieee->stats.tx_packets++;
// ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
void ieee80211_reset_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock,flags);
init_mgmt_queue(ieee);
if (ieee->tx_pending.txb){
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
ieee->queue_stop = 0;
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_rtl_wake_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
struct sk_buff *skb;
struct ieee80211_hdr_3addr *header;
spin_lock_irqsave(&ieee->lock,flags);
if (! ieee->queue_stop) goto exit;
ieee->queue_stop = 0;
if(ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE){
while (!ieee->queue_stop && (skb = dequeue_mgmt(ieee))){
header = (struct ieee80211_hdr_3addr *) skb->data;
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
if (!ieee->queue_stop && ieee->tx_pending.txb)
ieee80211_resume_tx(ieee);
if (!ieee->queue_stop && netif_queue_stopped(ieee->dev)){
ieee->softmac_stats.swtxawake++;
netif_wake_queue(ieee->dev);
}
exit :
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_rtl_stop_queue(struct ieee80211_device *ieee)
{
//unsigned long flags;
//spin_lock_irqsave(&ieee->lock,flags);
if (! netif_queue_stopped(ieee->dev)){
netif_stop_queue(ieee->dev);
ieee->softmac_stats.swtxstop++;
}
ieee->queue_stop = 1;
//spin_unlock_irqrestore(&ieee->lock,flags);
}
inline void ieee80211_randomize_cell(struct ieee80211_device *ieee)
{
get_random_bytes(ieee->current_network.bssid, ETH_ALEN);
/* an IBSS cell address must have the two less significant
* bits of the first byte = 2
*/
ieee->current_network.bssid[0] &= ~0x01;
ieee->current_network.bssid[0] |= 0x02;
}
/* called in user context only */
void ieee80211_start_master_bss(struct ieee80211_device *ieee)
{
ieee->assoc_id = 1;
if (ieee->current_network.ssid_len == 0){
strncpy(ieee->current_network.ssid,
IEEE80211_DEFAULT_TX_ESSID,
IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
memcpy(ieee->current_network.bssid, ieee->dev->dev_addr, ETH_ALEN);
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->state = IEEE80211_LINKED;
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_start_monitor_mode(struct ieee80211_device *ieee)
{
if(ieee->raw_tx){
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
void ieee80211_start_ibss_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, start_ibss_wq);
#else
void ieee80211_start_ibss_wq(struct ieee80211_device *ieee)
{
#endif
/* iwconfig mode ad-hoc will schedule this and return
* on the other hand this will block further iwconfig SET
* operations because of the wx_sem hold.
* Anyway some most set operations set a flag to speed-up
* (abort) this wq (when syncro scanning) before sleeping
* on the semaphore
*/
if(!ieee->proto_started){
printk("==========oh driver down return\n");
return;
}
down(&ieee->wx_sem);
if (ieee->current_network.ssid_len == 0){
strcpy(ieee->current_network.ssid,IEEE80211_DEFAULT_TX_ESSID);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
ieee->state = IEEE80211_NOLINK;
/* check if we have this cell in our network list */
ieee80211_softmac_check_all_nets(ieee);
#ifdef ENABLE_DOT11D //if creating an ad-hoc, set its channel to 10 temporarily--this is the requirement for ASUS, not 11D, so disable 11d.
// if((IS_DOT11D_ENABLE(ieee)) && (ieee->state == IEEE80211_NOLINK))
if (ieee->state == IEEE80211_NOLINK)
ieee->current_network.channel = 6;
#endif
/* if not then the state is not linked. Maybe the user swithced to
* ad-hoc mode just after being in monitor mode, or just after
* being very few time in managed mode (so the card have had no
* time to scan all the chans..) or we have just run up the iface
* after setting ad-hoc mode. So we have to give another try..
* Here, in ibss mode, should be safe to do this without extra care
* (in bss mode we had to make sure no-one tryed to associate when
* we had just checked the ieee->state and we was going to start the
* scan) beacause in ibss mode the ieee80211_new_net function, when
* finds a good net, just set the ieee->state to IEEE80211_LINKED,
* so, at worst, we waste a bit of time to initiate an unneeded syncro
* scan, that will stop at the first round because it sees the state
* associated.
*/
if (ieee->state == IEEE80211_NOLINK)
ieee80211_start_scan_syncro(ieee);
/* the network definitively is not here.. create a new cell */
if (ieee->state == IEEE80211_NOLINK){
printk("creating new IBSS cell\n");
if(!ieee->wap_set)
ieee80211_randomize_cell(ieee);
if(ieee->modulation & IEEE80211_CCK_MODULATION){
ieee->current_network.rates_len = 4;
ieee->current_network.rates[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
ieee->current_network.rates[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
ieee->current_network.rates[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
ieee->current_network.rates[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}else
ieee->current_network.rates_len = 0;
if(ieee->modulation & IEEE80211_OFDM_MODULATION){
ieee->current_network.rates_ex_len = 8;
ieee->current_network.rates_ex[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
ieee->current_network.rates_ex[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
ieee->current_network.rates_ex[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
ieee->current_network.rates_ex[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
ieee->current_network.rates_ex[4] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
ieee->current_network.rates_ex[5] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
ieee->current_network.rates_ex[6] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
ieee->current_network.rates_ex[7] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
ieee->rate = 108;
}else{
ieee->current_network.rates_ex_len = 0;
ieee->rate = 22;
}
// By default, WMM function will be disabled in IBSS mode
ieee->current_network.QoS_Enable = 0;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
ieee->current_network.atim_window = 0;
ieee->current_network.capability = WLAN_CAPABILITY_IBSS;
if(ieee->short_slot)
ieee->current_network.capability |= WLAN_CAPABILITY_SHORT_SLOT;
}
ieee->state = IEEE80211_LINKED;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
ieee80211_start_send_beacons(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
up(&ieee->wx_sem);
}
inline void ieee80211_start_ibss(struct ieee80211_device *ieee)
{
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
queue_delayed_work(ieee->wq, &ieee->start_ibss_wq, 150);
#else
schedule_task(&ieee->start_ibss_wq);
#endif
}
/* this is called only in user context, with wx_sem held */
void ieee80211_start_bss(struct ieee80211_device *ieee)
{
unsigned long flags;
#ifdef ENABLE_DOT11D
//
// Ref: 802.11d 11.1.3.3
// STA shall not start a BSS unless properly formed Beacon frame including a Country IE.
//
if(IS_DOT11D_ENABLE(ieee) && !IS_COUNTRY_IE_VALID(ieee))
{
if(! ieee->bGlobalDomain)
{
return;
}
}
#endif
/* check if we have already found the net we
* are interested in (if any).
* if not (we are disassociated and we are not
* in associating / authenticating phase) start the background scanning.
*/
ieee80211_softmac_check_all_nets(ieee);
/* ensure no-one start an associating process (thus setting
* the ieee->state to ieee80211_ASSOCIATING) while we
* have just cheked it and we are going to enable scan.
* The ieee80211_new_net function is always called with
* lock held (from both ieee80211_softmac_check_all_nets and
* the rx path), so we cannot be in the middle of such function
*/
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->state == IEEE80211_NOLINK){
#ifdef ENABLE_IPS
if(ieee->ieee80211_ips_leave_wq != NULL)
ieee->ieee80211_ips_leave_wq(ieee->dev);
#endif
ieee->actscanning = true;
ieee80211_rtl_start_scan(ieee);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
/* called only in userspace context */
void ieee80211_disassociate(struct ieee80211_device *ieee)
{
netif_carrier_off(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)
ieee80211_reset_queue(ieee);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
#ifdef ENABLE_DOT11D
if(IS_DOT11D_ENABLE(ieee))
Dot11d_Reset(ieee);
#endif
ieee->state = IEEE80211_NOLINK;
ieee->is_set_key = false;
ieee->link_change(ieee->dev);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
notify_wx_assoc_event(ieee);
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
void ieee80211_associate_retry_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, associate_retry_wq);
#else
void ieee80211_associate_retry_wq(struct ieee80211_device *ieee)
{
#endif
unsigned long flags;
down(&ieee->wx_sem);
if(!ieee->proto_started)
goto exit;
if(ieee->state != IEEE80211_ASSOCIATING_RETRY)
goto exit;
/* until we do not set the state to IEEE80211_NOLINK
* there are no possibility to have someone else trying
* to start an association procdure (we get here with
* ieee->state = IEEE80211_ASSOCIATING).
* When we set the state to IEEE80211_NOLINK it is possible
* that the RX path run an attempt to associate, but
* both ieee80211_softmac_check_all_nets and the
* RX path works with ieee->lock held so there are no
* problems. If we are still disassociated then start a scan.
* the lock here is necessary to ensure no one try to start
* an association procedure when we have just checked the
* state and we are going to start the scan.
*/
ieee->beinretry = true;
ieee->state = IEEE80211_NOLINK;
ieee80211_softmac_check_all_nets(ieee);
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->state == IEEE80211_NOLINK)
{
ieee->is_roaming= false;
ieee->actscanning = true;
ieee80211_rtl_start_scan(ieee);
}
spin_unlock_irqrestore(&ieee->lock, flags);
ieee->beinretry = false;
exit:
up(&ieee->wx_sem);
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee)
{
u8 broadcast_addr[] = {0xff,0xff,0xff,0xff,0xff,0xff};
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_probe_resp(ieee, broadcast_addr);
if (!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_BEACON);
return skb;
}
struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_get_beacon_(ieee);
if(!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
return skb;
}
void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee, u8 shutdown)
{
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
ieee80211_stop_protocol(ieee, shutdown);
up(&ieee->wx_sem);
}
void ieee80211_stop_protocol(struct ieee80211_device *ieee, u8 shutdown)
{
if (!ieee->proto_started)
return;
if(shutdown)
ieee->proto_started = 0;
ieee->proto_stoppping = 1;
ieee80211_stop_send_beacons(ieee);
del_timer_sync(&ieee->associate_timer);
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
cancel_delayed_work(&ieee->associate_retry_wq);
cancel_delayed_work(&ieee->start_ibss_wq);
#endif
ieee80211_stop_scan(ieee);
ieee80211_disassociate(ieee);
RemoveAllTS(ieee); //added as we disconnect from the previous BSS, Remove all TS
ieee->proto_stoppping = 0;
}
void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 0;
down(&ieee->wx_sem);
ieee80211_start_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_start_protocol(struct ieee80211_device *ieee)
{
short ch = 0;
int i = 0;
if (ieee->proto_started)
return;
ieee->proto_started = 1;
if (ieee->current_network.channel == 0){
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
return; /* no channel found */
#ifdef ENABLE_DOT11D
}while(!GET_DOT11D_INFO(ieee)->channel_map[ch]);
#else
}while(!ieee->channel_map[ch]);
#endif
ieee->current_network.channel = ch;
}
if (ieee->current_network.beacon_interval == 0)
ieee->current_network.beacon_interval = 100;
// printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
// ieee->set_chan(ieee->dev,ieee->current_network.channel);
for(i = 0; i < 17; i++) {
ieee->last_rxseq_num[i] = -1;
ieee->last_rxfrag_num[i] = -1;
ieee->last_packet_time[i] = 0;
}
ieee->init_wmmparam_flag = 0;//reinitialize AC_xx_PARAM registers.
ieee->state = IEEE80211_NOLINK;
/* if the user set the MAC of the ad-hoc cell and then
* switch to managed mode, shall we make sure that association
* attempts does not fail just because the user provide the essid
* and the nic is still checking for the AP MAC ??
*/
if (ieee->iw_mode == IW_MODE_INFRA)
ieee80211_start_bss(ieee);
else if (ieee->iw_mode == IW_MODE_ADHOC)
ieee80211_start_ibss(ieee);
else if (ieee->iw_mode == IW_MODE_MASTER)
ieee80211_start_master_bss(ieee);
else if(ieee->iw_mode == IW_MODE_MONITOR)
ieee80211_start_monitor_mode(ieee);
}
#define DRV_NAME "Ieee80211"
void ieee80211_softmac_init(struct ieee80211_device *ieee)
{
int i;
memset(&ieee->current_network, 0, sizeof(struct ieee80211_network));
ieee->state = IEEE80211_NOLINK;
ieee->sync_scan_hurryup = 0;
for(i = 0; i < 5; i++) {
ieee->seq_ctrl[i] = 0;
}
#ifdef ENABLE_DOT11D
ieee->pDot11dInfo = kzalloc(sizeof(RT_DOT11D_INFO), GFP_ATOMIC);
if (!ieee->pDot11dInfo)
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc memory for DOT11D\n");
#endif
//added for AP roaming
ieee->LinkDetectInfo.SlotNum = 2;
ieee->LinkDetectInfo.NumRecvBcnInPeriod=0;
ieee->LinkDetectInfo.NumRecvDataInPeriod=0;
ieee->assoc_id = 0;
ieee->queue_stop = 0;
ieee->scanning = 0;
ieee->softmac_features = 0; //so IEEE2100-like driver are happy
ieee->wap_set = 0;
ieee->ssid_set = 0;
ieee->proto_started = 0;
ieee->basic_rate = IEEE80211_DEFAULT_BASIC_RATE;
ieee->rate = 22;
ieee->ps = IEEE80211_PS_DISABLED;
ieee->sta_sleep = 0;
ieee->Regdot11HTOperationalRateSet[0]= 0xff;//support MCS 0~7
ieee->Regdot11HTOperationalRateSet[1]= 0xff;//support MCS 8~15
ieee->Regdot11HTOperationalRateSet[4]= 0x01;
//added by amy
ieee->actscanning = false;
ieee->beinretry = false;
ieee->is_set_key = false;
init_mgmt_queue(ieee);
ieee->sta_edca_param[0] = 0x0000A403;
ieee->sta_edca_param[1] = 0x0000A427;
ieee->sta_edca_param[2] = 0x005E4342;
ieee->sta_edca_param[3] = 0x002F3262;
ieee->aggregation = true;
ieee->enable_rx_imm_BA = 1;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
init_timer(&ieee->scan_timer);
ieee->scan_timer.data = (unsigned long)ieee;
ieee->scan_timer.function = ieee80211_softmac_scan_cb;
#endif
ieee->tx_pending.txb = NULL;
init_timer(&ieee->associate_timer);
ieee->associate_timer.data = (unsigned long)ieee;
ieee->associate_timer.function = ieee80211_associate_abort_cb;
init_timer(&ieee->beacon_timer);
ieee->beacon_timer.data = (unsigned long) ieee;
ieee->beacon_timer.function = ieee80211_send_beacon_cb;
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
#ifdef PF_SYNCTHREAD
ieee->wq = create_workqueue(DRV_NAME,0);
#else
ieee->wq = create_workqueue(DRV_NAME);
#endif
#endif
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
INIT_DELAYED_WORK(&ieee->start_ibss_wq,ieee80211_start_ibss_wq);
INIT_WORK(&ieee->associate_complete_wq, ieee80211_associate_complete_wq);
INIT_WORK(&ieee->associate_procedure_wq, ieee80211_associate_procedure_wq);
INIT_DELAYED_WORK(&ieee->softmac_scan_wq,ieee80211_softmac_scan_wq);
INIT_DELAYED_WORK(&ieee->associate_retry_wq, ieee80211_associate_retry_wq);
INIT_WORK(&ieee->wx_sync_scan_wq,ieee80211_wx_sync_scan_wq);
#else
INIT_WORK(&ieee->start_ibss_wq,(void(*)(void*)) ieee80211_start_ibss_wq,ieee);
INIT_WORK(&ieee->associate_retry_wq,(void(*)(void*)) ieee80211_associate_retry_wq,ieee);
INIT_WORK(&ieee->associate_complete_wq,(void(*)(void*)) ieee80211_associate_complete_wq,ieee);
INIT_WORK(&ieee->associate_procedure_wq,(void(*)(void*)) ieee80211_associate_procedure_wq,ieee);
INIT_WORK(&ieee->softmac_scan_wq,(void(*)(void*)) ieee80211_softmac_scan_wq,ieee);
INIT_WORK(&ieee->wx_sync_scan_wq,(void(*)(void*)) ieee80211_wx_sync_scan_wq,ieee);
#endif
#else
tq_init(&ieee->start_ibss_wq,(void(*)(void*)) ieee80211_start_ibss_wq,ieee);
tq_init(&ieee->associate_retry_wq,(void(*)(void*)) ieee80211_associate_retry_wq,ieee);
tq_init(&ieee->associate_complete_wq,(void(*)(void*)) ieee80211_associate_complete_wq,ieee);
tq_init(&ieee->associate_procedure_wq,(void(*)(void*)) ieee80211_associate_procedure_wq,ieee);
tq_init(&ieee->softmac_scan_wq,(void(*)(void*)) ieee80211_softmac_scan_wq,ieee);
tq_init(&ieee->wx_sync_scan_wq,(void(*)(void*)) ieee80211_wx_sync_scan_wq,ieee);
#endif
sema_init(&ieee->wx_sem, 1);
sema_init(&ieee->scan_sem, 1);
#ifdef ENABLE_IPS
sema_init(&ieee->ips_sem,1);
#endif
spin_lock_init(&ieee->mgmt_tx_lock);
spin_lock_init(&ieee->beacon_lock);
tasklet_init(&ieee->ps_task,
(void(*)(unsigned long)) ieee80211_sta_ps,
(unsigned long)ieee);
}
void ieee80211_softmac_free(struct ieee80211_device *ieee)
{
down(&ieee->wx_sem);
#ifdef ENABLE_DOT11D
if(NULL != ieee->pDot11dInfo)
{
kfree(ieee->pDot11dInfo);
ieee->pDot11dInfo = NULL;
}
#endif
del_timer_sync(&ieee->associate_timer);
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
cancel_delayed_work(&ieee->associate_retry_wq);
destroy_workqueue(ieee->wq);
#endif
up(&ieee->wx_sem);
}
/********************************************************
* Start of WPA code. *
* this is stolen from the ipw2200 driver *
********************************************************/
static int ieee80211_wpa_enable(struct ieee80211_device *ieee, int value)
{
/* This is called when wpa_supplicant loads and closes the driver
* interface. */
printk("%s WPA\n",value ? "enabling" : "disabling");
ieee->wpa_enabled = value;
return 0;
}
void ieee80211_wpa_assoc_frame(struct ieee80211_device *ieee, char *wpa_ie, int wpa_ie_len)
{
/* make sure WPA is enabled */
ieee80211_wpa_enable(ieee, 1);
ieee80211_disassociate(ieee);
}
static int ieee80211_wpa_mlme(struct ieee80211_device *ieee, int command, int reason)
{
int ret = 0;
switch (command) {
case IEEE_MLME_STA_DEAUTH:
// silently ignore
break;
case IEEE_MLME_STA_DISASSOC:
ieee80211_disassociate(ieee);
break;
default:
printk("Unknown MLME request: %d\n", command);
ret = -EOPNOTSUPP;
}
return ret;
}
static int ieee80211_wpa_set_wpa_ie(struct ieee80211_device *ieee,
struct ieee_param *param, int plen)
{
u8 *buf;
if (param->u.wpa_ie.len > MAX_WPA_IE_LEN ||
(param->u.wpa_ie.len && param->u.wpa_ie.data == NULL))
return -EINVAL;
if (param->u.wpa_ie.len) {
buf = kmemdup(param->u.wpa_ie.data, param->u.wpa_ie.len,
GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
kfree(ieee->wpa_ie);
ieee->wpa_ie = buf;
ieee->wpa_ie_len = param->u.wpa_ie.len;
} else {
kfree(ieee->wpa_ie);
ieee->wpa_ie = NULL;
ieee->wpa_ie_len = 0;
}
ieee80211_wpa_assoc_frame(ieee, ieee->wpa_ie, ieee->wpa_ie_len);
return 0;
}
#define AUTH_ALG_OPEN_SYSTEM 0x1
#define AUTH_ALG_SHARED_KEY 0x2
static int ieee80211_wpa_set_auth_algs(struct ieee80211_device *ieee, int value)
{
struct ieee80211_security sec = {
.flags = SEC_AUTH_MODE,
};
int ret = 0;
if (value & AUTH_ALG_SHARED_KEY) {
sec.auth_mode = WLAN_AUTH_SHARED_KEY;
ieee->open_wep = 0;
ieee->auth_mode = 1;
} else if (value & AUTH_ALG_OPEN_SYSTEM){
sec.auth_mode = WLAN_AUTH_OPEN;
ieee->open_wep = 1;
ieee->auth_mode = 0;
}
else if (value & IW_AUTH_ALG_LEAP){
sec.auth_mode = WLAN_AUTH_LEAP;
ieee->open_wep = 1;
ieee->auth_mode = 2;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
//else
// ret = -EOPNOTSUPP;
return ret;
}
static int ieee80211_wpa_set_param(struct ieee80211_device *ieee, u8 name, u32 value)
{
int ret=0;
unsigned long flags;
switch (name) {
case IEEE_PARAM_WPA_ENABLED:
ret = ieee80211_wpa_enable(ieee, value);
break;
case IEEE_PARAM_TKIP_COUNTERMEASURES:
ieee->tkip_countermeasures=value;
break;
case IEEE_PARAM_DROP_UNENCRYPTED: {
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
struct ieee80211_security sec = {
.flags = SEC_ENABLED,
.enabled = value,
};
ieee->drop_unencrypted = value;
/* We only change SEC_LEVEL for open mode. Others
* are set by ipw_wpa_set_encryption.
*/
if (!value) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_0;
}
else {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
break;
}
case IEEE_PARAM_PRIVACY_INVOKED:
ieee->privacy_invoked=value;
break;
case IEEE_PARAM_AUTH_ALGS:
ret = ieee80211_wpa_set_auth_algs(ieee, value);
break;
case IEEE_PARAM_IEEE_802_1X:
ieee->ieee802_1x=value;
break;
case IEEE_PARAM_WPAX_SELECT:
// added for WPA2 mixed mode
spin_lock_irqsave(&ieee->wpax_suitlist_lock,flags);
ieee->wpax_type_set = 1;
ieee->wpax_type_notify = value;
spin_unlock_irqrestore(&ieee->wpax_suitlist_lock,flags);
break;
default:
printk("Unknown WPA param: %d\n",name);
ret = -EOPNOTSUPP;
}
return ret;
}
/* implementation borrowed from hostap driver */
static int ieee80211_wpa_set_encryption(struct ieee80211_device *ieee,
struct ieee_param *param, int param_len)
{
int ret = 0;
struct ieee80211_crypto_ops *ops;
struct ieee80211_crypt_data **crypt;
struct ieee80211_security sec = {
.flags = 0,
};
param->u.crypt.err = 0;
param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
if (param_len !=
(int) ((char *) param->u.crypt.key - (char *) param) +
param->u.crypt.key_len) {
printk("Len mismatch %d, %d\n", param_len,
param->u.crypt.key_len);
return -EINVAL;
}
if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
if (param->u.crypt.idx >= WEP_KEYS)
return -EINVAL;
crypt = &ieee->crypt[param->u.crypt.idx];
} else {
return -EINVAL;
}
if (strcmp(param->u.crypt.alg, "none") == 0) {
if (crypt) {
sec.enabled = 0;
// FIXME FIXME
//sec.encrypt = 0;
sec.level = SEC_LEVEL_0;
sec.flags |= SEC_ENABLED | SEC_LEVEL;
ieee80211_crypt_delayed_deinit(ieee, crypt);
}
goto done;
}
sec.enabled = 1;
// FIXME FIXME
// sec.encrypt = 1;
sec.flags |= SEC_ENABLED;
/* IPW HW cannot build TKIP MIC, host decryption still needed. */
if (!(ieee->host_encrypt || ieee->host_decrypt) &&
strcmp(param->u.crypt.alg, "TKIP"))
goto skip_host_crypt;
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL && strcmp(param->u.crypt.alg, "WEP") == 0)
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
/* set WEP40 first, it will be modified according to WEP104 or
* WEP40 at other place */
else if (ops == NULL && strcmp(param->u.crypt.alg, "TKIP") == 0)
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
else if (ops == NULL && strcmp(param->u.crypt.alg, "CCMP") == 0)
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL) {
printk("unknown crypto alg '%s'\n", param->u.crypt.alg);
param->u.crypt.err = IEEE_CRYPT_ERR_UNKNOWN_ALG;
ret = -EINVAL;
goto done;
}
if (*crypt == NULL || (*crypt)->ops != ops) {
struct ieee80211_crypt_data *new_crypt;
ieee80211_crypt_delayed_deinit(ieee, crypt);
new_crypt = kmalloc(sizeof(*new_crypt), GFP_KERNEL);
if (new_crypt == NULL) {
ret = -ENOMEM;
goto done;
}
memset(new_crypt, 0, sizeof(struct ieee80211_crypt_data));
new_crypt->ops = ops;
if (new_crypt->ops)
new_crypt->priv =
new_crypt->ops->init(param->u.crypt.idx);
if (new_crypt->priv == NULL) {
kfree(new_crypt);
param->u.crypt.err = IEEE_CRYPT_ERR_CRYPT_INIT_FAILED;
ret = -EINVAL;
goto done;
}
*crypt = new_crypt;
}
if (param->u.crypt.key_len > 0 && (*crypt)->ops->set_key &&
(*crypt)->ops->set_key(param->u.crypt.key,
param->u.crypt.key_len, param->u.crypt.seq,
(*crypt)->priv) < 0) {
printk("key setting failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_KEY_SET_FAILED;
ret = -EINVAL;
goto done;
}
skip_host_crypt:
if (param->u.crypt.set_tx) {
ieee->tx_keyidx = param->u.crypt.idx;
sec.active_key = param->u.crypt.idx;
sec.flags |= SEC_ACTIVE_KEY;
} else
sec.flags &= ~SEC_ACTIVE_KEY;
if (param->u.crypt.alg != NULL) {
memcpy(sec.keys[param->u.crypt.idx],
param->u.crypt.key,
param->u.crypt.key_len);
sec.key_sizes[param->u.crypt.idx] = param->u.crypt.key_len;
sec.flags |= (1 << param->u.crypt.idx);
if (strcmp(param->u.crypt.alg, "WEP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
} else if (strcmp(param->u.crypt.alg, "TKIP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_2;
} else if (strcmp(param->u.crypt.alg, "CCMP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_3;
}
}
done:
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
/* Do not reset port if card is in Managed mode since resetting will
* generate new IEEE 802.11 authentication which may end up in looping
* with IEEE 802.1X. If your hardware requires a reset after WEP
* configuration (for example... Prism2), implement the reset_port in
* the callbacks structures used to initialize the 802.11 stack. */
if (ieee->reset_on_keychange &&
ieee->iw_mode != IW_MODE_INFRA &&
ieee->reset_port &&
ieee->reset_port(ieee->dev)) {
printk("reset_port failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_CARD_CONF_FAILED;
return -EINVAL;
}
return ret;
}
inline struct sk_buff *ieee80211_disassociate_skb(
struct ieee80211_network *beacon,
struct ieee80211_device *ieee,
u8 asRsn)
{
struct sk_buff *skb;
struct ieee80211_disassoc *disass;
skb = dev_alloc_skb(sizeof(struct ieee80211_disassoc));
if (!skb)
return NULL;
disass = (struct ieee80211_disassoc *) skb_put(skb,sizeof(struct ieee80211_disassoc));
disass->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_DISASSOC);
disass->header.duration_id = 0;
memcpy(disass->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(disass->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(disass->header.addr3, beacon->bssid, ETH_ALEN);
disass->reason = asRsn;
return skb;
}
void
SendDisassociation(
struct ieee80211_device *ieee,
u8* asSta,
u8 asRsn
)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
skb = ieee80211_disassociate_skb(beacon,ieee,asRsn);
if (skb){
softmac_mgmt_xmit(skb, ieee);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p)
{
struct ieee_param *param;
int ret=0;
down(&ieee->wx_sem);
//IEEE_DEBUG_INFO("wpa_supplicant: len=%d\n", p->length);
if (p->length < sizeof(struct ieee_param) || !p->pointer){
ret = -EINVAL;
goto out;
}
param = kmalloc(p->length, GFP_KERNEL);
if (param == NULL){
ret = -ENOMEM;
goto out;
}
if (copy_from_user(param, p->pointer, p->length)) {
kfree(param);
ret = -EFAULT;
goto out;
}
switch (param->cmd) {
case IEEE_CMD_SET_WPA_PARAM:
ret = ieee80211_wpa_set_param(ieee, param->u.wpa_param.name,
param->u.wpa_param.value);
break;
case IEEE_CMD_SET_WPA_IE:
ret = ieee80211_wpa_set_wpa_ie(ieee, param, p->length);
break;
case IEEE_CMD_SET_ENCRYPTION:
ret = ieee80211_wpa_set_encryption(ieee, param, p->length);
break;
case IEEE_CMD_MLME:
ret = ieee80211_wpa_mlme(ieee, param->u.mlme.command,
param->u.mlme.reason_code);
break;
default:
printk("Unknown WPA supplicant request: %d\n",param->cmd);
ret = -EOPNOTSUPP;
break;
}
if (ret == 0 && copy_to_user(p->pointer, param, p->length))
ret = -EFAULT;
kfree(param);
out:
up(&ieee->wx_sem);
return ret;
}
void notify_wx_assoc_event(struct ieee80211_device *ieee)
{
union iwreq_data wrqu;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
if (ieee->state == IEEE80211_LINKED)
memcpy(wrqu.ap_addr.sa_data, ieee->current_network.bssid, ETH_ALEN);
else
memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
wireless_send_event(ieee->dev, SIOCGIWAP, &wrqu, NULL);
}
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
//EXPORT_SYMBOL(ieee80211_get_beacon);
//EXPORT_SYMBOL(ieee80211_rtl_wake_queue);
//EXPORT_SYMBOL(ieee80211_rtl_stop_queue);
//EXPORT_SYMBOL(ieee80211_reset_queue);
//EXPORT_SYMBOL(ieee80211_softmac_stop_protocol);
//EXPORT_SYMBOL(ieee80211_softmac_start_protocol);
//EXPORT_SYMBOL(ieee80211_is_shortslot);
//EXPORT_SYMBOL(ieee80211_is_54g);
//EXPORT_SYMBOL(ieee80211_wpa_supplicant_ioctl);
//EXPORT_SYMBOL(ieee80211_ps_tx_ack);
//EXPORT_SYMBOL(ieee80211_softmac_xmit);
//EXPORT_SYMBOL(ieee80211_stop_send_beacons);
//EXPORT_SYMBOL(notify_wx_assoc_event);
//EXPORT_SYMBOL(SendDisassociation);
//EXPORT_SYMBOL(ieee80211_disassociate);
//EXPORT_SYMBOL(ieee80211_start_send_beacons);
//EXPORT_SYMBOL(ieee80211_stop_scan);
//EXPORT_SYMBOL(ieee80211_send_probe_requests);
//EXPORT_SYMBOL(ieee80211_softmac_scan_syncro);
//EXPORT_SYMBOL(ieee80211_start_scan_syncro);
#else
EXPORT_SYMBOL_NOVERS(ieee80211_get_beacon);
EXPORT_SYMBOL_NOVERS(ieee80211_rtl_wake_queue);
EXPORT_SYMBOL_NOVERS(ieee80211_rtl_stop_queue);
EXPORT_SYMBOL_NOVERS(ieee80211_reset_queue);
EXPORT_SYMBOL_NOVERS(ieee80211_softmac_stop_protocol);
EXPORT_SYMBOL_NOVERS(ieee80211_softmac_start_protocol);
EXPORT_SYMBOL_NOVERS(ieee80211_is_shortslot);
EXPORT_SYMBOL_NOVERS(ieee80211_is_54g);
EXPORT_SYMBOL_NOVERS(ieee80211_wpa_supplicant_ioctl);
EXPORT_SYMBOL_NOVERS(ieee80211_ps_tx_ack);
EXPORT_SYMBOL_NOVERS(ieee80211_softmac_xmit);
EXPORT_SYMBOL_NOVERS(ieee80211_stop_send_beacons);
EXPORT_SYMBOL_NOVERS(notify_wx_assoc_event);
EXPORT_SYMBOL_NOVERS(SendDisassociation);
EXPORT_SYMBOL_NOVERS(ieee80211_disassociate);
EXPORT_SYMBOL_NOVERS(ieee80211_start_send_beacons);
EXPORT_SYMBOL_NOVERS(ieee80211_stop_scan);
EXPORT_SYMBOL_NOVERS(ieee80211_send_probe_requests);
EXPORT_SYMBOL_NOVERS(ieee80211_softmac_scan_syncro);
EXPORT_SYMBOL_NOVERS(ieee80211_start_scan_syncro);
EXPORT_SYMBOL_NOVERS(ieee80211_sta_ps_send_null_frame);
EXPORT_SYMBOL_NOVERS(ieee80211_sta_ps_send_pspoll_frame);
#endif
| gpl-2.0 |
adrynalyne/clean_kernel_htc-mecha | drivers/staging/vt6656/wpa.c | 761 | 10091 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: wpa.c
*
* Purpose: Handles the Basic Service Set & Node Database functions
*
* Functions:
* WPA_ParseRSN - Parse RSN IE.
*
* Revision History:
*
* Author: Kyle Hsu
*
* Date: July 14, 2003
*
*/
#include "ttype.h"
#include "tmacro.h"
#include "tether.h"
#include "device.h"
#include "80211hdr.h"
#include "bssdb.h"
#include "wmgr.h"
#include "wpa.h"
#include "80211mgr.h"
/*--------------------- Static Variables --------------------------*/
static int msglevel =MSG_LEVEL_INFO;
const BYTE abyOUI00[4] = { 0x00, 0x50, 0xf2, 0x00 };
const BYTE abyOUI01[4] = { 0x00, 0x50, 0xf2, 0x01 };
const BYTE abyOUI02[4] = { 0x00, 0x50, 0xf2, 0x02 };
const BYTE abyOUI03[4] = { 0x00, 0x50, 0xf2, 0x03 };
const BYTE abyOUI04[4] = { 0x00, 0x50, 0xf2, 0x04 };
const BYTE abyOUI05[4] = { 0x00, 0x50, 0xf2, 0x05 };
/*+
*
* Description:
* Clear RSN information in BSSList.
*
* Parameters:
* In:
* pBSSList - BSS list.
* Out:
* none
*
* Return Value: none.
*
-*/
void
WPA_ClearRSN (
PKnownBSS pBSSList
)
{
int ii;
pBSSList->byGKType = WPA_TKIP;
for (ii=0; ii < 4; ii ++)
pBSSList->abyPKType[ii] = WPA_TKIP;
pBSSList->wPKCount = 0;
for (ii=0; ii < 4; ii ++)
pBSSList->abyAuthType[ii] = WPA_AUTH_IEEE802_1X;
pBSSList->wAuthCount = 0;
pBSSList->byDefaultK_as_PK = 0;
pBSSList->byReplayIdx = 0;
pBSSList->sRSNCapObj.bRSNCapExist = FALSE;
pBSSList->sRSNCapObj.wRSNCap = 0;
pBSSList->bWPAValid = FALSE;
}
/*+
*
* Description:
* Parse RSN IE.
*
* Parameters:
* In:
* pBSSList - BSS list.
* pRSN - Pointer to the RSN IE.
* Out:
* none
*
* Return Value: none.
*
-*/
void
WPA_ParseRSN (
PKnownBSS pBSSList,
PWLAN_IE_RSN_EXT pRSN
)
{
PWLAN_IE_RSN_AUTH pIE_RSN_Auth = NULL;
int i, j, m, n = 0;
PBYTE pbyCaps;
WPA_ClearRSN(pBSSList);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"WPA_ParseRSN: [%d]\n", pRSN->len);
// information element header makes sense
if ((pRSN->len >= 6) // oui1(4)+ver(2)
&& (pRSN->byElementID == WLAN_EID_RSN_WPA) && !memcmp(pRSN->abyOUI, abyOUI01, 4)
&& (pRSN->wVersion == 1)) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Legal RSN\n");
// update each variable if pRSN is long enough to contain the variable
if (pRSN->len >= 10) //oui1(4)+ver(2)+GKSuite(4)
{
if ( !memcmp(pRSN->abyMulticast, abyOUI01, 4))
pBSSList->byGKType = WPA_WEP40;
else if ( !memcmp(pRSN->abyMulticast, abyOUI02, 4))
pBSSList->byGKType = WPA_TKIP;
else if ( !memcmp(pRSN->abyMulticast, abyOUI03, 4))
pBSSList->byGKType = WPA_AESWRAP;
else if ( !memcmp(pRSN->abyMulticast, abyOUI04, 4))
pBSSList->byGKType = WPA_AESCCMP;
else if ( !memcmp(pRSN->abyMulticast, abyOUI05, 4))
pBSSList->byGKType = WPA_WEP104;
else
// any vendor checks here
pBSSList->byGKType = WPA_NONE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"byGKType: %x\n", pBSSList->byGKType);
}
if (pRSN->len >= 12) //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)
{
j = 0;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wPKCount: %d, sizeof(pBSSList->abyPKType): %zu\n", pRSN->wPKCount, sizeof(pBSSList->abyPKType));
for(i = 0; (i < pRSN->wPKCount) && (j < sizeof(pBSSList->abyPKType)/sizeof(BYTE)); i++) {
if(pRSN->len >= 12+i*4+4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*i)
if ( !memcmp(pRSN->PKSList[i].abyOUI, abyOUI00, 4))
pBSSList->abyPKType[j++] = WPA_NONE;
else if ( !memcmp(pRSN->PKSList[i].abyOUI, abyOUI02, 4))
pBSSList->abyPKType[j++] = WPA_TKIP;
else if ( !memcmp(pRSN->PKSList[i].abyOUI, abyOUI03, 4))
pBSSList->abyPKType[j++] = WPA_AESWRAP;
else if ( !memcmp(pRSN->PKSList[i].abyOUI, abyOUI04, 4))
pBSSList->abyPKType[j++] = WPA_AESCCMP;
else
// any vendor checks here
;
}
else
break;
//DBG_PRN_GRP14(("abyPKType[%d]: %X\n", j-1, pBSSList->abyPKType[j-1]));
} //for
pBSSList->wPKCount = (WORD)j;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wPKCount: %d\n", pBSSList->wPKCount);
}
m = pRSN->wPKCount;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"m: %d\n", m);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"14+m*4: %d\n", 14+m*4);
if (pRSN->len >= 14+m*4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*m)+AKC(2)
// overlay IE_RSN_Auth structure into correct place
pIE_RSN_Auth = (PWLAN_IE_RSN_AUTH) pRSN->PKSList[m].abyOUI;
j = 0;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wAuthCount: %d, sizeof(pBSSList->abyAuthType): %zu\n",
pIE_RSN_Auth->wAuthCount, sizeof(pBSSList->abyAuthType));
for(i = 0; (i < pIE_RSN_Auth->wAuthCount) && (j < sizeof(pBSSList->abyAuthType)/sizeof(BYTE)); i++) {
if(pRSN->len >= 14+4+(m+i)*4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*m)+AKC(2)+AKS(4*i)
if ( !memcmp(pIE_RSN_Auth->AuthKSList[i].abyOUI, abyOUI01, 4))
pBSSList->abyAuthType[j++] = WPA_AUTH_IEEE802_1X;
else if ( !memcmp(pIE_RSN_Auth->AuthKSList[i].abyOUI, abyOUI02, 4))
pBSSList->abyAuthType[j++] = WPA_AUTH_PSK;
else
// any vendor checks here
;
}
else
break;
//DBG_PRN_GRP14(("abyAuthType[%d]: %X\n", j-1, pBSSList->abyAuthType[j-1]));
}
if(j > 0)
pBSSList->wAuthCount = (WORD)j;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wAuthCount: %d\n", pBSSList->wAuthCount);
}
if (pIE_RSN_Auth != NULL) {
n = pIE_RSN_Auth->wAuthCount;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"n: %d\n", n);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"14+4+(m+n)*4: %d\n", 14+4+(m+n)*4);
if(pRSN->len+2 >= 14+4+(m+n)*4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*m)+AKC(2)+AKS(4*n)+Cap(2)
pbyCaps = (PBYTE)pIE_RSN_Auth->AuthKSList[n].abyOUI;
pBSSList->byDefaultK_as_PK = (*pbyCaps) & WPA_GROUPFLAG;
pBSSList->byReplayIdx = 2 << ((*pbyCaps >> WPA_REPLAYBITSSHIFT) & WPA_REPLAYBITS);
pBSSList->sRSNCapObj.bRSNCapExist = TRUE;
pBSSList->sRSNCapObj.wRSNCap = *(PWORD)pbyCaps;
//DBG_PRN_GRP14(("pbyCaps: %X\n", *pbyCaps));
//DBG_PRN_GRP14(("byDefaultK_as_PK: %X\n", pBSSList->byDefaultK_as_PK));
//DBG_PRN_GRP14(("byReplayIdx: %X\n", pBSSList->byReplayIdx));
}
}
pBSSList->bWPAValid = TRUE;
}
}
/*+
*
* Description:
* Search RSN information in BSSList.
*
* Parameters:
* In:
* byCmd - Search type
* byEncrypt- Encrcypt Type
* pBSSList - BSS list
* Out:
* none
*
* Return Value: none.
*
-*/
BOOL
WPA_SearchRSN (
BYTE byCmd,
BYTE byEncrypt,
PKnownBSS pBSSList
)
{
int ii;
BYTE byPKType = WPA_NONE;
if (pBSSList->bWPAValid == FALSE)
return FALSE;
switch(byCmd) {
case 0:
if (byEncrypt != pBSSList->byGKType)
return FALSE;
if (pBSSList->wPKCount > 0) {
for (ii = 0; ii < pBSSList->wPKCount; ii ++) {
if (pBSSList->abyPKType[ii] == WPA_AESCCMP)
byPKType = WPA_AESCCMP;
else if ((pBSSList->abyPKType[ii] == WPA_TKIP) && (byPKType != WPA_AESCCMP))
byPKType = WPA_TKIP;
else if ((pBSSList->abyPKType[ii] == WPA_WEP40) && (byPKType != WPA_AESCCMP) && (byPKType != WPA_TKIP))
byPKType = WPA_WEP40;
else if ((pBSSList->abyPKType[ii] == WPA_WEP104) && (byPKType != WPA_AESCCMP) && (byPKType != WPA_TKIP))
byPKType = WPA_WEP104;
}
if (byEncrypt != byPKType)
return FALSE;
}
return TRUE;
// if (pBSSList->wAuthCount > 0)
// for (ii=0; ii < pBSSList->wAuthCount; ii ++)
// if (byAuth == pBSSList->abyAuthType[ii])
// break;
break;
default:
break;
}
return FALSE;
}
/*+
*
* Description:
* Check if RSN IE makes sense.
*
* Parameters:
* In:
* pRSN - Pointer to the RSN IE.
* Out:
* none
*
* Return Value: none.
*
-*/
BOOL
WPAb_Is_RSN (
PWLAN_IE_RSN_EXT pRSN
)
{
if (pRSN == NULL)
return FALSE;
if ((pRSN->len >= 6) && // oui1(4)+ver(2)
(pRSN->byElementID == WLAN_EID_RSN_WPA) && !memcmp(pRSN->abyOUI, abyOUI01, 4) &&
(pRSN->wVersion == 1)) {
return TRUE;
}
else
return FALSE;
}
| gpl-2.0 |
spairal/linux-for-lobster | drivers/spi/spi_lm70llp.c | 761 | 9444 | /*
* spi_lm70llp.c - driver for LM70EVAL-LLP board for the LM70 sensor
*
* Copyright (C) 2006 Kaiwan N Billimoria <kaiwan@designergraphix.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/parport.h>
#include <linux/sysfs.h>
#include <linux/workqueue.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_bitbang.h>
/*
* The LM70 communicates with a host processor using a 3-wire variant of
* the SPI/Microwire bus interface. This driver specifically supports an
* NS LM70 LLP Evaluation Board, interfacing to a PC using its parallel
* port to bitbang an SPI-parport bridge. Accordingly, this is an SPI
* master controller driver. The hwmon/lm70 driver is a "SPI protocol
* driver", layered on top of this one and usable without the lm70llp.
*
* Datasheet and Schematic:
* The LM70 is a temperature sensor chip from National Semiconductor; its
* datasheet is available at http://www.national.com/pf/LM/LM70.html
* The schematic for this particular board (the LM70EVAL-LLP) is
* available (on page 4) here:
* http://www.national.com/appinfo/tempsensors/files/LM70LLPEVALmanual.pdf
*
* Also see Documentation/spi/spi-lm70llp. The SPI<->parport code here is
* (heavily) based on spi-butterfly by David Brownell.
*
* The LM70 LLP connects to the PC parallel port in the following manner:
*
* Parallel LM70 LLP
* Port Direction JP2 Header
* ----------- --------- ------------
* D0 2 - -
* D1 3 --> V+ 5
* D2 4 --> V+ 5
* D3 5 --> V+ 5
* D4 6 --> V+ 5
* D5 7 --> nCS 8
* D6 8 --> SCLK 3
* D7 9 --> SI/O 5
* GND 25 - GND 7
* Select 13 <-- SI/O 1
*
* Note that parport pin 13 actually gets inverted by the transistor
* arrangement which lets either the parport or the LM70 drive the
* SI/SO signal (see the schematic for details).
*/
#define DRVNAME "spi-lm70llp"
#define lm70_INIT 0xBE
#define SIO 0x10
#define nCS 0x20
#define SCLK 0x40
/*-------------------------------------------------------------------------*/
struct spi_lm70llp {
struct spi_bitbang bitbang;
struct parport *port;
struct pardevice *pd;
struct spi_device *spidev_lm70;
struct spi_board_info info;
//struct device *dev;
};
/* REVISIT : ugly global ; provides "exclusive open" facility */
static struct spi_lm70llp *lm70llp;
/*-------------------------------------------------------------------*/
static inline struct spi_lm70llp *spidev_to_pp(struct spi_device *spi)
{
return spi->controller_data;
}
/*---------------------- LM70 LLP eval board-specific inlines follow */
/* NOTE: we don't actually need to reread the output values, since they'll
* still be what we wrote before. Plus, going through parport builds in
* a ~1ms/operation delay; these SPI transfers could easily be faster.
*/
static inline void deassertCS(struct spi_lm70llp *pp)
{
u8 data = parport_read_data(pp->port);
data &= ~0x80; /* pull D7/SI-out low while de-asserted */
parport_write_data(pp->port, data | nCS);
}
static inline void assertCS(struct spi_lm70llp *pp)
{
u8 data = parport_read_data(pp->port);
data |= 0x80; /* pull D7/SI-out high so lm70 drives SO-in */
parport_write_data(pp->port, data & ~nCS);
}
static inline void clkHigh(struct spi_lm70llp *pp)
{
u8 data = parport_read_data(pp->port);
parport_write_data(pp->port, data | SCLK);
}
static inline void clkLow(struct spi_lm70llp *pp)
{
u8 data = parport_read_data(pp->port);
parport_write_data(pp->port, data & ~SCLK);
}
/*------------------------- SPI-LM70-specific inlines ----------------------*/
static inline void spidelay(unsigned d)
{
udelay(d);
}
static inline void setsck(struct spi_device *s, int is_on)
{
struct spi_lm70llp *pp = spidev_to_pp(s);
if (is_on)
clkHigh(pp);
else
clkLow(pp);
}
static inline void setmosi(struct spi_device *s, int is_on)
{
/* FIXME update D7 ... this way we can put the chip
* into shutdown mode and read the manufacturer ID,
* but we can't put it back into operational mode.
*/
}
/*
* getmiso:
* Why do we return 0 when the SIO line is high and vice-versa?
* The fact is, the lm70 eval board from NS (which this driver drives),
* is wired in just such a way : when the lm70's SIO goes high, a transistor
* switches it to low reflecting this on the parport (pin 13), and vice-versa.
*/
static inline int getmiso(struct spi_device *s)
{
struct spi_lm70llp *pp = spidev_to_pp(s);
return ((SIO == (parport_read_status(pp->port) & SIO)) ? 0 : 1 );
}
/*--------------------------------------------------------------------*/
#include "spi_bitbang_txrx.h"
static void lm70_chipselect(struct spi_device *spi, int value)
{
struct spi_lm70llp *pp = spidev_to_pp(spi);
if (value)
assertCS(pp);
else
deassertCS(pp);
}
/*
* Our actual bitbanger routine.
*/
static u32 lm70_txrx(struct spi_device *spi, unsigned nsecs, u32 word, u8 bits)
{
return bitbang_txrx_be_cpha0(spi, nsecs, 0, word, bits);
}
static void spi_lm70llp_attach(struct parport *p)
{
struct pardevice *pd;
struct spi_lm70llp *pp;
struct spi_master *master;
int status;
if (lm70llp) {
printk(KERN_WARNING
"%s: spi_lm70llp instance already loaded. Aborting.\n",
DRVNAME);
return;
}
/* TODO: this just _assumes_ a lm70 is there ... no probe;
* the lm70 driver could verify it, reading the manf ID.
*/
master = spi_alloc_master(p->physport->dev, sizeof *pp);
if (!master) {
status = -ENOMEM;
goto out_fail;
}
pp = spi_master_get_devdata(master);
master->bus_num = -1; /* dynamic alloc of a bus number */
master->num_chipselect = 1;
/*
* SPI and bitbang hookup.
*/
pp->bitbang.master = spi_master_get(master);
pp->bitbang.chipselect = lm70_chipselect;
pp->bitbang.txrx_word[SPI_MODE_0] = lm70_txrx;
pp->bitbang.flags = SPI_3WIRE;
/*
* Parport hookup
*/
pp->port = p;
pd = parport_register_device(p, DRVNAME,
NULL, NULL, NULL,
PARPORT_FLAG_EXCL, pp);
if (!pd) {
status = -ENOMEM;
goto out_free_master;
}
pp->pd = pd;
status = parport_claim(pd);
if (status < 0)
goto out_parport_unreg;
/*
* Start SPI ...
*/
status = spi_bitbang_start(&pp->bitbang);
if (status < 0) {
printk(KERN_WARNING
"%s: spi_bitbang_start failed with status %d\n",
DRVNAME, status);
goto out_off_and_release;
}
/*
* The modalias name MUST match the device_driver name
* for the bus glue code to match and subsequently bind them.
* We are binding to the generic drivers/hwmon/lm70.c device
* driver.
*/
strcpy(pp->info.modalias, "lm70");
pp->info.max_speed_hz = 6 * 1000 * 1000;
pp->info.chip_select = 0;
pp->info.mode = SPI_3WIRE | SPI_MODE_0;
/* power up the chip, and let the LM70 control SI/SO */
parport_write_data(pp->port, lm70_INIT);
/* Enable access to our primary data structure via
* the board info's (void *)controller_data.
*/
pp->info.controller_data = pp;
pp->spidev_lm70 = spi_new_device(pp->bitbang.master, &pp->info);
if (pp->spidev_lm70)
dev_dbg(&pp->spidev_lm70->dev, "spidev_lm70 at %s\n",
dev_name(&pp->spidev_lm70->dev));
else {
printk(KERN_WARNING "%s: spi_new_device failed\n", DRVNAME);
status = -ENODEV;
goto out_bitbang_stop;
}
pp->spidev_lm70->bits_per_word = 8;
lm70llp = pp;
return;
out_bitbang_stop:
spi_bitbang_stop(&pp->bitbang);
out_off_and_release:
/* power down */
parport_write_data(pp->port, 0);
mdelay(10);
parport_release(pp->pd);
out_parport_unreg:
parport_unregister_device(pd);
out_free_master:
(void) spi_master_put(master);
out_fail:
pr_info("%s: spi_lm70llp probe fail, status %d\n", DRVNAME, status);
}
static void spi_lm70llp_detach(struct parport *p)
{
struct spi_lm70llp *pp;
if (!lm70llp || lm70llp->port != p)
return;
pp = lm70llp;
spi_bitbang_stop(&pp->bitbang);
/* power down */
parport_write_data(pp->port, 0);
parport_release(pp->pd);
parport_unregister_device(pp->pd);
(void) spi_master_put(pp->bitbang.master);
lm70llp = NULL;
}
static struct parport_driver spi_lm70llp_drv = {
.name = DRVNAME,
.attach = spi_lm70llp_attach,
.detach = spi_lm70llp_detach,
};
static int __init init_spi_lm70llp(void)
{
return parport_register_driver(&spi_lm70llp_drv);
}
module_init(init_spi_lm70llp);
static void __exit cleanup_spi_lm70llp(void)
{
parport_unregister_driver(&spi_lm70llp_drv);
}
module_exit(cleanup_spi_lm70llp);
MODULE_AUTHOR("Kaiwan N Billimoria <kaiwan@designergraphix.com>");
MODULE_DESCRIPTION(
"Parport adapter for the National Semiconductor LM70 LLP eval board");
MODULE_LICENSE("GPL");
| gpl-2.0 |
arco/htc-kernel-msm7225 | drivers/infiniband/hw/qib/qib_qp.c | 761 | 31733 | /*
* Copyright (c) 2006, 2007, 2008, 2009, 2010 QLogic Corporation.
* All rights reserved.
* Copyright (c) 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/err.h>
#include <linux/vmalloc.h>
#include "qib.h"
#define BITS_PER_PAGE (PAGE_SIZE*BITS_PER_BYTE)
#define BITS_PER_PAGE_MASK (BITS_PER_PAGE-1)
static inline unsigned mk_qpn(struct qib_qpn_table *qpt,
struct qpn_map *map, unsigned off)
{
return (map - qpt->map) * BITS_PER_PAGE + off;
}
static inline unsigned find_next_offset(struct qib_qpn_table *qpt,
struct qpn_map *map, unsigned off,
unsigned r)
{
if (qpt->mask) {
off++;
if ((off & qpt->mask) >> 1 != r)
off = ((off & qpt->mask) ?
(off | qpt->mask) + 1 : off) | (r << 1);
} else
off = find_next_zero_bit(map->page, BITS_PER_PAGE, off);
return off;
}
/*
* Convert the AETH credit code into the number of credits.
*/
static u32 credit_table[31] = {
0, /* 0 */
1, /* 1 */
2, /* 2 */
3, /* 3 */
4, /* 4 */
6, /* 5 */
8, /* 6 */
12, /* 7 */
16, /* 8 */
24, /* 9 */
32, /* A */
48, /* B */
64, /* C */
96, /* D */
128, /* E */
192, /* F */
256, /* 10 */
384, /* 11 */
512, /* 12 */
768, /* 13 */
1024, /* 14 */
1536, /* 15 */
2048, /* 16 */
3072, /* 17 */
4096, /* 18 */
6144, /* 19 */
8192, /* 1A */
12288, /* 1B */
16384, /* 1C */
24576, /* 1D */
32768 /* 1E */
};
static void get_map_page(struct qib_qpn_table *qpt, struct qpn_map *map)
{
unsigned long page = get_zeroed_page(GFP_KERNEL);
/*
* Free the page if someone raced with us installing it.
*/
spin_lock(&qpt->lock);
if (map->page)
free_page(page);
else
map->page = (void *)page;
spin_unlock(&qpt->lock);
}
/*
* Allocate the next available QPN or
* zero/one for QP type IB_QPT_SMI/IB_QPT_GSI.
*/
static int alloc_qpn(struct qib_devdata *dd, struct qib_qpn_table *qpt,
enum ib_qp_type type, u8 port)
{
u32 i, offset, max_scan, qpn;
struct qpn_map *map;
u32 ret;
int r;
if (type == IB_QPT_SMI || type == IB_QPT_GSI) {
unsigned n;
ret = type == IB_QPT_GSI;
n = 1 << (ret + 2 * (port - 1));
spin_lock(&qpt->lock);
if (qpt->flags & n)
ret = -EINVAL;
else
qpt->flags |= n;
spin_unlock(&qpt->lock);
goto bail;
}
r = smp_processor_id();
if (r >= dd->n_krcv_queues)
r %= dd->n_krcv_queues;
qpn = qpt->last + 1;
if (qpn >= QPN_MAX)
qpn = 2;
if (qpt->mask && ((qpn & qpt->mask) >> 1) != r)
qpn = ((qpn & qpt->mask) ? (qpn | qpt->mask) + 1 : qpn) |
(r << 1);
offset = qpn & BITS_PER_PAGE_MASK;
map = &qpt->map[qpn / BITS_PER_PAGE];
max_scan = qpt->nmaps - !offset;
for (i = 0;;) {
if (unlikely(!map->page)) {
get_map_page(qpt, map);
if (unlikely(!map->page))
break;
}
do {
if (!test_and_set_bit(offset, map->page)) {
qpt->last = qpn;
ret = qpn;
goto bail;
}
offset = find_next_offset(qpt, map, offset, r);
qpn = mk_qpn(qpt, map, offset);
/*
* This test differs from alloc_pidmap().
* If find_next_offset() does find a zero
* bit, we don't need to check for QPN
* wrapping around past our starting QPN.
* We just need to be sure we don't loop
* forever.
*/
} while (offset < BITS_PER_PAGE && qpn < QPN_MAX);
/*
* In order to keep the number of pages allocated to a
* minimum, we scan the all existing pages before increasing
* the size of the bitmap table.
*/
if (++i > max_scan) {
if (qpt->nmaps == QPNMAP_ENTRIES)
break;
map = &qpt->map[qpt->nmaps++];
offset = qpt->mask ? (r << 1) : 0;
} else if (map < &qpt->map[qpt->nmaps]) {
++map;
offset = qpt->mask ? (r << 1) : 0;
} else {
map = &qpt->map[0];
offset = qpt->mask ? (r << 1) : 2;
}
qpn = mk_qpn(qpt, map, offset);
}
ret = -ENOMEM;
bail:
return ret;
}
static void free_qpn(struct qib_qpn_table *qpt, u32 qpn)
{
struct qpn_map *map;
map = qpt->map + qpn / BITS_PER_PAGE;
if (map->page)
clear_bit(qpn & BITS_PER_PAGE_MASK, map->page);
}
/*
* Put the QP into the hash table.
* The hash table holds a reference to the QP.
*/
static void insert_qp(struct qib_ibdev *dev, struct qib_qp *qp)
{
struct qib_ibport *ibp = to_iport(qp->ibqp.device, qp->port_num);
unsigned n = qp->ibqp.qp_num % dev->qp_table_size;
unsigned long flags;
spin_lock_irqsave(&dev->qpt_lock, flags);
if (qp->ibqp.qp_num == 0)
ibp->qp0 = qp;
else if (qp->ibqp.qp_num == 1)
ibp->qp1 = qp;
else {
qp->next = dev->qp_table[n];
dev->qp_table[n] = qp;
}
atomic_inc(&qp->refcount);
spin_unlock_irqrestore(&dev->qpt_lock, flags);
}
/*
* Remove the QP from the table so it can't be found asynchronously by
* the receive interrupt routine.
*/
static void remove_qp(struct qib_ibdev *dev, struct qib_qp *qp)
{
struct qib_ibport *ibp = to_iport(qp->ibqp.device, qp->port_num);
struct qib_qp *q, **qpp;
unsigned long flags;
qpp = &dev->qp_table[qp->ibqp.qp_num % dev->qp_table_size];
spin_lock_irqsave(&dev->qpt_lock, flags);
if (ibp->qp0 == qp) {
ibp->qp0 = NULL;
atomic_dec(&qp->refcount);
} else if (ibp->qp1 == qp) {
ibp->qp1 = NULL;
atomic_dec(&qp->refcount);
} else
for (; (q = *qpp) != NULL; qpp = &q->next)
if (q == qp) {
*qpp = qp->next;
qp->next = NULL;
atomic_dec(&qp->refcount);
break;
}
spin_unlock_irqrestore(&dev->qpt_lock, flags);
}
/**
* qib_free_all_qps - check for QPs still in use
* @qpt: the QP table to empty
*
* There should not be any QPs still in use.
* Free memory for table.
*/
unsigned qib_free_all_qps(struct qib_devdata *dd)
{
struct qib_ibdev *dev = &dd->verbs_dev;
unsigned long flags;
struct qib_qp *qp;
unsigned n, qp_inuse = 0;
for (n = 0; n < dd->num_pports; n++) {
struct qib_ibport *ibp = &dd->pport[n].ibport_data;
if (!qib_mcast_tree_empty(ibp))
qp_inuse++;
if (ibp->qp0)
qp_inuse++;
if (ibp->qp1)
qp_inuse++;
}
spin_lock_irqsave(&dev->qpt_lock, flags);
for (n = 0; n < dev->qp_table_size; n++) {
qp = dev->qp_table[n];
dev->qp_table[n] = NULL;
for (; qp; qp = qp->next)
qp_inuse++;
}
spin_unlock_irqrestore(&dev->qpt_lock, flags);
return qp_inuse;
}
/**
* qib_lookup_qpn - return the QP with the given QPN
* @qpt: the QP table
* @qpn: the QP number to look up
*
* The caller is responsible for decrementing the QP reference count
* when done.
*/
struct qib_qp *qib_lookup_qpn(struct qib_ibport *ibp, u32 qpn)
{
struct qib_ibdev *dev = &ppd_from_ibp(ibp)->dd->verbs_dev;
unsigned long flags;
struct qib_qp *qp;
spin_lock_irqsave(&dev->qpt_lock, flags);
if (qpn == 0)
qp = ibp->qp0;
else if (qpn == 1)
qp = ibp->qp1;
else
for (qp = dev->qp_table[qpn % dev->qp_table_size]; qp;
qp = qp->next)
if (qp->ibqp.qp_num == qpn)
break;
if (qp)
atomic_inc(&qp->refcount);
spin_unlock_irqrestore(&dev->qpt_lock, flags);
return qp;
}
/**
* qib_reset_qp - initialize the QP state to the reset state
* @qp: the QP to reset
* @type: the QP type
*/
static void qib_reset_qp(struct qib_qp *qp, enum ib_qp_type type)
{
qp->remote_qpn = 0;
qp->qkey = 0;
qp->qp_access_flags = 0;
atomic_set(&qp->s_dma_busy, 0);
qp->s_flags &= QIB_S_SIGNAL_REQ_WR;
qp->s_hdrwords = 0;
qp->s_wqe = NULL;
qp->s_draining = 0;
qp->s_next_psn = 0;
qp->s_last_psn = 0;
qp->s_sending_psn = 0;
qp->s_sending_hpsn = 0;
qp->s_psn = 0;
qp->r_psn = 0;
qp->r_msn = 0;
if (type == IB_QPT_RC) {
qp->s_state = IB_OPCODE_RC_SEND_LAST;
qp->r_state = IB_OPCODE_RC_SEND_LAST;
} else {
qp->s_state = IB_OPCODE_UC_SEND_LAST;
qp->r_state = IB_OPCODE_UC_SEND_LAST;
}
qp->s_ack_state = IB_OPCODE_RC_ACKNOWLEDGE;
qp->r_nak_state = 0;
qp->r_aflags = 0;
qp->r_flags = 0;
qp->s_head = 0;
qp->s_tail = 0;
qp->s_cur = 0;
qp->s_acked = 0;
qp->s_last = 0;
qp->s_ssn = 1;
qp->s_lsn = 0;
qp->s_mig_state = IB_MIG_MIGRATED;
memset(qp->s_ack_queue, 0, sizeof(qp->s_ack_queue));
qp->r_head_ack_queue = 0;
qp->s_tail_ack_queue = 0;
qp->s_num_rd_atomic = 0;
if (qp->r_rq.wq) {
qp->r_rq.wq->head = 0;
qp->r_rq.wq->tail = 0;
}
qp->r_sge.num_sge = 0;
}
static void clear_mr_refs(struct qib_qp *qp, int clr_sends)
{
unsigned n;
if (test_and_clear_bit(QIB_R_REWIND_SGE, &qp->r_aflags))
while (qp->s_rdma_read_sge.num_sge) {
atomic_dec(&qp->s_rdma_read_sge.sge.mr->refcount);
if (--qp->s_rdma_read_sge.num_sge)
qp->s_rdma_read_sge.sge =
*qp->s_rdma_read_sge.sg_list++;
}
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
if (clr_sends) {
while (qp->s_last != qp->s_head) {
struct qib_swqe *wqe = get_swqe_ptr(qp, qp->s_last);
unsigned i;
for (i = 0; i < wqe->wr.num_sge; i++) {
struct qib_sge *sge = &wqe->sg_list[i];
atomic_dec(&sge->mr->refcount);
}
if (qp->ibqp.qp_type == IB_QPT_UD ||
qp->ibqp.qp_type == IB_QPT_SMI ||
qp->ibqp.qp_type == IB_QPT_GSI)
atomic_dec(&to_iah(wqe->wr.wr.ud.ah)->refcount);
if (++qp->s_last >= qp->s_size)
qp->s_last = 0;
}
if (qp->s_rdma_mr) {
atomic_dec(&qp->s_rdma_mr->refcount);
qp->s_rdma_mr = NULL;
}
}
if (qp->ibqp.qp_type != IB_QPT_RC)
return;
for (n = 0; n < ARRAY_SIZE(qp->s_ack_queue); n++) {
struct qib_ack_entry *e = &qp->s_ack_queue[n];
if (e->opcode == IB_OPCODE_RC_RDMA_READ_REQUEST &&
e->rdma_sge.mr) {
atomic_dec(&e->rdma_sge.mr->refcount);
e->rdma_sge.mr = NULL;
}
}
}
/**
* qib_error_qp - put a QP into the error state
* @qp: the QP to put into the error state
* @err: the receive completion error to signal if a RWQE is active
*
* Flushes both send and receive work queues.
* Returns true if last WQE event should be generated.
* The QP s_lock should be held and interrupts disabled.
* If we are already in error state, just return.
*/
int qib_error_qp(struct qib_qp *qp, enum ib_wc_status err)
{
struct qib_ibdev *dev = to_idev(qp->ibqp.device);
struct ib_wc wc;
int ret = 0;
if (qp->state == IB_QPS_ERR || qp->state == IB_QPS_RESET)
goto bail;
qp->state = IB_QPS_ERR;
if (qp->s_flags & (QIB_S_TIMER | QIB_S_WAIT_RNR)) {
qp->s_flags &= ~(QIB_S_TIMER | QIB_S_WAIT_RNR);
del_timer(&qp->s_timer);
}
spin_lock(&dev->pending_lock);
if (!list_empty(&qp->iowait) && !(qp->s_flags & QIB_S_BUSY)) {
qp->s_flags &= ~QIB_S_ANY_WAIT_IO;
list_del_init(&qp->iowait);
}
spin_unlock(&dev->pending_lock);
if (!(qp->s_flags & QIB_S_BUSY)) {
qp->s_hdrwords = 0;
if (qp->s_rdma_mr) {
atomic_dec(&qp->s_rdma_mr->refcount);
qp->s_rdma_mr = NULL;
}
if (qp->s_tx) {
qib_put_txreq(qp->s_tx);
qp->s_tx = NULL;
}
}
/* Schedule the sending tasklet to drain the send work queue. */
if (qp->s_last != qp->s_head)
qib_schedule_send(qp);
clear_mr_refs(qp, 0);
memset(&wc, 0, sizeof(wc));
wc.qp = &qp->ibqp;
wc.opcode = IB_WC_RECV;
if (test_and_clear_bit(QIB_R_WRID_VALID, &qp->r_aflags)) {
wc.wr_id = qp->r_wr_id;
wc.status = err;
qib_cq_enter(to_icq(qp->ibqp.recv_cq), &wc, 1);
}
wc.status = IB_WC_WR_FLUSH_ERR;
if (qp->r_rq.wq) {
struct qib_rwq *wq;
u32 head;
u32 tail;
spin_lock(&qp->r_rq.lock);
/* sanity check pointers before trusting them */
wq = qp->r_rq.wq;
head = wq->head;
if (head >= qp->r_rq.size)
head = 0;
tail = wq->tail;
if (tail >= qp->r_rq.size)
tail = 0;
while (tail != head) {
wc.wr_id = get_rwqe_ptr(&qp->r_rq, tail)->wr_id;
if (++tail >= qp->r_rq.size)
tail = 0;
qib_cq_enter(to_icq(qp->ibqp.recv_cq), &wc, 1);
}
wq->tail = tail;
spin_unlock(&qp->r_rq.lock);
} else if (qp->ibqp.event_handler)
ret = 1;
bail:
return ret;
}
/**
* qib_modify_qp - modify the attributes of a queue pair
* @ibqp: the queue pair who's attributes we're modifying
* @attr: the new attributes
* @attr_mask: the mask of attributes to modify
* @udata: user data for libibverbs.so
*
* Returns 0 on success, otherwise returns an errno.
*/
int qib_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_udata *udata)
{
struct qib_ibdev *dev = to_idev(ibqp->device);
struct qib_qp *qp = to_iqp(ibqp);
enum ib_qp_state cur_state, new_state;
struct ib_event ev;
int lastwqe = 0;
int mig = 0;
int ret;
u32 pmtu = 0; /* for gcc warning only */
spin_lock_irq(&qp->r_lock);
spin_lock(&qp->s_lock);
cur_state = attr_mask & IB_QP_CUR_STATE ?
attr->cur_qp_state : qp->state;
new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state;
if (!ib_modify_qp_is_ok(cur_state, new_state, ibqp->qp_type,
attr_mask))
goto inval;
if (attr_mask & IB_QP_AV) {
if (attr->ah_attr.dlid >= QIB_MULTICAST_LID_BASE)
goto inval;
if (qib_check_ah(qp->ibqp.device, &attr->ah_attr))
goto inval;
}
if (attr_mask & IB_QP_ALT_PATH) {
if (attr->alt_ah_attr.dlid >= QIB_MULTICAST_LID_BASE)
goto inval;
if (qib_check_ah(qp->ibqp.device, &attr->alt_ah_attr))
goto inval;
if (attr->alt_pkey_index >= qib_get_npkeys(dd_from_dev(dev)))
goto inval;
}
if (attr_mask & IB_QP_PKEY_INDEX)
if (attr->pkey_index >= qib_get_npkeys(dd_from_dev(dev)))
goto inval;
if (attr_mask & IB_QP_MIN_RNR_TIMER)
if (attr->min_rnr_timer > 31)
goto inval;
if (attr_mask & IB_QP_PORT)
if (qp->ibqp.qp_type == IB_QPT_SMI ||
qp->ibqp.qp_type == IB_QPT_GSI ||
attr->port_num == 0 ||
attr->port_num > ibqp->device->phys_port_cnt)
goto inval;
if (attr_mask & IB_QP_DEST_QPN)
if (attr->dest_qp_num > QIB_QPN_MASK)
goto inval;
if (attr_mask & IB_QP_RETRY_CNT)
if (attr->retry_cnt > 7)
goto inval;
if (attr_mask & IB_QP_RNR_RETRY)
if (attr->rnr_retry > 7)
goto inval;
/*
* Don't allow invalid path_mtu values. OK to set greater
* than the active mtu (or even the max_cap, if we have tuned
* that to a small mtu. We'll set qp->path_mtu
* to the lesser of requested attribute mtu and active,
* for packetizing messages.
* Note that the QP port has to be set in INIT and MTU in RTR.
*/
if (attr_mask & IB_QP_PATH_MTU) {
struct qib_devdata *dd = dd_from_dev(dev);
int mtu, pidx = qp->port_num - 1;
mtu = ib_mtu_enum_to_int(attr->path_mtu);
if (mtu == -1)
goto inval;
if (mtu > dd->pport[pidx].ibmtu) {
switch (dd->pport[pidx].ibmtu) {
case 4096:
pmtu = IB_MTU_4096;
break;
case 2048:
pmtu = IB_MTU_2048;
break;
case 1024:
pmtu = IB_MTU_1024;
break;
case 512:
pmtu = IB_MTU_512;
break;
case 256:
pmtu = IB_MTU_256;
break;
default:
pmtu = IB_MTU_2048;
}
} else
pmtu = attr->path_mtu;
}
if (attr_mask & IB_QP_PATH_MIG_STATE) {
if (attr->path_mig_state == IB_MIG_REARM) {
if (qp->s_mig_state == IB_MIG_ARMED)
goto inval;
if (new_state != IB_QPS_RTS)
goto inval;
} else if (attr->path_mig_state == IB_MIG_MIGRATED) {
if (qp->s_mig_state == IB_MIG_REARM)
goto inval;
if (new_state != IB_QPS_RTS && new_state != IB_QPS_SQD)
goto inval;
if (qp->s_mig_state == IB_MIG_ARMED)
mig = 1;
} else
goto inval;
}
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
if (attr->max_dest_rd_atomic > QIB_MAX_RDMA_ATOMIC)
goto inval;
switch (new_state) {
case IB_QPS_RESET:
if (qp->state != IB_QPS_RESET) {
qp->state = IB_QPS_RESET;
spin_lock(&dev->pending_lock);
if (!list_empty(&qp->iowait))
list_del_init(&qp->iowait);
spin_unlock(&dev->pending_lock);
qp->s_flags &= ~(QIB_S_TIMER | QIB_S_ANY_WAIT);
spin_unlock(&qp->s_lock);
spin_unlock_irq(&qp->r_lock);
/* Stop the sending work queue and retry timer */
cancel_work_sync(&qp->s_work);
del_timer_sync(&qp->s_timer);
wait_event(qp->wait_dma, !atomic_read(&qp->s_dma_busy));
if (qp->s_tx) {
qib_put_txreq(qp->s_tx);
qp->s_tx = NULL;
}
remove_qp(dev, qp);
wait_event(qp->wait, !atomic_read(&qp->refcount));
spin_lock_irq(&qp->r_lock);
spin_lock(&qp->s_lock);
clear_mr_refs(qp, 1);
qib_reset_qp(qp, ibqp->qp_type);
}
break;
case IB_QPS_RTR:
/* Allow event to retrigger if QP set to RTR more than once */
qp->r_flags &= ~QIB_R_COMM_EST;
qp->state = new_state;
break;
case IB_QPS_SQD:
qp->s_draining = qp->s_last != qp->s_cur;
qp->state = new_state;
break;
case IB_QPS_SQE:
if (qp->ibqp.qp_type == IB_QPT_RC)
goto inval;
qp->state = new_state;
break;
case IB_QPS_ERR:
lastwqe = qib_error_qp(qp, IB_WC_WR_FLUSH_ERR);
break;
default:
qp->state = new_state;
break;
}
if (attr_mask & IB_QP_PKEY_INDEX)
qp->s_pkey_index = attr->pkey_index;
if (attr_mask & IB_QP_PORT)
qp->port_num = attr->port_num;
if (attr_mask & IB_QP_DEST_QPN)
qp->remote_qpn = attr->dest_qp_num;
if (attr_mask & IB_QP_SQ_PSN) {
qp->s_next_psn = attr->sq_psn & QIB_PSN_MASK;
qp->s_psn = qp->s_next_psn;
qp->s_sending_psn = qp->s_next_psn;
qp->s_last_psn = qp->s_next_psn - 1;
qp->s_sending_hpsn = qp->s_last_psn;
}
if (attr_mask & IB_QP_RQ_PSN)
qp->r_psn = attr->rq_psn & QIB_PSN_MASK;
if (attr_mask & IB_QP_ACCESS_FLAGS)
qp->qp_access_flags = attr->qp_access_flags;
if (attr_mask & IB_QP_AV) {
qp->remote_ah_attr = attr->ah_attr;
qp->s_srate = attr->ah_attr.static_rate;
}
if (attr_mask & IB_QP_ALT_PATH) {
qp->alt_ah_attr = attr->alt_ah_attr;
qp->s_alt_pkey_index = attr->alt_pkey_index;
}
if (attr_mask & IB_QP_PATH_MIG_STATE) {
qp->s_mig_state = attr->path_mig_state;
if (mig) {
qp->remote_ah_attr = qp->alt_ah_attr;
qp->port_num = qp->alt_ah_attr.port_num;
qp->s_pkey_index = qp->s_alt_pkey_index;
}
}
if (attr_mask & IB_QP_PATH_MTU)
qp->path_mtu = pmtu;
if (attr_mask & IB_QP_RETRY_CNT) {
qp->s_retry_cnt = attr->retry_cnt;
qp->s_retry = attr->retry_cnt;
}
if (attr_mask & IB_QP_RNR_RETRY) {
qp->s_rnr_retry_cnt = attr->rnr_retry;
qp->s_rnr_retry = attr->rnr_retry;
}
if (attr_mask & IB_QP_MIN_RNR_TIMER)
qp->r_min_rnr_timer = attr->min_rnr_timer;
if (attr_mask & IB_QP_TIMEOUT)
qp->timeout = attr->timeout;
if (attr_mask & IB_QP_QKEY)
qp->qkey = attr->qkey;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
qp->r_max_rd_atomic = attr->max_dest_rd_atomic;
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC)
qp->s_max_rd_atomic = attr->max_rd_atomic;
spin_unlock(&qp->s_lock);
spin_unlock_irq(&qp->r_lock);
if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
insert_qp(dev, qp);
if (lastwqe) {
ev.device = qp->ibqp.device;
ev.element.qp = &qp->ibqp;
ev.event = IB_EVENT_QP_LAST_WQE_REACHED;
qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
}
if (mig) {
ev.device = qp->ibqp.device;
ev.element.qp = &qp->ibqp;
ev.event = IB_EVENT_PATH_MIG;
qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
}
ret = 0;
goto bail;
inval:
spin_unlock(&qp->s_lock);
spin_unlock_irq(&qp->r_lock);
ret = -EINVAL;
bail:
return ret;
}
int qib_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_qp_init_attr *init_attr)
{
struct qib_qp *qp = to_iqp(ibqp);
attr->qp_state = qp->state;
attr->cur_qp_state = attr->qp_state;
attr->path_mtu = qp->path_mtu;
attr->path_mig_state = qp->s_mig_state;
attr->qkey = qp->qkey;
attr->rq_psn = qp->r_psn & QIB_PSN_MASK;
attr->sq_psn = qp->s_next_psn & QIB_PSN_MASK;
attr->dest_qp_num = qp->remote_qpn;
attr->qp_access_flags = qp->qp_access_flags;
attr->cap.max_send_wr = qp->s_size - 1;
attr->cap.max_recv_wr = qp->ibqp.srq ? 0 : qp->r_rq.size - 1;
attr->cap.max_send_sge = qp->s_max_sge;
attr->cap.max_recv_sge = qp->r_rq.max_sge;
attr->cap.max_inline_data = 0;
attr->ah_attr = qp->remote_ah_attr;
attr->alt_ah_attr = qp->alt_ah_attr;
attr->pkey_index = qp->s_pkey_index;
attr->alt_pkey_index = qp->s_alt_pkey_index;
attr->en_sqd_async_notify = 0;
attr->sq_draining = qp->s_draining;
attr->max_rd_atomic = qp->s_max_rd_atomic;
attr->max_dest_rd_atomic = qp->r_max_rd_atomic;
attr->min_rnr_timer = qp->r_min_rnr_timer;
attr->port_num = qp->port_num;
attr->timeout = qp->timeout;
attr->retry_cnt = qp->s_retry_cnt;
attr->rnr_retry = qp->s_rnr_retry_cnt;
attr->alt_port_num = qp->alt_ah_attr.port_num;
attr->alt_timeout = qp->alt_timeout;
init_attr->event_handler = qp->ibqp.event_handler;
init_attr->qp_context = qp->ibqp.qp_context;
init_attr->send_cq = qp->ibqp.send_cq;
init_attr->recv_cq = qp->ibqp.recv_cq;
init_attr->srq = qp->ibqp.srq;
init_attr->cap = attr->cap;
if (qp->s_flags & QIB_S_SIGNAL_REQ_WR)
init_attr->sq_sig_type = IB_SIGNAL_REQ_WR;
else
init_attr->sq_sig_type = IB_SIGNAL_ALL_WR;
init_attr->qp_type = qp->ibqp.qp_type;
init_attr->port_num = qp->port_num;
return 0;
}
/**
* qib_compute_aeth - compute the AETH (syndrome + MSN)
* @qp: the queue pair to compute the AETH for
*
* Returns the AETH.
*/
__be32 qib_compute_aeth(struct qib_qp *qp)
{
u32 aeth = qp->r_msn & QIB_MSN_MASK;
if (qp->ibqp.srq) {
/*
* Shared receive queues don't generate credits.
* Set the credit field to the invalid value.
*/
aeth |= QIB_AETH_CREDIT_INVAL << QIB_AETH_CREDIT_SHIFT;
} else {
u32 min, max, x;
u32 credits;
struct qib_rwq *wq = qp->r_rq.wq;
u32 head;
u32 tail;
/* sanity check pointers before trusting them */
head = wq->head;
if (head >= qp->r_rq.size)
head = 0;
tail = wq->tail;
if (tail >= qp->r_rq.size)
tail = 0;
/*
* Compute the number of credits available (RWQEs).
* XXX Not holding the r_rq.lock here so there is a small
* chance that the pair of reads are not atomic.
*/
credits = head - tail;
if ((int)credits < 0)
credits += qp->r_rq.size;
/*
* Binary search the credit table to find the code to
* use.
*/
min = 0;
max = 31;
for (;;) {
x = (min + max) / 2;
if (credit_table[x] == credits)
break;
if (credit_table[x] > credits)
max = x;
else if (min == x)
break;
else
min = x;
}
aeth |= x << QIB_AETH_CREDIT_SHIFT;
}
return cpu_to_be32(aeth);
}
/**
* qib_create_qp - create a queue pair for a device
* @ibpd: the protection domain who's device we create the queue pair for
* @init_attr: the attributes of the queue pair
* @udata: user data for libibverbs.so
*
* Returns the queue pair on success, otherwise returns an errno.
*
* Called by the ib_create_qp() core verbs function.
*/
struct ib_qp *qib_create_qp(struct ib_pd *ibpd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata)
{
struct qib_qp *qp;
int err;
struct qib_swqe *swq = NULL;
struct qib_ibdev *dev;
struct qib_devdata *dd;
size_t sz;
size_t sg_list_sz;
struct ib_qp *ret;
if (init_attr->cap.max_send_sge > ib_qib_max_sges ||
init_attr->cap.max_send_wr > ib_qib_max_qp_wrs) {
ret = ERR_PTR(-EINVAL);
goto bail;
}
/* Check receive queue parameters if no SRQ is specified. */
if (!init_attr->srq) {
if (init_attr->cap.max_recv_sge > ib_qib_max_sges ||
init_attr->cap.max_recv_wr > ib_qib_max_qp_wrs) {
ret = ERR_PTR(-EINVAL);
goto bail;
}
if (init_attr->cap.max_send_sge +
init_attr->cap.max_send_wr +
init_attr->cap.max_recv_sge +
init_attr->cap.max_recv_wr == 0) {
ret = ERR_PTR(-EINVAL);
goto bail;
}
}
switch (init_attr->qp_type) {
case IB_QPT_SMI:
case IB_QPT_GSI:
if (init_attr->port_num == 0 ||
init_attr->port_num > ibpd->device->phys_port_cnt) {
ret = ERR_PTR(-EINVAL);
goto bail;
}
case IB_QPT_UC:
case IB_QPT_RC:
case IB_QPT_UD:
sz = sizeof(struct qib_sge) *
init_attr->cap.max_send_sge +
sizeof(struct qib_swqe);
swq = vmalloc((init_attr->cap.max_send_wr + 1) * sz);
if (swq == NULL) {
ret = ERR_PTR(-ENOMEM);
goto bail;
}
sz = sizeof(*qp);
sg_list_sz = 0;
if (init_attr->srq) {
struct qib_srq *srq = to_isrq(init_attr->srq);
if (srq->rq.max_sge > 1)
sg_list_sz = sizeof(*qp->r_sg_list) *
(srq->rq.max_sge - 1);
} else if (init_attr->cap.max_recv_sge > 1)
sg_list_sz = sizeof(*qp->r_sg_list) *
(init_attr->cap.max_recv_sge - 1);
qp = kzalloc(sz + sg_list_sz, GFP_KERNEL);
if (!qp) {
ret = ERR_PTR(-ENOMEM);
goto bail_swq;
}
if (init_attr->srq)
sz = 0;
else {
qp->r_rq.size = init_attr->cap.max_recv_wr + 1;
qp->r_rq.max_sge = init_attr->cap.max_recv_sge;
sz = (sizeof(struct ib_sge) * qp->r_rq.max_sge) +
sizeof(struct qib_rwqe);
qp->r_rq.wq = vmalloc_user(sizeof(struct qib_rwq) +
qp->r_rq.size * sz);
if (!qp->r_rq.wq) {
ret = ERR_PTR(-ENOMEM);
goto bail_qp;
}
}
/*
* ib_create_qp() will initialize qp->ibqp
* except for qp->ibqp.qp_num.
*/
spin_lock_init(&qp->r_lock);
spin_lock_init(&qp->s_lock);
spin_lock_init(&qp->r_rq.lock);
atomic_set(&qp->refcount, 0);
init_waitqueue_head(&qp->wait);
init_waitqueue_head(&qp->wait_dma);
init_timer(&qp->s_timer);
qp->s_timer.data = (unsigned long)qp;
INIT_WORK(&qp->s_work, qib_do_send);
INIT_LIST_HEAD(&qp->iowait);
INIT_LIST_HEAD(&qp->rspwait);
qp->state = IB_QPS_RESET;
qp->s_wq = swq;
qp->s_size = init_attr->cap.max_send_wr + 1;
qp->s_max_sge = init_attr->cap.max_send_sge;
if (init_attr->sq_sig_type == IB_SIGNAL_REQ_WR)
qp->s_flags = QIB_S_SIGNAL_REQ_WR;
dev = to_idev(ibpd->device);
dd = dd_from_dev(dev);
err = alloc_qpn(dd, &dev->qpn_table, init_attr->qp_type,
init_attr->port_num);
if (err < 0) {
ret = ERR_PTR(err);
vfree(qp->r_rq.wq);
goto bail_qp;
}
qp->ibqp.qp_num = err;
qp->port_num = init_attr->port_num;
qp->processor_id = smp_processor_id();
qib_reset_qp(qp, init_attr->qp_type);
break;
default:
/* Don't support raw QPs */
ret = ERR_PTR(-ENOSYS);
goto bail;
}
init_attr->cap.max_inline_data = 0;
/*
* Return the address of the RWQ as the offset to mmap.
* See qib_mmap() for details.
*/
if (udata && udata->outlen >= sizeof(__u64)) {
if (!qp->r_rq.wq) {
__u64 offset = 0;
err = ib_copy_to_udata(udata, &offset,
sizeof(offset));
if (err) {
ret = ERR_PTR(err);
goto bail_ip;
}
} else {
u32 s = sizeof(struct qib_rwq) + qp->r_rq.size * sz;
qp->ip = qib_create_mmap_info(dev, s,
ibpd->uobject->context,
qp->r_rq.wq);
if (!qp->ip) {
ret = ERR_PTR(-ENOMEM);
goto bail_ip;
}
err = ib_copy_to_udata(udata, &(qp->ip->offset),
sizeof(qp->ip->offset));
if (err) {
ret = ERR_PTR(err);
goto bail_ip;
}
}
}
spin_lock(&dev->n_qps_lock);
if (dev->n_qps_allocated == ib_qib_max_qps) {
spin_unlock(&dev->n_qps_lock);
ret = ERR_PTR(-ENOMEM);
goto bail_ip;
}
dev->n_qps_allocated++;
spin_unlock(&dev->n_qps_lock);
if (qp->ip) {
spin_lock_irq(&dev->pending_lock);
list_add(&qp->ip->pending_mmaps, &dev->pending_mmaps);
spin_unlock_irq(&dev->pending_lock);
}
ret = &qp->ibqp;
goto bail;
bail_ip:
if (qp->ip)
kref_put(&qp->ip->ref, qib_release_mmap_info);
else
vfree(qp->r_rq.wq);
free_qpn(&dev->qpn_table, qp->ibqp.qp_num);
bail_qp:
kfree(qp);
bail_swq:
vfree(swq);
bail:
return ret;
}
/**
* qib_destroy_qp - destroy a queue pair
* @ibqp: the queue pair to destroy
*
* Returns 0 on success.
*
* Note that this can be called while the QP is actively sending or
* receiving!
*/
int qib_destroy_qp(struct ib_qp *ibqp)
{
struct qib_qp *qp = to_iqp(ibqp);
struct qib_ibdev *dev = to_idev(ibqp->device);
/* Make sure HW and driver activity is stopped. */
spin_lock_irq(&qp->s_lock);
if (qp->state != IB_QPS_RESET) {
qp->state = IB_QPS_RESET;
spin_lock(&dev->pending_lock);
if (!list_empty(&qp->iowait))
list_del_init(&qp->iowait);
spin_unlock(&dev->pending_lock);
qp->s_flags &= ~(QIB_S_TIMER | QIB_S_ANY_WAIT);
spin_unlock_irq(&qp->s_lock);
cancel_work_sync(&qp->s_work);
del_timer_sync(&qp->s_timer);
wait_event(qp->wait_dma, !atomic_read(&qp->s_dma_busy));
if (qp->s_tx) {
qib_put_txreq(qp->s_tx);
qp->s_tx = NULL;
}
remove_qp(dev, qp);
wait_event(qp->wait, !atomic_read(&qp->refcount));
clear_mr_refs(qp, 1);
} else
spin_unlock_irq(&qp->s_lock);
/* all user's cleaned up, mark it available */
free_qpn(&dev->qpn_table, qp->ibqp.qp_num);
spin_lock(&dev->n_qps_lock);
dev->n_qps_allocated--;
spin_unlock(&dev->n_qps_lock);
if (qp->ip)
kref_put(&qp->ip->ref, qib_release_mmap_info);
else
vfree(qp->r_rq.wq);
vfree(qp->s_wq);
kfree(qp);
return 0;
}
/**
* qib_init_qpn_table - initialize the QP number table for a device
* @qpt: the QPN table
*/
void qib_init_qpn_table(struct qib_devdata *dd, struct qib_qpn_table *qpt)
{
spin_lock_init(&qpt->lock);
qpt->last = 1; /* start with QPN 2 */
qpt->nmaps = 1;
qpt->mask = dd->qpn_mask;
}
/**
* qib_free_qpn_table - free the QP number table for a device
* @qpt: the QPN table
*/
void qib_free_qpn_table(struct qib_qpn_table *qpt)
{
int i;
for (i = 0; i < ARRAY_SIZE(qpt->map); i++)
if (qpt->map[i].page)
free_page((unsigned long) qpt->map[i].page);
}
/**
* qib_get_credit - flush the send work queue of a QP
* @qp: the qp who's send work queue to flush
* @aeth: the Acknowledge Extended Transport Header
*
* The QP s_lock should be held.
*/
void qib_get_credit(struct qib_qp *qp, u32 aeth)
{
u32 credit = (aeth >> QIB_AETH_CREDIT_SHIFT) & QIB_AETH_CREDIT_MASK;
/*
* If the credit is invalid, we can send
* as many packets as we like. Otherwise, we have to
* honor the credit field.
*/
if (credit == QIB_AETH_CREDIT_INVAL) {
if (!(qp->s_flags & QIB_S_UNLIMITED_CREDIT)) {
qp->s_flags |= QIB_S_UNLIMITED_CREDIT;
if (qp->s_flags & QIB_S_WAIT_SSN_CREDIT) {
qp->s_flags &= ~QIB_S_WAIT_SSN_CREDIT;
qib_schedule_send(qp);
}
}
} else if (!(qp->s_flags & QIB_S_UNLIMITED_CREDIT)) {
/* Compute new LSN (i.e., MSN + credit) */
credit = (aeth + credit_table[credit]) & QIB_MSN_MASK;
if (qib_cmp24(credit, qp->s_lsn) > 0) {
qp->s_lsn = credit;
if (qp->s_flags & QIB_S_WAIT_SSN_CREDIT) {
qp->s_flags &= ~QIB_S_WAIT_SSN_CREDIT;
qib_schedule_send(qp);
}
}
}
}
| gpl-2.0 |
dev-harsh1998/Phantom-Jalebi | arch/x86/kernel/microcode_intel.c | 2297 | 9612 | /*
* Intel CPU Microcode Update Driver for Linux
*
* Copyright (C) 2000-2006 Tigran Aivazian <tigran@aivazian.fsnet.co.uk>
* 2006 Shaohua Li <shaohua.li@intel.com>
*
* This driver allows to upgrade microcode on Intel processors
* belonging to IA-32 family - PentiumPro, Pentium II,
* Pentium III, Xeon, Pentium 4, etc.
*
* Reference: Section 8.11 of Volume 3a, IA-32 Intel? Architecture
* Software Developer's Manual
* Order Number 253668 or free download from:
*
* http://developer.intel.com/Assets/PDF/manual/253668.pdf
*
* For more information, go to http://www.urbanmyth.org/microcode
*
* 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.
*
* 1.0 16 Feb 2000, Tigran Aivazian <tigran@sco.com>
* Initial release.
* 1.01 18 Feb 2000, Tigran Aivazian <tigran@sco.com>
* Added read() support + cleanups.
* 1.02 21 Feb 2000, Tigran Aivazian <tigran@sco.com>
* Added 'device trimming' support. open(O_WRONLY) zeroes
* and frees the saved copy of applied microcode.
* 1.03 29 Feb 2000, Tigran Aivazian <tigran@sco.com>
* Made to use devfs (/dev/cpu/microcode) + cleanups.
* 1.04 06 Jun 2000, Simon Trimmer <simon@veritas.com>
* Added misc device support (now uses both devfs and misc).
* Added MICROCODE_IOCFREE ioctl to clear memory.
* 1.05 09 Jun 2000, Simon Trimmer <simon@veritas.com>
* Messages for error cases (non Intel & no suitable microcode).
* 1.06 03 Aug 2000, Tigran Aivazian <tigran@veritas.com>
* Removed ->release(). Removed exclusive open and status bitmap.
* Added microcode_rwsem to serialize read()/write()/ioctl().
* Removed global kernel lock usage.
* 1.07 07 Sep 2000, Tigran Aivazian <tigran@veritas.com>
* Write 0 to 0x8B msr and then cpuid before reading revision,
* so that it works even if there were no update done by the
* BIOS. Otherwise, reading from 0x8B gives junk (which happened
* to be 0 on my machine which is why it worked even when I
* disabled update by the BIOS)
* Thanks to Eric W. Biederman <ebiederman@lnxi.com> for the fix.
* 1.08 11 Dec 2000, Richard Schaal <richard.schaal@intel.com> and
* Tigran Aivazian <tigran@veritas.com>
* Intel Pentium 4 processor support and bugfixes.
* 1.09 30 Oct 2001, Tigran Aivazian <tigran@veritas.com>
* Bugfix for HT (Hyper-Threading) enabled processors
* whereby processor resources are shared by all logical processors
* in a single CPU package.
* 1.10 28 Feb 2002 Asit K Mallick <asit.k.mallick@intel.com> and
* Tigran Aivazian <tigran@veritas.com>,
* Serialize updates as required on HT processors due to
* speculative nature of implementation.
* 1.11 22 Mar 2002 Tigran Aivazian <tigran@veritas.com>
* Fix the panic when writing zero-length microcode chunk.
* 1.12 29 Sep 2003 Nitin Kamble <nitin.a.kamble@intel.com>,
* Jun Nakajima <jun.nakajima@intel.com>
* Support for the microcode updates in the new format.
* 1.13 10 Oct 2003 Tigran Aivazian <tigran@veritas.com>
* Removed ->read() method and obsoleted MICROCODE_IOCFREE ioctl
* because we no longer hold a copy of applied microcode
* in kernel memory.
* 1.14 25 Jun 2004 Tigran Aivazian <tigran@veritas.com>
* Fix sigmatch() macro to handle old CPUs with pf == 0.
* Thanks to Stuart Swales for pointing out this bug.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/firmware.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <asm/microcode_intel.h>
#include <asm/processor.h>
#include <asm/msr.h>
MODULE_DESCRIPTION("Microcode Update Driver");
MODULE_AUTHOR("Tigran Aivazian <tigran@aivazian.fsnet.co.uk>");
MODULE_LICENSE("GPL");
static int collect_cpu_info(int cpu_num, struct cpu_signature *csig)
{
struct cpuinfo_x86 *c = &cpu_data(cpu_num);
unsigned int val[2];
memset(csig, 0, sizeof(*csig));
csig->sig = cpuid_eax(0x00000001);
if ((c->x86_model >= 5) || (c->x86 > 6)) {
/* get processor flags from MSR 0x17 */
rdmsr(MSR_IA32_PLATFORM_ID, val[0], val[1]);
csig->pf = 1 << ((val[1] >> 18) & 7);
}
csig->rev = c->microcode;
pr_info("CPU%d sig=0x%x, pf=0x%x, revision=0x%x\n",
cpu_num, csig->sig, csig->pf, csig->rev);
return 0;
}
/*
* return 0 - no update found
* return 1 - found update
*/
static int get_matching_mc(struct microcode_intel *mc_intel, int cpu)
{
struct cpu_signature cpu_sig;
unsigned int csig, cpf, crev;
collect_cpu_info(cpu, &cpu_sig);
csig = cpu_sig.sig;
cpf = cpu_sig.pf;
crev = cpu_sig.rev;
return get_matching_microcode(csig, cpf, mc_intel, crev);
}
int apply_microcode(int cpu)
{
struct microcode_intel *mc_intel;
struct ucode_cpu_info *uci;
unsigned int val[2];
int cpu_num = raw_smp_processor_id();
struct cpuinfo_x86 *c = &cpu_data(cpu_num);
uci = ucode_cpu_info + cpu;
mc_intel = uci->mc;
/* We should bind the task to the CPU */
BUG_ON(cpu_num != cpu);
if (mc_intel == NULL)
return 0;
/*
* Microcode on this CPU could be updated earlier. Only apply the
* microcode patch in mc_intel when it is newer than the one on this
* CPU.
*/
if (get_matching_mc(mc_intel, cpu) == 0)
return 0;
/* write microcode via MSR 0x79 */
wrmsr(MSR_IA32_UCODE_WRITE,
(unsigned long) mc_intel->bits,
(unsigned long) mc_intel->bits >> 16 >> 16);
wrmsr(MSR_IA32_UCODE_REV, 0, 0);
/* As documented in the SDM: Do a CPUID 1 here */
sync_core();
/* get the current revision from MSR 0x8B */
rdmsr(MSR_IA32_UCODE_REV, val[0], val[1]);
if (val[1] != mc_intel->hdr.rev) {
pr_err("CPU%d update to revision 0x%x failed\n",
cpu_num, mc_intel->hdr.rev);
return -1;
}
pr_info("CPU%d updated to revision 0x%x, date = %04x-%02x-%02x\n",
cpu_num, val[1],
mc_intel->hdr.date & 0xffff,
mc_intel->hdr.date >> 24,
(mc_intel->hdr.date >> 16) & 0xff);
uci->cpu_sig.rev = val[1];
c->microcode = val[1];
return 0;
}
static enum ucode_state generic_load_microcode(int cpu, void *data, size_t size,
int (*get_ucode_data)(void *, const void *, size_t))
{
struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
u8 *ucode_ptr = data, *new_mc = NULL, *mc = NULL;
int new_rev = uci->cpu_sig.rev;
unsigned int leftover = size;
enum ucode_state state = UCODE_OK;
unsigned int curr_mc_size = 0;
unsigned int csig, cpf;
while (leftover) {
struct microcode_header_intel mc_header;
unsigned int mc_size;
if (get_ucode_data(&mc_header, ucode_ptr, sizeof(mc_header)))
break;
mc_size = get_totalsize(&mc_header);
if (!mc_size || mc_size > leftover) {
pr_err("error! Bad data in microcode data file\n");
break;
}
/* For performance reasons, reuse mc area when possible */
if (!mc || mc_size > curr_mc_size) {
vfree(mc);
mc = vmalloc(mc_size);
if (!mc)
break;
curr_mc_size = mc_size;
}
if (get_ucode_data(mc, ucode_ptr, mc_size) ||
microcode_sanity_check(mc, 1) < 0) {
break;
}
csig = uci->cpu_sig.sig;
cpf = uci->cpu_sig.pf;
if (get_matching_microcode(csig, cpf, mc, new_rev)) {
vfree(new_mc);
new_rev = mc_header.rev;
new_mc = mc;
mc = NULL; /* trigger new vmalloc */
}
ucode_ptr += mc_size;
leftover -= mc_size;
}
vfree(mc);
if (leftover) {
vfree(new_mc);
state = UCODE_ERROR;
goto out;
}
if (!new_mc) {
state = UCODE_NFOUND;
goto out;
}
vfree(uci->mc);
uci->mc = (struct microcode_intel *)new_mc;
/*
* If early loading microcode is supported, save this mc into
* permanent memory. So it will be loaded early when a CPU is hot added
* or resumes.
*/
save_mc_for_early(new_mc);
pr_debug("CPU%d found a matching microcode update with version 0x%x (current=0x%x)\n",
cpu, new_rev, uci->cpu_sig.rev);
out:
return state;
}
static int get_ucode_fw(void *to, const void *from, size_t n)
{
memcpy(to, from, n);
return 0;
}
static enum ucode_state request_microcode_fw(int cpu, struct device *device,
bool refresh_fw)
{
char name[30];
struct cpuinfo_x86 *c = &cpu_data(cpu);
const struct firmware *firmware;
enum ucode_state ret;
sprintf(name, "intel-ucode/%02x-%02x-%02x",
c->x86, c->x86_model, c->x86_mask);
if (request_firmware(&firmware, name, device)) {
pr_debug("data file %s load failed\n", name);
return UCODE_NFOUND;
}
ret = generic_load_microcode(cpu, (void *)firmware->data,
firmware->size, &get_ucode_fw);
release_firmware(firmware);
return ret;
}
static int get_ucode_user(void *to, const void *from, size_t n)
{
return copy_from_user(to, from, n);
}
static enum ucode_state
request_microcode_user(int cpu, const void __user *buf, size_t size)
{
return generic_load_microcode(cpu, (void *)buf, size, &get_ucode_user);
}
static void microcode_fini_cpu(int cpu)
{
struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
vfree(uci->mc);
uci->mc = NULL;
}
static struct microcode_ops microcode_intel_ops = {
.request_microcode_user = request_microcode_user,
.request_microcode_fw = request_microcode_fw,
.collect_cpu_info = collect_cpu_info,
.apply_microcode = apply_microcode,
.microcode_fini_cpu = microcode_fini_cpu,
};
struct microcode_ops * __init init_intel_microcode(void)
{
struct cpuinfo_x86 *c = &cpu_data(0);
if (c->x86_vendor != X86_VENDOR_INTEL || c->x86 < 6 ||
cpu_has(c, X86_FEATURE_IA64)) {
pr_err("Intel CPU family 0x%x not supported\n", c->x86);
return NULL;
}
return µcode_intel_ops;
}
| gpl-2.0 |
artefvck/android_kernel_asus_T00F | arch/arm/mach-pxa/colibri-pxa300.c | 4089 | 4671 | /*
* arch/arm/mach-pxa/colibri-pxa300.c
*
* Support for Toradex PXA300/310 based Colibri module
*
* Daniel Mack <daniel@caiaq.de>
* Matthias Meier <matthias.j.meier@gmx.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <asm/mach-types.h>
#include <asm/sizes.h>
#include <asm/mach/arch.h>
#include <asm/mach/irq.h>
#include <mach/pxa300.h>
#include <mach/colibri.h>
#include <linux/platform_data/usb-ohci-pxa27x.h>
#include <linux/platform_data/video-pxafb.h>
#include <mach/audio.h>
#include "generic.h"
#include "devices.h"
#ifdef CONFIG_MACH_COLIBRI_EVALBOARD
static mfp_cfg_t colibri_pxa300_evalboard_pin_config[] __initdata = {
/* MMC */
GPIO7_MMC1_CLK,
GPIO14_MMC1_CMD,
GPIO3_MMC1_DAT0,
GPIO4_MMC1_DAT1,
GPIO5_MMC1_DAT2,
GPIO6_MMC1_DAT3,
GPIO13_GPIO, /* GPIO13_COLIBRI_PXA300_SD_DETECT */
/* UHC */
GPIO0_2_USBH_PEN,
GPIO1_2_USBH_PWR,
GPIO77_USB_P3_1,
GPIO78_USB_P3_2,
GPIO79_USB_P3_3,
GPIO80_USB_P3_4,
GPIO81_USB_P3_5,
GPIO82_USB_P3_6,
/* I2C */
GPIO21_I2C_SCL,
GPIO22_I2C_SDA,
};
#else
static mfp_cfg_t colibri_pxa300_evalboard_pin_config[] __initdata = {};
#endif
#if defined(CONFIG_AX88796)
#define COLIBRI_ETH_IRQ_GPIO mfp_to_gpio(GPIO26_GPIO)
/*
* Asix AX88796 Ethernet
*/
static struct ax_plat_data colibri_asix_platdata = {
.flags = 0, /* defined later */
.wordlength = 2,
};
static struct resource colibri_asix_resource[] = {
[0] = {
.start = PXA3xx_CS2_PHYS,
.end = PXA3xx_CS2_PHYS + (0x20 * 2) - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_GPIO_TO_IRQ(COLIBRI_ETH_IRQ_GPIO),
.end = PXA_GPIO_TO_IRQ(COLIBRI_ETH_IRQ_GPIO),
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_FALLING,
}
};
static struct platform_device asix_device = {
.name = "ax88796",
.id = 0,
.num_resources = ARRAY_SIZE(colibri_asix_resource),
.resource = colibri_asix_resource,
.dev = {
.platform_data = &colibri_asix_platdata
}
};
static mfp_cfg_t colibri_pxa300_eth_pin_config[] __initdata = {
GPIO1_nCS2, /* AX88796 chip select */
GPIO26_GPIO | MFP_PULL_HIGH /* AX88796 IRQ */
};
static void __init colibri_pxa300_init_eth(void)
{
colibri_pxa3xx_init_eth(&colibri_asix_platdata);
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa300_eth_pin_config));
platform_device_register(&asix_device);
}
#else
static inline void __init colibri_pxa300_init_eth(void) {}
#endif /* CONFIG_AX88796 */
#if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE)
static mfp_cfg_t colibri_pxa300_lcd_pin_config[] __initdata = {
GPIO54_LCD_LDD_0,
GPIO55_LCD_LDD_1,
GPIO56_LCD_LDD_2,
GPIO57_LCD_LDD_3,
GPIO58_LCD_LDD_4,
GPIO59_LCD_LDD_5,
GPIO60_LCD_LDD_6,
GPIO61_LCD_LDD_7,
GPIO62_LCD_LDD_8,
GPIO63_LCD_LDD_9,
GPIO64_LCD_LDD_10,
GPIO65_LCD_LDD_11,
GPIO66_LCD_LDD_12,
GPIO67_LCD_LDD_13,
GPIO68_LCD_LDD_14,
GPIO69_LCD_LDD_15,
GPIO70_LCD_LDD_16,
GPIO71_LCD_LDD_17,
GPIO62_LCD_CS_N,
GPIO72_LCD_FCLK,
GPIO73_LCD_LCLK,
GPIO74_LCD_PCLK,
GPIO75_LCD_BIAS,
GPIO76_LCD_VSYNC,
};
static void __init colibri_pxa300_init_lcd(void)
{
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa300_lcd_pin_config));
}
#else
static inline void colibri_pxa300_init_lcd(void) {}
#endif /* CONFIG_FB_PXA || CONFIG_FB_PXA_MODULE */
#if defined(CONFIG_SND_AC97_CODEC) || defined(CONFIG_SND_AC97_CODEC_MODULE)
static mfp_cfg_t colibri_pxa310_ac97_pin_config[] __initdata = {
GPIO24_AC97_SYSCLK,
GPIO23_AC97_nACRESET,
GPIO25_AC97_SDATA_IN_0,
GPIO27_AC97_SDATA_OUT,
GPIO28_AC97_SYNC,
GPIO29_AC97_BITCLK
};
static inline void __init colibri_pxa310_init_ac97(void)
{
/* no AC97 codec on Colibri PXA300 */
if (!cpu_is_pxa310())
return;
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa310_ac97_pin_config));
pxa_set_ac97_info(NULL);
}
#else
static inline void colibri_pxa310_init_ac97(void) {}
#endif
void __init colibri_pxa300_init(void)
{
colibri_pxa300_init_eth();
colibri_pxa3xx_init_nand();
colibri_pxa300_init_lcd();
colibri_pxa3xx_init_lcd(mfp_to_gpio(GPIO39_GPIO));
colibri_pxa310_init_ac97();
/* Evalboard init */
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa300_evalboard_pin_config));
colibri_evalboard_init();
}
MACHINE_START(COLIBRI300, "Toradex Colibri PXA300")
.atag_offset = 0x100,
.init_machine = colibri_pxa300_init,
.map_io = pxa3xx_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa3xx_init_irq,
.handle_irq = pxa3xx_handle_irq,
.init_time = pxa_timer_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
danielgpalmer/linux-picosam9g45 | drivers/hwmon/tmp401.c | 4857 | 18543 | /* tmp401.c
*
* Copyright (C) 2007,2008 Hans de Goede <hdegoede@redhat.com>
* Preliminary tmp411 support by:
* Gabriel Konat, Sander Leget, Wouter Willems
* Copyright (C) 2009 Andre Prendel <andre.prendel@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Driver for the Texas Instruments TMP401 SMBUS temperature sensor IC.
*
* Note this IC is in some aspect similar to the LM90, but it has quite a
* few differences too, for example the local temp has a higher resolution
* and thus has 16 bits registers for its value and limit instead of 8 bits.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x4c, I2C_CLIENT_END };
enum chips { tmp401, tmp411 };
/*
* The TMP401 registers, note some registers have different addresses for
* reading and writing
*/
#define TMP401_STATUS 0x02
#define TMP401_CONFIG_READ 0x03
#define TMP401_CONFIG_WRITE 0x09
#define TMP401_CONVERSION_RATE_READ 0x04
#define TMP401_CONVERSION_RATE_WRITE 0x0A
#define TMP401_TEMP_CRIT_HYST 0x21
#define TMP401_CONSECUTIVE_ALERT 0x22
#define TMP401_MANUFACTURER_ID_REG 0xFE
#define TMP401_DEVICE_ID_REG 0xFF
#define TMP411_N_FACTOR_REG 0x18
static const u8 TMP401_TEMP_MSB[2] = { 0x00, 0x01 };
static const u8 TMP401_TEMP_LSB[2] = { 0x15, 0x10 };
static const u8 TMP401_TEMP_LOW_LIMIT_MSB_READ[2] = { 0x06, 0x08 };
static const u8 TMP401_TEMP_LOW_LIMIT_MSB_WRITE[2] = { 0x0C, 0x0E };
static const u8 TMP401_TEMP_LOW_LIMIT_LSB[2] = { 0x17, 0x14 };
static const u8 TMP401_TEMP_HIGH_LIMIT_MSB_READ[2] = { 0x05, 0x07 };
static const u8 TMP401_TEMP_HIGH_LIMIT_MSB_WRITE[2] = { 0x0B, 0x0D };
static const u8 TMP401_TEMP_HIGH_LIMIT_LSB[2] = { 0x16, 0x13 };
/* These are called the THERM limit / hysteresis / mask in the datasheet */
static const u8 TMP401_TEMP_CRIT_LIMIT[2] = { 0x20, 0x19 };
static const u8 TMP411_TEMP_LOWEST_MSB[2] = { 0x30, 0x34 };
static const u8 TMP411_TEMP_LOWEST_LSB[2] = { 0x31, 0x35 };
static const u8 TMP411_TEMP_HIGHEST_MSB[2] = { 0x32, 0x36 };
static const u8 TMP411_TEMP_HIGHEST_LSB[2] = { 0x33, 0x37 };
/* Flags */
#define TMP401_CONFIG_RANGE 0x04
#define TMP401_CONFIG_SHUTDOWN 0x40
#define TMP401_STATUS_LOCAL_CRIT 0x01
#define TMP401_STATUS_REMOTE_CRIT 0x02
#define TMP401_STATUS_REMOTE_OPEN 0x04
#define TMP401_STATUS_REMOTE_LOW 0x08
#define TMP401_STATUS_REMOTE_HIGH 0x10
#define TMP401_STATUS_LOCAL_LOW 0x20
#define TMP401_STATUS_LOCAL_HIGH 0x40
/* Manufacturer / Device ID's */
#define TMP401_MANUFACTURER_ID 0x55
#define TMP401_DEVICE_ID 0x11
#define TMP411_DEVICE_ID 0x12
/*
* Driver data (common to all clients)
*/
static const struct i2c_device_id tmp401_id[] = {
{ "tmp401", tmp401 },
{ "tmp411", tmp411 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tmp401_id);
/*
* Client data (each client gets its own)
*/
struct tmp401_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid; /* zero until following fields are valid */
unsigned long last_updated; /* in jiffies */
enum chips kind;
/* register values */
u8 status;
u8 config;
u16 temp[2];
u16 temp_low[2];
u16 temp_high[2];
u8 temp_crit[2];
u8 temp_crit_hyst;
u16 temp_lowest[2];
u16 temp_highest[2];
};
/*
* Sysfs attr show / store functions
*/
static int tmp401_register_to_temp(u16 reg, u8 config)
{
int temp = reg;
if (config & TMP401_CONFIG_RANGE)
temp -= 64 * 256;
return (temp * 625 + 80) / 160;
}
static u16 tmp401_temp_to_register(long temp, u8 config)
{
if (config & TMP401_CONFIG_RANGE) {
temp = SENSORS_LIMIT(temp, -64000, 191000);
temp += 64000;
} else
temp = SENSORS_LIMIT(temp, 0, 127000);
return (temp * 160 + 312) / 625;
}
static int tmp401_crit_register_to_temp(u8 reg, u8 config)
{
int temp = reg;
if (config & TMP401_CONFIG_RANGE)
temp -= 64;
return temp * 1000;
}
static u8 tmp401_crit_temp_to_register(long temp, u8 config)
{
if (config & TMP401_CONFIG_RANGE) {
temp = SENSORS_LIMIT(temp, -64000, 191000);
temp += 64000;
} else
temp = SENSORS_LIMIT(temp, 0, 127000);
return (temp + 500) / 1000;
}
static struct tmp401_data *tmp401_update_device_reg16(
struct i2c_client *client, struct tmp401_data *data)
{
int i;
for (i = 0; i < 2; i++) {
/*
* High byte must be read first immediately followed
* by the low byte
*/
data->temp[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_MSB[i]) << 8;
data->temp[i] |= i2c_smbus_read_byte_data(client,
TMP401_TEMP_LSB[i]);
data->temp_low[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_LOW_LIMIT_MSB_READ[i]) << 8;
data->temp_low[i] |= i2c_smbus_read_byte_data(client,
TMP401_TEMP_LOW_LIMIT_LSB[i]);
data->temp_high[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_HIGH_LIMIT_MSB_READ[i]) << 8;
data->temp_high[i] |= i2c_smbus_read_byte_data(client,
TMP401_TEMP_HIGH_LIMIT_LSB[i]);
data->temp_crit[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_CRIT_LIMIT[i]);
if (data->kind == tmp411) {
data->temp_lowest[i] = i2c_smbus_read_byte_data(client,
TMP411_TEMP_LOWEST_MSB[i]) << 8;
data->temp_lowest[i] |= i2c_smbus_read_byte_data(
client, TMP411_TEMP_LOWEST_LSB[i]);
data->temp_highest[i] = i2c_smbus_read_byte_data(
client, TMP411_TEMP_HIGHEST_MSB[i]) << 8;
data->temp_highest[i] |= i2c_smbus_read_byte_data(
client, TMP411_TEMP_HIGHEST_LSB[i]);
}
}
return data;
}
static struct tmp401_data *tmp401_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct tmp401_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
data->status = i2c_smbus_read_byte_data(client, TMP401_STATUS);
data->config = i2c_smbus_read_byte_data(client,
TMP401_CONFIG_READ);
tmp401_update_device_reg16(client, data);
data->temp_crit_hyst = i2c_smbus_read_byte_data(client,
TMP401_TEMP_CRIT_HYST);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_temp_value(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp[index], data->config));
}
static ssize_t show_temp_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_low[index], data->config));
}
static ssize_t show_temp_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_high[index], data->config));
}
static ssize_t show_temp_crit(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_crit_register_to_temp(data->temp_crit[index],
data->config));
}
static ssize_t show_temp_crit_hyst(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int temp, index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
mutex_lock(&data->update_lock);
temp = tmp401_crit_register_to_temp(data->temp_crit[index],
data->config);
temp -= data->temp_crit_hyst * 1000;
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
static ssize_t show_temp_lowest(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_lowest[index],
data->config));
}
static ssize_t show_temp_highest(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_highest[index],
data->config));
}
static ssize_t show_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int mask = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
if (data->status & mask)
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_temp_min(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u16 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
reg = tmp401_temp_to_register(val, data->config);
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_LOW_LIMIT_MSB_WRITE[index], reg >> 8);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_LOW_LIMIT_LSB[index], reg & 0xFF);
data->temp_low[index] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_temp_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u16 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
reg = tmp401_temp_to_register(val, data->config);
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_HIGH_LIMIT_MSB_WRITE[index], reg >> 8);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_HIGH_LIMIT_LSB[index], reg & 0xFF);
data->temp_high[index] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_temp_crit(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u8 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
reg = tmp401_crit_temp_to_register(val, data->config);
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_CRIT_LIMIT[index], reg);
data->temp_crit[index] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_temp_crit_hyst(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int temp, index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u8 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
if (data->config & TMP401_CONFIG_RANGE)
val = SENSORS_LIMIT(val, -64000, 191000);
else
val = SENSORS_LIMIT(val, 0, 127000);
mutex_lock(&data->update_lock);
temp = tmp401_crit_register_to_temp(data->temp_crit[index],
data->config);
val = SENSORS_LIMIT(val, temp - 255000, temp);
reg = ((temp - val) + 500) / 1000;
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_CRIT_HYST, reg);
data->temp_crit_hyst = reg;
mutex_unlock(&data->update_lock);
return count;
}
/*
* Resets the historical measurements of minimum and maximum temperatures.
* This is done by writing any value to any of the minimum/maximum registers
* (0x30-0x37).
*/
static ssize_t reset_temp_history(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count)
{
long val;
if (kstrtol(buf, 10, &val))
return -EINVAL;
if (val != 1) {
dev_err(dev, "temp_reset_history value %ld not"
" supported. Use 1 to reset the history!\n", val);
return -EINVAL;
}
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP411_TEMP_LOWEST_MSB[0], val);
return count;
}
static struct sensor_device_attribute tmp401_attr[] = {
SENSOR_ATTR(temp1_input, S_IRUGO, show_temp_value, NULL, 0),
SENSOR_ATTR(temp1_min, S_IWUSR | S_IRUGO, show_temp_min,
store_temp_min, 0),
SENSOR_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp_max,
store_temp_max, 0),
SENSOR_ATTR(temp1_crit, S_IWUSR | S_IRUGO, show_temp_crit,
store_temp_crit, 0),
SENSOR_ATTR(temp1_crit_hyst, S_IWUSR | S_IRUGO, show_temp_crit_hyst,
store_temp_crit_hyst, 0),
SENSOR_ATTR(temp1_min_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_LOCAL_LOW),
SENSOR_ATTR(temp1_max_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_LOCAL_HIGH),
SENSOR_ATTR(temp1_crit_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_LOCAL_CRIT),
SENSOR_ATTR(temp2_input, S_IRUGO, show_temp_value, NULL, 1),
SENSOR_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_temp_min,
store_temp_min, 1),
SENSOR_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_temp_max,
store_temp_max, 1),
SENSOR_ATTR(temp2_crit, S_IWUSR | S_IRUGO, show_temp_crit,
store_temp_crit, 1),
SENSOR_ATTR(temp2_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL, 1),
SENSOR_ATTR(temp2_fault, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_OPEN),
SENSOR_ATTR(temp2_min_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_LOW),
SENSOR_ATTR(temp2_max_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_HIGH),
SENSOR_ATTR(temp2_crit_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_CRIT),
};
/*
* Additional features of the TMP411 chip.
* The TMP411 stores the minimum and maximum
* temperature measured since power-on, chip-reset, or
* minimum and maximum register reset for both the local
* and remote channels.
*/
static struct sensor_device_attribute tmp411_attr[] = {
SENSOR_ATTR(temp1_highest, S_IRUGO, show_temp_highest, NULL, 0),
SENSOR_ATTR(temp1_lowest, S_IRUGO, show_temp_lowest, NULL, 0),
SENSOR_ATTR(temp2_highest, S_IRUGO, show_temp_highest, NULL, 1),
SENSOR_ATTR(temp2_lowest, S_IRUGO, show_temp_lowest, NULL, 1),
SENSOR_ATTR(temp_reset_history, S_IWUSR, NULL, reset_temp_history, 0),
};
/*
* Begin non sysfs callback code (aka Real code)
*/
static void tmp401_init_client(struct i2c_client *client)
{
int config, config_orig;
/* Set the conversion rate to 2 Hz */
i2c_smbus_write_byte_data(client, TMP401_CONVERSION_RATE_WRITE, 5);
/* Start conversions (disable shutdown if necessary) */
config = i2c_smbus_read_byte_data(client, TMP401_CONFIG_READ);
if (config < 0) {
dev_warn(&client->dev, "Initialization failed!\n");
return;
}
config_orig = config;
config &= ~TMP401_CONFIG_SHUTDOWN;
if (config != config_orig)
i2c_smbus_write_byte_data(client, TMP401_CONFIG_WRITE, config);
}
static int tmp401_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
enum chips kind;
struct i2c_adapter *adapter = client->adapter;
u8 reg;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
/* Detect and identify the chip */
reg = i2c_smbus_read_byte_data(client, TMP401_MANUFACTURER_ID_REG);
if (reg != TMP401_MANUFACTURER_ID)
return -ENODEV;
reg = i2c_smbus_read_byte_data(client, TMP401_DEVICE_ID_REG);
switch (reg) {
case TMP401_DEVICE_ID:
kind = tmp401;
break;
case TMP411_DEVICE_ID:
kind = tmp411;
break;
default:
return -ENODEV;
}
reg = i2c_smbus_read_byte_data(client, TMP401_CONFIG_READ);
if (reg & 0x1b)
return -ENODEV;
reg = i2c_smbus_read_byte_data(client, TMP401_CONVERSION_RATE_READ);
/* Datasheet says: 0x1-0x6 */
if (reg > 15)
return -ENODEV;
strlcpy(info->type, tmp401_id[kind].name, I2C_NAME_SIZE);
return 0;
}
static int tmp401_remove(struct i2c_client *client)
{
struct tmp401_data *data = i2c_get_clientdata(client);
int i;
if (data->hwmon_dev)
hwmon_device_unregister(data->hwmon_dev);
for (i = 0; i < ARRAY_SIZE(tmp401_attr); i++)
device_remove_file(&client->dev, &tmp401_attr[i].dev_attr);
if (data->kind == tmp411) {
for (i = 0; i < ARRAY_SIZE(tmp411_attr); i++)
device_remove_file(&client->dev,
&tmp411_attr[i].dev_attr);
}
kfree(data);
return 0;
}
static int tmp401_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int i, err = 0;
struct tmp401_data *data;
const char *names[] = { "TMP401", "TMP411" };
data = kzalloc(sizeof(struct tmp401_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
data->kind = id->driver_data;
/* Initialize the TMP401 chip */
tmp401_init_client(client);
/* Register sysfs hooks */
for (i = 0; i < ARRAY_SIZE(tmp401_attr); i++) {
err = device_create_file(&client->dev,
&tmp401_attr[i].dev_attr);
if (err)
goto exit_remove;
}
/* Register additional tmp411 sysfs hooks */
if (data->kind == tmp411) {
for (i = 0; i < ARRAY_SIZE(tmp411_attr); i++) {
err = device_create_file(&client->dev,
&tmp411_attr[i].dev_attr);
if (err)
goto exit_remove;
}
}
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto exit_remove;
}
dev_info(&client->dev, "Detected TI %s chip\n", names[data->kind]);
return 0;
exit_remove:
tmp401_remove(client); /* will also free data for us */
return err;
}
static struct i2c_driver tmp401_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "tmp401",
},
.probe = tmp401_probe,
.remove = tmp401_remove,
.id_table = tmp401_id,
.detect = tmp401_detect,
.address_list = normal_i2c,
};
module_i2c_driver(tmp401_driver);
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_DESCRIPTION("Texas Instruments TMP401 temperature sensor driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
gandalf-3d/mordorKernel-note3 | drivers/hwmon/pc87360.c | 4857 | 56677 | /*
* pc87360.c - Part of lm_sensors, Linux kernel modules
* for hardware monitoring
* Copyright (C) 2004, 2007 Jean Delvare <khali@linux-fr.org>
*
* Copied from smsc47m1.c:
* Copyright (C) 2002 Mark D. Studebaker <mdsxyz123@yahoo.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*
* Supports the following chips:
*
* Chip #vin #fan #pwm #temp devid
* PC87360 - 2 2 - 0xE1
* PC87363 - 2 2 - 0xE8
* PC87364 - 3 3 - 0xE4
* PC87365 11 3 3 2 0xE5
* PC87366 11 3 3 3-4 0xE9
*
* This driver assumes that no more than one chip is present, and one of
* the standard Super-I/O addresses is used (0x2E/0x2F or 0x4E/0x4F).
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/acpi.h>
#include <linux/io.h>
static u8 devid;
static struct platform_device *pdev;
static unsigned short extra_isa[3];
static u8 confreg[4];
static int init = 1;
module_param(init, int, 0);
MODULE_PARM_DESC(init,
"Chip initialization level:\n"
" 0: None\n"
"*1: Forcibly enable internal voltage and temperature channels, except in9\n"
" 2: Forcibly enable all voltage and temperature channels, except in9\n"
" 3: Forcibly enable all voltage and temperature channels, including in9");
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
/*
* Super-I/O registers and operations
*/
#define DEV 0x07 /* Register: Logical device select */
#define DEVID 0x20 /* Register: Device ID */
#define ACT 0x30 /* Register: Device activation */
#define BASE 0x60 /* Register: Base address */
#define FSCM 0x09 /* Logical device: fans */
#define VLM 0x0d /* Logical device: voltages */
#define TMS 0x0e /* Logical device: temperatures */
#define LDNI_MAX 3
static const u8 logdev[LDNI_MAX] = { FSCM, VLM, TMS };
#define LD_FAN 0
#define LD_IN 1
#define LD_TEMP 2
static inline void superio_outb(int sioaddr, int reg, int val)
{
outb(reg, sioaddr);
outb(val, sioaddr + 1);
}
static inline int superio_inb(int sioaddr, int reg)
{
outb(reg, sioaddr);
return inb(sioaddr + 1);
}
static inline void superio_exit(int sioaddr)
{
outb(0x02, sioaddr);
outb(0x02, sioaddr + 1);
}
/*
* Logical devices
*/
#define PC87360_EXTENT 0x10
#define PC87365_REG_BANK 0x09
#define NO_BANK 0xff
/*
* Fan registers and conversions
*/
/* nr has to be 0 or 1 (PC87360/87363) or 2 (PC87364/87365/87366) */
#define PC87360_REG_PRESCALE(nr) (0x00 + 2 * (nr))
#define PC87360_REG_PWM(nr) (0x01 + 2 * (nr))
#define PC87360_REG_FAN_MIN(nr) (0x06 + 3 * (nr))
#define PC87360_REG_FAN(nr) (0x07 + 3 * (nr))
#define PC87360_REG_FAN_STATUS(nr) (0x08 + 3 * (nr))
#define FAN_FROM_REG(val, div) ((val) == 0 ? 0 : \
480000 / ((val) * (div)))
#define FAN_TO_REG(val, div) ((val) <= 100 ? 0 : \
480000 / ((val) * (div)))
#define FAN_DIV_FROM_REG(val) (1 << (((val) >> 5) & 0x03))
#define FAN_STATUS_FROM_REG(val) ((val) & 0x07)
#define FAN_CONFIG_MONITOR(val, nr) (((val) >> (2 + (nr) * 3)) & 1)
#define FAN_CONFIG_CONTROL(val, nr) (((val) >> (3 + (nr) * 3)) & 1)
#define FAN_CONFIG_INVERT(val, nr) (((val) >> (4 + (nr) * 3)) & 1)
#define PWM_FROM_REG(val, inv) ((inv) ? 255 - (val) : (val))
static inline u8 PWM_TO_REG(int val, int inv)
{
if (inv)
val = 255 - val;
if (val < 0)
return 0;
if (val > 255)
return 255;
return val;
}
/*
* Voltage registers and conversions
*/
#define PC87365_REG_IN_CONVRATE 0x07
#define PC87365_REG_IN_CONFIG 0x08
#define PC87365_REG_IN 0x0B
#define PC87365_REG_IN_MIN 0x0D
#define PC87365_REG_IN_MAX 0x0C
#define PC87365_REG_IN_STATUS 0x0A
#define PC87365_REG_IN_ALARMS1 0x00
#define PC87365_REG_IN_ALARMS2 0x01
#define PC87365_REG_VID 0x06
#define IN_FROM_REG(val, ref) (((val) * (ref) + 128) / 256)
#define IN_TO_REG(val, ref) ((val) < 0 ? 0 : \
(val) * 256 >= (ref) * 255 ? 255 : \
((val) * 256 + (ref) / 2) / (ref))
/*
* Temperature registers and conversions
*/
#define PC87365_REG_TEMP_CONFIG 0x08
#define PC87365_REG_TEMP 0x0B
#define PC87365_REG_TEMP_MIN 0x0D
#define PC87365_REG_TEMP_MAX 0x0C
#define PC87365_REG_TEMP_CRIT 0x0E
#define PC87365_REG_TEMP_STATUS 0x0A
#define PC87365_REG_TEMP_ALARMS 0x00
#define TEMP_FROM_REG(val) ((val) * 1000)
#define TEMP_TO_REG(val) ((val) < -55000 ? -55 : \
(val) > 127000 ? 127 : \
(val) < 0 ? ((val) - 500) / 1000 : \
((val) + 500) / 1000)
/*
* Device data
*/
struct pc87360_data {
const char *name;
struct device *hwmon_dev;
struct mutex lock;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
int address[3];
u8 fannr, innr, tempnr;
u8 fan[3]; /* Register value */
u8 fan_min[3]; /* Register value */
u8 fan_status[3]; /* Register value */
u8 pwm[3]; /* Register value */
u16 fan_conf; /* Configuration register values, combined */
u16 in_vref; /* 1 mV/bit */
u8 in[14]; /* Register value */
u8 in_min[14]; /* Register value */
u8 in_max[14]; /* Register value */
u8 in_crit[3]; /* Register value */
u8 in_status[14]; /* Register value */
u16 in_alarms; /* Register values, combined, masked */
u8 vid_conf; /* Configuration register value */
u8 vrm;
u8 vid; /* Register value */
s8 temp[3]; /* Register value */
s8 temp_min[3]; /* Register value */
s8 temp_max[3]; /* Register value */
s8 temp_crit[3]; /* Register value */
u8 temp_status[3]; /* Register value */
u8 temp_alarms; /* Register value, masked */
};
/*
* Functions declaration
*/
static int pc87360_probe(struct platform_device *pdev);
static int __devexit pc87360_remove(struct platform_device *pdev);
static int pc87360_read_value(struct pc87360_data *data, u8 ldi, u8 bank,
u8 reg);
static void pc87360_write_value(struct pc87360_data *data, u8 ldi, u8 bank,
u8 reg, u8 value);
static void pc87360_init_device(struct platform_device *pdev,
int use_thermistors);
static struct pc87360_data *pc87360_update_device(struct device *dev);
/*
* Driver data
*/
static struct platform_driver pc87360_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "pc87360",
},
.probe = pc87360_probe,
.remove = __devexit_p(pc87360_remove),
};
/*
* Sysfs stuff
*/
static ssize_t show_fan_input(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", FAN_FROM_REG(data->fan[attr->index],
FAN_DIV_FROM_REG(data->fan_status[attr->index])));
}
static ssize_t show_fan_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", FAN_FROM_REG(data->fan_min[attr->index],
FAN_DIV_FROM_REG(data->fan_status[attr->index])));
}
static ssize_t show_fan_div(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n",
FAN_DIV_FROM_REG(data->fan_status[attr->index]));
}
static ssize_t show_fan_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n",
FAN_STATUS_FROM_REG(data->fan_status[attr->index]));
}
static ssize_t set_fan_min(struct device *dev,
struct device_attribute *devattr, const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long fan_min;
int err;
err = kstrtol(buf, 10, &fan_min);
if (err)
return err;
mutex_lock(&data->update_lock);
fan_min = FAN_TO_REG(fan_min,
FAN_DIV_FROM_REG(data->fan_status[attr->index]));
/* If it wouldn't fit, change clock divisor */
while (fan_min > 255
&& (data->fan_status[attr->index] & 0x60) != 0x60) {
fan_min >>= 1;
data->fan[attr->index] >>= 1;
data->fan_status[attr->index] += 0x20;
}
data->fan_min[attr->index] = fan_min > 255 ? 255 : fan_min;
pc87360_write_value(data, LD_FAN, NO_BANK,
PC87360_REG_FAN_MIN(attr->index),
data->fan_min[attr->index]);
/* Write new divider, preserve alarm bits */
pc87360_write_value(data, LD_FAN, NO_BANK,
PC87360_REG_FAN_STATUS(attr->index),
data->fan_status[attr->index] & 0xF9);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute fan_input[] = {
SENSOR_ATTR(fan1_input, S_IRUGO, show_fan_input, NULL, 0),
SENSOR_ATTR(fan2_input, S_IRUGO, show_fan_input, NULL, 1),
SENSOR_ATTR(fan3_input, S_IRUGO, show_fan_input, NULL, 2),
};
static struct sensor_device_attribute fan_status[] = {
SENSOR_ATTR(fan1_status, S_IRUGO, show_fan_status, NULL, 0),
SENSOR_ATTR(fan2_status, S_IRUGO, show_fan_status, NULL, 1),
SENSOR_ATTR(fan3_status, S_IRUGO, show_fan_status, NULL, 2),
};
static struct sensor_device_attribute fan_div[] = {
SENSOR_ATTR(fan1_div, S_IRUGO, show_fan_div, NULL, 0),
SENSOR_ATTR(fan2_div, S_IRUGO, show_fan_div, NULL, 1),
SENSOR_ATTR(fan3_div, S_IRUGO, show_fan_div, NULL, 2),
};
static struct sensor_device_attribute fan_min[] = {
SENSOR_ATTR(fan1_min, S_IWUSR | S_IRUGO, show_fan_min, set_fan_min, 0),
SENSOR_ATTR(fan2_min, S_IWUSR | S_IRUGO, show_fan_min, set_fan_min, 1),
SENSOR_ATTR(fan3_min, S_IWUSR | S_IRUGO, show_fan_min, set_fan_min, 2),
};
#define FAN_UNIT_ATTRS(X) \
{ &fan_input[X].dev_attr.attr, \
&fan_status[X].dev_attr.attr, \
&fan_div[X].dev_attr.attr, \
&fan_min[X].dev_attr.attr, \
NULL \
}
static ssize_t show_pwm(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n",
PWM_FROM_REG(data->pwm[attr->index],
FAN_CONFIG_INVERT(data->fan_conf,
attr->index)));
}
static ssize_t set_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm[attr->index] = PWM_TO_REG(val,
FAN_CONFIG_INVERT(data->fan_conf, attr->index));
pc87360_write_value(data, LD_FAN, NO_BANK, PC87360_REG_PWM(attr->index),
data->pwm[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute pwm[] = {
SENSOR_ATTR(pwm1, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 0),
SENSOR_ATTR(pwm2, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 1),
SENSOR_ATTR(pwm3, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 2),
};
static struct attribute *pc8736x_fan_attr[][5] = {
FAN_UNIT_ATTRS(0),
FAN_UNIT_ATTRS(1),
FAN_UNIT_ATTRS(2)
};
static const struct attribute_group pc8736x_fan_attr_group[] = {
{ .attrs = pc8736x_fan_attr[0], },
{ .attrs = pc8736x_fan_attr[1], },
{ .attrs = pc8736x_fan_attr[2], },
};
static ssize_t show_in_input(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in[attr->index],
data->in_vref));
}
static ssize_t show_in_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in_min[attr->index],
data->in_vref));
}
static ssize_t show_in_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in_max[attr->index],
data->in_vref));
}
static ssize_t show_in_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", data->in_status[attr->index]);
}
static ssize_t set_in_min(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[attr->index] = IN_TO_REG(val, data->in_vref);
pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_IN_MIN,
data->in_min[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_in_max(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[attr->index] = IN_TO_REG(val,
data->in_vref);
pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_IN_MAX,
data->in_max[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute in_input[] = {
SENSOR_ATTR(in0_input, S_IRUGO, show_in_input, NULL, 0),
SENSOR_ATTR(in1_input, S_IRUGO, show_in_input, NULL, 1),
SENSOR_ATTR(in2_input, S_IRUGO, show_in_input, NULL, 2),
SENSOR_ATTR(in3_input, S_IRUGO, show_in_input, NULL, 3),
SENSOR_ATTR(in4_input, S_IRUGO, show_in_input, NULL, 4),
SENSOR_ATTR(in5_input, S_IRUGO, show_in_input, NULL, 5),
SENSOR_ATTR(in6_input, S_IRUGO, show_in_input, NULL, 6),
SENSOR_ATTR(in7_input, S_IRUGO, show_in_input, NULL, 7),
SENSOR_ATTR(in8_input, S_IRUGO, show_in_input, NULL, 8),
SENSOR_ATTR(in9_input, S_IRUGO, show_in_input, NULL, 9),
SENSOR_ATTR(in10_input, S_IRUGO, show_in_input, NULL, 10),
};
static struct sensor_device_attribute in_status[] = {
SENSOR_ATTR(in0_status, S_IRUGO, show_in_status, NULL, 0),
SENSOR_ATTR(in1_status, S_IRUGO, show_in_status, NULL, 1),
SENSOR_ATTR(in2_status, S_IRUGO, show_in_status, NULL, 2),
SENSOR_ATTR(in3_status, S_IRUGO, show_in_status, NULL, 3),
SENSOR_ATTR(in4_status, S_IRUGO, show_in_status, NULL, 4),
SENSOR_ATTR(in5_status, S_IRUGO, show_in_status, NULL, 5),
SENSOR_ATTR(in6_status, S_IRUGO, show_in_status, NULL, 6),
SENSOR_ATTR(in7_status, S_IRUGO, show_in_status, NULL, 7),
SENSOR_ATTR(in8_status, S_IRUGO, show_in_status, NULL, 8),
SENSOR_ATTR(in9_status, S_IRUGO, show_in_status, NULL, 9),
SENSOR_ATTR(in10_status, S_IRUGO, show_in_status, NULL, 10),
};
static struct sensor_device_attribute in_min[] = {
SENSOR_ATTR(in0_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 0),
SENSOR_ATTR(in1_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 1),
SENSOR_ATTR(in2_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 2),
SENSOR_ATTR(in3_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 3),
SENSOR_ATTR(in4_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 4),
SENSOR_ATTR(in5_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 5),
SENSOR_ATTR(in6_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 6),
SENSOR_ATTR(in7_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 7),
SENSOR_ATTR(in8_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 8),
SENSOR_ATTR(in9_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 9),
SENSOR_ATTR(in10_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 10),
};
static struct sensor_device_attribute in_max[] = {
SENSOR_ATTR(in0_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 0),
SENSOR_ATTR(in1_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 1),
SENSOR_ATTR(in2_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 2),
SENSOR_ATTR(in3_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 3),
SENSOR_ATTR(in4_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 4),
SENSOR_ATTR(in5_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 5),
SENSOR_ATTR(in6_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 6),
SENSOR_ATTR(in7_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 7),
SENSOR_ATTR(in8_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 8),
SENSOR_ATTR(in9_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 9),
SENSOR_ATTR(in10_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 10),
};
/* (temp & vin) channel status register alarm bits (pdf sec.11.5.12) */
#define CHAN_ALM_MIN 0x02 /* min limit crossed */
#define CHAN_ALM_MAX 0x04 /* max limit exceeded */
#define TEMP_ALM_CRIT 0x08 /* temp crit exceeded (temp only) */
/*
* show_in_min/max_alarm() reads data from the per-channel status
* register (sec 11.5.12), not the vin event status registers (sec
* 11.5.2) that (legacy) show_in_alarm() resds (via data->in_alarms)
*/
static ssize_t show_in_min_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MIN));
}
static ssize_t show_in_max_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MAX));
}
static struct sensor_device_attribute in_min_alarm[] = {
SENSOR_ATTR(in0_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 0),
SENSOR_ATTR(in1_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 1),
SENSOR_ATTR(in2_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 2),
SENSOR_ATTR(in3_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 3),
SENSOR_ATTR(in4_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 4),
SENSOR_ATTR(in5_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 5),
SENSOR_ATTR(in6_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 6),
SENSOR_ATTR(in7_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 7),
SENSOR_ATTR(in8_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 8),
SENSOR_ATTR(in9_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 9),
SENSOR_ATTR(in10_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 10),
};
static struct sensor_device_attribute in_max_alarm[] = {
SENSOR_ATTR(in0_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 0),
SENSOR_ATTR(in1_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 1),
SENSOR_ATTR(in2_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 2),
SENSOR_ATTR(in3_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 3),
SENSOR_ATTR(in4_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 4),
SENSOR_ATTR(in5_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 5),
SENSOR_ATTR(in6_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 6),
SENSOR_ATTR(in7_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 7),
SENSOR_ATTR(in8_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 8),
SENSOR_ATTR(in9_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 9),
SENSOR_ATTR(in10_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 10),
};
#define VIN_UNIT_ATTRS(X) \
&in_input[X].dev_attr.attr, \
&in_status[X].dev_attr.attr, \
&in_min[X].dev_attr.attr, \
&in_max[X].dev_attr.attr, \
&in_min_alarm[X].dev_attr.attr, \
&in_max_alarm[X].dev_attr.attr
static ssize_t show_vid(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", vid_from_reg(data->vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid, NULL);
static ssize_t show_vrm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct pc87360_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%u\n", data->vrm);
}
static ssize_t set_vrm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct pc87360_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
data->vrm = val;
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm, set_vrm);
static ssize_t show_in_alarms(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", data->in_alarms);
}
static DEVICE_ATTR(alarms_in, S_IRUGO, show_in_alarms, NULL);
static struct attribute *pc8736x_vin_attr_array[] = {
VIN_UNIT_ATTRS(0),
VIN_UNIT_ATTRS(1),
VIN_UNIT_ATTRS(2),
VIN_UNIT_ATTRS(3),
VIN_UNIT_ATTRS(4),
VIN_UNIT_ATTRS(5),
VIN_UNIT_ATTRS(6),
VIN_UNIT_ATTRS(7),
VIN_UNIT_ATTRS(8),
VIN_UNIT_ATTRS(9),
VIN_UNIT_ATTRS(10),
&dev_attr_cpu0_vid.attr,
&dev_attr_vrm.attr,
&dev_attr_alarms_in.attr,
NULL
};
static const struct attribute_group pc8736x_vin_group = {
.attrs = pc8736x_vin_attr_array,
};
static ssize_t show_therm_input(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in[attr->index],
data->in_vref));
}
static ssize_t show_therm_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in_min[attr->index],
data->in_vref));
}
static ssize_t show_therm_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in_max[attr->index],
data->in_vref));
}
static ssize_t show_therm_crit(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", IN_FROM_REG(data->in_crit[attr->index-11],
data->in_vref));
}
static ssize_t show_therm_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", data->in_status[attr->index]);
}
static ssize_t set_therm_min(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[attr->index] = IN_TO_REG(val, data->in_vref);
pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_TEMP_MIN,
data->in_min[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_therm_max(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[attr->index] = IN_TO_REG(val, data->in_vref);
pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_TEMP_MAX,
data->in_max[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_therm_crit(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_crit[attr->index-11] = IN_TO_REG(val, data->in_vref);
pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_TEMP_CRIT,
data->in_crit[attr->index-11]);
mutex_unlock(&data->update_lock);
return count;
}
/*
* the +11 term below reflects the fact that VLM units 11,12,13 are
* used in the chip to measure voltage across the thermistors
*/
static struct sensor_device_attribute therm_input[] = {
SENSOR_ATTR(temp4_input, S_IRUGO, show_therm_input, NULL, 0 + 11),
SENSOR_ATTR(temp5_input, S_IRUGO, show_therm_input, NULL, 1 + 11),
SENSOR_ATTR(temp6_input, S_IRUGO, show_therm_input, NULL, 2 + 11),
};
static struct sensor_device_attribute therm_status[] = {
SENSOR_ATTR(temp4_status, S_IRUGO, show_therm_status, NULL, 0 + 11),
SENSOR_ATTR(temp5_status, S_IRUGO, show_therm_status, NULL, 1 + 11),
SENSOR_ATTR(temp6_status, S_IRUGO, show_therm_status, NULL, 2 + 11),
};
static struct sensor_device_attribute therm_min[] = {
SENSOR_ATTR(temp4_min, S_IRUGO | S_IWUSR,
show_therm_min, set_therm_min, 0 + 11),
SENSOR_ATTR(temp5_min, S_IRUGO | S_IWUSR,
show_therm_min, set_therm_min, 1 + 11),
SENSOR_ATTR(temp6_min, S_IRUGO | S_IWUSR,
show_therm_min, set_therm_min, 2 + 11),
};
static struct sensor_device_attribute therm_max[] = {
SENSOR_ATTR(temp4_max, S_IRUGO | S_IWUSR,
show_therm_max, set_therm_max, 0 + 11),
SENSOR_ATTR(temp5_max, S_IRUGO | S_IWUSR,
show_therm_max, set_therm_max, 1 + 11),
SENSOR_ATTR(temp6_max, S_IRUGO | S_IWUSR,
show_therm_max, set_therm_max, 2 + 11),
};
static struct sensor_device_attribute therm_crit[] = {
SENSOR_ATTR(temp4_crit, S_IRUGO | S_IWUSR,
show_therm_crit, set_therm_crit, 0 + 11),
SENSOR_ATTR(temp5_crit, S_IRUGO | S_IWUSR,
show_therm_crit, set_therm_crit, 1 + 11),
SENSOR_ATTR(temp6_crit, S_IRUGO | S_IWUSR,
show_therm_crit, set_therm_crit, 2 + 11),
};
/*
* show_therm_min/max_alarm() reads data from the per-channel voltage
* status register (sec 11.5.12)
*/
static ssize_t show_therm_min_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MIN));
}
static ssize_t show_therm_max_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MAX));
}
static ssize_t show_therm_crit_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->in_status[nr] & TEMP_ALM_CRIT));
}
static struct sensor_device_attribute therm_min_alarm[] = {
SENSOR_ATTR(temp4_min_alarm, S_IRUGO,
show_therm_min_alarm, NULL, 0 + 11),
SENSOR_ATTR(temp5_min_alarm, S_IRUGO,
show_therm_min_alarm, NULL, 1 + 11),
SENSOR_ATTR(temp6_min_alarm, S_IRUGO,
show_therm_min_alarm, NULL, 2 + 11),
};
static struct sensor_device_attribute therm_max_alarm[] = {
SENSOR_ATTR(temp4_max_alarm, S_IRUGO,
show_therm_max_alarm, NULL, 0 + 11),
SENSOR_ATTR(temp5_max_alarm, S_IRUGO,
show_therm_max_alarm, NULL, 1 + 11),
SENSOR_ATTR(temp6_max_alarm, S_IRUGO,
show_therm_max_alarm, NULL, 2 + 11),
};
static struct sensor_device_attribute therm_crit_alarm[] = {
SENSOR_ATTR(temp4_crit_alarm, S_IRUGO,
show_therm_crit_alarm, NULL, 0 + 11),
SENSOR_ATTR(temp5_crit_alarm, S_IRUGO,
show_therm_crit_alarm, NULL, 1 + 11),
SENSOR_ATTR(temp6_crit_alarm, S_IRUGO,
show_therm_crit_alarm, NULL, 2 + 11),
};
#define THERM_UNIT_ATTRS(X) \
&therm_input[X].dev_attr.attr, \
&therm_status[X].dev_attr.attr, \
&therm_min[X].dev_attr.attr, \
&therm_max[X].dev_attr.attr, \
&therm_crit[X].dev_attr.attr, \
&therm_min_alarm[X].dev_attr.attr, \
&therm_max_alarm[X].dev_attr.attr, \
&therm_crit_alarm[X].dev_attr.attr
static struct attribute *pc8736x_therm_attr_array[] = {
THERM_UNIT_ATTRS(0),
THERM_UNIT_ATTRS(1),
THERM_UNIT_ATTRS(2),
NULL
};
static const struct attribute_group pc8736x_therm_group = {
.attrs = pc8736x_therm_attr_array,
};
static ssize_t show_temp_input(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[attr->index]));
}
static ssize_t show_temp_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_min[attr->index]));
}
static ssize_t show_temp_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_max[attr->index]));
}
static ssize_t show_temp_crit(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%d\n",
TEMP_FROM_REG(data->temp_crit[attr->index]));
}
static ssize_t show_temp_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%d\n", data->temp_status[attr->index]);
}
static ssize_t set_temp_min(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_min[attr->index] = TEMP_TO_REG(val);
pc87360_write_value(data, LD_TEMP, attr->index, PC87365_REG_TEMP_MIN,
data->temp_min[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_max(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_max[attr->index] = TEMP_TO_REG(val);
pc87360_write_value(data, LD_TEMP, attr->index, PC87365_REG_TEMP_MAX,
data->temp_max[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_crit(struct device *dev,
struct device_attribute *devattr, const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct pc87360_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_crit[attr->index] = TEMP_TO_REG(val);
pc87360_write_value(data, LD_TEMP, attr->index, PC87365_REG_TEMP_CRIT,
data->temp_crit[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute temp_input[] = {
SENSOR_ATTR(temp1_input, S_IRUGO, show_temp_input, NULL, 0),
SENSOR_ATTR(temp2_input, S_IRUGO, show_temp_input, NULL, 1),
SENSOR_ATTR(temp3_input, S_IRUGO, show_temp_input, NULL, 2),
};
static struct sensor_device_attribute temp_status[] = {
SENSOR_ATTR(temp1_status, S_IRUGO, show_temp_status, NULL, 0),
SENSOR_ATTR(temp2_status, S_IRUGO, show_temp_status, NULL, 1),
SENSOR_ATTR(temp3_status, S_IRUGO, show_temp_status, NULL, 2),
};
static struct sensor_device_attribute temp_min[] = {
SENSOR_ATTR(temp1_min, S_IRUGO | S_IWUSR,
show_temp_min, set_temp_min, 0),
SENSOR_ATTR(temp2_min, S_IRUGO | S_IWUSR,
show_temp_min, set_temp_min, 1),
SENSOR_ATTR(temp3_min, S_IRUGO | S_IWUSR,
show_temp_min, set_temp_min, 2),
};
static struct sensor_device_attribute temp_max[] = {
SENSOR_ATTR(temp1_max, S_IRUGO | S_IWUSR,
show_temp_max, set_temp_max, 0),
SENSOR_ATTR(temp2_max, S_IRUGO | S_IWUSR,
show_temp_max, set_temp_max, 1),
SENSOR_ATTR(temp3_max, S_IRUGO | S_IWUSR,
show_temp_max, set_temp_max, 2),
};
static struct sensor_device_attribute temp_crit[] = {
SENSOR_ATTR(temp1_crit, S_IRUGO | S_IWUSR,
show_temp_crit, set_temp_crit, 0),
SENSOR_ATTR(temp2_crit, S_IRUGO | S_IWUSR,
show_temp_crit, set_temp_crit, 1),
SENSOR_ATTR(temp3_crit, S_IRUGO | S_IWUSR,
show_temp_crit, set_temp_crit, 2),
};
static ssize_t show_temp_alarms(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
return sprintf(buf, "%u\n", data->temp_alarms);
}
static DEVICE_ATTR(alarms_temp, S_IRUGO, show_temp_alarms, NULL);
/*
* show_temp_min/max_alarm() reads data from the per-channel status
* register (sec 12.3.7), not the temp event status registers (sec
* 12.3.2) that show_temp_alarm() reads (via data->temp_alarms)
*/
static ssize_t show_temp_min_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->temp_status[nr] & CHAN_ALM_MIN));
}
static ssize_t show_temp_max_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->temp_status[nr] & CHAN_ALM_MAX));
}
static ssize_t show_temp_crit_alarm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->temp_status[nr] & TEMP_ALM_CRIT));
}
static struct sensor_device_attribute temp_min_alarm[] = {
SENSOR_ATTR(temp1_min_alarm, S_IRUGO, show_temp_min_alarm, NULL, 0),
SENSOR_ATTR(temp2_min_alarm, S_IRUGO, show_temp_min_alarm, NULL, 1),
SENSOR_ATTR(temp3_min_alarm, S_IRUGO, show_temp_min_alarm, NULL, 2),
};
static struct sensor_device_attribute temp_max_alarm[] = {
SENSOR_ATTR(temp1_max_alarm, S_IRUGO, show_temp_max_alarm, NULL, 0),
SENSOR_ATTR(temp2_max_alarm, S_IRUGO, show_temp_max_alarm, NULL, 1),
SENSOR_ATTR(temp3_max_alarm, S_IRUGO, show_temp_max_alarm, NULL, 2),
};
static struct sensor_device_attribute temp_crit_alarm[] = {
SENSOR_ATTR(temp1_crit_alarm, S_IRUGO, show_temp_crit_alarm, NULL, 0),
SENSOR_ATTR(temp2_crit_alarm, S_IRUGO, show_temp_crit_alarm, NULL, 1),
SENSOR_ATTR(temp3_crit_alarm, S_IRUGO, show_temp_crit_alarm, NULL, 2),
};
#define TEMP_FAULT 0x40 /* open diode */
static ssize_t show_temp_fault(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = pc87360_update_device(dev);
unsigned nr = to_sensor_dev_attr(devattr)->index;
return sprintf(buf, "%u\n", !!(data->temp_status[nr] & TEMP_FAULT));
}
static struct sensor_device_attribute temp_fault[] = {
SENSOR_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0),
SENSOR_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1),
SENSOR_ATTR(temp3_fault, S_IRUGO, show_temp_fault, NULL, 2),
};
#define TEMP_UNIT_ATTRS(X) \
{ &temp_input[X].dev_attr.attr, \
&temp_status[X].dev_attr.attr, \
&temp_min[X].dev_attr.attr, \
&temp_max[X].dev_attr.attr, \
&temp_crit[X].dev_attr.attr, \
&temp_min_alarm[X].dev_attr.attr, \
&temp_max_alarm[X].dev_attr.attr, \
&temp_crit_alarm[X].dev_attr.attr, \
&temp_fault[X].dev_attr.attr, \
NULL \
}
static struct attribute *pc8736x_temp_attr[][10] = {
TEMP_UNIT_ATTRS(0),
TEMP_UNIT_ATTRS(1),
TEMP_UNIT_ATTRS(2)
};
static const struct attribute_group pc8736x_temp_attr_group[] = {
{ .attrs = pc8736x_temp_attr[0] },
{ .attrs = pc8736x_temp_attr[1] },
{ .attrs = pc8736x_temp_attr[2] }
};
static ssize_t show_name(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct pc87360_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
/*
* Device detection, registration and update
*/
static int __init pc87360_find(int sioaddr, u8 *devid,
unsigned short *addresses)
{
u16 val;
int i;
int nrdev; /* logical device count */
/* No superio_enter */
/* Identify device */
val = force_id ? force_id : superio_inb(sioaddr, DEVID);
switch (val) {
case 0xE1: /* PC87360 */
case 0xE8: /* PC87363 */
case 0xE4: /* PC87364 */
nrdev = 1;
break;
case 0xE5: /* PC87365 */
case 0xE9: /* PC87366 */
nrdev = 3;
break;
default:
superio_exit(sioaddr);
return -ENODEV;
}
/* Remember the device id */
*devid = val;
for (i = 0; i < nrdev; i++) {
/* select logical device */
superio_outb(sioaddr, DEV, logdev[i]);
val = superio_inb(sioaddr, ACT);
if (!(val & 0x01)) {
pr_info("Device 0x%02x not activated\n", logdev[i]);
continue;
}
val = (superio_inb(sioaddr, BASE) << 8)
| superio_inb(sioaddr, BASE + 1);
if (!val) {
pr_info("Base address not set for device 0x%02x\n",
logdev[i]);
continue;
}
addresses[i] = val;
if (i == 0) { /* Fans */
confreg[0] = superio_inb(sioaddr, 0xF0);
confreg[1] = superio_inb(sioaddr, 0xF1);
pr_debug("Fan %d: mon=%d ctrl=%d inv=%d\n", 1,
(confreg[0] >> 2) & 1, (confreg[0] >> 3) & 1,
(confreg[0] >> 4) & 1);
pr_debug("Fan %d: mon=%d ctrl=%d inv=%d\n", 2,
(confreg[0] >> 5) & 1, (confreg[0] >> 6) & 1,
(confreg[0] >> 7) & 1);
pr_debug("Fan %d: mon=%d ctrl=%d inv=%d\n", 3,
confreg[1] & 1, (confreg[1] >> 1) & 1,
(confreg[1] >> 2) & 1);
} else if (i == 1) { /* Voltages */
/* Are we using thermistors? */
if (*devid == 0xE9) { /* PC87366 */
/*
* These registers are not logical-device
* specific, just that we won't need them if
* we don't use the VLM device
*/
confreg[2] = superio_inb(sioaddr, 0x2B);
confreg[3] = superio_inb(sioaddr, 0x25);
if (confreg[2] & 0x40) {
pr_info("Using thermistors for "
"temperature monitoring\n");
}
if (confreg[3] & 0xE0) {
pr_info("VID inputs routed (mode %u)\n",
confreg[3] >> 5);
}
}
}
}
superio_exit(sioaddr);
return 0;
}
static void pc87360_remove_files(struct device *dev)
{
int i;
device_remove_file(dev, &dev_attr_name);
device_remove_file(dev, &dev_attr_alarms_temp);
for (i = 0; i < ARRAY_SIZE(pc8736x_temp_attr_group); i++)
sysfs_remove_group(&dev->kobj, &pc8736x_temp_attr_group[i]);
for (i = 0; i < ARRAY_SIZE(pc8736x_fan_attr_group); i++) {
sysfs_remove_group(&pdev->dev.kobj, &pc8736x_fan_attr_group[i]);
device_remove_file(dev, &pwm[i].dev_attr);
}
sysfs_remove_group(&dev->kobj, &pc8736x_therm_group);
sysfs_remove_group(&dev->kobj, &pc8736x_vin_group);
}
static int __devinit pc87360_probe(struct platform_device *pdev)
{
int i;
struct pc87360_data *data;
int err = 0;
const char *name = "pc87360";
int use_thermistors = 0;
struct device *dev = &pdev->dev;
data = kzalloc(sizeof(struct pc87360_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->fannr = 2;
data->innr = 0;
data->tempnr = 0;
switch (devid) {
case 0xe8:
name = "pc87363";
break;
case 0xe4:
name = "pc87364";
data->fannr = 3;
break;
case 0xe5:
name = "pc87365";
data->fannr = extra_isa[0] ? 3 : 0;
data->innr = extra_isa[1] ? 11 : 0;
data->tempnr = extra_isa[2] ? 2 : 0;
break;
case 0xe9:
name = "pc87366";
data->fannr = extra_isa[0] ? 3 : 0;
data->innr = extra_isa[1] ? 14 : 0;
data->tempnr = extra_isa[2] ? 3 : 0;
break;
}
data->name = name;
data->valid = 0;
mutex_init(&data->lock);
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
for (i = 0; i < LDNI_MAX; i++) {
data->address[i] = extra_isa[i];
if (data->address[i]
&& !request_region(extra_isa[i], PC87360_EXTENT,
pc87360_driver.driver.name)) {
dev_err(dev, "Region 0x%x-0x%x already "
"in use!\n", extra_isa[i],
extra_isa[i]+PC87360_EXTENT-1);
for (i--; i >= 0; i--)
release_region(extra_isa[i], PC87360_EXTENT);
err = -EBUSY;
goto ERROR1;
}
}
/* Retrieve the fans configuration from Super-I/O space */
if (data->fannr)
data->fan_conf = confreg[0] | (confreg[1] << 8);
/*
* Use the correct reference voltage
* Unless both the VLM and the TMS logical devices agree to
* use an external Vref, the internal one is used.
*/
if (data->innr) {
i = pc87360_read_value(data, LD_IN, NO_BANK,
PC87365_REG_IN_CONFIG);
if (data->tempnr) {
i &= pc87360_read_value(data, LD_TEMP, NO_BANK,
PC87365_REG_TEMP_CONFIG);
}
data->in_vref = (i&0x02) ? 3025 : 2966;
dev_dbg(dev, "Using %s reference voltage\n",
(i&0x02) ? "external" : "internal");
data->vid_conf = confreg[3];
data->vrm = vid_which_vrm();
}
/* Fan clock dividers may be needed before any data is read */
for (i = 0; i < data->fannr; i++) {
if (FAN_CONFIG_MONITOR(data->fan_conf, i))
data->fan_status[i] = pc87360_read_value(data,
LD_FAN, NO_BANK,
PC87360_REG_FAN_STATUS(i));
}
if (init > 0) {
if (devid == 0xe9 && data->address[1]) /* PC87366 */
use_thermistors = confreg[2] & 0x40;
pc87360_init_device(pdev, use_thermistors);
}
/* Register all-or-nothing sysfs groups */
if (data->innr) {
err = sysfs_create_group(&dev->kobj, &pc8736x_vin_group);
if (err)
goto ERROR3;
}
if (data->innr == 14) {
err = sysfs_create_group(&dev->kobj, &pc8736x_therm_group);
if (err)
goto ERROR3;
}
/* create device attr-files for varying sysfs groups */
if (data->tempnr) {
for (i = 0; i < data->tempnr; i++) {
err = sysfs_create_group(&dev->kobj,
&pc8736x_temp_attr_group[i]);
if (err)
goto ERROR3;
}
err = device_create_file(dev, &dev_attr_alarms_temp);
if (err)
goto ERROR3;
}
for (i = 0; i < data->fannr; i++) {
if (FAN_CONFIG_MONITOR(data->fan_conf, i)) {
err = sysfs_create_group(&dev->kobj,
&pc8736x_fan_attr_group[i]);
if (err)
goto ERROR3;
}
if (FAN_CONFIG_CONTROL(data->fan_conf, i)) {
err = device_create_file(dev, &pwm[i].dev_attr);
if (err)
goto ERROR3;
}
}
err = device_create_file(dev, &dev_attr_name);
if (err)
goto ERROR3;
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto ERROR3;
}
return 0;
ERROR3:
pc87360_remove_files(dev);
for (i = 0; i < 3; i++) {
if (data->address[i])
release_region(data->address[i], PC87360_EXTENT);
}
ERROR1:
kfree(data);
return err;
}
static int __devexit pc87360_remove(struct platform_device *pdev)
{
struct pc87360_data *data = platform_get_drvdata(pdev);
int i;
hwmon_device_unregister(data->hwmon_dev);
pc87360_remove_files(&pdev->dev);
for (i = 0; i < 3; i++) {
if (data->address[i])
release_region(data->address[i], PC87360_EXTENT);
}
kfree(data);
return 0;
}
/*
* ldi is the logical device index
* bank is for voltages and temperatures only
*/
static int pc87360_read_value(struct pc87360_data *data, u8 ldi, u8 bank,
u8 reg)
{
int res;
mutex_lock(&(data->lock));
if (bank != NO_BANK)
outb_p(bank, data->address[ldi] + PC87365_REG_BANK);
res = inb_p(data->address[ldi] + reg);
mutex_unlock(&(data->lock));
return res;
}
static void pc87360_write_value(struct pc87360_data *data, u8 ldi, u8 bank,
u8 reg, u8 value)
{
mutex_lock(&(data->lock));
if (bank != NO_BANK)
outb_p(bank, data->address[ldi] + PC87365_REG_BANK);
outb_p(value, data->address[ldi] + reg);
mutex_unlock(&(data->lock));
}
/* (temp & vin) channel conversion status register flags (pdf sec.11.5.12) */
#define CHAN_CNVRTD 0x80 /* new data ready */
#define CHAN_ENA 0x01 /* enabled channel (temp or vin) */
#define CHAN_ALM_ENA 0x10 /* propagate to alarms-reg ?? (chk val!) */
#define CHAN_READY (CHAN_ENA|CHAN_CNVRTD) /* sample ready mask */
#define TEMP_OTS_OE 0x20 /* OTS Output Enable */
#define VIN_RW1C_MASK (CHAN_READY|CHAN_ALM_MAX|CHAN_ALM_MIN) /* 0x87 */
#define TEMP_RW1C_MASK (VIN_RW1C_MASK|TEMP_ALM_CRIT|TEMP_FAULT) /* 0xCF */
static void pc87360_init_device(struct platform_device *pdev,
int use_thermistors)
{
struct pc87360_data *data = platform_get_drvdata(pdev);
int i, nr;
const u8 init_in[14] = { 2, 2, 2, 2, 2, 2, 2, 1, 1, 3, 1, 2, 2, 2 };
const u8 init_temp[3] = { 2, 2, 1 };
u8 reg;
if (init >= 2 && data->innr) {
reg = pc87360_read_value(data, LD_IN, NO_BANK,
PC87365_REG_IN_CONVRATE);
dev_info(&pdev->dev, "VLM conversion set to "
"1s period, 160us delay\n");
pc87360_write_value(data, LD_IN, NO_BANK,
PC87365_REG_IN_CONVRATE,
(reg & 0xC0) | 0x11);
}
nr = data->innr < 11 ? data->innr : 11;
for (i = 0; i < nr; i++) {
reg = pc87360_read_value(data, LD_IN, i,
PC87365_REG_IN_STATUS);
dev_dbg(&pdev->dev, "bios in%d status:0x%02x\n", i, reg);
if (init >= init_in[i]) {
/* Forcibly enable voltage channel */
if (!(reg & CHAN_ENA)) {
dev_dbg(&pdev->dev, "Forcibly "
"enabling in%d\n", i);
pc87360_write_value(data, LD_IN, i,
PC87365_REG_IN_STATUS,
(reg & 0x68) | 0x87);
}
}
}
/*
* We can't blindly trust the Super-I/O space configuration bit,
* most BIOS won't set it properly
*/
dev_dbg(&pdev->dev, "bios thermistors:%d\n", use_thermistors);
for (i = 11; i < data->innr; i++) {
reg = pc87360_read_value(data, LD_IN, i,
PC87365_REG_TEMP_STATUS);
use_thermistors = use_thermistors || (reg & CHAN_ENA);
/* thermistors are temp[4-6], measured on vin[11-14] */
dev_dbg(&pdev->dev, "bios temp%d_status:0x%02x\n", i-7, reg);
}
dev_dbg(&pdev->dev, "using thermistors:%d\n", use_thermistors);
i = use_thermistors ? 2 : 0;
for (; i < data->tempnr; i++) {
reg = pc87360_read_value(data, LD_TEMP, i,
PC87365_REG_TEMP_STATUS);
dev_dbg(&pdev->dev, "bios temp%d_status:0x%02x\n", i + 1, reg);
if (init >= init_temp[i]) {
/* Forcibly enable temperature channel */
if (!(reg & CHAN_ENA)) {
dev_dbg(&pdev->dev,
"Forcibly enabling temp%d\n", i + 1);
pc87360_write_value(data, LD_TEMP, i,
PC87365_REG_TEMP_STATUS,
0xCF);
}
}
}
if (use_thermistors) {
for (i = 11; i < data->innr; i++) {
if (init >= init_in[i]) {
/*
* The pin may already be used by thermal
* diodes
*/
reg = pc87360_read_value(data, LD_TEMP,
(i - 11) / 2, PC87365_REG_TEMP_STATUS);
if (reg & CHAN_ENA) {
dev_dbg(&pdev->dev,
"Skipping temp%d, pin already in use by temp%d\n",
i - 7, (i - 11) / 2);
continue;
}
/* Forcibly enable thermistor channel */
reg = pc87360_read_value(data, LD_IN, i,
PC87365_REG_IN_STATUS);
if (!(reg & CHAN_ENA)) {
dev_dbg(&pdev->dev,
"Forcibly enabling temp%d\n",
i - 7);
pc87360_write_value(data, LD_IN, i,
PC87365_REG_TEMP_STATUS,
(reg & 0x60) | 0x8F);
}
}
}
}
if (data->innr) {
reg = pc87360_read_value(data, LD_IN, NO_BANK,
PC87365_REG_IN_CONFIG);
dev_dbg(&pdev->dev, "bios vin-cfg:0x%02x\n", reg);
if (reg & CHAN_ENA) {
dev_dbg(&pdev->dev,
"Forcibly enabling monitoring (VLM)\n");
pc87360_write_value(data, LD_IN, NO_BANK,
PC87365_REG_IN_CONFIG,
reg & 0xFE);
}
}
if (data->tempnr) {
reg = pc87360_read_value(data, LD_TEMP, NO_BANK,
PC87365_REG_TEMP_CONFIG);
dev_dbg(&pdev->dev, "bios temp-cfg:0x%02x\n", reg);
if (reg & CHAN_ENA) {
dev_dbg(&pdev->dev,
"Forcibly enabling monitoring (TMS)\n");
pc87360_write_value(data, LD_TEMP, NO_BANK,
PC87365_REG_TEMP_CONFIG,
reg & 0xFE);
}
if (init >= 2) {
/* Chip config as documented by National Semi. */
pc87360_write_value(data, LD_TEMP, 0xF, 0xA, 0x08);
/*
* We voluntarily omit the bank here, in case the
* sequence itself matters. It shouldn't be a problem,
* since nobody else is supposed to access the
* device at that point.
*/
pc87360_write_value(data, LD_TEMP, NO_BANK, 0xB, 0x04);
pc87360_write_value(data, LD_TEMP, NO_BANK, 0xC, 0x35);
pc87360_write_value(data, LD_TEMP, NO_BANK, 0xD, 0x05);
pc87360_write_value(data, LD_TEMP, NO_BANK, 0xE, 0x05);
}
}
}
static void pc87360_autodiv(struct device *dev, int nr)
{
struct pc87360_data *data = dev_get_drvdata(dev);
u8 old_min = data->fan_min[nr];
/* Increase clock divider if needed and possible */
if ((data->fan_status[nr] & 0x04) /* overflow flag */
|| (data->fan[nr] >= 224)) { /* next to overflow */
if ((data->fan_status[nr] & 0x60) != 0x60) {
data->fan_status[nr] += 0x20;
data->fan_min[nr] >>= 1;
data->fan[nr] >>= 1;
dev_dbg(dev, "Increasing "
"clock divider to %d for fan %d\n",
FAN_DIV_FROM_REG(data->fan_status[nr]), nr + 1);
}
} else {
/* Decrease clock divider if possible */
while (!(data->fan_min[nr] & 0x80) /* min "nails" divider */
&& data->fan[nr] < 85 /* bad accuracy */
&& (data->fan_status[nr] & 0x60) != 0x00) {
data->fan_status[nr] -= 0x20;
data->fan_min[nr] <<= 1;
data->fan[nr] <<= 1;
dev_dbg(dev, "Decreasing "
"clock divider to %d for fan %d\n",
FAN_DIV_FROM_REG(data->fan_status[nr]),
nr + 1);
}
}
/* Write new fan min if it changed */
if (old_min != data->fan_min[nr]) {
pc87360_write_value(data, LD_FAN, NO_BANK,
PC87360_REG_FAN_MIN(nr),
data->fan_min[nr]);
}
}
static struct pc87360_data *pc87360_update_device(struct device *dev)
{
struct pc87360_data *data = dev_get_drvdata(dev);
u8 i;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ * 2) || !data->valid) {
dev_dbg(dev, "Data update\n");
/* Fans */
for (i = 0; i < data->fannr; i++) {
if (FAN_CONFIG_MONITOR(data->fan_conf, i)) {
data->fan_status[i] =
pc87360_read_value(data, LD_FAN,
NO_BANK, PC87360_REG_FAN_STATUS(i));
data->fan[i] = pc87360_read_value(data, LD_FAN,
NO_BANK, PC87360_REG_FAN(i));
data->fan_min[i] = pc87360_read_value(data,
LD_FAN, NO_BANK,
PC87360_REG_FAN_MIN(i));
/* Change clock divider if needed */
pc87360_autodiv(dev, i);
/* Clear bits and write new divider */
pc87360_write_value(data, LD_FAN, NO_BANK,
PC87360_REG_FAN_STATUS(i),
data->fan_status[i]);
}
if (FAN_CONFIG_CONTROL(data->fan_conf, i))
data->pwm[i] = pc87360_read_value(data, LD_FAN,
NO_BANK, PC87360_REG_PWM(i));
}
/* Voltages */
for (i = 0; i < data->innr; i++) {
data->in_status[i] = pc87360_read_value(data, LD_IN, i,
PC87365_REG_IN_STATUS);
/* Clear bits */
pc87360_write_value(data, LD_IN, i,
PC87365_REG_IN_STATUS,
data->in_status[i]);
if ((data->in_status[i] & CHAN_READY) == CHAN_READY) {
data->in[i] = pc87360_read_value(data, LD_IN,
i, PC87365_REG_IN);
}
if (data->in_status[i] & CHAN_ENA) {
data->in_min[i] = pc87360_read_value(data,
LD_IN, i,
PC87365_REG_IN_MIN);
data->in_max[i] = pc87360_read_value(data,
LD_IN, i,
PC87365_REG_IN_MAX);
if (i >= 11)
data->in_crit[i-11] =
pc87360_read_value(data, LD_IN,
i, PC87365_REG_TEMP_CRIT);
}
}
if (data->innr) {
data->in_alarms = pc87360_read_value(data, LD_IN,
NO_BANK, PC87365_REG_IN_ALARMS1)
| ((pc87360_read_value(data, LD_IN,
NO_BANK, PC87365_REG_IN_ALARMS2)
& 0x07) << 8);
data->vid = (data->vid_conf & 0xE0) ?
pc87360_read_value(data, LD_IN,
NO_BANK, PC87365_REG_VID) : 0x1F;
}
/* Temperatures */
for (i = 0; i < data->tempnr; i++) {
data->temp_status[i] = pc87360_read_value(data,
LD_TEMP, i,
PC87365_REG_TEMP_STATUS);
/* Clear bits */
pc87360_write_value(data, LD_TEMP, i,
PC87365_REG_TEMP_STATUS,
data->temp_status[i]);
if ((data->temp_status[i] & CHAN_READY) == CHAN_READY) {
data->temp[i] = pc87360_read_value(data,
LD_TEMP, i,
PC87365_REG_TEMP);
}
if (data->temp_status[i] & CHAN_ENA) {
data->temp_min[i] = pc87360_read_value(data,
LD_TEMP, i,
PC87365_REG_TEMP_MIN);
data->temp_max[i] = pc87360_read_value(data,
LD_TEMP, i,
PC87365_REG_TEMP_MAX);
data->temp_crit[i] = pc87360_read_value(data,
LD_TEMP, i,
PC87365_REG_TEMP_CRIT);
}
}
if (data->tempnr) {
data->temp_alarms = pc87360_read_value(data, LD_TEMP,
NO_BANK, PC87365_REG_TEMP_ALARMS)
& 0x3F;
}
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static int __init pc87360_device_add(unsigned short address)
{
struct resource res[3];
int err, i, res_count;
pdev = platform_device_alloc("pc87360", address);
if (!pdev) {
err = -ENOMEM;
pr_err("Device allocation failed\n");
goto exit;
}
memset(res, 0, 3 * sizeof(struct resource));
res_count = 0;
for (i = 0; i < 3; i++) {
if (!extra_isa[i])
continue;
res[res_count].start = extra_isa[i];
res[res_count].end = extra_isa[i] + PC87360_EXTENT - 1;
res[res_count].name = "pc87360",
res[res_count].flags = IORESOURCE_IO,
err = acpi_check_resource_conflict(&res[res_count]);
if (err)
goto exit_device_put;
res_count++;
}
err = platform_device_add_resources(pdev, res, res_count);
if (err) {
pr_err("Device resources addition failed (%d)\n", err);
goto exit_device_put;
}
err = platform_device_add(pdev);
if (err) {
pr_err("Device addition failed (%d)\n", err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
exit:
return err;
}
static int __init pc87360_init(void)
{
int err, i;
unsigned short address = 0;
if (pc87360_find(0x2e, &devid, extra_isa)
&& pc87360_find(0x4e, &devid, extra_isa)) {
pr_warn("PC8736x not detected, module not inserted\n");
return -ENODEV;
}
/* Arbitrarily pick one of the addresses */
for (i = 0; i < 3; i++) {
if (extra_isa[i] != 0x0000) {
address = extra_isa[i];
break;
}
}
if (address == 0x0000) {
pr_warn("No active logical device, module not inserted\n");
return -ENODEV;
}
err = platform_driver_register(&pc87360_driver);
if (err)
goto exit;
/* Sets global pdev as a side effect */
err = pc87360_device_add(address);
if (err)
goto exit_driver;
return 0;
exit_driver:
platform_driver_unregister(&pc87360_driver);
exit:
return err;
}
static void __exit pc87360_exit(void)
{
platform_device_unregister(pdev);
platform_driver_unregister(&pc87360_driver);
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("PC8736x hardware monitor");
MODULE_LICENSE("GPL");
module_init(pc87360_init);
module_exit(pc87360_exit);
| gpl-2.0 |
Megatron007/Megabyte_kernel_victara | drivers/regulator/mc13xxx-regulator-core.c | 4857 | 8900 | /*
* Regulator Driver for Freescale MC13xxx PMIC
*
* Copyright 2010 Yong Shen <yong.shen@linaro.org>
*
* Based on mc13783 regulator driver :
* Copyright (C) 2008 Sascha Hauer, Pengutronix <s.hauer@pengutronix.de>
* Copyright 2009 Alberto Panizzo <maramaopercheseimorto@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Regs infos taken from mc13xxx drivers from freescale and mc13xxx.pdf file
* from freescale
*/
#include <linux/mfd/mc13xxx.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/of_regulator.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/of.h>
#include "mc13xxx.h"
static int mc13xxx_regulator_enable(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
int ret;
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_rmw(priv->mc13xxx, mc13xxx_regulators[id].reg,
mc13xxx_regulators[id].enable_bit,
mc13xxx_regulators[id].enable_bit);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_regulator_disable(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
int ret;
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_rmw(priv->mc13xxx, mc13xxx_regulators[id].reg,
mc13xxx_regulators[id].enable_bit, 0);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_regulator_is_enabled(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int ret, id = rdev_get_id(rdev);
unsigned int val;
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_read(priv->mc13xxx, mc13xxx_regulators[id].reg, &val);
mc13xxx_unlock(priv->mc13xxx);
if (ret)
return ret;
return (val & mc13xxx_regulators[id].enable_bit) != 0;
}
int mc13xxx_regulator_list_voltage(struct regulator_dev *rdev,
unsigned selector)
{
int id = rdev_get_id(rdev);
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
if (selector >= mc13xxx_regulators[id].desc.n_voltages)
return -EINVAL;
return mc13xxx_regulators[id].voltages[selector];
}
EXPORT_SYMBOL_GPL(mc13xxx_regulator_list_voltage);
int mc13xxx_get_best_voltage_index(struct regulator_dev *rdev,
int min_uV, int max_uV)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int reg_id = rdev_get_id(rdev);
int i;
int bestmatch;
int bestindex;
/*
* Locate the minimum voltage fitting the criteria on
* this regulator. The switchable voltages are not
* in strict falling order so we need to check them
* all for the best match.
*/
bestmatch = INT_MAX;
bestindex = -1;
for (i = 0; i < mc13xxx_regulators[reg_id].desc.n_voltages; i++) {
if (mc13xxx_regulators[reg_id].voltages[i] >= min_uV &&
mc13xxx_regulators[reg_id].voltages[i] < bestmatch) {
bestmatch = mc13xxx_regulators[reg_id].voltages[i];
bestindex = i;
}
}
if (bestindex < 0 || bestmatch > max_uV) {
dev_warn(&rdev->dev, "no possible value for %d<=x<=%d uV\n",
min_uV, max_uV);
return -EINVAL;
}
return bestindex;
}
EXPORT_SYMBOL_GPL(mc13xxx_get_best_voltage_index);
static int mc13xxx_regulator_set_voltage(struct regulator_dev *rdev, int min_uV,
int max_uV, unsigned *selector)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int value, id = rdev_get_id(rdev);
int ret;
dev_dbg(rdev_get_dev(rdev), "%s id: %d min_uV: %d max_uV: %d\n",
__func__, id, min_uV, max_uV);
/* Find the best index */
value = mc13xxx_get_best_voltage_index(rdev, min_uV, max_uV);
dev_dbg(rdev_get_dev(rdev), "%s best value: %d\n", __func__, value);
if (value < 0)
return value;
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_rmw(priv->mc13xxx, mc13xxx_regulators[id].vsel_reg,
mc13xxx_regulators[id].vsel_mask,
value << mc13xxx_regulators[id].vsel_shift);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_regulator_get_voltage(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int ret, id = rdev_get_id(rdev);
unsigned int val;
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_read(priv->mc13xxx,
mc13xxx_regulators[id].vsel_reg, &val);
mc13xxx_unlock(priv->mc13xxx);
if (ret)
return ret;
val = (val & mc13xxx_regulators[id].vsel_mask)
>> mc13xxx_regulators[id].vsel_shift;
dev_dbg(rdev_get_dev(rdev), "%s id: %d val: %d\n", __func__, id, val);
BUG_ON(val >= mc13xxx_regulators[id].desc.n_voltages);
return mc13xxx_regulators[id].voltages[val];
}
struct regulator_ops mc13xxx_regulator_ops = {
.enable = mc13xxx_regulator_enable,
.disable = mc13xxx_regulator_disable,
.is_enabled = mc13xxx_regulator_is_enabled,
.list_voltage = mc13xxx_regulator_list_voltage,
.set_voltage = mc13xxx_regulator_set_voltage,
.get_voltage = mc13xxx_regulator_get_voltage,
};
EXPORT_SYMBOL_GPL(mc13xxx_regulator_ops);
int mc13xxx_fixed_regulator_set_voltage(struct regulator_dev *rdev, int min_uV,
int max_uV, unsigned *selector)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
dev_dbg(rdev_get_dev(rdev), "%s id: %d min_uV: %d max_uV: %d\n",
__func__, id, min_uV, max_uV);
if (min_uV >= mc13xxx_regulators[id].voltages[0] &&
max_uV <= mc13xxx_regulators[id].voltages[0])
return 0;
else
return -EINVAL;
}
EXPORT_SYMBOL_GPL(mc13xxx_fixed_regulator_set_voltage);
int mc13xxx_fixed_regulator_get_voltage(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
return mc13xxx_regulators[id].voltages[0];
}
EXPORT_SYMBOL_GPL(mc13xxx_fixed_regulator_get_voltage);
struct regulator_ops mc13xxx_fixed_regulator_ops = {
.enable = mc13xxx_regulator_enable,
.disable = mc13xxx_regulator_disable,
.is_enabled = mc13xxx_regulator_is_enabled,
.list_voltage = mc13xxx_regulator_list_voltage,
.set_voltage = mc13xxx_fixed_regulator_set_voltage,
.get_voltage = mc13xxx_fixed_regulator_get_voltage,
};
EXPORT_SYMBOL_GPL(mc13xxx_fixed_regulator_ops);
int mc13xxx_sw_regulator_is_enabled(struct regulator_dev *rdev)
{
return 1;
}
EXPORT_SYMBOL_GPL(mc13xxx_sw_regulator_is_enabled);
#ifdef CONFIG_OF
int __devinit mc13xxx_get_num_regulators_dt(struct platform_device *pdev)
{
struct device_node *parent, *child;
int num = 0;
of_node_get(pdev->dev.parent->of_node);
parent = of_find_node_by_name(pdev->dev.parent->of_node, "regulators");
if (!parent)
return -ENODEV;
for_each_child_of_node(parent, child)
num++;
return num;
}
EXPORT_SYMBOL_GPL(mc13xxx_get_num_regulators_dt);
struct mc13xxx_regulator_init_data * __devinit mc13xxx_parse_regulators_dt(
struct platform_device *pdev, struct mc13xxx_regulator *regulators,
int num_regulators)
{
struct mc13xxx_regulator_priv *priv = platform_get_drvdata(pdev);
struct mc13xxx_regulator_init_data *data, *p;
struct device_node *parent, *child;
int i;
of_node_get(pdev->dev.parent->of_node);
parent = of_find_node_by_name(pdev->dev.parent->of_node, "regulators");
if (!parent)
return NULL;
data = devm_kzalloc(&pdev->dev, sizeof(*data) * priv->num_regulators,
GFP_KERNEL);
if (!data)
return NULL;
p = data;
for_each_child_of_node(parent, child) {
for (i = 0; i < num_regulators; i++) {
if (!of_node_cmp(child->name,
regulators[i].desc.name)) {
p->id = i;
p->init_data = of_get_regulator_init_data(
&pdev->dev, child);
p->node = child;
p++;
break;
}
}
}
return data;
}
EXPORT_SYMBOL_GPL(mc13xxx_parse_regulators_dt);
#endif
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Yong Shen <yong.shen@linaro.org>");
MODULE_DESCRIPTION("Regulator Driver for Freescale MC13xxx PMIC");
MODULE_ALIAS("mc13xxx-regulator-core");
| gpl-2.0 |
tim-smart/kernel_lge_mako | drivers/hwmon/tmp401.c | 4857 | 18543 | /* tmp401.c
*
* Copyright (C) 2007,2008 Hans de Goede <hdegoede@redhat.com>
* Preliminary tmp411 support by:
* Gabriel Konat, Sander Leget, Wouter Willems
* Copyright (C) 2009 Andre Prendel <andre.prendel@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Driver for the Texas Instruments TMP401 SMBUS temperature sensor IC.
*
* Note this IC is in some aspect similar to the LM90, but it has quite a
* few differences too, for example the local temp has a higher resolution
* and thus has 16 bits registers for its value and limit instead of 8 bits.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x4c, I2C_CLIENT_END };
enum chips { tmp401, tmp411 };
/*
* The TMP401 registers, note some registers have different addresses for
* reading and writing
*/
#define TMP401_STATUS 0x02
#define TMP401_CONFIG_READ 0x03
#define TMP401_CONFIG_WRITE 0x09
#define TMP401_CONVERSION_RATE_READ 0x04
#define TMP401_CONVERSION_RATE_WRITE 0x0A
#define TMP401_TEMP_CRIT_HYST 0x21
#define TMP401_CONSECUTIVE_ALERT 0x22
#define TMP401_MANUFACTURER_ID_REG 0xFE
#define TMP401_DEVICE_ID_REG 0xFF
#define TMP411_N_FACTOR_REG 0x18
static const u8 TMP401_TEMP_MSB[2] = { 0x00, 0x01 };
static const u8 TMP401_TEMP_LSB[2] = { 0x15, 0x10 };
static const u8 TMP401_TEMP_LOW_LIMIT_MSB_READ[2] = { 0x06, 0x08 };
static const u8 TMP401_TEMP_LOW_LIMIT_MSB_WRITE[2] = { 0x0C, 0x0E };
static const u8 TMP401_TEMP_LOW_LIMIT_LSB[2] = { 0x17, 0x14 };
static const u8 TMP401_TEMP_HIGH_LIMIT_MSB_READ[2] = { 0x05, 0x07 };
static const u8 TMP401_TEMP_HIGH_LIMIT_MSB_WRITE[2] = { 0x0B, 0x0D };
static const u8 TMP401_TEMP_HIGH_LIMIT_LSB[2] = { 0x16, 0x13 };
/* These are called the THERM limit / hysteresis / mask in the datasheet */
static const u8 TMP401_TEMP_CRIT_LIMIT[2] = { 0x20, 0x19 };
static const u8 TMP411_TEMP_LOWEST_MSB[2] = { 0x30, 0x34 };
static const u8 TMP411_TEMP_LOWEST_LSB[2] = { 0x31, 0x35 };
static const u8 TMP411_TEMP_HIGHEST_MSB[2] = { 0x32, 0x36 };
static const u8 TMP411_TEMP_HIGHEST_LSB[2] = { 0x33, 0x37 };
/* Flags */
#define TMP401_CONFIG_RANGE 0x04
#define TMP401_CONFIG_SHUTDOWN 0x40
#define TMP401_STATUS_LOCAL_CRIT 0x01
#define TMP401_STATUS_REMOTE_CRIT 0x02
#define TMP401_STATUS_REMOTE_OPEN 0x04
#define TMP401_STATUS_REMOTE_LOW 0x08
#define TMP401_STATUS_REMOTE_HIGH 0x10
#define TMP401_STATUS_LOCAL_LOW 0x20
#define TMP401_STATUS_LOCAL_HIGH 0x40
/* Manufacturer / Device ID's */
#define TMP401_MANUFACTURER_ID 0x55
#define TMP401_DEVICE_ID 0x11
#define TMP411_DEVICE_ID 0x12
/*
* Driver data (common to all clients)
*/
static const struct i2c_device_id tmp401_id[] = {
{ "tmp401", tmp401 },
{ "tmp411", tmp411 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tmp401_id);
/*
* Client data (each client gets its own)
*/
struct tmp401_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid; /* zero until following fields are valid */
unsigned long last_updated; /* in jiffies */
enum chips kind;
/* register values */
u8 status;
u8 config;
u16 temp[2];
u16 temp_low[2];
u16 temp_high[2];
u8 temp_crit[2];
u8 temp_crit_hyst;
u16 temp_lowest[2];
u16 temp_highest[2];
};
/*
* Sysfs attr show / store functions
*/
static int tmp401_register_to_temp(u16 reg, u8 config)
{
int temp = reg;
if (config & TMP401_CONFIG_RANGE)
temp -= 64 * 256;
return (temp * 625 + 80) / 160;
}
static u16 tmp401_temp_to_register(long temp, u8 config)
{
if (config & TMP401_CONFIG_RANGE) {
temp = SENSORS_LIMIT(temp, -64000, 191000);
temp += 64000;
} else
temp = SENSORS_LIMIT(temp, 0, 127000);
return (temp * 160 + 312) / 625;
}
static int tmp401_crit_register_to_temp(u8 reg, u8 config)
{
int temp = reg;
if (config & TMP401_CONFIG_RANGE)
temp -= 64;
return temp * 1000;
}
static u8 tmp401_crit_temp_to_register(long temp, u8 config)
{
if (config & TMP401_CONFIG_RANGE) {
temp = SENSORS_LIMIT(temp, -64000, 191000);
temp += 64000;
} else
temp = SENSORS_LIMIT(temp, 0, 127000);
return (temp + 500) / 1000;
}
static struct tmp401_data *tmp401_update_device_reg16(
struct i2c_client *client, struct tmp401_data *data)
{
int i;
for (i = 0; i < 2; i++) {
/*
* High byte must be read first immediately followed
* by the low byte
*/
data->temp[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_MSB[i]) << 8;
data->temp[i] |= i2c_smbus_read_byte_data(client,
TMP401_TEMP_LSB[i]);
data->temp_low[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_LOW_LIMIT_MSB_READ[i]) << 8;
data->temp_low[i] |= i2c_smbus_read_byte_data(client,
TMP401_TEMP_LOW_LIMIT_LSB[i]);
data->temp_high[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_HIGH_LIMIT_MSB_READ[i]) << 8;
data->temp_high[i] |= i2c_smbus_read_byte_data(client,
TMP401_TEMP_HIGH_LIMIT_LSB[i]);
data->temp_crit[i] = i2c_smbus_read_byte_data(client,
TMP401_TEMP_CRIT_LIMIT[i]);
if (data->kind == tmp411) {
data->temp_lowest[i] = i2c_smbus_read_byte_data(client,
TMP411_TEMP_LOWEST_MSB[i]) << 8;
data->temp_lowest[i] |= i2c_smbus_read_byte_data(
client, TMP411_TEMP_LOWEST_LSB[i]);
data->temp_highest[i] = i2c_smbus_read_byte_data(
client, TMP411_TEMP_HIGHEST_MSB[i]) << 8;
data->temp_highest[i] |= i2c_smbus_read_byte_data(
client, TMP411_TEMP_HIGHEST_LSB[i]);
}
}
return data;
}
static struct tmp401_data *tmp401_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct tmp401_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
data->status = i2c_smbus_read_byte_data(client, TMP401_STATUS);
data->config = i2c_smbus_read_byte_data(client,
TMP401_CONFIG_READ);
tmp401_update_device_reg16(client, data);
data->temp_crit_hyst = i2c_smbus_read_byte_data(client,
TMP401_TEMP_CRIT_HYST);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_temp_value(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp[index], data->config));
}
static ssize_t show_temp_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_low[index], data->config));
}
static ssize_t show_temp_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_high[index], data->config));
}
static ssize_t show_temp_crit(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_crit_register_to_temp(data->temp_crit[index],
data->config));
}
static ssize_t show_temp_crit_hyst(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int temp, index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
mutex_lock(&data->update_lock);
temp = tmp401_crit_register_to_temp(data->temp_crit[index],
data->config);
temp -= data->temp_crit_hyst * 1000;
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
static ssize_t show_temp_lowest(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_lowest[index],
data->config));
}
static ssize_t show_temp_highest(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
return sprintf(buf, "%d\n",
tmp401_register_to_temp(data->temp_highest[index],
data->config));
}
static ssize_t show_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int mask = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
if (data->status & mask)
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_temp_min(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u16 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
reg = tmp401_temp_to_register(val, data->config);
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_LOW_LIMIT_MSB_WRITE[index], reg >> 8);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_LOW_LIMIT_LSB[index], reg & 0xFF);
data->temp_low[index] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_temp_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u16 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
reg = tmp401_temp_to_register(val, data->config);
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_HIGH_LIMIT_MSB_WRITE[index], reg >> 8);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_HIGH_LIMIT_LSB[index], reg & 0xFF);
data->temp_high[index] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_temp_crit(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u8 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
reg = tmp401_crit_temp_to_register(val, data->config);
mutex_lock(&data->update_lock);
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_CRIT_LIMIT[index], reg);
data->temp_crit[index] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_temp_crit_hyst(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
int temp, index = to_sensor_dev_attr(devattr)->index;
struct tmp401_data *data = tmp401_update_device(dev);
long val;
u8 reg;
if (kstrtol(buf, 10, &val))
return -EINVAL;
if (data->config & TMP401_CONFIG_RANGE)
val = SENSORS_LIMIT(val, -64000, 191000);
else
val = SENSORS_LIMIT(val, 0, 127000);
mutex_lock(&data->update_lock);
temp = tmp401_crit_register_to_temp(data->temp_crit[index],
data->config);
val = SENSORS_LIMIT(val, temp - 255000, temp);
reg = ((temp - val) + 500) / 1000;
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP401_TEMP_CRIT_HYST, reg);
data->temp_crit_hyst = reg;
mutex_unlock(&data->update_lock);
return count;
}
/*
* Resets the historical measurements of minimum and maximum temperatures.
* This is done by writing any value to any of the minimum/maximum registers
* (0x30-0x37).
*/
static ssize_t reset_temp_history(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count)
{
long val;
if (kstrtol(buf, 10, &val))
return -EINVAL;
if (val != 1) {
dev_err(dev, "temp_reset_history value %ld not"
" supported. Use 1 to reset the history!\n", val);
return -EINVAL;
}
i2c_smbus_write_byte_data(to_i2c_client(dev),
TMP411_TEMP_LOWEST_MSB[0], val);
return count;
}
static struct sensor_device_attribute tmp401_attr[] = {
SENSOR_ATTR(temp1_input, S_IRUGO, show_temp_value, NULL, 0),
SENSOR_ATTR(temp1_min, S_IWUSR | S_IRUGO, show_temp_min,
store_temp_min, 0),
SENSOR_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp_max,
store_temp_max, 0),
SENSOR_ATTR(temp1_crit, S_IWUSR | S_IRUGO, show_temp_crit,
store_temp_crit, 0),
SENSOR_ATTR(temp1_crit_hyst, S_IWUSR | S_IRUGO, show_temp_crit_hyst,
store_temp_crit_hyst, 0),
SENSOR_ATTR(temp1_min_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_LOCAL_LOW),
SENSOR_ATTR(temp1_max_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_LOCAL_HIGH),
SENSOR_ATTR(temp1_crit_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_LOCAL_CRIT),
SENSOR_ATTR(temp2_input, S_IRUGO, show_temp_value, NULL, 1),
SENSOR_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_temp_min,
store_temp_min, 1),
SENSOR_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_temp_max,
store_temp_max, 1),
SENSOR_ATTR(temp2_crit, S_IWUSR | S_IRUGO, show_temp_crit,
store_temp_crit, 1),
SENSOR_ATTR(temp2_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL, 1),
SENSOR_ATTR(temp2_fault, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_OPEN),
SENSOR_ATTR(temp2_min_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_LOW),
SENSOR_ATTR(temp2_max_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_HIGH),
SENSOR_ATTR(temp2_crit_alarm, S_IRUGO, show_status, NULL,
TMP401_STATUS_REMOTE_CRIT),
};
/*
* Additional features of the TMP411 chip.
* The TMP411 stores the minimum and maximum
* temperature measured since power-on, chip-reset, or
* minimum and maximum register reset for both the local
* and remote channels.
*/
static struct sensor_device_attribute tmp411_attr[] = {
SENSOR_ATTR(temp1_highest, S_IRUGO, show_temp_highest, NULL, 0),
SENSOR_ATTR(temp1_lowest, S_IRUGO, show_temp_lowest, NULL, 0),
SENSOR_ATTR(temp2_highest, S_IRUGO, show_temp_highest, NULL, 1),
SENSOR_ATTR(temp2_lowest, S_IRUGO, show_temp_lowest, NULL, 1),
SENSOR_ATTR(temp_reset_history, S_IWUSR, NULL, reset_temp_history, 0),
};
/*
* Begin non sysfs callback code (aka Real code)
*/
static void tmp401_init_client(struct i2c_client *client)
{
int config, config_orig;
/* Set the conversion rate to 2 Hz */
i2c_smbus_write_byte_data(client, TMP401_CONVERSION_RATE_WRITE, 5);
/* Start conversions (disable shutdown if necessary) */
config = i2c_smbus_read_byte_data(client, TMP401_CONFIG_READ);
if (config < 0) {
dev_warn(&client->dev, "Initialization failed!\n");
return;
}
config_orig = config;
config &= ~TMP401_CONFIG_SHUTDOWN;
if (config != config_orig)
i2c_smbus_write_byte_data(client, TMP401_CONFIG_WRITE, config);
}
static int tmp401_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
enum chips kind;
struct i2c_adapter *adapter = client->adapter;
u8 reg;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
/* Detect and identify the chip */
reg = i2c_smbus_read_byte_data(client, TMP401_MANUFACTURER_ID_REG);
if (reg != TMP401_MANUFACTURER_ID)
return -ENODEV;
reg = i2c_smbus_read_byte_data(client, TMP401_DEVICE_ID_REG);
switch (reg) {
case TMP401_DEVICE_ID:
kind = tmp401;
break;
case TMP411_DEVICE_ID:
kind = tmp411;
break;
default:
return -ENODEV;
}
reg = i2c_smbus_read_byte_data(client, TMP401_CONFIG_READ);
if (reg & 0x1b)
return -ENODEV;
reg = i2c_smbus_read_byte_data(client, TMP401_CONVERSION_RATE_READ);
/* Datasheet says: 0x1-0x6 */
if (reg > 15)
return -ENODEV;
strlcpy(info->type, tmp401_id[kind].name, I2C_NAME_SIZE);
return 0;
}
static int tmp401_remove(struct i2c_client *client)
{
struct tmp401_data *data = i2c_get_clientdata(client);
int i;
if (data->hwmon_dev)
hwmon_device_unregister(data->hwmon_dev);
for (i = 0; i < ARRAY_SIZE(tmp401_attr); i++)
device_remove_file(&client->dev, &tmp401_attr[i].dev_attr);
if (data->kind == tmp411) {
for (i = 0; i < ARRAY_SIZE(tmp411_attr); i++)
device_remove_file(&client->dev,
&tmp411_attr[i].dev_attr);
}
kfree(data);
return 0;
}
static int tmp401_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int i, err = 0;
struct tmp401_data *data;
const char *names[] = { "TMP401", "TMP411" };
data = kzalloc(sizeof(struct tmp401_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
data->kind = id->driver_data;
/* Initialize the TMP401 chip */
tmp401_init_client(client);
/* Register sysfs hooks */
for (i = 0; i < ARRAY_SIZE(tmp401_attr); i++) {
err = device_create_file(&client->dev,
&tmp401_attr[i].dev_attr);
if (err)
goto exit_remove;
}
/* Register additional tmp411 sysfs hooks */
if (data->kind == tmp411) {
for (i = 0; i < ARRAY_SIZE(tmp411_attr); i++) {
err = device_create_file(&client->dev,
&tmp411_attr[i].dev_attr);
if (err)
goto exit_remove;
}
}
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto exit_remove;
}
dev_info(&client->dev, "Detected TI %s chip\n", names[data->kind]);
return 0;
exit_remove:
tmp401_remove(client); /* will also free data for us */
return err;
}
static struct i2c_driver tmp401_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "tmp401",
},
.probe = tmp401_probe,
.remove = tmp401_remove,
.id_table = tmp401_id,
.detect = tmp401_detect,
.address_list = normal_i2c,
};
module_i2c_driver(tmp401_driver);
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_DESCRIPTION("Texas Instruments TMP401 temperature sensor driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
killerkink/kernel_sony_c2105 | drivers/hwmon/adm1026.c | 4857 | 60662 | /*
* adm1026.c - Part of lm_sensors, Linux kernel modules for hardware
* monitoring
* Copyright (C) 2002, 2003 Philip Pokorny <ppokorny@penguincomputing.com>
* Copyright (C) 2004 Justin Thiessen <jthiessen@penguincomputing.com>
*
* Chip details at:
*
* <http://www.onsemi.com/PowerSolutions/product.do?id=ADM1026>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x2c, 0x2d, 0x2e, I2C_CLIENT_END };
static int gpio_input[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_output[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_inverted[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_normal[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int gpio_fan[8] = { -1, -1, -1, -1, -1, -1, -1, -1 };
module_param_array(gpio_input, int, NULL, 0);
MODULE_PARM_DESC(gpio_input, "List of GPIO pins (0-16) to program as inputs");
module_param_array(gpio_output, int, NULL, 0);
MODULE_PARM_DESC(gpio_output, "List of GPIO pins (0-16) to program as "
"outputs");
module_param_array(gpio_inverted, int, NULL, 0);
MODULE_PARM_DESC(gpio_inverted, "List of GPIO pins (0-16) to program as "
"inverted");
module_param_array(gpio_normal, int, NULL, 0);
MODULE_PARM_DESC(gpio_normal, "List of GPIO pins (0-16) to program as "
"normal/non-inverted");
module_param_array(gpio_fan, int, NULL, 0);
MODULE_PARM_DESC(gpio_fan, "List of GPIO pins (0-7) to program as fan tachs");
/* Many ADM1026 constants specified below */
/* The ADM1026 registers */
#define ADM1026_REG_CONFIG1 0x00
#define CFG1_MONITOR 0x01
#define CFG1_INT_ENABLE 0x02
#define CFG1_INT_CLEAR 0x04
#define CFG1_AIN8_9 0x08
#define CFG1_THERM_HOT 0x10
#define CFG1_DAC_AFC 0x20
#define CFG1_PWM_AFC 0x40
#define CFG1_RESET 0x80
#define ADM1026_REG_CONFIG2 0x01
/* CONFIG2 controls FAN0/GPIO0 through FAN7/GPIO7 */
#define ADM1026_REG_CONFIG3 0x07
#define CFG3_GPIO16_ENABLE 0x01
#define CFG3_CI_CLEAR 0x02
#define CFG3_VREF_250 0x04
#define CFG3_GPIO16_DIR 0x40
#define CFG3_GPIO16_POL 0x80
#define ADM1026_REG_E2CONFIG 0x13
#define E2CFG_READ 0x01
#define E2CFG_WRITE 0x02
#define E2CFG_ERASE 0x04
#define E2CFG_ROM 0x08
#define E2CFG_CLK_EXT 0x80
/*
* There are 10 general analog inputs and 7 dedicated inputs
* They are:
* 0 - 9 = AIN0 - AIN9
* 10 = Vbat
* 11 = 3.3V Standby
* 12 = 3.3V Main
* 13 = +5V
* 14 = Vccp (CPU core voltage)
* 15 = +12V
* 16 = -12V
*/
static u16 ADM1026_REG_IN[] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x27, 0x29, 0x26, 0x2a,
0x2b, 0x2c, 0x2d, 0x2e, 0x2f
};
static u16 ADM1026_REG_IN_MIN[] = {
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d,
0x5e, 0x5f, 0x6d, 0x49, 0x6b, 0x4a,
0x4b, 0x4c, 0x4d, 0x4e, 0x4f
};
static u16 ADM1026_REG_IN_MAX[] = {
0x50, 0x51, 0x52, 0x53, 0x54, 0x55,
0x56, 0x57, 0x6c, 0x41, 0x6a, 0x42,
0x43, 0x44, 0x45, 0x46, 0x47
};
/*
* Temperatures are:
* 0 - Internal
* 1 - External 1
* 2 - External 2
*/
static u16 ADM1026_REG_TEMP[] = { 0x1f, 0x28, 0x29 };
static u16 ADM1026_REG_TEMP_MIN[] = { 0x69, 0x48, 0x49 };
static u16 ADM1026_REG_TEMP_MAX[] = { 0x68, 0x40, 0x41 };
static u16 ADM1026_REG_TEMP_TMIN[] = { 0x10, 0x11, 0x12 };
static u16 ADM1026_REG_TEMP_THERM[] = { 0x0d, 0x0e, 0x0f };
static u16 ADM1026_REG_TEMP_OFFSET[] = { 0x1e, 0x6e, 0x6f };
#define ADM1026_REG_FAN(nr) (0x38 + (nr))
#define ADM1026_REG_FAN_MIN(nr) (0x60 + (nr))
#define ADM1026_REG_FAN_DIV_0_3 0x02
#define ADM1026_REG_FAN_DIV_4_7 0x03
#define ADM1026_REG_DAC 0x04
#define ADM1026_REG_PWM 0x05
#define ADM1026_REG_GPIO_CFG_0_3 0x08
#define ADM1026_REG_GPIO_CFG_4_7 0x09
#define ADM1026_REG_GPIO_CFG_8_11 0x0a
#define ADM1026_REG_GPIO_CFG_12_15 0x0b
/* CFG_16 in REG_CFG3 */
#define ADM1026_REG_GPIO_STATUS_0_7 0x24
#define ADM1026_REG_GPIO_STATUS_8_15 0x25
/* STATUS_16 in REG_STATUS4 */
#define ADM1026_REG_GPIO_MASK_0_7 0x1c
#define ADM1026_REG_GPIO_MASK_8_15 0x1d
/* MASK_16 in REG_MASK4 */
#define ADM1026_REG_COMPANY 0x16
#define ADM1026_REG_VERSTEP 0x17
/* These are the recognized values for the above regs */
#define ADM1026_COMPANY_ANALOG_DEV 0x41
#define ADM1026_VERSTEP_GENERIC 0x40
#define ADM1026_VERSTEP_ADM1026 0x44
#define ADM1026_REG_MASK1 0x18
#define ADM1026_REG_MASK2 0x19
#define ADM1026_REG_MASK3 0x1a
#define ADM1026_REG_MASK4 0x1b
#define ADM1026_REG_STATUS1 0x20
#define ADM1026_REG_STATUS2 0x21
#define ADM1026_REG_STATUS3 0x22
#define ADM1026_REG_STATUS4 0x23
#define ADM1026_FAN_ACTIVATION_TEMP_HYST -6
#define ADM1026_FAN_CONTROL_TEMP_RANGE 20
#define ADM1026_PWM_MAX 255
/*
* Conversions. Rounding and limit checking is only done on the TO_REG
* variants. Note that you should be a bit careful with which arguments
* these macros are called: arguments may be evaluated more than once.
*/
/*
* IN are scaled according to built-in resistors. These are the
* voltages corresponding to 3/4 of full scale (192 or 0xc0)
* NOTE: The -12V input needs an additional factor to account
* for the Vref pullup resistor.
* NEG12_OFFSET = SCALE * Vref / V-192 - Vref
* = 13875 * 2.50 / 1.875 - 2500
* = 16000
*
* The values in this table are based on Table II, page 15 of the
* datasheet.
*/
static int adm1026_scaling[] = { /* .001 Volts */
2250, 2250, 2250, 2250, 2250, 2250,
1875, 1875, 1875, 1875, 3000, 3330,
3330, 4995, 2250, 12000, 13875
};
#define NEG12_OFFSET 16000
#define SCALE(val, from, to) (((val)*(to) + ((from)/2))/(from))
#define INS_TO_REG(n, val) (SENSORS_LIMIT(SCALE(val, adm1026_scaling[n], 192),\
0, 255))
#define INS_FROM_REG(n, val) (SCALE(val, 192, adm1026_scaling[n]))
/*
* FAN speed is measured using 22.5kHz clock and counts for 2 pulses
* and we assume a 2 pulse-per-rev fan tach signal
* 22500 kHz * 60 (sec/min) * 2 (pulse) / 2 (pulse/rev) == 1350000
*/
#define FAN_TO_REG(val, div) ((val) <= 0 ? 0xff : \
SENSORS_LIMIT(1350000 / ((val) * (div)), \
1, 254))
#define FAN_FROM_REG(val, div) ((val) == 0 ? -1 : (val) == 0xff ? 0 : \
1350000 / ((val) * (div)))
#define DIV_FROM_REG(val) (1 << (val))
#define DIV_TO_REG(val) ((val) >= 8 ? 3 : (val) >= 4 ? 2 : (val) >= 2 ? 1 : 0)
/* Temperature is reported in 1 degC increments */
#define TEMP_TO_REG(val) (SENSORS_LIMIT(((val) + ((val) < 0 ? -500 : 500)) \
/ 1000, -127, 127))
#define TEMP_FROM_REG(val) ((val) * 1000)
#define OFFSET_TO_REG(val) (SENSORS_LIMIT(((val) + ((val) < 0 ? -500 : 500)) \
/ 1000, -127, 127))
#define OFFSET_FROM_REG(val) ((val) * 1000)
#define PWM_TO_REG(val) (SENSORS_LIMIT(val, 0, 255))
#define PWM_FROM_REG(val) (val)
#define PWM_MIN_TO_REG(val) ((val) & 0xf0)
#define PWM_MIN_FROM_REG(val) (((val) & 0xf0) + ((val) >> 4))
/*
* Analog output is a voltage, and scaled to millivolts. The datasheet
* indicates that the DAC could be used to drive the fans, but in our
* example board (Arima HDAMA) it isn't connected to the fans at all.
*/
#define DAC_TO_REG(val) (SENSORS_LIMIT(((((val) * 255) + 500) / 2500), 0, 255))
#define DAC_FROM_REG(val) (((val) * 2500) / 255)
/*
* Chip sampling rates
*
* Some sensors are not updated more frequently than once per second
* so it doesn't make sense to read them more often than that.
* We cache the results and return the saved data if the driver
* is called again before a second has elapsed.
*
* Also, there is significant configuration data for this chip
* So, we keep the config data up to date in the cache
* when it is written and only sample it once every 5 *minutes*
*/
#define ADM1026_DATA_INTERVAL (1 * HZ)
#define ADM1026_CONFIG_INTERVAL (5 * 60 * HZ)
/*
* We allow for multiple chips in a single system.
*
* For each registered ADM1026, we need to keep state information
* at client->data. The adm1026_data structure is dynamically
* allocated, when a new client structure is allocated.
*/
struct pwm_data {
u8 pwm;
u8 enable;
u8 auto_pwm_min;
};
struct adm1026_data {
struct device *hwmon_dev;
struct mutex update_lock;
int valid; /* !=0 if following fields are valid */
unsigned long last_reading; /* In jiffies */
unsigned long last_config; /* In jiffies */
u8 in[17]; /* Register value */
u8 in_max[17]; /* Register value */
u8 in_min[17]; /* Register value */
s8 temp[3]; /* Register value */
s8 temp_min[3]; /* Register value */
s8 temp_max[3]; /* Register value */
s8 temp_tmin[3]; /* Register value */
s8 temp_crit[3]; /* Register value */
s8 temp_offset[3]; /* Register value */
u8 fan[8]; /* Register value */
u8 fan_min[8]; /* Register value */
u8 fan_div[8]; /* Decoded value */
struct pwm_data pwm1; /* Pwm control values */
u8 vrm; /* VRM version */
u8 analog_out; /* Register value (DAC) */
long alarms; /* Register encoding, combined */
long alarm_mask; /* Register encoding, combined */
long gpio; /* Register encoding, combined */
long gpio_mask; /* Register encoding, combined */
u8 gpio_config[17]; /* Decoded value */
u8 config1; /* Register value */
u8 config2; /* Register value */
u8 config3; /* Register value */
};
static int adm1026_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int adm1026_detect(struct i2c_client *client,
struct i2c_board_info *info);
static int adm1026_remove(struct i2c_client *client);
static int adm1026_read_value(struct i2c_client *client, u8 reg);
static int adm1026_write_value(struct i2c_client *client, u8 reg, int value);
static void adm1026_print_gpio(struct i2c_client *client);
static void adm1026_fixup_gpio(struct i2c_client *client);
static struct adm1026_data *adm1026_update_device(struct device *dev);
static void adm1026_init_client(struct i2c_client *client);
static const struct i2c_device_id adm1026_id[] = {
{ "adm1026", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adm1026_id);
static struct i2c_driver adm1026_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "adm1026",
},
.probe = adm1026_probe,
.remove = adm1026_remove,
.id_table = adm1026_id,
.detect = adm1026_detect,
.address_list = normal_i2c,
};
static int adm1026_read_value(struct i2c_client *client, u8 reg)
{
int res;
if (reg < 0x80) {
/* "RAM" locations */
res = i2c_smbus_read_byte_data(client, reg) & 0xff;
} else {
/* EEPROM, do nothing */
res = 0;
}
return res;
}
static int adm1026_write_value(struct i2c_client *client, u8 reg, int value)
{
int res;
if (reg < 0x80) {
/* "RAM" locations */
res = i2c_smbus_write_byte_data(client, reg, value);
} else {
/* EEPROM, do nothing */
res = 0;
}
return res;
}
static void adm1026_init_client(struct i2c_client *client)
{
int value, i;
struct adm1026_data *data = i2c_get_clientdata(client);
dev_dbg(&client->dev, "Initializing device\n");
/* Read chip config */
data->config1 = adm1026_read_value(client, ADM1026_REG_CONFIG1);
data->config2 = adm1026_read_value(client, ADM1026_REG_CONFIG2);
data->config3 = adm1026_read_value(client, ADM1026_REG_CONFIG3);
/* Inform user of chip config */
dev_dbg(&client->dev, "ADM1026_REG_CONFIG1 is: 0x%02x\n",
data->config1);
if ((data->config1 & CFG1_MONITOR) == 0) {
dev_dbg(&client->dev, "Monitoring not currently "
"enabled.\n");
}
if (data->config1 & CFG1_INT_ENABLE) {
dev_dbg(&client->dev, "SMBALERT interrupts are "
"enabled.\n");
}
if (data->config1 & CFG1_AIN8_9) {
dev_dbg(&client->dev, "in8 and in9 enabled. "
"temp3 disabled.\n");
} else {
dev_dbg(&client->dev, "temp3 enabled. in8 and "
"in9 disabled.\n");
}
if (data->config1 & CFG1_THERM_HOT) {
dev_dbg(&client->dev, "Automatic THERM, PWM, "
"and temp limits enabled.\n");
}
if (data->config3 & CFG3_GPIO16_ENABLE) {
dev_dbg(&client->dev, "GPIO16 enabled. THERM "
"pin disabled.\n");
} else {
dev_dbg(&client->dev, "THERM pin enabled. "
"GPIO16 disabled.\n");
}
if (data->config3 & CFG3_VREF_250)
dev_dbg(&client->dev, "Vref is 2.50 Volts.\n");
else
dev_dbg(&client->dev, "Vref is 1.82 Volts.\n");
/* Read and pick apart the existing GPIO configuration */
value = 0;
for (i = 0; i <= 15; ++i) {
if ((i & 0x03) == 0) {
value = adm1026_read_value(client,
ADM1026_REG_GPIO_CFG_0_3 + i / 4);
}
data->gpio_config[i] = value & 0x03;
value >>= 2;
}
data->gpio_config[16] = (data->config3 >> 6) & 0x03;
/* ... and then print it */
adm1026_print_gpio(client);
/*
* If the user asks us to reprogram the GPIO config, then
* do it now.
*/
if (gpio_input[0] != -1 || gpio_output[0] != -1
|| gpio_inverted[0] != -1 || gpio_normal[0] != -1
|| gpio_fan[0] != -1) {
adm1026_fixup_gpio(client);
}
/*
* WE INTENTIONALLY make no changes to the limits,
* offsets, pwms, fans and zones. If they were
* configured, we don't want to mess with them.
* If they weren't, the default is 100% PWM, no
* control and will suffice until 'sensors -s'
* can be run by the user. We DO set the default
* value for pwm1.auto_pwm_min to its maximum
* so that enabling automatic pwm fan control
* without first setting a value for pwm1.auto_pwm_min
* will not result in potentially dangerous fan speed decrease.
*/
data->pwm1.auto_pwm_min = 255;
/* Start monitoring */
value = adm1026_read_value(client, ADM1026_REG_CONFIG1);
/* Set MONITOR, clear interrupt acknowledge and s/w reset */
value = (value | CFG1_MONITOR) & (~CFG1_INT_CLEAR & ~CFG1_RESET);
dev_dbg(&client->dev, "Setting CONFIG to: 0x%02x\n", value);
data->config1 = value;
adm1026_write_value(client, ADM1026_REG_CONFIG1, value);
/* initialize fan_div[] to hardware defaults */
value = adm1026_read_value(client, ADM1026_REG_FAN_DIV_0_3) |
(adm1026_read_value(client, ADM1026_REG_FAN_DIV_4_7) << 8);
for (i = 0; i <= 7; ++i) {
data->fan_div[i] = DIV_FROM_REG(value & 0x03);
value >>= 2;
}
}
static void adm1026_print_gpio(struct i2c_client *client)
{
struct adm1026_data *data = i2c_get_clientdata(client);
int i;
dev_dbg(&client->dev, "GPIO config is:\n");
for (i = 0; i <= 7; ++i) {
if (data->config2 & (1 << i)) {
dev_dbg(&client->dev, "\t%sGP%s%d\n",
data->gpio_config[i] & 0x02 ? "" : "!",
data->gpio_config[i] & 0x01 ? "OUT" : "IN",
i);
} else {
dev_dbg(&client->dev, "\tFAN%d\n", i);
}
}
for (i = 8; i <= 15; ++i) {
dev_dbg(&client->dev, "\t%sGP%s%d\n",
data->gpio_config[i] & 0x02 ? "" : "!",
data->gpio_config[i] & 0x01 ? "OUT" : "IN",
i);
}
if (data->config3 & CFG3_GPIO16_ENABLE) {
dev_dbg(&client->dev, "\t%sGP%s16\n",
data->gpio_config[16] & 0x02 ? "" : "!",
data->gpio_config[16] & 0x01 ? "OUT" : "IN");
} else {
/* GPIO16 is THERM */
dev_dbg(&client->dev, "\tTHERM\n");
}
}
static void adm1026_fixup_gpio(struct i2c_client *client)
{
struct adm1026_data *data = i2c_get_clientdata(client);
int i;
int value;
/* Make the changes requested. */
/*
* We may need to unlock/stop monitoring or soft-reset the
* chip before we can make changes. This hasn't been
* tested much. FIXME
*/
/* Make outputs */
for (i = 0; i <= 16; ++i) {
if (gpio_output[i] >= 0 && gpio_output[i] <= 16)
data->gpio_config[gpio_output[i]] |= 0x01;
/* if GPIO0-7 is output, it isn't a FAN tach */
if (gpio_output[i] >= 0 && gpio_output[i] <= 7)
data->config2 |= 1 << gpio_output[i];
}
/* Input overrides output */
for (i = 0; i <= 16; ++i) {
if (gpio_input[i] >= 0 && gpio_input[i] <= 16)
data->gpio_config[gpio_input[i]] &= ~0x01;
/* if GPIO0-7 is input, it isn't a FAN tach */
if (gpio_input[i] >= 0 && gpio_input[i] <= 7)
data->config2 |= 1 << gpio_input[i];
}
/* Inverted */
for (i = 0; i <= 16; ++i) {
if (gpio_inverted[i] >= 0 && gpio_inverted[i] <= 16)
data->gpio_config[gpio_inverted[i]] &= ~0x02;
}
/* Normal overrides inverted */
for (i = 0; i <= 16; ++i) {
if (gpio_normal[i] >= 0 && gpio_normal[i] <= 16)
data->gpio_config[gpio_normal[i]] |= 0x02;
}
/* Fan overrides input and output */
for (i = 0; i <= 7; ++i) {
if (gpio_fan[i] >= 0 && gpio_fan[i] <= 7)
data->config2 &= ~(1 << gpio_fan[i]);
}
/* Write new configs to registers */
adm1026_write_value(client, ADM1026_REG_CONFIG2, data->config2);
data->config3 = (data->config3 & 0x3f)
| ((data->gpio_config[16] & 0x03) << 6);
adm1026_write_value(client, ADM1026_REG_CONFIG3, data->config3);
for (i = 15, value = 0; i >= 0; --i) {
value <<= 2;
value |= data->gpio_config[i] & 0x03;
if ((i & 0x03) == 0) {
adm1026_write_value(client,
ADM1026_REG_GPIO_CFG_0_3 + i/4,
value);
value = 0;
}
}
/* Print the new config */
adm1026_print_gpio(client);
}
static struct adm1026_data *adm1026_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
int i;
long value, alarms, gpio;
mutex_lock(&data->update_lock);
if (!data->valid
|| time_after(jiffies,
data->last_reading + ADM1026_DATA_INTERVAL)) {
/* Things that change quickly */
dev_dbg(&client->dev, "Reading sensor values\n");
for (i = 0; i <= 16; ++i) {
data->in[i] =
adm1026_read_value(client, ADM1026_REG_IN[i]);
}
for (i = 0; i <= 7; ++i) {
data->fan[i] =
adm1026_read_value(client, ADM1026_REG_FAN(i));
}
for (i = 0; i <= 2; ++i) {
/*
* NOTE: temp[] is s8 and we assume 2's complement
* "conversion" in the assignment
*/
data->temp[i] =
adm1026_read_value(client, ADM1026_REG_TEMP[i]);
}
data->pwm1.pwm = adm1026_read_value(client,
ADM1026_REG_PWM);
data->analog_out = adm1026_read_value(client,
ADM1026_REG_DAC);
/* GPIO16 is MSbit of alarms, move it to gpio */
alarms = adm1026_read_value(client, ADM1026_REG_STATUS4);
gpio = alarms & 0x80 ? 0x0100 : 0; /* GPIO16 */
alarms &= 0x7f;
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_STATUS3);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_STATUS2);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_STATUS1);
data->alarms = alarms;
/* Read the GPIO values */
gpio |= adm1026_read_value(client,
ADM1026_REG_GPIO_STATUS_8_15);
gpio <<= 8;
gpio |= adm1026_read_value(client,
ADM1026_REG_GPIO_STATUS_0_7);
data->gpio = gpio;
data->last_reading = jiffies;
}; /* last_reading */
if (!data->valid ||
time_after(jiffies, data->last_config + ADM1026_CONFIG_INTERVAL)) {
/* Things that don't change often */
dev_dbg(&client->dev, "Reading config values\n");
for (i = 0; i <= 16; ++i) {
data->in_min[i] = adm1026_read_value(client,
ADM1026_REG_IN_MIN[i]);
data->in_max[i] = adm1026_read_value(client,
ADM1026_REG_IN_MAX[i]);
}
value = adm1026_read_value(client, ADM1026_REG_FAN_DIV_0_3)
| (adm1026_read_value(client, ADM1026_REG_FAN_DIV_4_7)
<< 8);
for (i = 0; i <= 7; ++i) {
data->fan_min[i] = adm1026_read_value(client,
ADM1026_REG_FAN_MIN(i));
data->fan_div[i] = DIV_FROM_REG(value & 0x03);
value >>= 2;
}
for (i = 0; i <= 2; ++i) {
/*
* NOTE: temp_xxx[] are s8 and we assume 2's
* complement "conversion" in the assignment
*/
data->temp_min[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_MIN[i]);
data->temp_max[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_MAX[i]);
data->temp_tmin[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_TMIN[i]);
data->temp_crit[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_THERM[i]);
data->temp_offset[i] = adm1026_read_value(client,
ADM1026_REG_TEMP_OFFSET[i]);
}
/* Read the STATUS/alarm masks */
alarms = adm1026_read_value(client, ADM1026_REG_MASK4);
gpio = alarms & 0x80 ? 0x0100 : 0; /* GPIO16 */
alarms = (alarms & 0x7f) << 8;
alarms |= adm1026_read_value(client, ADM1026_REG_MASK3);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_MASK2);
alarms <<= 8;
alarms |= adm1026_read_value(client, ADM1026_REG_MASK1);
data->alarm_mask = alarms;
/* Read the GPIO values */
gpio |= adm1026_read_value(client,
ADM1026_REG_GPIO_MASK_8_15);
gpio <<= 8;
gpio |= adm1026_read_value(client, ADM1026_REG_GPIO_MASK_0_7);
data->gpio_mask = gpio;
/* Read various values from CONFIG1 */
data->config1 = adm1026_read_value(client,
ADM1026_REG_CONFIG1);
if (data->config1 & CFG1_PWM_AFC) {
data->pwm1.enable = 2;
data->pwm1.auto_pwm_min =
PWM_MIN_FROM_REG(data->pwm1.pwm);
}
/* Read the GPIO config */
data->config2 = adm1026_read_value(client,
ADM1026_REG_CONFIG2);
data->config3 = adm1026_read_value(client,
ADM1026_REG_CONFIG3);
data->gpio_config[16] = (data->config3 >> 6) & 0x03;
value = 0;
for (i = 0; i <= 15; ++i) {
if ((i & 0x03) == 0) {
value = adm1026_read_value(client,
ADM1026_REG_GPIO_CFG_0_3 + i/4);
}
data->gpio_config[i] = value & 0x03;
value >>= 2;
}
data->last_config = jiffies;
}; /* last_config */
data->valid = 1;
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_in(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(nr, data->in[nr]));
}
static ssize_t show_in_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(nr, data->in_min[nr]));
}
static ssize_t set_in_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[nr] = INS_TO_REG(nr, val);
adm1026_write_value(client, ADM1026_REG_IN_MIN[nr], data->in_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(nr, data->in_max[nr]));
}
static ssize_t set_in_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[nr] = INS_TO_REG(nr, val);
adm1026_write_value(client, ADM1026_REG_IN_MAX[nr], data->in_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define in_reg(offset) \
static SENSOR_DEVICE_ATTR(in##offset##_input, S_IRUGO, show_in, \
NULL, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_min, S_IRUGO | S_IWUSR, \
show_in_min, set_in_min, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_max, S_IRUGO | S_IWUSR, \
show_in_max, set_in_max, offset);
in_reg(0);
in_reg(1);
in_reg(2);
in_reg(3);
in_reg(4);
in_reg(5);
in_reg(6);
in_reg(7);
in_reg(8);
in_reg(9);
in_reg(10);
in_reg(11);
in_reg(12);
in_reg(13);
in_reg(14);
in_reg(15);
static ssize_t show_in16(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(16, data->in[16]) -
NEG12_OFFSET);
}
static ssize_t show_in16_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(16, data->in_min[16])
- NEG12_OFFSET);
}
static ssize_t set_in16_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[16] = INS_TO_REG(16, val + NEG12_OFFSET);
adm1026_write_value(client, ADM1026_REG_IN_MIN[16], data->in_min[16]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in16_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", INS_FROM_REG(16, data->in_max[16])
- NEG12_OFFSET);
}
static ssize_t set_in16_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[16] = INS_TO_REG(16, val+NEG12_OFFSET);
adm1026_write_value(client, ADM1026_REG_IN_MAX[16], data->in_max[16]);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(in16_input, S_IRUGO, show_in16, NULL, 16);
static SENSOR_DEVICE_ATTR(in16_min, S_IRUGO | S_IWUSR, show_in16_min,
set_in16_min, 16);
static SENSOR_DEVICE_ATTR(in16_max, S_IRUGO | S_IWUSR, show_in16_max,
set_in16_max, 16);
/* Now add fan read/write functions */
static ssize_t show_fan(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr],
data->fan_div[nr]));
}
static ssize_t show_fan_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan_min[nr],
data->fan_div[nr]));
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->fan_min[nr] = FAN_TO_REG(val, data->fan_div[nr]);
adm1026_write_value(client, ADM1026_REG_FAN_MIN(nr),
data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define fan_offset(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, show_fan, NULL, \
offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
show_fan_min, set_fan_min, offset - 1);
fan_offset(1);
fan_offset(2);
fan_offset(3);
fan_offset(4);
fan_offset(5);
fan_offset(6);
fan_offset(7);
fan_offset(8);
/* Adjust fan_min to account for new fan divisor */
static void fixup_fan_min(struct device *dev, int fan, int old_div)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
int new_min;
int new_div = data->fan_div[fan];
/* 0 and 0xff are special. Don't adjust them */
if (data->fan_min[fan] == 0 || data->fan_min[fan] == 0xff)
return;
new_min = data->fan_min[fan] * old_div / new_div;
new_min = SENSORS_LIMIT(new_min, 1, 254);
data->fan_min[fan] = new_min;
adm1026_write_value(client, ADM1026_REG_FAN_MIN(fan), new_min);
}
/* Now add fan_div read/write functions */
static ssize_t show_fan_div(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", data->fan_div[nr]);
}
static ssize_t set_fan_div(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int orig_div, new_div;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
new_div = DIV_TO_REG(val);
mutex_lock(&data->update_lock);
orig_div = data->fan_div[nr];
data->fan_div[nr] = DIV_FROM_REG(new_div);
if (nr < 4) { /* 0 <= nr < 4 */
adm1026_write_value(client, ADM1026_REG_FAN_DIV_0_3,
(DIV_TO_REG(data->fan_div[0]) << 0) |
(DIV_TO_REG(data->fan_div[1]) << 2) |
(DIV_TO_REG(data->fan_div[2]) << 4) |
(DIV_TO_REG(data->fan_div[3]) << 6));
} else { /* 3 < nr < 8 */
adm1026_write_value(client, ADM1026_REG_FAN_DIV_4_7,
(DIV_TO_REG(data->fan_div[4]) << 0) |
(DIV_TO_REG(data->fan_div[5]) << 2) |
(DIV_TO_REG(data->fan_div[6]) << 4) |
(DIV_TO_REG(data->fan_div[7]) << 6));
}
if (data->fan_div[nr] != orig_div)
fixup_fan_min(dev, nr, orig_div);
mutex_unlock(&data->update_lock);
return count;
}
#define fan_offset_div(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_div, S_IRUGO | S_IWUSR, \
show_fan_div, set_fan_div, offset - 1);
fan_offset_div(1);
fan_offset_div(2);
fan_offset_div(3);
fan_offset_div(4);
fan_offset_div(5);
fan_offset_div(6);
fan_offset_div(7);
fan_offset_div(8);
/* Temps */
static ssize_t show_temp(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[nr]));
}
static ssize_t show_temp_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_min[nr]));
}
static ssize_t set_temp_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_min[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_MIN[nr],
data->temp_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_max[nr]));
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_max[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_MAX[nr],
data->temp_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_input, S_IRUGO, show_temp, \
NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_min, S_IRUGO | S_IWUSR, \
show_temp_min, set_temp_min, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max, S_IRUGO | S_IWUSR, \
show_temp_max, set_temp_max, offset - 1);
temp_reg(1);
temp_reg(2);
temp_reg(3);
static ssize_t show_temp_offset(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_offset[nr]));
}
static ssize_t set_temp_offset(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_offset[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_OFFSET[nr],
data->temp_offset[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_offset_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_offset, S_IRUGO | S_IWUSR, \
show_temp_offset, set_temp_offset, offset - 1);
temp_offset_reg(1);
temp_offset_reg(2);
temp_offset_reg(3);
static ssize_t show_temp_auto_point1_temp_hyst(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(
ADM1026_FAN_ACTIVATION_TEMP_HYST + data->temp_tmin[nr]));
}
static ssize_t show_temp_auto_point2_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_tmin[nr] +
ADM1026_FAN_CONTROL_TEMP_RANGE));
}
static ssize_t show_temp_auto_point1_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_tmin[nr]));
}
static ssize_t set_temp_auto_point1_temp(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_tmin[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_TMIN[nr],
data->temp_tmin[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_auto_point(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_auto_point1_temp, \
S_IRUGO | S_IWUSR, show_temp_auto_point1_temp, \
set_temp_auto_point1_temp, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_auto_point1_temp_hyst, S_IRUGO,\
show_temp_auto_point1_temp_hyst, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_auto_point2_temp, S_IRUGO, \
show_temp_auto_point2_temp, NULL, offset - 1);
temp_auto_point(1);
temp_auto_point(2);
temp_auto_point(3);
static ssize_t show_temp_crit_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", (data->config1 & CFG1_THERM_HOT) >> 4);
}
static ssize_t set_temp_crit_enable(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (val > 1)
return -EINVAL;
mutex_lock(&data->update_lock);
data->config1 = (data->config1 & ~CFG1_THERM_HOT) | (val << 4);
adm1026_write_value(client, ADM1026_REG_CONFIG1, data->config1);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_crit_enable(offset) \
static DEVICE_ATTR(temp##offset##_crit_enable, S_IRUGO | S_IWUSR, \
show_temp_crit_enable, set_temp_crit_enable);
temp_crit_enable(1);
temp_crit_enable(2);
temp_crit_enable(3);
static ssize_t show_temp_crit(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_crit[nr]));
}
static ssize_t set_temp_crit(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_crit[nr] = TEMP_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_TEMP_THERM[nr],
data->temp_crit[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_crit_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_crit, S_IRUGO | S_IWUSR, \
show_temp_crit, set_temp_crit, offset - 1);
temp_crit_reg(1);
temp_crit_reg(2);
temp_crit_reg(3);
static ssize_t show_analog_out_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", DAC_FROM_REG(data->analog_out));
}
static ssize_t set_analog_out_reg(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->analog_out = DAC_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_DAC, data->analog_out);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(analog_out, S_IRUGO | S_IWUSR, show_analog_out_reg,
set_analog_out_reg);
static ssize_t show_vid_reg(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
int vid = (data->gpio >> 11) & 0x1f;
dev_dbg(dev, "Setting VID from GPIO11-15.\n");
return sprintf(buf, "%d\n", vid_from_reg(vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid_reg, NULL);
static ssize_t show_vrm_reg(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", data->vrm);
}
static ssize_t store_vrm_reg(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct adm1026_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
data->vrm = val;
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm_reg, store_vrm_reg);
static ssize_t show_alarms_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->alarms);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms_reg, NULL);
static ssize_t show_alarm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%ld\n", (data->alarms >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in9_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in11_alarm, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(in12_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(in13_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(in14_alarm, S_IRUGO, show_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(in15_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(in16_alarm, S_IRUGO, show_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 8);
static SENSOR_DEVICE_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 9);
static SENSOR_DEVICE_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 10);
static SENSOR_DEVICE_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 11);
static SENSOR_DEVICE_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 12);
static SENSOR_DEVICE_ATTR(in5_alarm, S_IRUGO, show_alarm, NULL, 13);
static SENSOR_DEVICE_ATTR(in6_alarm, S_IRUGO, show_alarm, NULL, 14);
static SENSOR_DEVICE_ATTR(in7_alarm, S_IRUGO, show_alarm, NULL, 15);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 16);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 17);
static SENSOR_DEVICE_ATTR(fan3_alarm, S_IRUGO, show_alarm, NULL, 18);
static SENSOR_DEVICE_ATTR(fan4_alarm, S_IRUGO, show_alarm, NULL, 19);
static SENSOR_DEVICE_ATTR(fan5_alarm, S_IRUGO, show_alarm, NULL, 20);
static SENSOR_DEVICE_ATTR(fan6_alarm, S_IRUGO, show_alarm, NULL, 21);
static SENSOR_DEVICE_ATTR(fan7_alarm, S_IRUGO, show_alarm, NULL, 22);
static SENSOR_DEVICE_ATTR(fan8_alarm, S_IRUGO, show_alarm, NULL, 23);
static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 24);
static SENSOR_DEVICE_ATTR(in10_alarm, S_IRUGO, show_alarm, NULL, 25);
static SENSOR_DEVICE_ATTR(in8_alarm, S_IRUGO, show_alarm, NULL, 26);
static ssize_t show_alarm_mask(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->alarm_mask);
}
static ssize_t set_alarm_mask(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
unsigned long mask;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->alarm_mask = val & 0x7fffffff;
mask = data->alarm_mask
| (data->gpio_mask & 0x10000 ? 0x80000000 : 0);
adm1026_write_value(client, ADM1026_REG_MASK1,
mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_MASK2,
mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_MASK3,
mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_MASK4,
mask & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(alarm_mask, S_IRUGO | S_IWUSR, show_alarm_mask,
set_alarm_mask);
static ssize_t show_gpio(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->gpio);
}
static ssize_t set_gpio(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long gpio;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->gpio = val & 0x1ffff;
gpio = data->gpio;
adm1026_write_value(client, ADM1026_REG_GPIO_STATUS_0_7, gpio & 0xff);
gpio >>= 8;
adm1026_write_value(client, ADM1026_REG_GPIO_STATUS_8_15, gpio & 0xff);
gpio = ((gpio >> 1) & 0x80) | (data->alarms >> 24 & 0x7f);
adm1026_write_value(client, ADM1026_REG_STATUS4, gpio & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(gpio, S_IRUGO | S_IWUSR, show_gpio, set_gpio);
static ssize_t show_gpio_mask(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%ld\n", data->gpio_mask);
}
static ssize_t set_gpio_mask(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
long mask;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->gpio_mask = val & 0x1ffff;
mask = data->gpio_mask;
adm1026_write_value(client, ADM1026_REG_GPIO_MASK_0_7, mask & 0xff);
mask >>= 8;
adm1026_write_value(client, ADM1026_REG_GPIO_MASK_8_15, mask & 0xff);
mask = ((mask >> 1) & 0x80) | (data->alarm_mask >> 24 & 0x7f);
adm1026_write_value(client, ADM1026_REG_MASK1, mask & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(gpio_mask, S_IRUGO | S_IWUSR, show_gpio_mask, set_gpio_mask);
static ssize_t show_pwm_reg(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", PWM_FROM_REG(data->pwm1.pwm));
}
static ssize_t set_pwm_reg(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
if (data->pwm1.enable == 1) {
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm1.pwm = PWM_TO_REG(val);
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
mutex_unlock(&data->update_lock);
}
return count;
}
static ssize_t show_auto_pwm_min(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", data->pwm1.auto_pwm_min);
}
static ssize_t set_auto_pwm_min(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm1.auto_pwm_min = SENSORS_LIMIT(val, 0, 255);
if (data->pwm1.enable == 2) { /* apply immediately */
data->pwm1.pwm = PWM_TO_REG((data->pwm1.pwm & 0x0f) |
PWM_MIN_TO_REG(data->pwm1.auto_pwm_min));
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
}
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_auto_pwm_max(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", ADM1026_PWM_MAX);
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct adm1026_data *data = adm1026_update_device(dev);
return sprintf(buf, "%d\n", data->pwm1.enable);
}
static ssize_t set_pwm_enable(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1026_data *data = i2c_get_clientdata(client);
int old_enable;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (val >= 3)
return -EINVAL;
mutex_lock(&data->update_lock);
old_enable = data->pwm1.enable;
data->pwm1.enable = val;
data->config1 = (data->config1 & ~CFG1_PWM_AFC)
| ((val == 2) ? CFG1_PWM_AFC : 0);
adm1026_write_value(client, ADM1026_REG_CONFIG1, data->config1);
if (val == 2) { /* apply pwm1_auto_pwm_min to pwm1 */
data->pwm1.pwm = PWM_TO_REG((data->pwm1.pwm & 0x0f) |
PWM_MIN_TO_REG(data->pwm1.auto_pwm_min));
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
} else if (!((old_enable == 1) && (val == 1))) {
/* set pwm to safe value */
data->pwm1.pwm = 255;
adm1026_write_value(client, ADM1026_REG_PWM, data->pwm1.pwm);
}
mutex_unlock(&data->update_lock);
return count;
}
/* enable PWM fan control */
static DEVICE_ATTR(pwm1, S_IRUGO | S_IWUSR, show_pwm_reg, set_pwm_reg);
static DEVICE_ATTR(pwm2, S_IRUGO | S_IWUSR, show_pwm_reg, set_pwm_reg);
static DEVICE_ATTR(pwm3, S_IRUGO | S_IWUSR, show_pwm_reg, set_pwm_reg);
static DEVICE_ATTR(pwm1_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
static DEVICE_ATTR(pwm2_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
static DEVICE_ATTR(pwm3_enable, S_IRUGO | S_IWUSR, show_pwm_enable,
set_pwm_enable);
static DEVICE_ATTR(temp1_auto_point1_pwm, S_IRUGO | S_IWUSR,
show_auto_pwm_min, set_auto_pwm_min);
static DEVICE_ATTR(temp2_auto_point1_pwm, S_IRUGO | S_IWUSR,
show_auto_pwm_min, set_auto_pwm_min);
static DEVICE_ATTR(temp3_auto_point1_pwm, S_IRUGO | S_IWUSR,
show_auto_pwm_min, set_auto_pwm_min);
static DEVICE_ATTR(temp1_auto_point2_pwm, S_IRUGO, show_auto_pwm_max, NULL);
static DEVICE_ATTR(temp2_auto_point2_pwm, S_IRUGO, show_auto_pwm_max, NULL);
static DEVICE_ATTR(temp3_auto_point2_pwm, S_IRUGO, show_auto_pwm_max, NULL);
static struct attribute *adm1026_attributes[] = {
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_max.dev_attr.attr,
&sensor_dev_attr_in0_min.dev_attr.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_max.dev_attr.attr,
&sensor_dev_attr_in1_min.dev_attr.attr,
&sensor_dev_attr_in1_alarm.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_max.dev_attr.attr,
&sensor_dev_attr_in2_min.dev_attr.attr,
&sensor_dev_attr_in2_alarm.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in3_max.dev_attr.attr,
&sensor_dev_attr_in3_min.dev_attr.attr,
&sensor_dev_attr_in3_alarm.dev_attr.attr,
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in4_max.dev_attr.attr,
&sensor_dev_attr_in4_min.dev_attr.attr,
&sensor_dev_attr_in4_alarm.dev_attr.attr,
&sensor_dev_attr_in5_input.dev_attr.attr,
&sensor_dev_attr_in5_max.dev_attr.attr,
&sensor_dev_attr_in5_min.dev_attr.attr,
&sensor_dev_attr_in5_alarm.dev_attr.attr,
&sensor_dev_attr_in6_input.dev_attr.attr,
&sensor_dev_attr_in6_max.dev_attr.attr,
&sensor_dev_attr_in6_min.dev_attr.attr,
&sensor_dev_attr_in6_alarm.dev_attr.attr,
&sensor_dev_attr_in7_input.dev_attr.attr,
&sensor_dev_attr_in7_max.dev_attr.attr,
&sensor_dev_attr_in7_min.dev_attr.attr,
&sensor_dev_attr_in7_alarm.dev_attr.attr,
&sensor_dev_attr_in10_input.dev_attr.attr,
&sensor_dev_attr_in10_max.dev_attr.attr,
&sensor_dev_attr_in10_min.dev_attr.attr,
&sensor_dev_attr_in10_alarm.dev_attr.attr,
&sensor_dev_attr_in11_input.dev_attr.attr,
&sensor_dev_attr_in11_max.dev_attr.attr,
&sensor_dev_attr_in11_min.dev_attr.attr,
&sensor_dev_attr_in11_alarm.dev_attr.attr,
&sensor_dev_attr_in12_input.dev_attr.attr,
&sensor_dev_attr_in12_max.dev_attr.attr,
&sensor_dev_attr_in12_min.dev_attr.attr,
&sensor_dev_attr_in12_alarm.dev_attr.attr,
&sensor_dev_attr_in13_input.dev_attr.attr,
&sensor_dev_attr_in13_max.dev_attr.attr,
&sensor_dev_attr_in13_min.dev_attr.attr,
&sensor_dev_attr_in13_alarm.dev_attr.attr,
&sensor_dev_attr_in14_input.dev_attr.attr,
&sensor_dev_attr_in14_max.dev_attr.attr,
&sensor_dev_attr_in14_min.dev_attr.attr,
&sensor_dev_attr_in14_alarm.dev_attr.attr,
&sensor_dev_attr_in15_input.dev_attr.attr,
&sensor_dev_attr_in15_max.dev_attr.attr,
&sensor_dev_attr_in15_min.dev_attr.attr,
&sensor_dev_attr_in15_alarm.dev_attr.attr,
&sensor_dev_attr_in16_input.dev_attr.attr,
&sensor_dev_attr_in16_max.dev_attr.attr,
&sensor_dev_attr_in16_min.dev_attr.attr,
&sensor_dev_attr_in16_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_div.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_div.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan3_div.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan3_alarm.dev_attr.attr,
&sensor_dev_attr_fan4_input.dev_attr.attr,
&sensor_dev_attr_fan4_div.dev_attr.attr,
&sensor_dev_attr_fan4_min.dev_attr.attr,
&sensor_dev_attr_fan4_alarm.dev_attr.attr,
&sensor_dev_attr_fan5_input.dev_attr.attr,
&sensor_dev_attr_fan5_div.dev_attr.attr,
&sensor_dev_attr_fan5_min.dev_attr.attr,
&sensor_dev_attr_fan5_alarm.dev_attr.attr,
&sensor_dev_attr_fan6_input.dev_attr.attr,
&sensor_dev_attr_fan6_div.dev_attr.attr,
&sensor_dev_attr_fan6_min.dev_attr.attr,
&sensor_dev_attr_fan6_alarm.dev_attr.attr,
&sensor_dev_attr_fan7_input.dev_attr.attr,
&sensor_dev_attr_fan7_div.dev_attr.attr,
&sensor_dev_attr_fan7_min.dev_attr.attr,
&sensor_dev_attr_fan7_alarm.dev_attr.attr,
&sensor_dev_attr_fan8_input.dev_attr.attr,
&sensor_dev_attr_fan8_div.dev_attr.attr,
&sensor_dev_attr_fan8_min.dev_attr.attr,
&sensor_dev_attr_fan8_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_offset.dev_attr.attr,
&sensor_dev_attr_temp2_offset.dev_attr.attr,
&sensor_dev_attr_temp1_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_temp2_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_temp1_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_temp2_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_temp1_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_temp2_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_temp1_crit.dev_attr.attr,
&sensor_dev_attr_temp2_crit.dev_attr.attr,
&dev_attr_temp1_crit_enable.attr,
&dev_attr_temp2_crit_enable.attr,
&dev_attr_cpu0_vid.attr,
&dev_attr_vrm.attr,
&dev_attr_alarms.attr,
&dev_attr_alarm_mask.attr,
&dev_attr_gpio.attr,
&dev_attr_gpio_mask.attr,
&dev_attr_pwm1.attr,
&dev_attr_pwm2.attr,
&dev_attr_pwm3.attr,
&dev_attr_pwm1_enable.attr,
&dev_attr_pwm2_enable.attr,
&dev_attr_pwm3_enable.attr,
&dev_attr_temp1_auto_point1_pwm.attr,
&dev_attr_temp2_auto_point1_pwm.attr,
&dev_attr_temp1_auto_point2_pwm.attr,
&dev_attr_temp2_auto_point2_pwm.attr,
&dev_attr_analog_out.attr,
NULL
};
static const struct attribute_group adm1026_group = {
.attrs = adm1026_attributes,
};
static struct attribute *adm1026_attributes_temp3[] = {
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_offset.dev_attr.attr,
&sensor_dev_attr_temp3_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_temp3_auto_point1_temp_hyst.dev_attr.attr,
&sensor_dev_attr_temp3_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_temp3_crit.dev_attr.attr,
&dev_attr_temp3_crit_enable.attr,
&dev_attr_temp3_auto_point1_pwm.attr,
&dev_attr_temp3_auto_point2_pwm.attr,
NULL
};
static const struct attribute_group adm1026_group_temp3 = {
.attrs = adm1026_attributes_temp3,
};
static struct attribute *adm1026_attributes_in8_9[] = {
&sensor_dev_attr_in8_input.dev_attr.attr,
&sensor_dev_attr_in8_max.dev_attr.attr,
&sensor_dev_attr_in8_min.dev_attr.attr,
&sensor_dev_attr_in8_alarm.dev_attr.attr,
&sensor_dev_attr_in9_input.dev_attr.attr,
&sensor_dev_attr_in9_max.dev_attr.attr,
&sensor_dev_attr_in9_min.dev_attr.attr,
&sensor_dev_attr_in9_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group adm1026_group_in8_9 = {
.attrs = adm1026_attributes_in8_9,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int adm1026_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int address = client->addr;
int company, verstep;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
/* We need to be able to do byte I/O */
return -ENODEV;
};
/* Now, we do the remaining detection. */
company = adm1026_read_value(client, ADM1026_REG_COMPANY);
verstep = adm1026_read_value(client, ADM1026_REG_VERSTEP);
dev_dbg(&adapter->dev, "Detecting device at %d,0x%02x with"
" COMPANY: 0x%02x and VERSTEP: 0x%02x\n",
i2c_adapter_id(client->adapter), client->addr,
company, verstep);
/* Determine the chip type. */
dev_dbg(&adapter->dev, "Autodetecting device at %d,0x%02x...\n",
i2c_adapter_id(adapter), address);
if (company == ADM1026_COMPANY_ANALOG_DEV
&& verstep == ADM1026_VERSTEP_ADM1026) {
/* Analog Devices ADM1026 */
} else if (company == ADM1026_COMPANY_ANALOG_DEV
&& (verstep & 0xf0) == ADM1026_VERSTEP_GENERIC) {
dev_err(&adapter->dev, "Unrecognized stepping "
"0x%02x. Defaulting to ADM1026.\n", verstep);
} else if ((verstep & 0xf0) == ADM1026_VERSTEP_GENERIC) {
dev_err(&adapter->dev, "Found version/stepping "
"0x%02x. Assuming generic ADM1026.\n",
verstep);
} else {
dev_dbg(&adapter->dev, "Autodetection failed\n");
/* Not an ADM1026... */
return -ENODEV;
}
strlcpy(info->type, "adm1026", I2C_NAME_SIZE);
return 0;
}
static int adm1026_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adm1026_data *data;
int err;
data = kzalloc(sizeof(struct adm1026_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
/* Set the VRM version */
data->vrm = vid_which_vrm();
/* Initialize the ADM1026 chip */
adm1026_init_client(client);
/* Register sysfs hooks */
err = sysfs_create_group(&client->dev.kobj, &adm1026_group);
if (err)
goto exitfree;
if (data->config1 & CFG1_AIN8_9)
err = sysfs_create_group(&client->dev.kobj,
&adm1026_group_in8_9);
else
err = sysfs_create_group(&client->dev.kobj,
&adm1026_group_temp3);
if (err)
goto exitremove;
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exitremove;
}
return 0;
/* Error out and cleanup code */
exitremove:
sysfs_remove_group(&client->dev.kobj, &adm1026_group);
if (data->config1 & CFG1_AIN8_9)
sysfs_remove_group(&client->dev.kobj, &adm1026_group_in8_9);
else
sysfs_remove_group(&client->dev.kobj, &adm1026_group_temp3);
exitfree:
kfree(data);
exit:
return err;
}
static int adm1026_remove(struct i2c_client *client)
{
struct adm1026_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &adm1026_group);
if (data->config1 & CFG1_AIN8_9)
sysfs_remove_group(&client->dev.kobj, &adm1026_group_in8_9);
else
sysfs_remove_group(&client->dev.kobj, &adm1026_group_temp3);
kfree(data);
return 0;
}
module_i2c_driver(adm1026_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Philip Pokorny <ppokorny@penguincomputing.com>, "
"Justin Thiessen <jthiessen@penguincomputing.com>");
MODULE_DESCRIPTION("ADM1026 driver");
| gpl-2.0 |
a-martynovich/kernel_goldfish | drivers/misc/ti-st/st_ll.c | 5113 | 4505 | /*
* Shared Transport driver
* HCI-LL module responsible for TI proprietary HCI_LL protocol
* Copyright (C) 2009-2010 Texas Instruments
* Author: Pavan Savoy <pavan_savoy@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#define pr_fmt(fmt) "(stll) :" fmt
#include <linux/skbuff.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/ti_wilink_st.h>
/**********************************************************************/
/* internal functions */
static void send_ll_cmd(struct st_data_s *st_data,
unsigned char cmd)
{
pr_debug("%s: writing %x", __func__, cmd);
st_int_write(st_data, &cmd, 1);
return;
}
static void ll_device_want_to_sleep(struct st_data_s *st_data)
{
struct kim_data_s *kim_data;
struct ti_st_plat_data *pdata;
pr_debug("%s", __func__);
/* sanity check */
if (st_data->ll_state != ST_LL_AWAKE)
pr_err("ERR hcill: ST_LL_GO_TO_SLEEP_IND"
"in state %ld", st_data->ll_state);
send_ll_cmd(st_data, LL_SLEEP_ACK);
/* update state */
st_data->ll_state = ST_LL_ASLEEP;
/* communicate to platform about chip asleep */
kim_data = st_data->kim_data;
pdata = kim_data->kim_pdev->dev.platform_data;
if (pdata->chip_asleep)
pdata->chip_asleep(NULL);
}
static void ll_device_want_to_wakeup(struct st_data_s *st_data)
{
struct kim_data_s *kim_data;
struct ti_st_plat_data *pdata;
/* diff actions in diff states */
switch (st_data->ll_state) {
case ST_LL_ASLEEP:
send_ll_cmd(st_data, LL_WAKE_UP_ACK); /* send wake_ack */
break;
case ST_LL_ASLEEP_TO_AWAKE:
/* duplicate wake_ind */
pr_err("duplicate wake_ind while waiting for Wake ack");
break;
case ST_LL_AWAKE:
/* duplicate wake_ind */
pr_err("duplicate wake_ind already AWAKE");
break;
case ST_LL_AWAKE_TO_ASLEEP:
/* duplicate wake_ind */
pr_err("duplicate wake_ind");
break;
}
/* update state */
st_data->ll_state = ST_LL_AWAKE;
/* communicate to platform about chip wakeup */
kim_data = st_data->kim_data;
pdata = kim_data->kim_pdev->dev.platform_data;
if (pdata->chip_asleep)
pdata->chip_awake(NULL);
}
/**********************************************************************/
/* functions invoked by ST Core */
/* called when ST Core wants to
* enable ST LL */
void st_ll_enable(struct st_data_s *ll)
{
ll->ll_state = ST_LL_AWAKE;
}
/* called when ST Core /local module wants to
* disable ST LL */
void st_ll_disable(struct st_data_s *ll)
{
ll->ll_state = ST_LL_INVALID;
}
/* called when ST Core wants to update the state */
void st_ll_wakeup(struct st_data_s *ll)
{
if (likely(ll->ll_state != ST_LL_AWAKE)) {
send_ll_cmd(ll, LL_WAKE_UP_IND); /* WAKE_IND */
ll->ll_state = ST_LL_ASLEEP_TO_AWAKE;
} else {
/* don't send the duplicate wake_indication */
pr_err(" Chip already AWAKE ");
}
}
/* called when ST Core wants the state */
unsigned long st_ll_getstate(struct st_data_s *ll)
{
pr_debug(" returning state %ld", ll->ll_state);
return ll->ll_state;
}
/* called from ST Core, when a PM related packet arrives */
unsigned long st_ll_sleep_state(struct st_data_s *st_data,
unsigned char cmd)
{
switch (cmd) {
case LL_SLEEP_IND: /* sleep ind */
pr_debug("sleep indication recvd");
ll_device_want_to_sleep(st_data);
break;
case LL_SLEEP_ACK: /* sleep ack */
pr_err("sleep ack rcvd: host shouldn't");
break;
case LL_WAKE_UP_IND: /* wake ind */
pr_debug("wake indication recvd");
ll_device_want_to_wakeup(st_data);
break;
case LL_WAKE_UP_ACK: /* wake ack */
pr_debug("wake ack rcvd");
st_data->ll_state = ST_LL_AWAKE;
break;
default:
pr_err(" unknown input/state ");
return -EINVAL;
}
return 0;
}
/* Called from ST CORE to initialize ST LL */
long st_ll_init(struct st_data_s *ll)
{
/* set state to invalid */
ll->ll_state = ST_LL_INVALID;
return 0;
}
/* Called from ST CORE to de-initialize ST LL */
long st_ll_deinit(struct st_data_s *ll)
{
return 0;
}
| gpl-2.0 |
QduZ9zEVr6/kernel-msm | drivers/media/dvb/frontends/dib7000m.c | 7929 | 42198 | /*
* Linux-DVB Driver for DiBcom's DiB7000M and
* first generation DiB7000P-demodulator-family.
*
* Copyright (C) 2005-7 DiBcom (http://www.dibcom.fr/)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include "dvb_frontend.h"
#include "dib7000m.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "turn on debugging (default: 0)");
#define dprintk(args...) do { if (debug) { printk(KERN_DEBUG "DiB7000M: "); printk(args); printk("\n"); } } while (0)
struct dib7000m_state {
struct dvb_frontend demod;
struct dib7000m_config cfg;
u8 i2c_addr;
struct i2c_adapter *i2c_adap;
struct dibx000_i2c_master i2c_master;
/* offset is 1 in case of the 7000MC */
u8 reg_offs;
u16 wbd_ref;
u8 current_band;
u32 current_bandwidth;
struct dibx000_agc_config *current_agc;
u32 timf;
u32 timf_default;
u32 internal_clk;
u8 div_force_off : 1;
u8 div_state : 1;
u16 div_sync_wait;
u16 revision;
u8 agc_state;
/* for the I2C transfer */
struct i2c_msg msg[2];
u8 i2c_write_buffer[4];
u8 i2c_read_buffer[2];
struct mutex i2c_buffer_lock;
};
enum dib7000m_power_mode {
DIB7000M_POWER_ALL = 0,
DIB7000M_POWER_NO,
DIB7000M_POWER_INTERF_ANALOG_AGC,
DIB7000M_POWER_COR4_DINTLV_ICIRM_EQUAL_CFROD,
DIB7000M_POWER_COR4_CRY_ESRAM_MOUT_NUD,
DIB7000M_POWER_INTERFACE_ONLY,
};
static u16 dib7000m_read_word(struct dib7000m_state *state, u16 reg)
{
u16 ret;
if (mutex_lock_interruptible(&state->i2c_buffer_lock) < 0) {
dprintk("could not acquire lock");
return 0;
}
state->i2c_write_buffer[0] = (reg >> 8) | 0x80;
state->i2c_write_buffer[1] = reg & 0xff;
memset(state->msg, 0, 2 * sizeof(struct i2c_msg));
state->msg[0].addr = state->i2c_addr >> 1;
state->msg[0].flags = 0;
state->msg[0].buf = state->i2c_write_buffer;
state->msg[0].len = 2;
state->msg[1].addr = state->i2c_addr >> 1;
state->msg[1].flags = I2C_M_RD;
state->msg[1].buf = state->i2c_read_buffer;
state->msg[1].len = 2;
if (i2c_transfer(state->i2c_adap, state->msg, 2) != 2)
dprintk("i2c read error on %d",reg);
ret = (state->i2c_read_buffer[0] << 8) | state->i2c_read_buffer[1];
mutex_unlock(&state->i2c_buffer_lock);
return ret;
}
static int dib7000m_write_word(struct dib7000m_state *state, u16 reg, u16 val)
{
int ret;
if (mutex_lock_interruptible(&state->i2c_buffer_lock) < 0) {
dprintk("could not acquire lock");
return -EINVAL;
}
state->i2c_write_buffer[0] = (reg >> 8) & 0xff;
state->i2c_write_buffer[1] = reg & 0xff;
state->i2c_write_buffer[2] = (val >> 8) & 0xff;
state->i2c_write_buffer[3] = val & 0xff;
memset(&state->msg[0], 0, sizeof(struct i2c_msg));
state->msg[0].addr = state->i2c_addr >> 1;
state->msg[0].flags = 0;
state->msg[0].buf = state->i2c_write_buffer;
state->msg[0].len = 4;
ret = (i2c_transfer(state->i2c_adap, state->msg, 1) != 1 ?
-EREMOTEIO : 0);
mutex_unlock(&state->i2c_buffer_lock);
return ret;
}
static void dib7000m_write_tab(struct dib7000m_state *state, u16 *buf)
{
u16 l = 0, r, *n;
n = buf;
l = *n++;
while (l) {
r = *n++;
if (state->reg_offs && (r >= 112 && r <= 331)) // compensate for 7000MC
r++;
do {
dib7000m_write_word(state, r, *n++);
r++;
} while (--l);
l = *n++;
}
}
static int dib7000m_set_output_mode(struct dib7000m_state *state, int mode)
{
int ret = 0;
u16 outreg, fifo_threshold, smo_mode,
sram = 0x0005; /* by default SRAM output is disabled */
outreg = 0;
fifo_threshold = 1792;
smo_mode = (dib7000m_read_word(state, 294 + state->reg_offs) & 0x0010) | (1 << 1);
dprintk( "setting output mode for demod %p to %d", &state->demod, mode);
switch (mode) {
case OUTMODE_MPEG2_PAR_GATED_CLK: // STBs with parallel gated clock
outreg = (1 << 10); /* 0x0400 */
break;
case OUTMODE_MPEG2_PAR_CONT_CLK: // STBs with parallel continues clock
outreg = (1 << 10) | (1 << 6); /* 0x0440 */
break;
case OUTMODE_MPEG2_SERIAL: // STBs with serial input
outreg = (1 << 10) | (2 << 6) | (0 << 1); /* 0x0482 */
break;
case OUTMODE_DIVERSITY:
if (state->cfg.hostbus_diversity)
outreg = (1 << 10) | (4 << 6); /* 0x0500 */
else
sram |= 0x0c00;
break;
case OUTMODE_MPEG2_FIFO: // e.g. USB feeding
smo_mode |= (3 << 1);
fifo_threshold = 512;
outreg = (1 << 10) | (5 << 6);
break;
case OUTMODE_HIGH_Z: // disable
outreg = 0;
break;
default:
dprintk( "Unhandled output_mode passed to be set for demod %p",&state->demod);
break;
}
if (state->cfg.output_mpeg2_in_188_bytes)
smo_mode |= (1 << 5) ;
ret |= dib7000m_write_word(state, 294 + state->reg_offs, smo_mode);
ret |= dib7000m_write_word(state, 295 + state->reg_offs, fifo_threshold); /* synchronous fread */
ret |= dib7000m_write_word(state, 1795, outreg);
ret |= dib7000m_write_word(state, 1805, sram);
if (state->revision == 0x4003) {
u16 clk_cfg1 = dib7000m_read_word(state, 909) & 0xfffd;
if (mode == OUTMODE_DIVERSITY)
clk_cfg1 |= (1 << 1); // P_O_CLK_en
dib7000m_write_word(state, 909, clk_cfg1);
}
return ret;
}
static void dib7000m_set_power_mode(struct dib7000m_state *state, enum dib7000m_power_mode mode)
{
/* by default everything is going to be powered off */
u16 reg_903 = 0xffff, reg_904 = 0xffff, reg_905 = 0xffff, reg_906 = 0x3fff;
u8 offset = 0;
/* now, depending on the requested mode, we power on */
switch (mode) {
/* power up everything in the demod */
case DIB7000M_POWER_ALL:
reg_903 = 0x0000; reg_904 = 0x0000; reg_905 = 0x0000; reg_906 = 0x0000;
break;
/* just leave power on the control-interfaces: GPIO and (I2C or SDIO or SRAM) */
case DIB7000M_POWER_INTERFACE_ONLY: /* TODO power up either SDIO or I2C or SRAM */
reg_905 &= ~((1 << 7) | (1 << 6) | (1 << 5) | (1 << 2));
break;
case DIB7000M_POWER_INTERF_ANALOG_AGC:
reg_903 &= ~((1 << 15) | (1 << 14) | (1 << 11) | (1 << 10));
reg_905 &= ~((1 << 7) | (1 << 6) | (1 << 5) | (1 << 4) | (1 << 2));
reg_906 &= ~((1 << 0));
break;
case DIB7000M_POWER_COR4_DINTLV_ICIRM_EQUAL_CFROD:
reg_903 = 0x0000; reg_904 = 0x801f; reg_905 = 0x0000; reg_906 = 0x0000;
break;
case DIB7000M_POWER_COR4_CRY_ESRAM_MOUT_NUD:
reg_903 = 0x0000; reg_904 = 0x8000; reg_905 = 0x010b; reg_906 = 0x0000;
break;
case DIB7000M_POWER_NO:
break;
}
/* always power down unused parts */
if (!state->cfg.mobile_mode)
reg_904 |= (1 << 7) | (1 << 6) | (1 << 4) | (1 << 2) | (1 << 1);
/* P_sdio_select_clk = 0 on MC and after*/
if (state->revision != 0x4000)
reg_906 <<= 1;
if (state->revision == 0x4003)
offset = 1;
dib7000m_write_word(state, 903 + offset, reg_903);
dib7000m_write_word(state, 904 + offset, reg_904);
dib7000m_write_word(state, 905 + offset, reg_905);
dib7000m_write_word(state, 906 + offset, reg_906);
}
static int dib7000m_set_adc_state(struct dib7000m_state *state, enum dibx000_adc_states no)
{
int ret = 0;
u16 reg_913 = dib7000m_read_word(state, 913),
reg_914 = dib7000m_read_word(state, 914);
switch (no) {
case DIBX000_SLOW_ADC_ON:
reg_914 |= (1 << 1) | (1 << 0);
ret |= dib7000m_write_word(state, 914, reg_914);
reg_914 &= ~(1 << 1);
break;
case DIBX000_SLOW_ADC_OFF:
reg_914 |= (1 << 1) | (1 << 0);
break;
case DIBX000_ADC_ON:
if (state->revision == 0x4000) { // workaround for PA/MA
// power-up ADC
dib7000m_write_word(state, 913, 0);
dib7000m_write_word(state, 914, reg_914 & 0x3);
// power-down bandgag
dib7000m_write_word(state, 913, (1 << 15));
dib7000m_write_word(state, 914, reg_914 & 0x3);
}
reg_913 &= 0x0fff;
reg_914 &= 0x0003;
break;
case DIBX000_ADC_OFF: // leave the VBG voltage on
reg_913 |= (1 << 14) | (1 << 13) | (1 << 12);
reg_914 |= (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2);
break;
case DIBX000_VBG_ENABLE:
reg_913 &= ~(1 << 15);
break;
case DIBX000_VBG_DISABLE:
reg_913 |= (1 << 15);
break;
default:
break;
}
// dprintk( "913: %x, 914: %x", reg_913, reg_914);
ret |= dib7000m_write_word(state, 913, reg_913);
ret |= dib7000m_write_word(state, 914, reg_914);
return ret;
}
static int dib7000m_set_bandwidth(struct dib7000m_state *state, u32 bw)
{
u32 timf;
if (!bw)
bw = 8000;
// store the current bandwidth for later use
state->current_bandwidth = bw;
if (state->timf == 0) {
dprintk( "using default timf");
timf = state->timf_default;
} else {
dprintk( "using updated timf");
timf = state->timf;
}
timf = timf * (bw / 50) / 160;
dib7000m_write_word(state, 23, (u16) ((timf >> 16) & 0xffff));
dib7000m_write_word(state, 24, (u16) ((timf ) & 0xffff));
return 0;
}
static int dib7000m_set_diversity_in(struct dvb_frontend *demod, int onoff)
{
struct dib7000m_state *state = demod->demodulator_priv;
if (state->div_force_off) {
dprintk( "diversity combination deactivated - forced by COFDM parameters");
onoff = 0;
}
state->div_state = (u8)onoff;
if (onoff) {
dib7000m_write_word(state, 263 + state->reg_offs, 6);
dib7000m_write_word(state, 264 + state->reg_offs, 6);
dib7000m_write_word(state, 266 + state->reg_offs, (state->div_sync_wait << 4) | (1 << 2) | (2 << 0));
} else {
dib7000m_write_word(state, 263 + state->reg_offs, 1);
dib7000m_write_word(state, 264 + state->reg_offs, 0);
dib7000m_write_word(state, 266 + state->reg_offs, 0);
}
return 0;
}
static int dib7000m_sad_calib(struct dib7000m_state *state)
{
/* internal */
// dib7000m_write_word(state, 928, (3 << 14) | (1 << 12) | (524 << 0)); // sampling clock of the SAD is writting in set_bandwidth
dib7000m_write_word(state, 929, (0 << 1) | (0 << 0));
dib7000m_write_word(state, 930, 776); // 0.625*3.3 / 4096
/* do the calibration */
dib7000m_write_word(state, 929, (1 << 0));
dib7000m_write_word(state, 929, (0 << 0));
msleep(1);
return 0;
}
static void dib7000m_reset_pll_common(struct dib7000m_state *state, const struct dibx000_bandwidth_config *bw)
{
dib7000m_write_word(state, 18, (u16) (((bw->internal*1000) >> 16) & 0xffff));
dib7000m_write_word(state, 19, (u16) ( (bw->internal*1000) & 0xffff));
dib7000m_write_word(state, 21, (u16) ( (bw->ifreq >> 16) & 0xffff));
dib7000m_write_word(state, 22, (u16) ( bw->ifreq & 0xffff));
dib7000m_write_word(state, 928, bw->sad_cfg);
}
static void dib7000m_reset_pll(struct dib7000m_state *state)
{
const struct dibx000_bandwidth_config *bw = state->cfg.bw;
u16 reg_907,reg_910;
/* default */
reg_907 = (bw->pll_bypass << 15) | (bw->modulo << 7) |
(bw->ADClkSrc << 6) | (bw->IO_CLK_en_core << 5) | (bw->bypclk_div << 2) |
(bw->enable_refdiv << 1) | (0 << 0);
reg_910 = (((bw->pll_ratio >> 6) & 0x3) << 3) | (bw->pll_range << 1) | bw->pll_reset;
// for this oscillator frequency should be 30 MHz for the Master (default values in the board_parameters give that value)
// this is only working only for 30 MHz crystals
if (!state->cfg.quartz_direct) {
reg_910 |= (1 << 5); // forcing the predivider to 1
// if the previous front-end is baseband, its output frequency is 15 MHz (prev freq divided by 2)
if(state->cfg.input_clk_is_div_2)
reg_907 |= (16 << 9);
else // otherwise the previous front-end puts out its input (default 30MHz) - no extra division necessary
reg_907 |= (8 << 9);
} else {
reg_907 |= (bw->pll_ratio & 0x3f) << 9;
reg_910 |= (bw->pll_prediv << 5);
}
dib7000m_write_word(state, 910, reg_910); // pll cfg
dib7000m_write_word(state, 907, reg_907); // clk cfg0
dib7000m_write_word(state, 908, 0x0006); // clk_cfg1
dib7000m_reset_pll_common(state, bw);
}
static void dib7000mc_reset_pll(struct dib7000m_state *state)
{
const struct dibx000_bandwidth_config *bw = state->cfg.bw;
u16 clk_cfg1;
// clk_cfg0
dib7000m_write_word(state, 907, (bw->pll_prediv << 8) | (bw->pll_ratio << 0));
// clk_cfg1
//dib7000m_write_word(state, 908, (1 << 14) | (3 << 12) |(0 << 11) |
clk_cfg1 = (0 << 14) | (3 << 12) |(0 << 11) |
(bw->IO_CLK_en_core << 10) | (bw->bypclk_div << 5) | (bw->enable_refdiv << 4) |
(1 << 3) | (bw->pll_range << 1) | (bw->pll_reset << 0);
dib7000m_write_word(state, 908, clk_cfg1);
clk_cfg1 = (clk_cfg1 & 0xfff7) | (bw->pll_bypass << 3);
dib7000m_write_word(state, 908, clk_cfg1);
// smpl_cfg
dib7000m_write_word(state, 910, (1 << 12) | (2 << 10) | (bw->modulo << 8) | (bw->ADClkSrc << 7));
dib7000m_reset_pll_common(state, bw);
}
static int dib7000m_reset_gpio(struct dib7000m_state *st)
{
/* reset the GPIOs */
dib7000m_write_word(st, 773, st->cfg.gpio_dir);
dib7000m_write_word(st, 774, st->cfg.gpio_val);
/* TODO 782 is P_gpio_od */
dib7000m_write_word(st, 775, st->cfg.gpio_pwm_pos);
dib7000m_write_word(st, 780, st->cfg.pwm_freq_div);
return 0;
}
static u16 dib7000m_defaults_common[] =
{
// auto search configuration
3, 2,
0x0004,
0x1000,
0x0814,
12, 6,
0x001b,
0x7740,
0x005b,
0x8d80,
0x01c9,
0xc380,
0x0000,
0x0080,
0x0000,
0x0090,
0x0001,
0xd4c0,
1, 26,
0x6680, // P_corm_thres Lock algorithms configuration
1, 170,
0x0410, // P_palf_alpha_regul, P_palf_filter_freeze, P_palf_filter_on
8, 173,
0,
0,
0,
0,
0,
0,
0,
0,
1, 182,
8192, // P_fft_nb_to_cut
2, 195,
0x0ccd, // P_pha3_thres
0, // P_cti_use_cpe, P_cti_use_prog
1, 205,
0x200f, // P_cspu_regul, P_cspu_win_cut
5, 214,
0x023d, // P_adp_regul_cnt
0x00a4, // P_adp_noise_cnt
0x00a4, // P_adp_regul_ext
0x7ff0, // P_adp_noise_ext
0x3ccc, // P_adp_fil
1, 226,
0, // P_2d_byp_ti_num
1, 255,
0x800, // P_equal_thres_wgn
1, 263,
0x0001,
1, 281,
0x0010, // P_fec_*
1, 294,
0x0062, // P_smo_mode, P_smo_rs_discard, P_smo_fifo_flush, P_smo_pid_parse, P_smo_error_discard
0
};
static u16 dib7000m_defaults[] =
{
/* set ADC level to -16 */
11, 76,
(1 << 13) - 825 - 117,
(1 << 13) - 837 - 117,
(1 << 13) - 811 - 117,
(1 << 13) - 766 - 117,
(1 << 13) - 737 - 117,
(1 << 13) - 693 - 117,
(1 << 13) - 648 - 117,
(1 << 13) - 619 - 117,
(1 << 13) - 575 - 117,
(1 << 13) - 531 - 117,
(1 << 13) - 501 - 117,
// Tuner IO bank: max drive (14mA)
1, 912,
0x2c8a,
1, 1817,
1,
0,
};
static int dib7000m_demod_reset(struct dib7000m_state *state)
{
dib7000m_set_power_mode(state, DIB7000M_POWER_ALL);
/* always leave the VBG voltage on - it consumes almost nothing but takes a long time to start */
dib7000m_set_adc_state(state, DIBX000_VBG_ENABLE);
/* restart all parts */
dib7000m_write_word(state, 898, 0xffff);
dib7000m_write_word(state, 899, 0xffff);
dib7000m_write_word(state, 900, 0xff0f);
dib7000m_write_word(state, 901, 0xfffc);
dib7000m_write_word(state, 898, 0);
dib7000m_write_word(state, 899, 0);
dib7000m_write_word(state, 900, 0);
dib7000m_write_word(state, 901, 0);
if (state->revision == 0x4000)
dib7000m_reset_pll(state);
else
dib7000mc_reset_pll(state);
if (dib7000m_reset_gpio(state) != 0)
dprintk( "GPIO reset was not successful.");
if (dib7000m_set_output_mode(state, OUTMODE_HIGH_Z) != 0)
dprintk( "OUTPUT_MODE could not be reset.");
/* unforce divstr regardless whether i2c enumeration was done or not */
dib7000m_write_word(state, 1794, dib7000m_read_word(state, 1794) & ~(1 << 1) );
dib7000m_set_bandwidth(state, 8000);
dib7000m_set_adc_state(state, DIBX000_SLOW_ADC_ON);
dib7000m_sad_calib(state);
dib7000m_set_adc_state(state, DIBX000_SLOW_ADC_OFF);
if (state->cfg.dvbt_mode)
dib7000m_write_word(state, 1796, 0x0); // select DVB-T output
if (state->cfg.mobile_mode)
dib7000m_write_word(state, 261 + state->reg_offs, 2);
else
dib7000m_write_word(state, 224 + state->reg_offs, 1);
// P_iqc_alpha_pha, P_iqc_alpha_amp, P_iqc_dcc_alpha, ...
if(state->cfg.tuner_is_baseband)
dib7000m_write_word(state, 36, 0x0755);
else
dib7000m_write_word(state, 36, 0x1f55);
// P_divclksel=3 P_divbitsel=1
if (state->revision == 0x4000)
dib7000m_write_word(state, 909, (3 << 10) | (1 << 6));
else
dib7000m_write_word(state, 909, (3 << 4) | 1);
dib7000m_write_tab(state, dib7000m_defaults_common);
dib7000m_write_tab(state, dib7000m_defaults);
dib7000m_set_power_mode(state, DIB7000M_POWER_INTERFACE_ONLY);
state->internal_clk = state->cfg.bw->internal;
return 0;
}
static void dib7000m_restart_agc(struct dib7000m_state *state)
{
// P_restart_iqc & P_restart_agc
dib7000m_write_word(state, 898, 0x0c00);
dib7000m_write_word(state, 898, 0x0000);
}
static int dib7000m_agc_soft_split(struct dib7000m_state *state)
{
u16 agc,split_offset;
if(!state->current_agc || !state->current_agc->perform_agc_softsplit || state->current_agc->split.max == 0)
return 0;
// n_agc_global
agc = dib7000m_read_word(state, 390);
if (agc > state->current_agc->split.min_thres)
split_offset = state->current_agc->split.min;
else if (agc < state->current_agc->split.max_thres)
split_offset = state->current_agc->split.max;
else
split_offset = state->current_agc->split.max *
(agc - state->current_agc->split.min_thres) /
(state->current_agc->split.max_thres - state->current_agc->split.min_thres);
dprintk( "AGC split_offset: %d",split_offset);
// P_agc_force_split and P_agc_split_offset
return dib7000m_write_word(state, 103, (dib7000m_read_word(state, 103) & 0xff00) | split_offset);
}
static int dib7000m_update_lna(struct dib7000m_state *state)
{
u16 dyn_gain;
if (state->cfg.update_lna) {
// read dyn_gain here (because it is demod-dependent and not fe)
dyn_gain = dib7000m_read_word(state, 390);
if (state->cfg.update_lna(&state->demod,dyn_gain)) { // LNA has changed
dib7000m_restart_agc(state);
return 1;
}
}
return 0;
}
static int dib7000m_set_agc_config(struct dib7000m_state *state, u8 band)
{
struct dibx000_agc_config *agc = NULL;
int i;
if (state->current_band == band && state->current_agc != NULL)
return 0;
state->current_band = band;
for (i = 0; i < state->cfg.agc_config_count; i++)
if (state->cfg.agc[i].band_caps & band) {
agc = &state->cfg.agc[i];
break;
}
if (agc == NULL) {
dprintk( "no valid AGC configuration found for band 0x%02x",band);
return -EINVAL;
}
state->current_agc = agc;
/* AGC */
dib7000m_write_word(state, 72 , agc->setup);
dib7000m_write_word(state, 73 , agc->inv_gain);
dib7000m_write_word(state, 74 , agc->time_stabiliz);
dib7000m_write_word(state, 97 , (agc->alpha_level << 12) | agc->thlock);
// Demod AGC loop configuration
dib7000m_write_word(state, 98, (agc->alpha_mant << 5) | agc->alpha_exp);
dib7000m_write_word(state, 99, (agc->beta_mant << 6) | agc->beta_exp);
dprintk( "WBD: ref: %d, sel: %d, active: %d, alpha: %d",
state->wbd_ref != 0 ? state->wbd_ref : agc->wbd_ref, agc->wbd_sel, !agc->perform_agc_softsplit, agc->wbd_sel);
/* AGC continued */
if (state->wbd_ref != 0)
dib7000m_write_word(state, 102, state->wbd_ref);
else // use default
dib7000m_write_word(state, 102, agc->wbd_ref);
dib7000m_write_word(state, 103, (agc->wbd_alpha << 9) | (agc->perform_agc_softsplit << 8) );
dib7000m_write_word(state, 104, agc->agc1_max);
dib7000m_write_word(state, 105, agc->agc1_min);
dib7000m_write_word(state, 106, agc->agc2_max);
dib7000m_write_word(state, 107, agc->agc2_min);
dib7000m_write_word(state, 108, (agc->agc1_pt1 << 8) | agc->agc1_pt2 );
dib7000m_write_word(state, 109, (agc->agc1_slope1 << 8) | agc->agc1_slope2);
dib7000m_write_word(state, 110, (agc->agc2_pt1 << 8) | agc->agc2_pt2);
dib7000m_write_word(state, 111, (agc->agc2_slope1 << 8) | agc->agc2_slope2);
if (state->revision > 0x4000) { // settings for the MC
dib7000m_write_word(state, 71, agc->agc1_pt3);
// dprintk( "929: %x %d %d",
// (dib7000m_read_word(state, 929) & 0xffe3) | (agc->wbd_inv << 4) | (agc->wbd_sel << 2), agc->wbd_inv, agc->wbd_sel);
dib7000m_write_word(state, 929, (dib7000m_read_word(state, 929) & 0xffe3) | (agc->wbd_inv << 4) | (agc->wbd_sel << 2));
} else {
// wrong default values
u16 b[9] = { 676, 696, 717, 737, 758, 778, 799, 819, 840 };
for (i = 0; i < 9; i++)
dib7000m_write_word(state, 88 + i, b[i]);
}
return 0;
}
static void dib7000m_update_timf(struct dib7000m_state *state)
{
u32 timf = (dib7000m_read_word(state, 436) << 16) | dib7000m_read_word(state, 437);
state->timf = timf * 160 / (state->current_bandwidth / 50);
dib7000m_write_word(state, 23, (u16) (timf >> 16));
dib7000m_write_word(state, 24, (u16) (timf & 0xffff));
dprintk( "updated timf_frequency: %d (default: %d)",state->timf, state->timf_default);
}
static int dib7000m_agc_startup(struct dvb_frontend *demod)
{
struct dtv_frontend_properties *ch = &demod->dtv_property_cache;
struct dib7000m_state *state = demod->demodulator_priv;
u16 cfg_72 = dib7000m_read_word(state, 72);
int ret = -1;
u8 *agc_state = &state->agc_state;
u8 agc_split;
switch (state->agc_state) {
case 0:
// set power-up level: interf+analog+AGC
dib7000m_set_power_mode(state, DIB7000M_POWER_INTERF_ANALOG_AGC);
dib7000m_set_adc_state(state, DIBX000_ADC_ON);
if (dib7000m_set_agc_config(state, BAND_OF_FREQUENCY(ch->frequency/1000)) != 0)
return -1;
ret = 7; /* ADC power up */
(*agc_state)++;
break;
case 1:
/* AGC initialization */
if (state->cfg.agc_control)
state->cfg.agc_control(&state->demod, 1);
dib7000m_write_word(state, 75, 32768);
if (!state->current_agc->perform_agc_softsplit) {
/* we are using the wbd - so slow AGC startup */
dib7000m_write_word(state, 103, 1 << 8); /* force 0 split on WBD and restart AGC */
(*agc_state)++;
ret = 5;
} else {
/* default AGC startup */
(*agc_state) = 4;
/* wait AGC rough lock time */
ret = 7;
}
dib7000m_restart_agc(state);
break;
case 2: /* fast split search path after 5sec */
dib7000m_write_word(state, 72, cfg_72 | (1 << 4)); /* freeze AGC loop */
dib7000m_write_word(state, 103, 2 << 9); /* fast split search 0.25kHz */
(*agc_state)++;
ret = 14;
break;
case 3: /* split search ended */
agc_split = (u8)dib7000m_read_word(state, 392); /* store the split value for the next time */
dib7000m_write_word(state, 75, dib7000m_read_word(state, 390)); /* set AGC gain start value */
dib7000m_write_word(state, 72, cfg_72 & ~(1 << 4)); /* std AGC loop */
dib7000m_write_word(state, 103, (state->current_agc->wbd_alpha << 9) | agc_split); /* standard split search */
dib7000m_restart_agc(state);
dprintk( "SPLIT %p: %hd", demod, agc_split);
(*agc_state)++;
ret = 5;
break;
case 4: /* LNA startup */
/* wait AGC accurate lock time */
ret = 7;
if (dib7000m_update_lna(state))
// wait only AGC rough lock time
ret = 5;
else
(*agc_state)++;
break;
case 5:
dib7000m_agc_soft_split(state);
if (state->cfg.agc_control)
state->cfg.agc_control(&state->demod, 0);
(*agc_state)++;
break;
default:
break;
}
return ret;
}
static void dib7000m_set_channel(struct dib7000m_state *state, struct dtv_frontend_properties *ch,
u8 seq)
{
u16 value, est[4];
dib7000m_set_bandwidth(state, BANDWIDTH_TO_KHZ(ch->bandwidth_hz));
/* nfft, guard, qam, alpha */
value = 0;
switch (ch->transmission_mode) {
case TRANSMISSION_MODE_2K: value |= (0 << 7); break;
case TRANSMISSION_MODE_4K: value |= (2 << 7); break;
default:
case TRANSMISSION_MODE_8K: value |= (1 << 7); break;
}
switch (ch->guard_interval) {
case GUARD_INTERVAL_1_32: value |= (0 << 5); break;
case GUARD_INTERVAL_1_16: value |= (1 << 5); break;
case GUARD_INTERVAL_1_4: value |= (3 << 5); break;
default:
case GUARD_INTERVAL_1_8: value |= (2 << 5); break;
}
switch (ch->modulation) {
case QPSK: value |= (0 << 3); break;
case QAM_16: value |= (1 << 3); break;
default:
case QAM_64: value |= (2 << 3); break;
}
switch (HIERARCHY_1) {
case HIERARCHY_2: value |= 2; break;
case HIERARCHY_4: value |= 4; break;
default:
case HIERARCHY_1: value |= 1; break;
}
dib7000m_write_word(state, 0, value);
dib7000m_write_word(state, 5, (seq << 4));
/* P_dintl_native, P_dintlv_inv, P_hrch, P_code_rate, P_select_hp */
value = 0;
if (1 != 0)
value |= (1 << 6);
if (ch->hierarchy == 1)
value |= (1 << 4);
if (1 == 1)
value |= 1;
switch ((ch->hierarchy == 0 || 1 == 1) ? ch->code_rate_HP : ch->code_rate_LP) {
case FEC_2_3: value |= (2 << 1); break;
case FEC_3_4: value |= (3 << 1); break;
case FEC_5_6: value |= (5 << 1); break;
case FEC_7_8: value |= (7 << 1); break;
default:
case FEC_1_2: value |= (1 << 1); break;
}
dib7000m_write_word(state, 267 + state->reg_offs, value);
/* offset loop parameters */
/* P_timf_alpha = 6, P_corm_alpha=6, P_corm_thres=0x80 */
dib7000m_write_word(state, 26, (6 << 12) | (6 << 8) | 0x80);
/* P_ctrl_inh_cor=0, P_ctrl_alpha_cor=4, P_ctrl_inh_isi=1, P_ctrl_alpha_isi=3, P_ctrl_inh_cor4=1, P_ctrl_alpha_cor4=3 */
dib7000m_write_word(state, 29, (0 << 14) | (4 << 10) | (1 << 9) | (3 << 5) | (1 << 4) | (0x3));
/* P_ctrl_freeze_pha_shift=0, P_ctrl_pha_off_max=3 */
dib7000m_write_word(state, 32, (0 << 4) | 0x3);
/* P_ctrl_sfreq_inh=0, P_ctrl_sfreq_step=5 */
dib7000m_write_word(state, 33, (0 << 4) | 0x5);
/* P_dvsy_sync_wait */
switch (ch->transmission_mode) {
case TRANSMISSION_MODE_8K: value = 256; break;
case TRANSMISSION_MODE_4K: value = 128; break;
case TRANSMISSION_MODE_2K:
default: value = 64; break;
}
switch (ch->guard_interval) {
case GUARD_INTERVAL_1_16: value *= 2; break;
case GUARD_INTERVAL_1_8: value *= 4; break;
case GUARD_INTERVAL_1_4: value *= 8; break;
default:
case GUARD_INTERVAL_1_32: value *= 1; break;
}
state->div_sync_wait = (value * 3) / 2 + 32; // add 50% SFN margin + compensate for one DVSY-fifo TODO
/* deactive the possibility of diversity reception if extended interleave - not for 7000MC */
/* P_dvsy_sync_mode = 0, P_dvsy_sync_enable=1, P_dvcb_comb_mode=2 */
if (1 == 1 || state->revision > 0x4000)
state->div_force_off = 0;
else
state->div_force_off = 1;
dib7000m_set_diversity_in(&state->demod, state->div_state);
/* channel estimation fine configuration */
switch (ch->modulation) {
case QAM_64:
est[0] = 0x0148; /* P_adp_regul_cnt 0.04 */
est[1] = 0xfff0; /* P_adp_noise_cnt -0.002 */
est[2] = 0x00a4; /* P_adp_regul_ext 0.02 */
est[3] = 0xfff8; /* P_adp_noise_ext -0.001 */
break;
case QAM_16:
est[0] = 0x023d; /* P_adp_regul_cnt 0.07 */
est[1] = 0xffdf; /* P_adp_noise_cnt -0.004 */
est[2] = 0x00a4; /* P_adp_regul_ext 0.02 */
est[3] = 0xfff0; /* P_adp_noise_ext -0.002 */
break;
default:
est[0] = 0x099a; /* P_adp_regul_cnt 0.3 */
est[1] = 0xffae; /* P_adp_noise_cnt -0.01 */
est[2] = 0x0333; /* P_adp_regul_ext 0.1 */
est[3] = 0xfff8; /* P_adp_noise_ext -0.002 */
break;
}
for (value = 0; value < 4; value++)
dib7000m_write_word(state, 214 + value + state->reg_offs, est[value]);
// set power-up level: autosearch
dib7000m_set_power_mode(state, DIB7000M_POWER_COR4_DINTLV_ICIRM_EQUAL_CFROD);
}
static int dib7000m_autosearch_start(struct dvb_frontend *demod)
{
struct dtv_frontend_properties *ch = &demod->dtv_property_cache;
struct dib7000m_state *state = demod->demodulator_priv;
struct dtv_frontend_properties schan;
int ret = 0;
u32 value, factor;
schan = *ch;
schan.modulation = QAM_64;
schan.guard_interval = GUARD_INTERVAL_1_32;
schan.transmission_mode = TRANSMISSION_MODE_8K;
schan.code_rate_HP = FEC_2_3;
schan.code_rate_LP = FEC_3_4;
schan.hierarchy = 0;
dib7000m_set_channel(state, &schan, 7);
factor = BANDWIDTH_TO_KHZ(schan.bandwidth_hz);
if (factor >= 5000)
factor = 1;
else
factor = 6;
// always use the setting for 8MHz here lock_time for 7,6 MHz are longer
value = 30 * state->internal_clk * factor;
ret |= dib7000m_write_word(state, 6, (u16) ((value >> 16) & 0xffff)); // lock0 wait time
ret |= dib7000m_write_word(state, 7, (u16) (value & 0xffff)); // lock0 wait time
value = 100 * state->internal_clk * factor;
ret |= dib7000m_write_word(state, 8, (u16) ((value >> 16) & 0xffff)); // lock1 wait time
ret |= dib7000m_write_word(state, 9, (u16) (value & 0xffff)); // lock1 wait time
value = 500 * state->internal_clk * factor;
ret |= dib7000m_write_word(state, 10, (u16) ((value >> 16) & 0xffff)); // lock2 wait time
ret |= dib7000m_write_word(state, 11, (u16) (value & 0xffff)); // lock2 wait time
// start search
value = dib7000m_read_word(state, 0);
ret |= dib7000m_write_word(state, 0, (u16) (value | (1 << 9)));
/* clear n_irq_pending */
if (state->revision == 0x4000)
dib7000m_write_word(state, 1793, 0);
else
dib7000m_read_word(state, 537);
ret |= dib7000m_write_word(state, 0, (u16) value);
return ret;
}
static int dib7000m_autosearch_irq(struct dib7000m_state *state, u16 reg)
{
u16 irq_pending = dib7000m_read_word(state, reg);
if (irq_pending & 0x1) { // failed
dprintk( "autosearch failed");
return 1;
}
if (irq_pending & 0x2) { // succeeded
dprintk( "autosearch succeeded");
return 2;
}
return 0; // still pending
}
static int dib7000m_autosearch_is_irq(struct dvb_frontend *demod)
{
struct dib7000m_state *state = demod->demodulator_priv;
if (state->revision == 0x4000)
return dib7000m_autosearch_irq(state, 1793);
else
return dib7000m_autosearch_irq(state, 537);
}
static int dib7000m_tune(struct dvb_frontend *demod)
{
struct dtv_frontend_properties *ch = &demod->dtv_property_cache;
struct dib7000m_state *state = demod->demodulator_priv;
int ret = 0;
u16 value;
// we are already tuned - just resuming from suspend
if (ch != NULL)
dib7000m_set_channel(state, ch, 0);
else
return -EINVAL;
// restart demod
ret |= dib7000m_write_word(state, 898, 0x4000);
ret |= dib7000m_write_word(state, 898, 0x0000);
msleep(45);
dib7000m_set_power_mode(state, DIB7000M_POWER_COR4_CRY_ESRAM_MOUT_NUD);
/* P_ctrl_inh_cor=0, P_ctrl_alpha_cor=4, P_ctrl_inh_isi=0, P_ctrl_alpha_isi=3, P_ctrl_inh_cor4=1, P_ctrl_alpha_cor4=3 */
ret |= dib7000m_write_word(state, 29, (0 << 14) | (4 << 10) | (0 << 9) | (3 << 5) | (1 << 4) | (0x3));
// never achieved a lock before - wait for timfreq to update
if (state->timf == 0)
msleep(200);
//dump_reg(state);
/* P_timf_alpha, P_corm_alpha=6, P_corm_thres=0x80 */
value = (6 << 8) | 0x80;
switch (ch->transmission_mode) {
case TRANSMISSION_MODE_2K: value |= (7 << 12); break;
case TRANSMISSION_MODE_4K: value |= (8 << 12); break;
default:
case TRANSMISSION_MODE_8K: value |= (9 << 12); break;
}
ret |= dib7000m_write_word(state, 26, value);
/* P_ctrl_freeze_pha_shift=0, P_ctrl_pha_off_max */
value = (0 << 4);
switch (ch->transmission_mode) {
case TRANSMISSION_MODE_2K: value |= 0x6; break;
case TRANSMISSION_MODE_4K: value |= 0x7; break;
default:
case TRANSMISSION_MODE_8K: value |= 0x8; break;
}
ret |= dib7000m_write_word(state, 32, value);
/* P_ctrl_sfreq_inh=0, P_ctrl_sfreq_step */
value = (0 << 4);
switch (ch->transmission_mode) {
case TRANSMISSION_MODE_2K: value |= 0x6; break;
case TRANSMISSION_MODE_4K: value |= 0x7; break;
default:
case TRANSMISSION_MODE_8K: value |= 0x8; break;
}
ret |= dib7000m_write_word(state, 33, value);
// we achieved a lock - it's time to update the timf freq
if ((dib7000m_read_word(state, 535) >> 6) & 0x1)
dib7000m_update_timf(state);
dib7000m_set_bandwidth(state, BANDWIDTH_TO_KHZ(ch->bandwidth_hz));
return ret;
}
static int dib7000m_wakeup(struct dvb_frontend *demod)
{
struct dib7000m_state *state = demod->demodulator_priv;
dib7000m_set_power_mode(state, DIB7000M_POWER_ALL);
if (dib7000m_set_adc_state(state, DIBX000_SLOW_ADC_ON) != 0)
dprintk( "could not start Slow ADC");
return 0;
}
static int dib7000m_sleep(struct dvb_frontend *demod)
{
struct dib7000m_state *st = demod->demodulator_priv;
dib7000m_set_output_mode(st, OUTMODE_HIGH_Z);
dib7000m_set_power_mode(st, DIB7000M_POWER_INTERFACE_ONLY);
return dib7000m_set_adc_state(st, DIBX000_SLOW_ADC_OFF) |
dib7000m_set_adc_state(st, DIBX000_ADC_OFF);
}
static int dib7000m_identify(struct dib7000m_state *state)
{
u16 value;
if ((value = dib7000m_read_word(state, 896)) != 0x01b3) {
dprintk( "wrong Vendor ID (0x%x)",value);
return -EREMOTEIO;
}
state->revision = dib7000m_read_word(state, 897);
if (state->revision != 0x4000 &&
state->revision != 0x4001 &&
state->revision != 0x4002 &&
state->revision != 0x4003) {
dprintk( "wrong Device ID (0x%x)",value);
return -EREMOTEIO;
}
/* protect this driver to be used with 7000PC */
if (state->revision == 0x4000 && dib7000m_read_word(state, 769) == 0x4000) {
dprintk( "this driver does not work with DiB7000PC");
return -EREMOTEIO;
}
switch (state->revision) {
case 0x4000: dprintk( "found DiB7000MA/PA/MB/PB"); break;
case 0x4001: state->reg_offs = 1; dprintk( "found DiB7000HC"); break;
case 0x4002: state->reg_offs = 1; dprintk( "found DiB7000MC"); break;
case 0x4003: state->reg_offs = 1; dprintk( "found DiB9000"); break;
}
return 0;
}
static int dib7000m_get_frontend(struct dvb_frontend* fe)
{
struct dtv_frontend_properties *fep = &fe->dtv_property_cache;
struct dib7000m_state *state = fe->demodulator_priv;
u16 tps = dib7000m_read_word(state,480);
fep->inversion = INVERSION_AUTO;
fep->bandwidth_hz = BANDWIDTH_TO_HZ(state->current_bandwidth);
switch ((tps >> 8) & 0x3) {
case 0: fep->transmission_mode = TRANSMISSION_MODE_2K; break;
case 1: fep->transmission_mode = TRANSMISSION_MODE_8K; break;
/* case 2: fep->transmission_mode = TRANSMISSION_MODE_4K; break; */
}
switch (tps & 0x3) {
case 0: fep->guard_interval = GUARD_INTERVAL_1_32; break;
case 1: fep->guard_interval = GUARD_INTERVAL_1_16; break;
case 2: fep->guard_interval = GUARD_INTERVAL_1_8; break;
case 3: fep->guard_interval = GUARD_INTERVAL_1_4; break;
}
switch ((tps >> 14) & 0x3) {
case 0: fep->modulation = QPSK; break;
case 1: fep->modulation = QAM_16; break;
case 2:
default: fep->modulation = QAM_64; break;
}
/* as long as the frontend_param structure is fixed for hierarchical transmission I refuse to use it */
/* (tps >> 13) & 0x1 == hrch is used, (tps >> 10) & 0x7 == alpha */
fep->hierarchy = HIERARCHY_NONE;
switch ((tps >> 5) & 0x7) {
case 1: fep->code_rate_HP = FEC_1_2; break;
case 2: fep->code_rate_HP = FEC_2_3; break;
case 3: fep->code_rate_HP = FEC_3_4; break;
case 5: fep->code_rate_HP = FEC_5_6; break;
case 7:
default: fep->code_rate_HP = FEC_7_8; break;
}
switch ((tps >> 2) & 0x7) {
case 1: fep->code_rate_LP = FEC_1_2; break;
case 2: fep->code_rate_LP = FEC_2_3; break;
case 3: fep->code_rate_LP = FEC_3_4; break;
case 5: fep->code_rate_LP = FEC_5_6; break;
case 7:
default: fep->code_rate_LP = FEC_7_8; break;
}
/* native interleaver: (dib7000m_read_word(state, 481) >> 5) & 0x1 */
return 0;
}
static int dib7000m_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *fep = &fe->dtv_property_cache;
struct dib7000m_state *state = fe->demodulator_priv;
int time, ret;
dib7000m_set_output_mode(state, OUTMODE_HIGH_Z);
dib7000m_set_bandwidth(state, BANDWIDTH_TO_KHZ(fep->bandwidth_hz));
if (fe->ops.tuner_ops.set_params)
fe->ops.tuner_ops.set_params(fe);
/* start up the AGC */
state->agc_state = 0;
do {
time = dib7000m_agc_startup(fe);
if (time != -1)
msleep(time);
} while (time != -1);
if (fep->transmission_mode == TRANSMISSION_MODE_AUTO ||
fep->guard_interval == GUARD_INTERVAL_AUTO ||
fep->modulation == QAM_AUTO ||
fep->code_rate_HP == FEC_AUTO) {
int i = 800, found;
dib7000m_autosearch_start(fe);
do {
msleep(1);
found = dib7000m_autosearch_is_irq(fe);
} while (found == 0 && i--);
dprintk("autosearch returns: %d",found);
if (found == 0 || found == 1)
return 0; // no channel found
dib7000m_get_frontend(fe);
}
ret = dib7000m_tune(fe);
/* make this a config parameter */
dib7000m_set_output_mode(state, OUTMODE_MPEG2_FIFO);
return ret;
}
static int dib7000m_read_status(struct dvb_frontend *fe, fe_status_t *stat)
{
struct dib7000m_state *state = fe->demodulator_priv;
u16 lock = dib7000m_read_word(state, 535);
*stat = 0;
if (lock & 0x8000)
*stat |= FE_HAS_SIGNAL;
if (lock & 0x3000)
*stat |= FE_HAS_CARRIER;
if (lock & 0x0100)
*stat |= FE_HAS_VITERBI;
if (lock & 0x0010)
*stat |= FE_HAS_SYNC;
if (lock & 0x0008)
*stat |= FE_HAS_LOCK;
return 0;
}
static int dib7000m_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct dib7000m_state *state = fe->demodulator_priv;
*ber = (dib7000m_read_word(state, 526) << 16) | dib7000m_read_word(state, 527);
return 0;
}
static int dib7000m_read_unc_blocks(struct dvb_frontend *fe, u32 *unc)
{
struct dib7000m_state *state = fe->demodulator_priv;
*unc = dib7000m_read_word(state, 534);
return 0;
}
static int dib7000m_read_signal_strength(struct dvb_frontend *fe, u16 *strength)
{
struct dib7000m_state *state = fe->demodulator_priv;
u16 val = dib7000m_read_word(state, 390);
*strength = 65535 - val;
return 0;
}
static int dib7000m_read_snr(struct dvb_frontend* fe, u16 *snr)
{
*snr = 0x0000;
return 0;
}
static int dib7000m_fe_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 1000;
return 0;
}
static void dib7000m_release(struct dvb_frontend *demod)
{
struct dib7000m_state *st = demod->demodulator_priv;
dibx000_exit_i2c_master(&st->i2c_master);
kfree(st);
}
struct i2c_adapter * dib7000m_get_i2c_master(struct dvb_frontend *demod, enum dibx000_i2c_interface intf, int gating)
{
struct dib7000m_state *st = demod->demodulator_priv;
return dibx000_get_i2c_adapter(&st->i2c_master, intf, gating);
}
EXPORT_SYMBOL(dib7000m_get_i2c_master);
int dib7000m_pid_filter_ctrl(struct dvb_frontend *fe, u8 onoff)
{
struct dib7000m_state *state = fe->demodulator_priv;
u16 val = dib7000m_read_word(state, 294 + state->reg_offs) & 0xffef;
val |= (onoff & 0x1) << 4;
dprintk("PID filter enabled %d", onoff);
return dib7000m_write_word(state, 294 + state->reg_offs, val);
}
EXPORT_SYMBOL(dib7000m_pid_filter_ctrl);
int dib7000m_pid_filter(struct dvb_frontend *fe, u8 id, u16 pid, u8 onoff)
{
struct dib7000m_state *state = fe->demodulator_priv;
dprintk("PID filter: index %x, PID %d, OnOff %d", id, pid, onoff);
return dib7000m_write_word(state, 300 + state->reg_offs + id,
onoff ? (1 << 13) | pid : 0);
}
EXPORT_SYMBOL(dib7000m_pid_filter);
#if 0
/* used with some prototype boards */
int dib7000m_i2c_enumeration(struct i2c_adapter *i2c, int no_of_demods,
u8 default_addr, struct dib7000m_config cfg[])
{
struct dib7000m_state st = { .i2c_adap = i2c };
int k = 0;
u8 new_addr = 0;
for (k = no_of_demods-1; k >= 0; k--) {
st.cfg = cfg[k];
/* designated i2c address */
new_addr = (0x40 + k) << 1;
st.i2c_addr = new_addr;
if (dib7000m_identify(&st) != 0) {
st.i2c_addr = default_addr;
if (dib7000m_identify(&st) != 0) {
dprintk("DiB7000M #%d: not identified", k);
return -EIO;
}
}
/* start diversity to pull_down div_str - just for i2c-enumeration */
dib7000m_set_output_mode(&st, OUTMODE_DIVERSITY);
dib7000m_write_word(&st, 1796, 0x0); // select DVB-T output
/* set new i2c address and force divstart */
dib7000m_write_word(&st, 1794, (new_addr << 2) | 0x2);
dprintk("IC %d initialized (to i2c_address 0x%x)", k, new_addr);
}
for (k = 0; k < no_of_demods; k++) {
st.cfg = cfg[k];
st.i2c_addr = (0x40 + k) << 1;
// unforce divstr
dib7000m_write_word(&st,1794, st.i2c_addr << 2);
/* deactivate div - it was just for i2c-enumeration */
dib7000m_set_output_mode(&st, OUTMODE_HIGH_Z);
}
return 0;
}
EXPORT_SYMBOL(dib7000m_i2c_enumeration);
#endif
static struct dvb_frontend_ops dib7000m_ops;
struct dvb_frontend * dib7000m_attach(struct i2c_adapter *i2c_adap, u8 i2c_addr, struct dib7000m_config *cfg)
{
struct dvb_frontend *demod;
struct dib7000m_state *st;
st = kzalloc(sizeof(struct dib7000m_state), GFP_KERNEL);
if (st == NULL)
return NULL;
memcpy(&st->cfg, cfg, sizeof(struct dib7000m_config));
st->i2c_adap = i2c_adap;
st->i2c_addr = i2c_addr;
demod = &st->demod;
demod->demodulator_priv = st;
memcpy(&st->demod.ops, &dib7000m_ops, sizeof(struct dvb_frontend_ops));
mutex_init(&st->i2c_buffer_lock);
st->timf_default = cfg->bw->timf;
if (dib7000m_identify(st) != 0)
goto error;
if (st->revision == 0x4000)
dibx000_init_i2c_master(&st->i2c_master, DIB7000, st->i2c_adap, st->i2c_addr);
else
dibx000_init_i2c_master(&st->i2c_master, DIB7000MC, st->i2c_adap, st->i2c_addr);
dib7000m_demod_reset(st);
return demod;
error:
kfree(st);
return NULL;
}
EXPORT_SYMBOL(dib7000m_attach);
static struct dvb_frontend_ops dib7000m_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "DiBcom 7000MA/MB/PA/PB/MC",
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 62500,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_RECOVER |
FE_CAN_HIERARCHY_AUTO,
},
.release = dib7000m_release,
.init = dib7000m_wakeup,
.sleep = dib7000m_sleep,
.set_frontend = dib7000m_set_frontend,
.get_tune_settings = dib7000m_fe_get_tune_settings,
.get_frontend = dib7000m_get_frontend,
.read_status = dib7000m_read_status,
.read_ber = dib7000m_read_ber,
.read_signal_strength = dib7000m_read_signal_strength,
.read_snr = dib7000m_read_snr,
.read_ucblocks = dib7000m_read_unc_blocks,
};
MODULE_AUTHOR("Patrick Boettcher <pboettcher@dibcom.fr>");
MODULE_DESCRIPTION("Driver for the DiBcom 7000MA/MB/PA/PB/MC COFDM demodulator");
MODULE_LICENSE("GPL");
| gpl-2.0 |
XPerience-AOSP-Lollipop/android_kernel_sony_lbmsm8960t | arch/xtensa/kernel/asm-offsets.c | 7929 | 4640 | /*
* arch/xtensa/kernel/asm-offsets.c
*
* Generates definitions from c-type structures used by assembly sources.
*
* 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) 2005 Tensilica Inc.
*
* Chris Zankel <chris@zankel.net>
*/
#include <asm/processor.h>
#include <asm/coprocessor.h>
#include <linux/types.h>
#include <linux/stddef.h>
#include <linux/thread_info.h>
#include <linux/ptrace.h>
#include <linux/mm.h>
#include <linux/kbuild.h>
#include <asm/ptrace.h>
#include <asm/uaccess.h>
int main(void)
{
/* struct pt_regs */
DEFINE(PT_PC, offsetof (struct pt_regs, pc));
DEFINE(PT_PS, offsetof (struct pt_regs, ps));
DEFINE(PT_DEPC, offsetof (struct pt_regs, depc));
DEFINE(PT_EXCCAUSE, offsetof (struct pt_regs, exccause));
DEFINE(PT_EXCVADDR, offsetof (struct pt_regs, excvaddr));
DEFINE(PT_DEBUGCAUSE, offsetof (struct pt_regs, debugcause));
DEFINE(PT_WMASK, offsetof (struct pt_regs, wmask));
DEFINE(PT_LBEG, offsetof (struct pt_regs, lbeg));
DEFINE(PT_LEND, offsetof (struct pt_regs, lend));
DEFINE(PT_LCOUNT, offsetof (struct pt_regs, lcount));
DEFINE(PT_SAR, offsetof (struct pt_regs, sar));
DEFINE(PT_ICOUNTLEVEL, offsetof (struct pt_regs, icountlevel));
DEFINE(PT_SYSCALL, offsetof (struct pt_regs, syscall));
DEFINE(PT_AREG, offsetof (struct pt_regs, areg[0]));
DEFINE(PT_AREG0, offsetof (struct pt_regs, areg[0]));
DEFINE(PT_AREG1, offsetof (struct pt_regs, areg[1]));
DEFINE(PT_AREG2, offsetof (struct pt_regs, areg[2]));
DEFINE(PT_AREG3, offsetof (struct pt_regs, areg[3]));
DEFINE(PT_AREG4, offsetof (struct pt_regs, areg[4]));
DEFINE(PT_AREG5, offsetof (struct pt_regs, areg[5]));
DEFINE(PT_AREG6, offsetof (struct pt_regs, areg[6]));
DEFINE(PT_AREG7, offsetof (struct pt_regs, areg[7]));
DEFINE(PT_AREG8, offsetof (struct pt_regs, areg[8]));
DEFINE(PT_AREG9, offsetof (struct pt_regs, areg[9]));
DEFINE(PT_AREG10, offsetof (struct pt_regs, areg[10]));
DEFINE(PT_AREG11, offsetof (struct pt_regs, areg[11]));
DEFINE(PT_AREG12, offsetof (struct pt_regs, areg[12]));
DEFINE(PT_AREG13, offsetof (struct pt_regs, areg[13]));
DEFINE(PT_AREG14, offsetof (struct pt_regs, areg[14]));
DEFINE(PT_AREG15, offsetof (struct pt_regs, areg[15]));
DEFINE(PT_WINDOWBASE, offsetof (struct pt_regs, windowbase));
DEFINE(PT_WINDOWSTART, offsetof(struct pt_regs, windowstart));
DEFINE(PT_SIZE, sizeof(struct pt_regs));
DEFINE(PT_AREG_END, offsetof (struct pt_regs, areg[XCHAL_NUM_AREGS]));
DEFINE(PT_USER_SIZE, offsetof(struct pt_regs, areg[XCHAL_NUM_AREGS]));
DEFINE(PT_XTREGS_OPT, offsetof(struct pt_regs, xtregs_opt));
DEFINE(XTREGS_OPT_SIZE, sizeof(xtregs_opt_t));
/* struct task_struct */
DEFINE(TASK_PTRACE, offsetof (struct task_struct, ptrace));
DEFINE(TASK_MM, offsetof (struct task_struct, mm));
DEFINE(TASK_ACTIVE_MM, offsetof (struct task_struct, active_mm));
DEFINE(TASK_PID, offsetof (struct task_struct, pid));
DEFINE(TASK_THREAD, offsetof (struct task_struct, thread));
DEFINE(TASK_THREAD_INFO, offsetof (struct task_struct, stack));
DEFINE(TASK_STRUCT_SIZE, sizeof (struct task_struct));
/* struct thread_info (offset from start_struct) */
DEFINE(THREAD_RA, offsetof (struct task_struct, thread.ra));
DEFINE(THREAD_SP, offsetof (struct task_struct, thread.sp));
DEFINE(THREAD_CPENABLE, offsetof (struct thread_info, cpenable));
#if XTENSA_HAVE_COPROCESSORS
DEFINE(THREAD_XTREGS_CP0, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP1, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP2, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP3, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP4, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP5, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP6, offsetof (struct thread_info, xtregs_cp));
DEFINE(THREAD_XTREGS_CP7, offsetof (struct thread_info, xtregs_cp));
#endif
DEFINE(THREAD_XTREGS_USER, offsetof (struct thread_info, xtregs_user));
DEFINE(XTREGS_USER_SIZE, sizeof(xtregs_user_t));
DEFINE(THREAD_CURRENT_DS, offsetof (struct task_struct, thread.current_ds));
/* struct mm_struct */
DEFINE(MM_USERS, offsetof(struct mm_struct, mm_users));
DEFINE(MM_PGD, offsetof (struct mm_struct, pgd));
DEFINE(MM_CONTEXT, offsetof (struct mm_struct, context));
/* struct page */
DEFINE(PAGE_FLAGS, offsetof(struct page, flags));
/* constants */
DEFINE(_CLONE_VM, CLONE_VM);
DEFINE(_CLONE_UNTRACED, CLONE_UNTRACED);
DEFINE(PG_ARCH_1, PG_arch_1);
return 0;
}
| gpl-2.0 |
aosp-lb-nozomi/android_kernel_sony_msm8660 | drivers/media/rc/keymaps/rc-technisat-usb2.c | 9465 | 2794 | /* rc-technisat-usb2.c - Keytable for SkyStar HD USB
*
* Copyright (C) 2010 Patrick Boettcher,
* Kernel Labs Inc. PO Box 745, St James, NY 11780
*
* Development was sponsored by Technisat Digital UK Limited, whose
* registered office is Witan Gate House 500 - 600 Witan Gate West,
* Milton Keynes, MK9 1SH
*
* 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.
*
*
* 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.
*
* THIS PROGRAM IS PROVIDED "AS IS" AND BOTH THE COPYRIGHT HOLDER AND
* TECHNISAT DIGITAL UK LTD DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS PROGRAM INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. NEITHER THE COPYRIGHT HOLDER
* NOR TECHNISAT DIGITAL UK LIMITED SHALL 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 PROGRAM. See the
* GNU General Public License for more details.
*/
#include <media/rc-map.h>
#include <linux/module.h>
static struct rc_map_table technisat_usb2[] = {
{0x0a0c, KEY_POWER},
{0x0a01, KEY_1},
{0x0a02, KEY_2},
{0x0a03, KEY_3},
{0x0a0d, KEY_MUTE},
{0x0a04, KEY_4},
{0x0a05, KEY_5},
{0x0a06, KEY_6},
{0x0a38, KEY_VIDEO}, /* EXT */
{0x0a07, KEY_7},
{0x0a08, KEY_8},
{0x0a09, KEY_9},
{0x0a00, KEY_0},
{0x0a4f, KEY_INFO},
{0x0a20, KEY_CHANNELUP},
{0x0a52, KEY_MENU},
{0x0a11, KEY_VOLUMEUP},
{0x0a57, KEY_OK},
{0x0a10, KEY_VOLUMEDOWN},
{0x0a2f, KEY_EPG},
{0x0a21, KEY_CHANNELDOWN},
{0x0a22, KEY_REFRESH},
{0x0a3c, KEY_TEXT},
{0x0a76, KEY_ENTER}, /* HOOK */
{0x0a0f, KEY_HELP},
{0x0a6b, KEY_RED},
{0x0a6c, KEY_GREEN},
{0x0a6d, KEY_YELLOW},
{0x0a6e, KEY_BLUE},
{0x0a29, KEY_STOP},
{0x0a23, KEY_LANGUAGE},
{0x0a53, KEY_TV},
{0x0a0a, KEY_PROGRAM},
};
static struct rc_map_list technisat_usb2_map = {
.map = {
.scan = technisat_usb2,
.size = ARRAY_SIZE(technisat_usb2),
.rc_type = RC_TYPE_RC5,
.name = RC_MAP_TECHNISAT_USB2,
}
};
static int __init init_rc_map(void)
{
return rc_map_register(&technisat_usb2_map);
}
static void __exit exit_rc_map(void)
{
rc_map_unregister(&technisat_usb2_map);
}
module_init(init_rc_map)
module_exit(exit_rc_map)
MODULE_AUTHOR("Patrick Boettcher <pboettcher@kernellabs.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
robutest/uclinux | drivers/parport/procfs.c | 9465 | 12560 | /* Sysctl interface for parport devices.
*
* Authors: David Campbell
* Tim Waugh <tim@cyberelk.demon.co.uk>
* Philip Blundell <philb@gnu.org>
* Andrea Arcangeli
* Riccardo Facchetti <fizban@tin.it>
*
* based on work by Grant Guenther <grant@torque.net>
* and Philip Blundell
*
* Cleaned up include files - Russell King <linux@arm.uk.linux.org>
*/
#include <linux/string.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/parport.h>
#include <linux/ctype.h>
#include <linux/sysctl.h>
#include <asm/uaccess.h>
#if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
#define PARPORT_MIN_TIMESLICE_VALUE 1ul
#define PARPORT_MAX_TIMESLICE_VALUE ((unsigned long) HZ)
#define PARPORT_MIN_SPINTIME_VALUE 1
#define PARPORT_MAX_SPINTIME_VALUE 1000
static int do_active_device(ctl_table *table, int write,
void __user *result, size_t *lenp, loff_t *ppos)
{
struct parport *port = (struct parport *)table->extra1;
char buffer[256];
struct pardevice *dev;
int len = 0;
if (write) /* can't happen anyway */
return -EACCES;
if (*ppos) {
*lenp = 0;
return 0;
}
for (dev = port->devices; dev ; dev = dev->next) {
if(dev == port->cad) {
len += sprintf(buffer, "%s\n", dev->name);
}
}
if(!len) {
len += sprintf(buffer, "%s\n", "none");
}
if (len > *lenp)
len = *lenp;
else
*lenp = len;
*ppos += len;
return copy_to_user(result, buffer, len) ? -EFAULT : 0;
}
#ifdef CONFIG_PARPORT_1284
static int do_autoprobe(ctl_table *table, int write,
void __user *result, size_t *lenp, loff_t *ppos)
{
struct parport_device_info *info = table->extra2;
const char *str;
char buffer[256];
int len = 0;
if (write) /* permissions stop this */
return -EACCES;
if (*ppos) {
*lenp = 0;
return 0;
}
if ((str = info->class_name) != NULL)
len += sprintf (buffer + len, "CLASS:%s;\n", str);
if ((str = info->model) != NULL)
len += sprintf (buffer + len, "MODEL:%s;\n", str);
if ((str = info->mfr) != NULL)
len += sprintf (buffer + len, "MANUFACTURER:%s;\n", str);
if ((str = info->description) != NULL)
len += sprintf (buffer + len, "DESCRIPTION:%s;\n", str);
if ((str = info->cmdset) != NULL)
len += sprintf (buffer + len, "COMMAND SET:%s;\n", str);
if (len > *lenp)
len = *lenp;
else
*lenp = len;
*ppos += len;
return copy_to_user (result, buffer, len) ? -EFAULT : 0;
}
#endif /* IEEE1284.3 support. */
static int do_hardware_base_addr (ctl_table *table, int write,
void __user *result,
size_t *lenp, loff_t *ppos)
{
struct parport *port = (struct parport *)table->extra1;
char buffer[20];
int len = 0;
if (*ppos) {
*lenp = 0;
return 0;
}
if (write) /* permissions prevent this anyway */
return -EACCES;
len += sprintf (buffer, "%lu\t%lu\n", port->base, port->base_hi);
if (len > *lenp)
len = *lenp;
else
*lenp = len;
*ppos += len;
return copy_to_user(result, buffer, len) ? -EFAULT : 0;
}
static int do_hardware_irq (ctl_table *table, int write,
void __user *result,
size_t *lenp, loff_t *ppos)
{
struct parport *port = (struct parport *)table->extra1;
char buffer[20];
int len = 0;
if (*ppos) {
*lenp = 0;
return 0;
}
if (write) /* permissions prevent this anyway */
return -EACCES;
len += sprintf (buffer, "%d\n", port->irq);
if (len > *lenp)
len = *lenp;
else
*lenp = len;
*ppos += len;
return copy_to_user(result, buffer, len) ? -EFAULT : 0;
}
static int do_hardware_dma (ctl_table *table, int write,
void __user *result,
size_t *lenp, loff_t *ppos)
{
struct parport *port = (struct parport *)table->extra1;
char buffer[20];
int len = 0;
if (*ppos) {
*lenp = 0;
return 0;
}
if (write) /* permissions prevent this anyway */
return -EACCES;
len += sprintf (buffer, "%d\n", port->dma);
if (len > *lenp)
len = *lenp;
else
*lenp = len;
*ppos += len;
return copy_to_user(result, buffer, len) ? -EFAULT : 0;
}
static int do_hardware_modes (ctl_table *table, int write,
void __user *result,
size_t *lenp, loff_t *ppos)
{
struct parport *port = (struct parport *)table->extra1;
char buffer[40];
int len = 0;
if (*ppos) {
*lenp = 0;
return 0;
}
if (write) /* permissions prevent this anyway */
return -EACCES;
{
#define printmode(x) {if(port->modes&PARPORT_MODE_##x){len+=sprintf(buffer+len,"%s%s",f?",":"",#x);f++;}}
int f = 0;
printmode(PCSPP);
printmode(TRISTATE);
printmode(COMPAT);
printmode(EPP);
printmode(ECP);
printmode(DMA);
#undef printmode
}
buffer[len++] = '\n';
if (len > *lenp)
len = *lenp;
else
*lenp = len;
*ppos += len;
return copy_to_user(result, buffer, len) ? -EFAULT : 0;
}
#define PARPORT_PORT_DIR(CHILD) { .procname = NULL, .mode = 0555, .child = CHILD }
#define PARPORT_PARPORT_DIR(CHILD) { .procname = "parport", \
.mode = 0555, .child = CHILD }
#define PARPORT_DEV_DIR(CHILD) { .procname = "dev", .mode = 0555, .child = CHILD }
#define PARPORT_DEVICES_ROOT_DIR { .procname = "devices", \
.mode = 0555, .child = NULL }
static const unsigned long parport_min_timeslice_value =
PARPORT_MIN_TIMESLICE_VALUE;
static const unsigned long parport_max_timeslice_value =
PARPORT_MAX_TIMESLICE_VALUE;
static const int parport_min_spintime_value =
PARPORT_MIN_SPINTIME_VALUE;
static const int parport_max_spintime_value =
PARPORT_MAX_SPINTIME_VALUE;
struct parport_sysctl_table {
struct ctl_table_header *sysctl_header;
ctl_table vars[12];
ctl_table device_dir[2];
ctl_table port_dir[2];
ctl_table parport_dir[2];
ctl_table dev_dir[2];
};
static const struct parport_sysctl_table parport_sysctl_template = {
.sysctl_header = NULL,
{
{
.procname = "spintime",
.data = NULL,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = (void*) &parport_min_spintime_value,
.extra2 = (void*) &parport_max_spintime_value
},
{
.procname = "base-addr",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_hardware_base_addr
},
{
.procname = "irq",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_hardware_irq
},
{
.procname = "dma",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_hardware_dma
},
{
.procname = "modes",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_hardware_modes
},
PARPORT_DEVICES_ROOT_DIR,
#ifdef CONFIG_PARPORT_1284
{
.procname = "autoprobe",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_autoprobe
},
{
.procname = "autoprobe0",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_autoprobe
},
{
.procname = "autoprobe1",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_autoprobe
},
{
.procname = "autoprobe2",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_autoprobe
},
{
.procname = "autoprobe3",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_autoprobe
},
#endif /* IEEE 1284 support */
{}
},
{
{
.procname = "active",
.data = NULL,
.maxlen = 0,
.mode = 0444,
.proc_handler = do_active_device
},
{}
},
{
PARPORT_PORT_DIR(NULL),
{}
},
{
PARPORT_PARPORT_DIR(NULL),
{}
},
{
PARPORT_DEV_DIR(NULL),
{}
}
};
struct parport_device_sysctl_table
{
struct ctl_table_header *sysctl_header;
ctl_table vars[2];
ctl_table device_dir[2];
ctl_table devices_root_dir[2];
ctl_table port_dir[2];
ctl_table parport_dir[2];
ctl_table dev_dir[2];
};
static const struct parport_device_sysctl_table
parport_device_sysctl_template = {
.sysctl_header = NULL,
{
{
.procname = "timeslice",
.data = NULL,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = proc_doulongvec_ms_jiffies_minmax,
.extra1 = (void*) &parport_min_timeslice_value,
.extra2 = (void*) &parport_max_timeslice_value
},
},
{
{
.procname = NULL,
.data = NULL,
.maxlen = 0,
.mode = 0555,
.child = NULL
},
{}
},
{
PARPORT_DEVICES_ROOT_DIR,
{}
},
{
PARPORT_PORT_DIR(NULL),
{}
},
{
PARPORT_PARPORT_DIR(NULL),
{}
},
{
PARPORT_DEV_DIR(NULL),
{}
}
};
struct parport_default_sysctl_table
{
struct ctl_table_header *sysctl_header;
ctl_table vars[3];
ctl_table default_dir[2];
ctl_table parport_dir[2];
ctl_table dev_dir[2];
};
static struct parport_default_sysctl_table
parport_default_sysctl_table = {
.sysctl_header = NULL,
{
{
.procname = "timeslice",
.data = &parport_default_timeslice,
.maxlen = sizeof(parport_default_timeslice),
.mode = 0644,
.proc_handler = proc_doulongvec_ms_jiffies_minmax,
.extra1 = (void*) &parport_min_timeslice_value,
.extra2 = (void*) &parport_max_timeslice_value
},
{
.procname = "spintime",
.data = &parport_default_spintime,
.maxlen = sizeof(parport_default_spintime),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = (void*) &parport_min_spintime_value,
.extra2 = (void*) &parport_max_spintime_value
},
{}
},
{
{
.procname = "default",
.mode = 0555,
.child = parport_default_sysctl_table.vars
},
{}
},
{
PARPORT_PARPORT_DIR(parport_default_sysctl_table.default_dir),
{}
},
{
PARPORT_DEV_DIR(parport_default_sysctl_table.parport_dir),
{}
}
};
int parport_proc_register(struct parport *port)
{
struct parport_sysctl_table *t;
int i;
t = kmalloc(sizeof(*t), GFP_KERNEL);
if (t == NULL)
return -ENOMEM;
memcpy(t, &parport_sysctl_template, sizeof(*t));
t->device_dir[0].extra1 = port;
for (i = 0; i < 5; i++)
t->vars[i].extra1 = port;
t->vars[0].data = &port->spintime;
t->vars[5].child = t->device_dir;
for (i = 0; i < 5; i++)
t->vars[6 + i].extra2 = &port->probe_info[i];
t->port_dir[0].procname = port->name;
t->port_dir[0].child = t->vars;
t->parport_dir[0].child = t->port_dir;
t->dev_dir[0].child = t->parport_dir;
t->sysctl_header = register_sysctl_table(t->dev_dir);
if (t->sysctl_header == NULL) {
kfree(t);
t = NULL;
}
port->sysctl_table = t;
return 0;
}
int parport_proc_unregister(struct parport *port)
{
if (port->sysctl_table) {
struct parport_sysctl_table *t = port->sysctl_table;
port->sysctl_table = NULL;
unregister_sysctl_table(t->sysctl_header);
kfree(t);
}
return 0;
}
int parport_device_proc_register(struct pardevice *device)
{
struct parport_device_sysctl_table *t;
struct parport * port = device->port;
t = kmalloc(sizeof(*t), GFP_KERNEL);
if (t == NULL)
return -ENOMEM;
memcpy(t, &parport_device_sysctl_template, sizeof(*t));
t->dev_dir[0].child = t->parport_dir;
t->parport_dir[0].child = t->port_dir;
t->port_dir[0].procname = port->name;
t->port_dir[0].child = t->devices_root_dir;
t->devices_root_dir[0].child = t->device_dir;
t->device_dir[0].procname = device->name;
t->device_dir[0].child = t->vars;
t->vars[0].data = &device->timeslice;
t->sysctl_header = register_sysctl_table(t->dev_dir);
if (t->sysctl_header == NULL) {
kfree(t);
t = NULL;
}
device->sysctl_table = t;
return 0;
}
int parport_device_proc_unregister(struct pardevice *device)
{
if (device->sysctl_table) {
struct parport_device_sysctl_table *t = device->sysctl_table;
device->sysctl_table = NULL;
unregister_sysctl_table(t->sysctl_header);
kfree(t);
}
return 0;
}
static int __init parport_default_proc_register(void)
{
parport_default_sysctl_table.sysctl_header =
register_sysctl_table(parport_default_sysctl_table.dev_dir);
return 0;
}
static void __exit parport_default_proc_unregister(void)
{
if (parport_default_sysctl_table.sysctl_header) {
unregister_sysctl_table(parport_default_sysctl_table.
sysctl_header);
parport_default_sysctl_table.sysctl_header = NULL;
}
}
#else /* no sysctl or no procfs*/
int parport_proc_register(struct parport *pp)
{
return 0;
}
int parport_proc_unregister(struct parport *pp)
{
return 0;
}
int parport_device_proc_register(struct pardevice *device)
{
return 0;
}
int parport_device_proc_unregister(struct pardevice *device)
{
return 0;
}
static int __init parport_default_proc_register (void)
{
return 0;
}
static void __exit parport_default_proc_unregister (void)
{
}
#endif
module_init(parport_default_proc_register)
module_exit(parport_default_proc_unregister)
| gpl-2.0 |
DC07/android_kernel_lge_dory | net/802/psnap.c | 12793 | 3535 | /*
* SNAP data link layer. Derived from 802.2
*
* Alan Cox <alan@lxorguk.ukuu.org.uk>,
* from the 802.2 layer by Greg Page.
* Merged in additions from Greg Page's psnap.c.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/datalink.h>
#include <net/llc.h>
#include <net/psnap.h>
#include <linux/mm.h>
#include <linux/in.h>
#include <linux/init.h>
#include <linux/rculist.h>
static LIST_HEAD(snap_list);
static DEFINE_SPINLOCK(snap_lock);
static struct llc_sap *snap_sap;
/*
* Find a snap client by matching the 5 bytes.
*/
static struct datalink_proto *find_snap_client(const unsigned char *desc)
{
struct datalink_proto *proto = NULL, *p;
list_for_each_entry_rcu(p, &snap_list, node) {
if (!memcmp(p->type, desc, 5)) {
proto = p;
break;
}
}
return proto;
}
/*
* A SNAP packet has arrived
*/
static int snap_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
int rc = 1;
struct datalink_proto *proto;
static struct packet_type snap_packet_type = {
.type = cpu_to_be16(ETH_P_SNAP),
};
if (unlikely(!pskb_may_pull(skb, 5)))
goto drop;
rcu_read_lock();
proto = find_snap_client(skb_transport_header(skb));
if (proto) {
/* Pass the frame on. */
skb->transport_header += 5;
skb_pull_rcsum(skb, 5);
rc = proto->rcvfunc(skb, dev, &snap_packet_type, orig_dev);
}
rcu_read_unlock();
if (unlikely(!proto))
goto drop;
out:
return rc;
drop:
kfree_skb(skb);
goto out;
}
/*
* Put a SNAP header on a frame and pass to 802.2
*/
static int snap_request(struct datalink_proto *dl,
struct sk_buff *skb, u8 *dest)
{
memcpy(skb_push(skb, 5), dl->type, 5);
llc_build_and_send_ui_pkt(snap_sap, skb, dest, snap_sap->laddr.lsap);
return 0;
}
/*
* Set up the SNAP layer
*/
EXPORT_SYMBOL(register_snap_client);
EXPORT_SYMBOL(unregister_snap_client);
static const char snap_err_msg[] __initconst =
KERN_CRIT "SNAP - unable to register with 802.2\n";
static int __init snap_init(void)
{
snap_sap = llc_sap_open(0xAA, snap_rcv);
if (!snap_sap) {
printk(snap_err_msg);
return -EBUSY;
}
return 0;
}
module_init(snap_init);
static void __exit snap_exit(void)
{
llc_sap_put(snap_sap);
}
module_exit(snap_exit);
/*
* Register SNAP clients. We don't yet use this for IP.
*/
struct datalink_proto *register_snap_client(const unsigned char *desc,
int (*rcvfunc)(struct sk_buff *,
struct net_device *,
struct packet_type *,
struct net_device *))
{
struct datalink_proto *proto = NULL;
spin_lock_bh(&snap_lock);
if (find_snap_client(desc))
goto out;
proto = kmalloc(sizeof(*proto), GFP_ATOMIC);
if (proto) {
memcpy(proto->type, desc, 5);
proto->rcvfunc = rcvfunc;
proto->header_length = 5 + 3; /* snap + 802.2 */
proto->request = snap_request;
list_add_rcu(&proto->node, &snap_list);
}
out:
spin_unlock_bh(&snap_lock);
return proto;
}
/*
* Unregister SNAP clients. Protocols no longer want to play with us ...
*/
void unregister_snap_client(struct datalink_proto *proto)
{
spin_lock_bh(&snap_lock);
list_del_rcu(&proto->node);
spin_unlock_bh(&snap_lock);
synchronize_net();
kfree(proto);
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
squirrel20/linux-4.8.15 | drivers/gpio/gpio-ep93xx.c | 250 | 10627 | /*
* Generic EP93xx GPIO handling
*
* Copyright (c) 2008 Ryan Mallon
* Copyright (c) 2011 H Hartley Sweeten <hsweeten@visionengravers.com>
*
* Based on code originally from:
* linux/arch/arm/mach-ep93xx/core.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/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/gpio/driver.h>
/* FIXME: this is here for gpio_to_irq() - get rid of this! */
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <mach/gpio-ep93xx.h>
#define irq_to_gpio(irq) ((irq) - gpio_to_irq(0))
struct ep93xx_gpio {
void __iomem *mmio_base;
struct gpio_chip gc[8];
};
/*************************************************************************
* Interrupt handling for EP93xx on-chip GPIOs
*************************************************************************/
static unsigned char gpio_int_unmasked[3];
static unsigned char gpio_int_enabled[3];
static unsigned char gpio_int_type1[3];
static unsigned char gpio_int_type2[3];
static unsigned char gpio_int_debounce[3];
/* Port ordering is: A B F */
static const u8 int_type1_register_offset[3] = { 0x90, 0xac, 0x4c };
static const u8 int_type2_register_offset[3] = { 0x94, 0xb0, 0x50 };
static const u8 eoi_register_offset[3] = { 0x98, 0xb4, 0x54 };
static const u8 int_en_register_offset[3] = { 0x9c, 0xb8, 0x58 };
static const u8 int_debounce_register_offset[3] = { 0xa8, 0xc4, 0x64 };
static void ep93xx_gpio_update_int_params(unsigned port)
{
BUG_ON(port > 2);
writeb_relaxed(0, EP93XX_GPIO_REG(int_en_register_offset[port]));
writeb_relaxed(gpio_int_type2[port],
EP93XX_GPIO_REG(int_type2_register_offset[port]));
writeb_relaxed(gpio_int_type1[port],
EP93XX_GPIO_REG(int_type1_register_offset[port]));
writeb(gpio_int_unmasked[port] & gpio_int_enabled[port],
EP93XX_GPIO_REG(int_en_register_offset[port]));
}
static void ep93xx_gpio_int_debounce(unsigned int irq, bool enable)
{
int line = irq_to_gpio(irq);
int port = line >> 3;
int port_mask = 1 << (line & 7);
if (enable)
gpio_int_debounce[port] |= port_mask;
else
gpio_int_debounce[port] &= ~port_mask;
writeb(gpio_int_debounce[port],
EP93XX_GPIO_REG(int_debounce_register_offset[port]));
}
static void ep93xx_gpio_ab_irq_handler(struct irq_desc *desc)
{
unsigned char status;
int i;
status = readb(EP93XX_GPIO_A_INT_STATUS);
for (i = 0; i < 8; i++) {
if (status & (1 << i)) {
int gpio_irq = gpio_to_irq(EP93XX_GPIO_LINE_A(0)) + i;
generic_handle_irq(gpio_irq);
}
}
status = readb(EP93XX_GPIO_B_INT_STATUS);
for (i = 0; i < 8; i++) {
if (status & (1 << i)) {
int gpio_irq = gpio_to_irq(EP93XX_GPIO_LINE_B(0)) + i;
generic_handle_irq(gpio_irq);
}
}
}
static void ep93xx_gpio_f_irq_handler(struct irq_desc *desc)
{
/*
* map discontiguous hw irq range to continuous sw irq range:
*
* IRQ_EP93XX_GPIO{0..7}MUX -> gpio_to_irq(EP93XX_GPIO_LINE_F({0..7})
*/
unsigned int irq = irq_desc_get_irq(desc);
int port_f_idx = ((irq + 1) & 7) ^ 4; /* {19..22,47..50} -> {0..7} */
int gpio_irq = gpio_to_irq(EP93XX_GPIO_LINE_F(0)) + port_f_idx;
generic_handle_irq(gpio_irq);
}
static void ep93xx_gpio_irq_ack(struct irq_data *d)
{
int line = irq_to_gpio(d->irq);
int port = line >> 3;
int port_mask = 1 << (line & 7);
if (irqd_get_trigger_type(d) == IRQ_TYPE_EDGE_BOTH) {
gpio_int_type2[port] ^= port_mask; /* switch edge direction */
ep93xx_gpio_update_int_params(port);
}
writeb(port_mask, EP93XX_GPIO_REG(eoi_register_offset[port]));
}
static void ep93xx_gpio_irq_mask_ack(struct irq_data *d)
{
int line = irq_to_gpio(d->irq);
int port = line >> 3;
int port_mask = 1 << (line & 7);
if (irqd_get_trigger_type(d) == IRQ_TYPE_EDGE_BOTH)
gpio_int_type2[port] ^= port_mask; /* switch edge direction */
gpio_int_unmasked[port] &= ~port_mask;
ep93xx_gpio_update_int_params(port);
writeb(port_mask, EP93XX_GPIO_REG(eoi_register_offset[port]));
}
static void ep93xx_gpio_irq_mask(struct irq_data *d)
{
int line = irq_to_gpio(d->irq);
int port = line >> 3;
gpio_int_unmasked[port] &= ~(1 << (line & 7));
ep93xx_gpio_update_int_params(port);
}
static void ep93xx_gpio_irq_unmask(struct irq_data *d)
{
int line = irq_to_gpio(d->irq);
int port = line >> 3;
gpio_int_unmasked[port] |= 1 << (line & 7);
ep93xx_gpio_update_int_params(port);
}
/*
* gpio_int_type1 controls whether the interrupt is level (0) or
* edge (1) triggered, while gpio_int_type2 controls whether it
* triggers on low/falling (0) or high/rising (1).
*/
static int ep93xx_gpio_irq_type(struct irq_data *d, unsigned int type)
{
const int gpio = irq_to_gpio(d->irq);
const int port = gpio >> 3;
const int port_mask = 1 << (gpio & 7);
irq_flow_handler_t handler;
gpio_direction_input(gpio);
switch (type) {
case IRQ_TYPE_EDGE_RISING:
gpio_int_type1[port] |= port_mask;
gpio_int_type2[port] |= port_mask;
handler = handle_edge_irq;
break;
case IRQ_TYPE_EDGE_FALLING:
gpio_int_type1[port] |= port_mask;
gpio_int_type2[port] &= ~port_mask;
handler = handle_edge_irq;
break;
case IRQ_TYPE_LEVEL_HIGH:
gpio_int_type1[port] &= ~port_mask;
gpio_int_type2[port] |= port_mask;
handler = handle_level_irq;
break;
case IRQ_TYPE_LEVEL_LOW:
gpio_int_type1[port] &= ~port_mask;
gpio_int_type2[port] &= ~port_mask;
handler = handle_level_irq;
break;
case IRQ_TYPE_EDGE_BOTH:
gpio_int_type1[port] |= port_mask;
/* set initial polarity based on current input level */
if (gpio_get_value(gpio))
gpio_int_type2[port] &= ~port_mask; /* falling */
else
gpio_int_type2[port] |= port_mask; /* rising */
handler = handle_edge_irq;
break;
default:
return -EINVAL;
}
irq_set_handler_locked(d, handler);
gpio_int_enabled[port] |= port_mask;
ep93xx_gpio_update_int_params(port);
return 0;
}
static struct irq_chip ep93xx_gpio_irq_chip = {
.name = "GPIO",
.irq_ack = ep93xx_gpio_irq_ack,
.irq_mask_ack = ep93xx_gpio_irq_mask_ack,
.irq_mask = ep93xx_gpio_irq_mask,
.irq_unmask = ep93xx_gpio_irq_unmask,
.irq_set_type = ep93xx_gpio_irq_type,
};
static void ep93xx_gpio_init_irq(void)
{
int gpio_irq;
for (gpio_irq = gpio_to_irq(0);
gpio_irq <= gpio_to_irq(EP93XX_GPIO_LINE_MAX_IRQ); ++gpio_irq) {
irq_set_chip_and_handler(gpio_irq, &ep93xx_gpio_irq_chip,
handle_level_irq);
irq_clear_status_flags(gpio_irq, IRQ_NOREQUEST);
}
irq_set_chained_handler(IRQ_EP93XX_GPIO_AB,
ep93xx_gpio_ab_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO0MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO1MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO2MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO3MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO4MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO5MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO6MUX,
ep93xx_gpio_f_irq_handler);
irq_set_chained_handler(IRQ_EP93XX_GPIO7MUX,
ep93xx_gpio_f_irq_handler);
}
/*************************************************************************
* gpiolib interface for EP93xx on-chip GPIOs
*************************************************************************/
struct ep93xx_gpio_bank {
const char *label;
int data;
int dir;
int base;
bool has_debounce;
};
#define EP93XX_GPIO_BANK(_label, _data, _dir, _base, _debounce) \
{ \
.label = _label, \
.data = _data, \
.dir = _dir, \
.base = _base, \
.has_debounce = _debounce, \
}
static struct ep93xx_gpio_bank ep93xx_gpio_banks[] = {
EP93XX_GPIO_BANK("A", 0x00, 0x10, 0, true),
EP93XX_GPIO_BANK("B", 0x04, 0x14, 8, true),
EP93XX_GPIO_BANK("C", 0x08, 0x18, 40, false),
EP93XX_GPIO_BANK("D", 0x0c, 0x1c, 24, false),
EP93XX_GPIO_BANK("E", 0x20, 0x24, 32, false),
EP93XX_GPIO_BANK("F", 0x30, 0x34, 16, true),
EP93XX_GPIO_BANK("G", 0x38, 0x3c, 48, false),
EP93XX_GPIO_BANK("H", 0x40, 0x44, 56, false),
};
static int ep93xx_gpio_set_debounce(struct gpio_chip *chip,
unsigned offset, unsigned debounce)
{
int gpio = chip->base + offset;
int irq = gpio_to_irq(gpio);
if (irq < 0)
return -EINVAL;
ep93xx_gpio_int_debounce(irq, debounce ? true : false);
return 0;
}
/*
* Map GPIO A0..A7 (0..7) to irq 64..71,
* B0..B7 (7..15) to irq 72..79, and
* F0..F7 (16..24) to irq 80..87.
*/
static int ep93xx_gpio_to_irq(struct gpio_chip *chip, unsigned offset)
{
int gpio = chip->base + offset;
if (gpio > EP93XX_GPIO_LINE_MAX_IRQ)
return -EINVAL;
return 64 + gpio;
}
static int ep93xx_gpio_add_bank(struct gpio_chip *gc, struct device *dev,
void __iomem *mmio_base, struct ep93xx_gpio_bank *bank)
{
void __iomem *data = mmio_base + bank->data;
void __iomem *dir = mmio_base + bank->dir;
int err;
err = bgpio_init(gc, dev, 1, data, NULL, NULL, dir, NULL, 0);
if (err)
return err;
gc->label = bank->label;
gc->base = bank->base;
if (bank->has_debounce) {
gc->set_debounce = ep93xx_gpio_set_debounce;
gc->to_irq = ep93xx_gpio_to_irq;
}
return devm_gpiochip_add_data(dev, gc, NULL);
}
static int ep93xx_gpio_probe(struct platform_device *pdev)
{
struct ep93xx_gpio *ep93xx_gpio;
struct resource *res;
int i;
struct device *dev = &pdev->dev;
ep93xx_gpio = devm_kzalloc(dev, sizeof(struct ep93xx_gpio), GFP_KERNEL);
if (!ep93xx_gpio)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ep93xx_gpio->mmio_base = devm_ioremap_resource(dev, res);
if (IS_ERR(ep93xx_gpio->mmio_base))
return PTR_ERR(ep93xx_gpio->mmio_base);
for (i = 0; i < ARRAY_SIZE(ep93xx_gpio_banks); i++) {
struct gpio_chip *gc = &ep93xx_gpio->gc[i];
struct ep93xx_gpio_bank *bank = &ep93xx_gpio_banks[i];
if (ep93xx_gpio_add_bank(gc, &pdev->dev,
ep93xx_gpio->mmio_base, bank))
dev_warn(&pdev->dev, "Unable to add gpio bank %s\n",
bank->label);
}
ep93xx_gpio_init_irq();
return 0;
}
static struct platform_driver ep93xx_gpio_driver = {
.driver = {
.name = "gpio-ep93xx",
},
.probe = ep93xx_gpio_probe,
};
static int __init ep93xx_gpio_init(void)
{
return platform_driver_register(&ep93xx_gpio_driver);
}
postcore_initcall(ep93xx_gpio_init);
MODULE_AUTHOR("Ryan Mallon <ryan@bluewatersys.com> "
"H Hartley Sweeten <hsweeten@visionengravers.com>");
MODULE_DESCRIPTION("EP93XX GPIO driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
darkspr1te/kernel_samsung_msm8660_shv-e160L | arch/x86/kernel/process_32.c | 506 | 10129 | /*
* Copyright (C) 1995 Linus Torvalds
*
* Pentium III FXSR, SSE support
* Gareth Hughes <gareth@valinux.com>, May 2000
*/
/*
* This file handles the architecture-dependent parts of process handling..
*/
#include <linux/stackprotector.h>
#include <linux/cpu.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/elfcore.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/user.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/mc146818rtc.h>
#include <linux/module.h>
#include <linux/kallsyms.h>
#include <linux/ptrace.h>
#include <linux/personality.h>
#include <linux/tick.h>
#include <linux/percpu.h>
#include <linux/prctl.h>
#include <linux/ftrace.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/kdebug.h>
#include <asm/pgtable.h>
#include <asm/system.h>
#include <asm/ldt.h>
#include <asm/processor.h>
#include <asm/i387.h>
#include <asm/desc.h>
#ifdef CONFIG_MATH_EMULATION
#include <asm/math_emu.h>
#endif
#include <linux/err.h>
#include <asm/tlbflush.h>
#include <asm/cpu.h>
#include <asm/idle.h>
#include <asm/syscalls.h>
#include <asm/debugreg.h>
asmlinkage void ret_from_fork(void) __asm__("ret_from_fork");
/*
* Return saved PC of a blocked thread.
*/
unsigned long thread_saved_pc(struct task_struct *tsk)
{
return ((unsigned long *)tsk->thread.sp)[3];
}
#ifndef CONFIG_SMP
static inline void play_dead(void)
{
BUG();
}
#endif
/*
* The idle thread. There's no useful work to be
* done, so just try to conserve power and have a
* low exit latency (ie sit in a loop waiting for
* somebody to say that they'd like to reschedule)
*/
void cpu_idle(void)
{
int cpu = smp_processor_id();
/*
* If we're the non-boot CPU, nothing set the stack canary up
* for us. CPU0 already has it initialized but no harm in
* doing it again. This is a good place for updating it, as
* we wont ever return from this function (so the invalid
* canaries already on the stack wont ever trigger).
*/
boot_init_stack_canary();
current_thread_info()->status |= TS_POLLING;
/* endless idle loop with no priority at all */
while (1) {
tick_nohz_stop_sched_tick(1);
idle_notifier_call_chain(IDLE_START);
while (!need_resched()) {
check_pgt_cache();
rmb();
if (cpu_is_offline(cpu))
play_dead();
local_irq_disable();
/* Don't trace irqs off for idle */
stop_critical_timings();
pm_idle();
start_critical_timings();
}
idle_notifier_call_chain(IDLE_END);
tick_nohz_restart_sched_tick();
preempt_enable_no_resched();
schedule();
preempt_disable();
}
}
void __show_regs(struct pt_regs *regs, int all)
{
unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L;
unsigned long d0, d1, d2, d3, d6, d7;
unsigned long sp;
unsigned short ss, gs;
if (user_mode_vm(regs)) {
sp = regs->sp;
ss = regs->ss & 0xffff;
gs = get_user_gs(regs);
} else {
sp = kernel_stack_pointer(regs);
savesegment(ss, ss);
savesegment(gs, gs);
}
show_regs_common();
printk(KERN_DEFAULT "EIP: %04x:[<%08lx>] EFLAGS: %08lx CPU: %d\n",
(u16)regs->cs, regs->ip, regs->flags,
smp_processor_id());
print_symbol("EIP is at %s\n", regs->ip);
printk(KERN_DEFAULT "EAX: %08lx EBX: %08lx ECX: %08lx EDX: %08lx\n",
regs->ax, regs->bx, regs->cx, regs->dx);
printk(KERN_DEFAULT "ESI: %08lx EDI: %08lx EBP: %08lx ESP: %08lx\n",
regs->si, regs->di, regs->bp, sp);
printk(KERN_DEFAULT " DS: %04x ES: %04x FS: %04x GS: %04x SS: %04x\n",
(u16)regs->ds, (u16)regs->es, (u16)regs->fs, gs, ss);
if (!all)
return;
cr0 = read_cr0();
cr2 = read_cr2();
cr3 = read_cr3();
cr4 = read_cr4_safe();
printk(KERN_DEFAULT "CR0: %08lx CR2: %08lx CR3: %08lx CR4: %08lx\n",
cr0, cr2, cr3, cr4);
get_debugreg(d0, 0);
get_debugreg(d1, 1);
get_debugreg(d2, 2);
get_debugreg(d3, 3);
printk(KERN_DEFAULT "DR0: %08lx DR1: %08lx DR2: %08lx DR3: %08lx\n",
d0, d1, d2, d3);
get_debugreg(d6, 6);
get_debugreg(d7, 7);
printk(KERN_DEFAULT "DR6: %08lx DR7: %08lx\n",
d6, d7);
}
void release_thread(struct task_struct *dead_task)
{
BUG_ON(dead_task->mm);
release_vm86_irqs(dead_task);
}
/*
* This gets called before we allocate a new thread and copy
* the current task into it.
*/
void prepare_to_copy(struct task_struct *tsk)
{
unlazy_fpu(tsk);
}
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long unused,
struct task_struct *p, struct pt_regs *regs)
{
struct pt_regs *childregs;
struct task_struct *tsk;
int err;
childregs = task_pt_regs(p);
*childregs = *regs;
childregs->ax = 0;
childregs->sp = sp;
p->thread.sp = (unsigned long) childregs;
p->thread.sp0 = (unsigned long) (childregs+1);
p->thread.ip = (unsigned long) ret_from_fork;
task_user_gs(p) = get_user_gs(regs);
p->thread.io_bitmap_ptr = NULL;
tsk = current;
err = -ENOMEM;
memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
if (unlikely(test_tsk_thread_flag(tsk, TIF_IO_BITMAP))) {
p->thread.io_bitmap_ptr = kmemdup(tsk->thread.io_bitmap_ptr,
IO_BITMAP_BYTES, GFP_KERNEL);
if (!p->thread.io_bitmap_ptr) {
p->thread.io_bitmap_max = 0;
return -ENOMEM;
}
set_tsk_thread_flag(p, TIF_IO_BITMAP);
}
err = 0;
/*
* Set a new TLS for the child thread?
*/
if (clone_flags & CLONE_SETTLS)
err = do_set_thread_area(p, -1,
(struct user_desc __user *)childregs->si, 0);
if (err && p->thread.io_bitmap_ptr) {
kfree(p->thread.io_bitmap_ptr);
p->thread.io_bitmap_max = 0;
}
return err;
}
void
start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp)
{
set_user_gs(regs, 0);
regs->fs = 0;
regs->ds = __USER_DS;
regs->es = __USER_DS;
regs->ss = __USER_DS;
regs->cs = __USER_CS;
regs->ip = new_ip;
regs->sp = new_sp;
/*
* Free the old FP and other extended state
*/
free_thread_xstate(current);
}
EXPORT_SYMBOL_GPL(start_thread);
/*
* switch_to(x,yn) should switch tasks from x to y.
*
* We fsave/fwait so that an exception goes off at the right time
* (as a call from the fsave or fwait in effect) rather than to
* the wrong process. Lazy FP saving no longer makes any sense
* with modern CPU's, and this simplifies a lot of things (SMP
* and UP become the same).
*
* NOTE! We used to use the x86 hardware context switching. The
* reason for not using it any more becomes apparent when you
* try to recover gracefully from saved state that is no longer
* valid (stale segment register values in particular). With the
* hardware task-switch, there is no way to fix up bad state in
* a reasonable manner.
*
* The fact that Intel documents the hardware task-switching to
* be slow is a fairly red herring - this code is not noticeably
* faster. However, there _is_ some room for improvement here,
* so the performance issues may eventually be a valid point.
* More important, however, is the fact that this allows us much
* more flexibility.
*
* The return value (in %ax) will be the "prev" task after
* the task-switch, and shows up in ret_from_fork in entry.S,
* for example.
*/
__notrace_funcgraph struct task_struct *
__switch_to(struct task_struct *prev_p, struct task_struct *next_p)
{
struct thread_struct *prev = &prev_p->thread,
*next = &next_p->thread;
int cpu = smp_processor_id();
struct tss_struct *tss = &per_cpu(init_tss, cpu);
fpu_switch_t fpu;
/* never put a printk in __switch_to... printk() calls wake_up*() indirectly */
fpu = switch_fpu_prepare(prev_p, next_p);
/*
* Reload esp0.
*/
load_sp0(tss, next);
/*
* Save away %gs. No need to save %fs, as it was saved on the
* stack on entry. No need to save %es and %ds, as those are
* always kernel segments while inside the kernel. Doing this
* before setting the new TLS descriptors avoids the situation
* where we temporarily have non-reloadable segments in %fs
* and %gs. This could be an issue if the NMI handler ever
* used %fs or %gs (it does not today), or if the kernel is
* running inside of a hypervisor layer.
*/
lazy_save_gs(prev->gs);
/*
* Load the per-thread Thread-Local Storage descriptor.
*/
load_TLS(next, cpu);
/*
* Restore IOPL if needed. In normal use, the flags restore
* in the switch assembly will handle this. But if the kernel
* is running virtualized at a non-zero CPL, the popf will
* not restore flags, so it must be done in a separate step.
*/
if (get_kernel_rpl() && unlikely(prev->iopl != next->iopl))
set_iopl_mask(next->iopl);
/*
* Now maybe handle debug registers and/or IO bitmaps
*/
if (unlikely(task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV ||
task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT))
__switch_to_xtra(prev_p, next_p, tss);
/*
* Leave lazy mode, flushing any hypercalls made here.
* This must be done before restoring TLS segments so
* the GDT and LDT are properly updated, and must be
* done before math_state_restore, so the TS bit is up
* to date.
*/
arch_end_context_switch(next_p);
/*
* Restore %gs if needed (which is common)
*/
if (prev->gs | next->gs)
lazy_load_gs(next->gs);
switch_fpu_finish(next_p, fpu);
percpu_write(current_task, next_p);
return prev_p;
}
#define top_esp (THREAD_SIZE - sizeof(unsigned long))
#define top_ebp (THREAD_SIZE - 2*sizeof(unsigned long))
unsigned long get_wchan(struct task_struct *p)
{
unsigned long bp, sp, ip;
unsigned long stack_page;
int count = 0;
if (!p || p == current || p->state == TASK_RUNNING)
return 0;
stack_page = (unsigned long)task_stack_page(p);
sp = p->thread.sp;
if (!stack_page || sp < stack_page || sp > top_esp+stack_page)
return 0;
/* include/asm-i386/system.h:switch_to() pushes bp last. */
bp = *(unsigned long *) sp;
do {
if (bp < stack_page || bp > top_ebp+stack_page)
return 0;
ip = *(unsigned long *) (bp+4);
if (!in_sched_functions(ip))
return ip;
bp = *(unsigned long *) bp;
} while (count++ < 16);
return 0;
}
| gpl-2.0 |
pccr10001/Kernel-2.6.32.61-for-PDK-7105 | drivers/net/ixp2000/ixpdev.c | 506 | 10792 | /*
* IXP2000 MSF network device driver
* Copyright (C) 2004, 2005 Lennert Buytenhek <buytenh@wantstofly.org>
* Dedicated to Marija Kulikova.
*
* 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/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <asm/hardware/uengine.h>
#include <asm/io.h>
#include "ixp2400_rx.ucode"
#include "ixp2400_tx.ucode"
#include "ixpdev_priv.h"
#include "ixpdev.h"
#include "pm3386.h"
#define DRV_MODULE_VERSION "0.2"
static int nds_count;
static struct net_device **nds;
static int nds_open;
static void (*set_port_admin_status)(int port, int up);
static struct ixpdev_rx_desc * const rx_desc =
(struct ixpdev_rx_desc *)(IXP2000_SRAM0_VIRT_BASE + RX_BUF_DESC_BASE);
static struct ixpdev_tx_desc * const tx_desc =
(struct ixpdev_tx_desc *)(IXP2000_SRAM0_VIRT_BASE + TX_BUF_DESC_BASE);
static int tx_pointer;
static int ixpdev_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct ixpdev_priv *ip = netdev_priv(dev);
struct ixpdev_tx_desc *desc;
int entry;
unsigned long flags;
if (unlikely(skb->len > PAGE_SIZE)) {
/* @@@ Count drops. */
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
entry = tx_pointer;
tx_pointer = (tx_pointer + 1) % TX_BUF_COUNT;
desc = tx_desc + entry;
desc->pkt_length = skb->len;
desc->channel = ip->channel;
skb_copy_and_csum_dev(skb, phys_to_virt(desc->buf_addr));
dev_kfree_skb(skb);
ixp2000_reg_write(RING_TX_PENDING,
TX_BUF_DESC_BASE + (entry * sizeof(struct ixpdev_tx_desc)));
dev->trans_start = jiffies;
local_irq_save(flags);
ip->tx_queue_entries++;
if (ip->tx_queue_entries == TX_BUF_COUNT_PER_CHAN)
netif_stop_queue(dev);
local_irq_restore(flags);
return NETDEV_TX_OK;
}
static int ixpdev_rx(struct net_device *dev, int processed, int budget)
{
while (processed < budget) {
struct ixpdev_rx_desc *desc;
struct sk_buff *skb;
void *buf;
u32 _desc;
_desc = ixp2000_reg_read(RING_RX_DONE);
if (_desc == 0)
return 0;
desc = rx_desc +
((_desc - RX_BUF_DESC_BASE) / sizeof(struct ixpdev_rx_desc));
buf = phys_to_virt(desc->buf_addr);
if (desc->pkt_length < 4 || desc->pkt_length > PAGE_SIZE) {
printk(KERN_ERR "ixp2000: rx err, length %d\n",
desc->pkt_length);
goto err;
}
if (desc->channel < 0 || desc->channel >= nds_count) {
printk(KERN_ERR "ixp2000: rx err, channel %d\n",
desc->channel);
goto err;
}
/* @@@ Make FCS stripping configurable. */
desc->pkt_length -= 4;
if (unlikely(!netif_running(nds[desc->channel])))
goto err;
skb = netdev_alloc_skb(dev, desc->pkt_length + 2);
if (likely(skb != NULL)) {
skb_reserve(skb, 2);
skb_copy_to_linear_data(skb, buf, desc->pkt_length);
skb_put(skb, desc->pkt_length);
skb->protocol = eth_type_trans(skb, nds[desc->channel]);
netif_receive_skb(skb);
}
err:
ixp2000_reg_write(RING_RX_PENDING, _desc);
processed++;
}
return processed;
}
/* dev always points to nds[0]. */
static int ixpdev_poll(struct napi_struct *napi, int budget)
{
struct ixpdev_priv *ip = container_of(napi, struct ixpdev_priv, napi);
struct net_device *dev = ip->dev;
int rx;
rx = 0;
do {
ixp2000_reg_write(IXP2000_IRQ_THD_RAW_STATUS_A_0, 0x00ff);
rx = ixpdev_rx(dev, rx, budget);
if (rx >= budget)
break;
} while (ixp2000_reg_read(IXP2000_IRQ_THD_RAW_STATUS_A_0) & 0x00ff);
napi_complete(napi);
ixp2000_reg_write(IXP2000_IRQ_THD_ENABLE_SET_A_0, 0x00ff);
return rx;
}
static void ixpdev_tx_complete(void)
{
int channel;
u32 wake;
wake = 0;
while (1) {
struct ixpdev_priv *ip;
u32 desc;
int entry;
desc = ixp2000_reg_read(RING_TX_DONE);
if (desc == 0)
break;
/* @@@ Check whether entries come back in order. */
entry = (desc - TX_BUF_DESC_BASE) / sizeof(struct ixpdev_tx_desc);
channel = tx_desc[entry].channel;
if (channel < 0 || channel >= nds_count) {
printk(KERN_ERR "ixp2000: txcomp channel index "
"out of bounds (%d, %.8i, %d)\n",
channel, (unsigned int)desc, entry);
continue;
}
ip = netdev_priv(nds[channel]);
if (ip->tx_queue_entries == TX_BUF_COUNT_PER_CHAN)
wake |= 1 << channel;
ip->tx_queue_entries--;
}
for (channel = 0; wake != 0; channel++) {
if (wake & (1 << channel)) {
netif_wake_queue(nds[channel]);
wake &= ~(1 << channel);
}
}
}
static irqreturn_t ixpdev_interrupt(int irq, void *dev_id)
{
u32 status;
status = ixp2000_reg_read(IXP2000_IRQ_THD_STATUS_A_0);
if (status == 0)
return IRQ_NONE;
/*
* Any of the eight receive units signaled RX?
*/
if (status & 0x00ff) {
struct net_device *dev = nds[0];
struct ixpdev_priv *ip = netdev_priv(dev);
ixp2000_reg_wrb(IXP2000_IRQ_THD_ENABLE_CLEAR_A_0, 0x00ff);
if (likely(napi_schedule_prep(&ip->napi))) {
__napi_schedule(&ip->napi);
} else {
printk(KERN_CRIT "ixp2000: irq while polling!!\n");
}
}
/*
* Any of the eight transmit units signaled TXdone?
*/
if (status & 0xff00) {
ixp2000_reg_wrb(IXP2000_IRQ_THD_RAW_STATUS_A_0, 0xff00);
ixpdev_tx_complete();
}
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void ixpdev_poll_controller(struct net_device *dev)
{
disable_irq(IRQ_IXP2000_THDA0);
ixpdev_interrupt(IRQ_IXP2000_THDA0, dev);
enable_irq(IRQ_IXP2000_THDA0);
}
#endif
static int ixpdev_open(struct net_device *dev)
{
struct ixpdev_priv *ip = netdev_priv(dev);
int err;
napi_enable(&ip->napi);
if (!nds_open++) {
err = request_irq(IRQ_IXP2000_THDA0, ixpdev_interrupt,
IRQF_SHARED, "ixp2000_eth", nds);
if (err) {
nds_open--;
napi_disable(&ip->napi);
return err;
}
ixp2000_reg_write(IXP2000_IRQ_THD_ENABLE_SET_A_0, 0xffff);
}
set_port_admin_status(ip->channel, 1);
netif_start_queue(dev);
return 0;
}
static int ixpdev_close(struct net_device *dev)
{
struct ixpdev_priv *ip = netdev_priv(dev);
netif_stop_queue(dev);
napi_disable(&ip->napi);
set_port_admin_status(ip->channel, 0);
if (!--nds_open) {
ixp2000_reg_write(IXP2000_IRQ_THD_ENABLE_CLEAR_A_0, 0xffff);
free_irq(IRQ_IXP2000_THDA0, nds);
}
return 0;
}
static struct net_device_stats *ixpdev_get_stats(struct net_device *dev)
{
struct ixpdev_priv *ip = netdev_priv(dev);
pm3386_get_stats(ip->channel, &(dev->stats));
return &(dev->stats);
}
static const struct net_device_ops ixpdev_netdev_ops = {
.ndo_open = ixpdev_open,
.ndo_stop = ixpdev_close,
.ndo_start_xmit = ixpdev_xmit,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_get_stats = ixpdev_get_stats,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = ixpdev_poll_controller,
#endif
};
struct net_device *ixpdev_alloc(int channel, int sizeof_priv)
{
struct net_device *dev;
struct ixpdev_priv *ip;
dev = alloc_etherdev(sizeof_priv);
if (dev == NULL)
return NULL;
dev->netdev_ops = &ixpdev_netdev_ops;
dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM;
ip = netdev_priv(dev);
ip->dev = dev;
netif_napi_add(dev, &ip->napi, ixpdev_poll, 64);
ip->channel = channel;
ip->tx_queue_entries = 0;
return dev;
}
int ixpdev_init(int __nds_count, struct net_device **__nds,
void (*__set_port_admin_status)(int port, int up))
{
int i;
int err;
BUILD_BUG_ON(RX_BUF_COUNT > 192 || TX_BUF_COUNT > 192);
printk(KERN_INFO "IXP2000 MSF ethernet driver %s\n", DRV_MODULE_VERSION);
nds_count = __nds_count;
nds = __nds;
set_port_admin_status = __set_port_admin_status;
for (i = 0; i < RX_BUF_COUNT; i++) {
void *buf;
buf = (void *)get_zeroed_page(GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
while (--i >= 0)
free_page((unsigned long)phys_to_virt(rx_desc[i].buf_addr));
goto err_out;
}
rx_desc[i].buf_addr = virt_to_phys(buf);
rx_desc[i].buf_length = PAGE_SIZE;
}
/* @@@ Maybe we shouldn't be preallocating TX buffers. */
for (i = 0; i < TX_BUF_COUNT; i++) {
void *buf;
buf = (void *)get_zeroed_page(GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
while (--i >= 0)
free_page((unsigned long)phys_to_virt(tx_desc[i].buf_addr));
goto err_free_rx;
}
tx_desc[i].buf_addr = virt_to_phys(buf);
}
/* 256 entries, ring status set means 'empty', base address 0x0000. */
ixp2000_reg_write(RING_RX_PENDING_BASE, 0x44000000);
ixp2000_reg_write(RING_RX_PENDING_HEAD, 0x00000000);
ixp2000_reg_write(RING_RX_PENDING_TAIL, 0x00000000);
/* 256 entries, ring status set means 'full', base address 0x0400. */
ixp2000_reg_write(RING_RX_DONE_BASE, 0x40000400);
ixp2000_reg_write(RING_RX_DONE_HEAD, 0x00000000);
ixp2000_reg_write(RING_RX_DONE_TAIL, 0x00000000);
for (i = 0; i < RX_BUF_COUNT; i++) {
ixp2000_reg_write(RING_RX_PENDING,
RX_BUF_DESC_BASE + (i * sizeof(struct ixpdev_rx_desc)));
}
ixp2000_uengine_load(0, &ixp2400_rx);
ixp2000_uengine_start_contexts(0, 0xff);
/* 256 entries, ring status set means 'empty', base address 0x0800. */
ixp2000_reg_write(RING_TX_PENDING_BASE, 0x44000800);
ixp2000_reg_write(RING_TX_PENDING_HEAD, 0x00000000);
ixp2000_reg_write(RING_TX_PENDING_TAIL, 0x00000000);
/* 256 entries, ring status set means 'full', base address 0x0c00. */
ixp2000_reg_write(RING_TX_DONE_BASE, 0x40000c00);
ixp2000_reg_write(RING_TX_DONE_HEAD, 0x00000000);
ixp2000_reg_write(RING_TX_DONE_TAIL, 0x00000000);
ixp2000_uengine_load(1, &ixp2400_tx);
ixp2000_uengine_start_contexts(1, 0xff);
for (i = 0; i < nds_count; i++) {
err = register_netdev(nds[i]);
if (err) {
while (--i >= 0)
unregister_netdev(nds[i]);
goto err_free_tx;
}
}
for (i = 0; i < nds_count; i++) {
printk(KERN_INFO "%s: IXP2000 MSF ethernet (port %d), "
"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x.\n", nds[i]->name, i,
nds[i]->dev_addr[0], nds[i]->dev_addr[1],
nds[i]->dev_addr[2], nds[i]->dev_addr[3],
nds[i]->dev_addr[4], nds[i]->dev_addr[5]);
}
return 0;
err_free_tx:
for (i = 0; i < TX_BUF_COUNT; i++)
free_page((unsigned long)phys_to_virt(tx_desc[i].buf_addr));
err_free_rx:
for (i = 0; i < RX_BUF_COUNT; i++)
free_page((unsigned long)phys_to_virt(rx_desc[i].buf_addr));
err_out:
return err;
}
void ixpdev_deinit(void)
{
int i;
/* @@@ Flush out pending packets. */
for (i = 0; i < nds_count; i++)
unregister_netdev(nds[i]);
ixp2000_uengine_stop_contexts(1, 0xff);
ixp2000_uengine_stop_contexts(0, 0xff);
ixp2000_uengine_reset(0x3);
for (i = 0; i < TX_BUF_COUNT; i++)
free_page((unsigned long)phys_to_virt(tx_desc[i].buf_addr));
for (i = 0; i < RX_BUF_COUNT; i++)
free_page((unsigned long)phys_to_virt(rx_desc[i].buf_addr));
}
| gpl-2.0 |
Perferom/android_kernel_huawei_msm7x25 | net/bluetooth/bnep/netdev.c | 506 | 6089 | /*
BNEP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2001-2002 Inventel Systemes
Written 2001-2002 by
Clément Moreau <clement.moreau@inventel.fr>
David Libault <david.libault@inventel.fr>
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/module.h>
#include <linux/socket.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/wait.h>
#include <asm/unaligned.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/l2cap.h>
#include "bnep.h"
#define BNEP_TX_QUEUE_LEN 20
static int bnep_net_open(struct net_device *dev)
{
netif_start_queue(dev);
return 0;
}
static int bnep_net_close(struct net_device *dev)
{
netif_stop_queue(dev);
return 0;
}
static void bnep_net_set_mc_list(struct net_device *dev)
{
#ifdef CONFIG_BT_BNEP_MC_FILTER
struct bnep_session *s = netdev_priv(dev);
struct sock *sk = s->sock->sk;
struct bnep_set_filter_req *r;
struct sk_buff *skb;
int size;
BT_DBG("%s mc_count %d", dev->name, dev->mc_count);
size = sizeof(*r) + (BNEP_MAX_MULTICAST_FILTERS + 1) * ETH_ALEN * 2;
skb = alloc_skb(size, GFP_ATOMIC);
if (!skb) {
BT_ERR("%s Multicast list allocation failed", dev->name);
return;
}
r = (void *) skb->data;
__skb_put(skb, sizeof(*r));
r->type = BNEP_CONTROL;
r->ctrl = BNEP_FILTER_MULTI_ADDR_SET;
if (dev->flags & (IFF_PROMISC | IFF_ALLMULTI)) {
u8 start[ETH_ALEN] = { 0x01 };
/* Request all addresses */
memcpy(__skb_put(skb, ETH_ALEN), start, ETH_ALEN);
memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN);
r->len = htons(ETH_ALEN * 2);
} else {
struct dev_mc_list *dmi = dev->mc_list;
int i, len = skb->len;
if (dev->flags & IFF_BROADCAST) {
memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN);
memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN);
}
/* FIXME: We should group addresses here. */
for (i = 0; i < dev->mc_count && i < BNEP_MAX_MULTICAST_FILTERS; i++) {
memcpy(__skb_put(skb, ETH_ALEN), dmi->dmi_addr, ETH_ALEN);
memcpy(__skb_put(skb, ETH_ALEN), dmi->dmi_addr, ETH_ALEN);
dmi = dmi->next;
}
r->len = htons(skb->len - len);
}
skb_queue_tail(&sk->sk_write_queue, skb);
wake_up_interruptible(sk->sk_sleep);
#endif
}
static int bnep_net_set_mac_addr(struct net_device *dev, void *arg)
{
BT_DBG("%s", dev->name);
return 0;
}
static void bnep_net_timeout(struct net_device *dev)
{
BT_DBG("net_timeout");
netif_wake_queue(dev);
}
#ifdef CONFIG_BT_BNEP_MC_FILTER
static inline int bnep_net_mc_filter(struct sk_buff *skb, struct bnep_session *s)
{
struct ethhdr *eh = (void *) skb->data;
if ((eh->h_dest[0] & 1) && !test_bit(bnep_mc_hash(eh->h_dest), (ulong *) &s->mc_filter))
return 1;
return 0;
}
#endif
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
/* Determine ether protocol. Based on eth_type_trans. */
static inline u16 bnep_net_eth_proto(struct sk_buff *skb)
{
struct ethhdr *eh = (void *) skb->data;
u16 proto = ntohs(eh->h_proto);
if (proto >= 1536)
return proto;
if (get_unaligned((__be16 *) skb->data) == htons(0xFFFF))
return ETH_P_802_3;
return ETH_P_802_2;
}
static inline int bnep_net_proto_filter(struct sk_buff *skb, struct bnep_session *s)
{
u16 proto = bnep_net_eth_proto(skb);
struct bnep_proto_filter *f = s->proto_filter;
int i;
for (i = 0; i < BNEP_MAX_PROTO_FILTERS && f[i].end; i++) {
if (proto >= f[i].start && proto <= f[i].end)
return 0;
}
BT_DBG("BNEP: filtered skb %p, proto 0x%.4x", skb, proto);
return 1;
}
#endif
static netdev_tx_t bnep_net_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct bnep_session *s = netdev_priv(dev);
struct sock *sk = s->sock->sk;
BT_DBG("skb %p, dev %p", skb, dev);
#ifdef CONFIG_BT_BNEP_MC_FILTER
if (bnep_net_mc_filter(skb, s)) {
kfree_skb(skb);
return NETDEV_TX_OK;
}
#endif
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
if (bnep_net_proto_filter(skb, s)) {
kfree_skb(skb);
return NETDEV_TX_OK;
}
#endif
/*
* We cannot send L2CAP packets from here as we are potentially in a bh.
* So we have to queue them and wake up session thread which is sleeping
* on the sk->sk_sleep.
*/
dev->trans_start = jiffies;
skb_queue_tail(&sk->sk_write_queue, skb);
wake_up_interruptible(sk->sk_sleep);
if (skb_queue_len(&sk->sk_write_queue) >= BNEP_TX_QUEUE_LEN) {
BT_DBG("tx queue is full");
/* Stop queuing.
* Session thread will do netif_wake_queue() */
netif_stop_queue(dev);
}
return NETDEV_TX_OK;
}
static const struct net_device_ops bnep_netdev_ops = {
.ndo_open = bnep_net_open,
.ndo_stop = bnep_net_close,
.ndo_start_xmit = bnep_net_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_multicast_list = bnep_net_set_mc_list,
.ndo_set_mac_address = bnep_net_set_mac_addr,
.ndo_tx_timeout = bnep_net_timeout,
.ndo_change_mtu = eth_change_mtu,
};
void bnep_net_setup(struct net_device *dev)
{
memset(dev->broadcast, 0xff, ETH_ALEN);
dev->addr_len = ETH_ALEN;
ether_setup(dev);
dev->netdev_ops = &bnep_netdev_ops;
dev->watchdog_timeo = HZ * 2;
}
| gpl-2.0 |
crysehillmes/android_kernel_samsung_klimtlte | drivers/usb/core/hcd-pci.c | 762 | 16132 | /*
* (C) Copyright David Brownell 2000-2002
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <asm/io.h>
#include <asm/irq.h>
#ifdef CONFIG_PPC_PMAC
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#endif
#include "usb.h"
/* PCI-based HCs are common, but plenty of non-PCI HCs are used too */
#ifdef CONFIG_PM_SLEEP
/* Coordinate handoffs between EHCI and companion controllers
* during system resume
*/
static DEFINE_MUTEX(companions_mutex);
#define CL_UHCI PCI_CLASS_SERIAL_USB_UHCI
#define CL_OHCI PCI_CLASS_SERIAL_USB_OHCI
#define CL_EHCI PCI_CLASS_SERIAL_USB_EHCI
enum companion_action {
SET_HS_COMPANION, CLEAR_HS_COMPANION, WAIT_FOR_COMPANIONS
};
static void companion_common(struct pci_dev *pdev, struct usb_hcd *hcd,
enum companion_action action)
{
struct pci_dev *companion;
struct usb_hcd *companion_hcd;
unsigned int slot = PCI_SLOT(pdev->devfn);
/* Iterate through other PCI functions in the same slot.
* If pdev is OHCI or UHCI then we are looking for EHCI, and
* vice versa.
*/
companion = NULL;
for_each_pci_dev(companion) {
if (companion->bus != pdev->bus ||
PCI_SLOT(companion->devfn) != slot)
continue;
companion_hcd = pci_get_drvdata(companion);
if (!companion_hcd)
continue;
/* For SET_HS_COMPANION, store a pointer to the EHCI bus in
* the OHCI/UHCI companion bus structure.
* For CLEAR_HS_COMPANION, clear the pointer to the EHCI bus
* in the OHCI/UHCI companion bus structure.
* For WAIT_FOR_COMPANIONS, wait until the OHCI/UHCI
* companion controllers have fully resumed.
*/
if ((pdev->class == CL_OHCI || pdev->class == CL_UHCI) &&
companion->class == CL_EHCI) {
/* action must be SET_HS_COMPANION */
dev_dbg(&companion->dev, "HS companion for %s\n",
dev_name(&pdev->dev));
hcd->self.hs_companion = &companion_hcd->self;
} else if (pdev->class == CL_EHCI &&
(companion->class == CL_OHCI ||
companion->class == CL_UHCI)) {
switch (action) {
case SET_HS_COMPANION:
dev_dbg(&pdev->dev, "HS companion for %s\n",
dev_name(&companion->dev));
companion_hcd->self.hs_companion = &hcd->self;
break;
case CLEAR_HS_COMPANION:
companion_hcd->self.hs_companion = NULL;
break;
case WAIT_FOR_COMPANIONS:
device_pm_wait_for_dev(&pdev->dev,
&companion->dev);
break;
}
}
}
}
static void set_hs_companion(struct pci_dev *pdev, struct usb_hcd *hcd)
{
mutex_lock(&companions_mutex);
dev_set_drvdata(&pdev->dev, hcd);
companion_common(pdev, hcd, SET_HS_COMPANION);
mutex_unlock(&companions_mutex);
}
static void clear_hs_companion(struct pci_dev *pdev, struct usb_hcd *hcd)
{
mutex_lock(&companions_mutex);
dev_set_drvdata(&pdev->dev, NULL);
/* If pdev is OHCI or UHCI, just clear its hs_companion pointer */
if (pdev->class == CL_OHCI || pdev->class == CL_UHCI)
hcd->self.hs_companion = NULL;
/* Otherwise search for companion buses and clear their pointers */
else
companion_common(pdev, hcd, CLEAR_HS_COMPANION);
mutex_unlock(&companions_mutex);
}
static void wait_for_companions(struct pci_dev *pdev, struct usb_hcd *hcd)
{
/* Only EHCI controllers need to wait.
* No locking is needed because a controller cannot be resumed
* while one of its companions is getting unbound.
*/
if (pdev->class == CL_EHCI)
companion_common(pdev, hcd, WAIT_FOR_COMPANIONS);
}
#else /* !CONFIG_PM_SLEEP */
static inline void set_hs_companion(struct pci_dev *d, struct usb_hcd *h) {}
static inline void clear_hs_companion(struct pci_dev *d, struct usb_hcd *h) {}
static inline void wait_for_companions(struct pci_dev *d, struct usb_hcd *h) {}
#endif /* !CONFIG_PM_SLEEP */
/*-------------------------------------------------------------------------*/
/* configure so an HC device and id are always provided */
/* always called with process context; sleeping is OK */
/**
* usb_hcd_pci_probe - initialize PCI-based HCDs
* @dev: USB Host Controller being probed
* @id: pci hotplug id connecting controller to HCD framework
* Context: !in_interrupt()
*
* Allocates basic PCI resources for this USB host controller, and
* then invokes the start() method for the HCD associated with it
* through the hotplug entry's driver_data.
*
* Store this function in the HCD's struct pci_driver as probe().
*/
int usb_hcd_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct hc_driver *driver;
struct usb_hcd *hcd;
int retval;
int hcd_irq = 0;
if (usb_disabled())
return -ENODEV;
if (!id)
return -EINVAL;
driver = (struct hc_driver *)id->driver_data;
if (!driver)
return -EINVAL;
if (pci_enable_device(dev) < 0)
return -ENODEV;
dev->current_state = PCI_D0;
/*
* The xHCI driver has its own irq management
* make sure irq setup is not touched for xhci in generic hcd code
*/
if ((driver->flags & HCD_MASK) != HCD_USB3) {
if (!dev->irq) {
dev_err(&dev->dev,
"Found HC with no IRQ. Check BIOS/PCI %s setup!\n",
pci_name(dev));
retval = -ENODEV;
goto disable_pci;
}
hcd_irq = dev->irq;
}
hcd = usb_create_hcd(driver, &dev->dev, pci_name(dev));
if (!hcd) {
retval = -ENOMEM;
goto disable_pci;
}
if (driver->flags & HCD_MEMORY) {
/* EHCI, OHCI */
hcd->rsrc_start = pci_resource_start(dev, 0);
hcd->rsrc_len = pci_resource_len(dev, 0);
if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description)) {
dev_dbg(&dev->dev, "controller already in use\n");
retval = -EBUSY;
goto clear_companion;
}
hcd->regs = ioremap_nocache(hcd->rsrc_start, hcd->rsrc_len);
if (hcd->regs == NULL) {
dev_dbg(&dev->dev, "error mapping memory\n");
retval = -EFAULT;
goto release_mem_region;
}
} else {
/* UHCI */
int region;
for (region = 0; region < PCI_ROM_RESOURCE; region++) {
if (!(pci_resource_flags(dev, region) &
IORESOURCE_IO))
continue;
hcd->rsrc_start = pci_resource_start(dev, region);
hcd->rsrc_len = pci_resource_len(dev, region);
if (request_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description))
break;
}
if (region == PCI_ROM_RESOURCE) {
dev_dbg(&dev->dev, "no i/o regions available\n");
retval = -EBUSY;
goto clear_companion;
}
}
pci_set_master(dev);
retval = usb_add_hcd(hcd, hcd_irq, IRQF_SHARED);
if (retval != 0)
goto unmap_registers;
set_hs_companion(dev, hcd);
if (pci_dev_run_wake(dev))
pm_runtime_put_noidle(&dev->dev);
return retval;
unmap_registers:
if (driver->flags & HCD_MEMORY) {
iounmap(hcd->regs);
release_mem_region:
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
} else
release_region(hcd->rsrc_start, hcd->rsrc_len);
clear_companion:
clear_hs_companion(dev, hcd);
usb_put_hcd(hcd);
disable_pci:
pci_disable_device(dev);
dev_err(&dev->dev, "init %s fail, %d\n", pci_name(dev), retval);
return retval;
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_probe);
/* may be called without controller electrically present */
/* may be called with controller, bus, and devices active */
/**
* usb_hcd_pci_remove - shutdown processing for PCI-based HCDs
* @dev: USB Host Controller being removed
* Context: !in_interrupt()
*
* Reverses the effect of usb_hcd_pci_probe(), first invoking
* the HCD's stop() method. It is always called from a thread
* context, normally "rmmod", "apmd", or something similar.
*
* Store this function in the HCD's struct pci_driver as remove().
*/
void usb_hcd_pci_remove(struct pci_dev *dev)
{
struct usb_hcd *hcd;
hcd = pci_get_drvdata(dev);
if (!hcd)
return;
if (pci_dev_run_wake(dev))
pm_runtime_get_noresume(&dev->dev);
/* Fake an interrupt request in order to give the driver a chance
* to test whether the controller hardware has been removed (e.g.,
* cardbus physical eject).
*/
local_irq_disable();
usb_hcd_irq(0, hcd);
local_irq_enable();
usb_remove_hcd(hcd);
if (hcd->driver->flags & HCD_MEMORY) {
iounmap(hcd->regs);
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
} else {
release_region(hcd->rsrc_start, hcd->rsrc_len);
}
clear_hs_companion(dev, hcd);
usb_put_hcd(hcd);
pci_disable_device(dev);
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_remove);
/**
* usb_hcd_pci_shutdown - shutdown host controller
* @dev: USB Host Controller being shutdown
*/
void usb_hcd_pci_shutdown(struct pci_dev *dev)
{
struct usb_hcd *hcd;
hcd = pci_get_drvdata(dev);
if (!hcd)
return;
if (test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags) &&
hcd->driver->shutdown) {
hcd->driver->shutdown(hcd);
pci_disable_device(dev);
}
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_shutdown);
#ifdef CONFIG_PM
#ifdef CONFIG_PPC_PMAC
static void powermac_set_asic(struct pci_dev *pci_dev, int enable)
{
/* Enanble or disable ASIC clocks for USB */
if (machine_is(powermac)) {
struct device_node *of_node;
of_node = pci_device_to_OF_node(pci_dev);
if (of_node)
pmac_call_feature(PMAC_FTR_USB_ENABLE,
of_node, 0, enable);
}
}
#else
static inline void powermac_set_asic(struct pci_dev *pci_dev, int enable)
{}
#endif /* CONFIG_PPC_PMAC */
static int check_root_hub_suspended(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
if (HCD_RH_RUNNING(hcd)) {
dev_warn(dev, "Root hub is not suspended\n");
return -EBUSY;
}
if (hcd->shared_hcd) {
hcd = hcd->shared_hcd;
if (HCD_RH_RUNNING(hcd)) {
dev_warn(dev, "Secondary root hub is not suspended\n");
return -EBUSY;
}
}
return 0;
}
#if defined(CONFIG_PM_SLEEP) || defined(CONFIG_PM_RUNTIME)
static int suspend_common(struct device *dev, bool do_wakeup)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
/* Root hub suspend should have stopped all downstream traffic,
* and all bus master traffic. And done so for both the interface
* and the stub usb_device (which we check here). But maybe it
* didn't; writing sysfs power/state files ignores such rules...
*/
retval = check_root_hub_suspended(dev);
if (retval)
return retval;
if (hcd->driver->pci_suspend && !HCD_DEAD(hcd)) {
/* Optimization: Don't suspend if a root-hub wakeup is
* pending and it would cause the HCD to wake up anyway.
*/
if (do_wakeup && HCD_WAKEUP_PENDING(hcd))
return -EBUSY;
if (do_wakeup && hcd->shared_hcd &&
HCD_WAKEUP_PENDING(hcd->shared_hcd))
return -EBUSY;
retval = hcd->driver->pci_suspend(hcd, do_wakeup);
suspend_report_result(hcd->driver->pci_suspend, retval);
/* Check again in case wakeup raced with pci_suspend */
if ((retval == 0 && do_wakeup && HCD_WAKEUP_PENDING(hcd)) ||
(retval == 0 && do_wakeup && hcd->shared_hcd &&
HCD_WAKEUP_PENDING(hcd->shared_hcd))) {
if (hcd->driver->pci_resume)
hcd->driver->pci_resume(hcd, false);
retval = -EBUSY;
}
if (retval)
return retval;
}
/* If MSI-X is enabled, the driver will have synchronized all vectors
* in pci_suspend(). If MSI or legacy PCI is enabled, that will be
* synchronized here.
*/
if (!hcd->msix_enabled)
synchronize_irq(pci_dev->irq);
/* Downstream ports from this root hub should already be quiesced, so
* there will be no DMA activity. Now we can shut down the upstream
* link (except maybe for PME# resume signaling). We'll enter a
* low power state during suspend_noirq, if the hardware allows.
*/
pci_disable_device(pci_dev);
return retval;
}
static int resume_common(struct device *dev, int event)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
if (HCD_RH_RUNNING(hcd) ||
(hcd->shared_hcd &&
HCD_RH_RUNNING(hcd->shared_hcd))) {
dev_dbg(dev, "can't resume, not suspended!\n");
return 0;
}
retval = pci_enable_device(pci_dev);
if (retval < 0) {
dev_err(dev, "can't re-enable after resume, %d!\n", retval);
return retval;
}
pci_set_master(pci_dev);
if (hcd->driver->pci_resume && !HCD_DEAD(hcd)) {
if (event != PM_EVENT_AUTO_RESUME)
wait_for_companions(pci_dev, hcd);
retval = hcd->driver->pci_resume(hcd,
event == PM_EVENT_RESTORE);
if (retval) {
dev_err(dev, "PCI post-resume error %d!\n", retval);
if (hcd->shared_hcd)
usb_hc_died(hcd->shared_hcd);
usb_hc_died(hcd);
}
}
return retval;
}
#endif /* SLEEP || RUNTIME */
#ifdef CONFIG_PM_SLEEP
static int hcd_pci_suspend(struct device *dev)
{
return suspend_common(dev, device_may_wakeup(dev));
}
static int hcd_pci_suspend_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
retval = check_root_hub_suspended(dev);
if (retval)
return retval;
pci_save_state(pci_dev);
/* If the root hub is dead rather than suspended, disallow remote
* wakeup. usb_hc_died() should ensure that both hosts are marked as
* dying, so we only need to check the primary roothub.
*/
if (HCD_DEAD(hcd))
device_set_wakeup_enable(dev, 0);
dev_dbg(dev, "wakeup: %d\n", device_may_wakeup(dev));
/* Possibly enable remote wakeup,
* choose the appropriate low-power state, and go to that state.
*/
retval = pci_prepare_to_sleep(pci_dev);
if (retval == -EIO) { /* Low-power not supported */
dev_dbg(dev, "--> PCI D0 legacy\n");
retval = 0;
} else if (retval == 0) {
dev_dbg(dev, "--> PCI %s\n",
pci_power_name(pci_dev->current_state));
} else {
suspend_report_result(pci_prepare_to_sleep, retval);
return retval;
}
powermac_set_asic(pci_dev, 0);
return retval;
}
static int hcd_pci_resume_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
powermac_set_asic(pci_dev, 1);
/* Go back to D0 and disable remote wakeup */
pci_back_from_sleep(pci_dev);
return 0;
}
static int hcd_pci_resume(struct device *dev)
{
return resume_common(dev, PM_EVENT_RESUME);
}
static int hcd_pci_restore(struct device *dev)
{
return resume_common(dev, PM_EVENT_RESTORE);
}
#else
#define hcd_pci_suspend NULL
#define hcd_pci_suspend_noirq NULL
#define hcd_pci_resume_noirq NULL
#define hcd_pci_resume NULL
#define hcd_pci_restore NULL
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_RUNTIME
static int hcd_pci_runtime_suspend(struct device *dev)
{
int retval;
retval = suspend_common(dev, true);
if (retval == 0)
powermac_set_asic(to_pci_dev(dev), 0);
dev_dbg(dev, "hcd_pci_runtime_suspend: %d\n", retval);
return retval;
}
static int hcd_pci_runtime_resume(struct device *dev)
{
int retval;
powermac_set_asic(to_pci_dev(dev), 1);
retval = resume_common(dev, PM_EVENT_AUTO_RESUME);
dev_dbg(dev, "hcd_pci_runtime_resume: %d\n", retval);
return retval;
}
#else
#define hcd_pci_runtime_suspend NULL
#define hcd_pci_runtime_resume NULL
#endif /* CONFIG_PM_RUNTIME */
const struct dev_pm_ops usb_hcd_pci_pm_ops = {
.suspend = hcd_pci_suspend,
.suspend_noirq = hcd_pci_suspend_noirq,
.resume_noirq = hcd_pci_resume_noirq,
.resume = hcd_pci_resume,
.freeze = check_root_hub_suspended,
.freeze_noirq = check_root_hub_suspended,
.thaw_noirq = NULL,
.thaw = NULL,
.poweroff = hcd_pci_suspend,
.poweroff_noirq = hcd_pci_suspend_noirq,
.restore_noirq = hcd_pci_resume_noirq,
.restore = hcd_pci_restore,
.runtime_suspend = hcd_pci_runtime_suspend,
.runtime_resume = hcd_pci_runtime_resume,
};
EXPORT_SYMBOL_GPL(usb_hcd_pci_pm_ops);
#endif /* CONFIG_PM */
| gpl-2.0 |
bood/htc-magic-kernel | drivers/video/sh_mobile_lcdcfb.c | 762 | 30253 | /*
* SuperH Mobile LCDC Framebuffer
*
* Copyright (c) 2008 Magnus Damm
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/fb.h>
#include <linux/clk.h>
#include <linux/pm_runtime.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/vmalloc.h>
#include <linux/ioctl.h>
#include <linux/slab.h>
#include <video/sh_mobile_lcdc.h>
#include <asm/atomic.h>
#define PALETTE_NR 16
#define SIDE_B_OFFSET 0x1000
#define MIRROR_OFFSET 0x2000
/* shared registers */
#define _LDDCKR 0x410
#define _LDDCKSTPR 0x414
#define _LDINTR 0x468
#define _LDSR 0x46c
#define _LDCNT1R 0x470
#define _LDCNT2R 0x474
#define _LDRCNTR 0x478
#define _LDDDSR 0x47c
#define _LDDWD0R 0x800
#define _LDDRDR 0x840
#define _LDDWAR 0x900
#define _LDDRAR 0x904
/* shared registers and their order for context save/restore */
static int lcdc_shared_regs[] = {
_LDDCKR,
_LDDCKSTPR,
_LDINTR,
_LDDDSR,
_LDCNT1R,
_LDCNT2R,
};
#define NR_SHARED_REGS ARRAY_SIZE(lcdc_shared_regs)
/* per-channel registers */
enum { LDDCKPAT1R, LDDCKPAT2R, LDMT1R, LDMT2R, LDMT3R, LDDFR, LDSM1R,
LDSM2R, LDSA1R, LDMLSR, LDHCNR, LDHSYNR, LDVLNR, LDVSYNR, LDPMR,
NR_CH_REGS };
static unsigned long lcdc_offs_mainlcd[NR_CH_REGS] = {
[LDDCKPAT1R] = 0x400,
[LDDCKPAT2R] = 0x404,
[LDMT1R] = 0x418,
[LDMT2R] = 0x41c,
[LDMT3R] = 0x420,
[LDDFR] = 0x424,
[LDSM1R] = 0x428,
[LDSM2R] = 0x42c,
[LDSA1R] = 0x430,
[LDMLSR] = 0x438,
[LDHCNR] = 0x448,
[LDHSYNR] = 0x44c,
[LDVLNR] = 0x450,
[LDVSYNR] = 0x454,
[LDPMR] = 0x460,
};
static unsigned long lcdc_offs_sublcd[NR_CH_REGS] = {
[LDDCKPAT1R] = 0x408,
[LDDCKPAT2R] = 0x40c,
[LDMT1R] = 0x600,
[LDMT2R] = 0x604,
[LDMT3R] = 0x608,
[LDDFR] = 0x60c,
[LDSM1R] = 0x610,
[LDSM2R] = 0x614,
[LDSA1R] = 0x618,
[LDMLSR] = 0x620,
[LDHCNR] = 0x624,
[LDHSYNR] = 0x628,
[LDVLNR] = 0x62c,
[LDVSYNR] = 0x630,
[LDPMR] = 0x63c,
};
#define START_LCDC 0x00000001
#define LCDC_RESET 0x00000100
#define DISPLAY_BEU 0x00000008
#define LCDC_ENABLE 0x00000001
#define LDINTR_FE 0x00000400
#define LDINTR_VSE 0x00000200
#define LDINTR_VEE 0x00000100
#define LDINTR_FS 0x00000004
#define LDINTR_VSS 0x00000002
#define LDINTR_VES 0x00000001
#define LDRCNTR_SRS 0x00020000
#define LDRCNTR_SRC 0x00010000
#define LDRCNTR_MRS 0x00000002
#define LDRCNTR_MRC 0x00000001
#define LDSR_MRS 0x00000100
struct sh_mobile_lcdc_priv;
struct sh_mobile_lcdc_chan {
struct sh_mobile_lcdc_priv *lcdc;
unsigned long *reg_offs;
unsigned long ldmt1r_value;
unsigned long enabled; /* ME and SE in LDCNT2R */
struct sh_mobile_lcdc_chan_cfg cfg;
u32 pseudo_palette[PALETTE_NR];
unsigned long saved_ch_regs[NR_CH_REGS];
struct fb_info *info;
dma_addr_t dma_handle;
struct fb_deferred_io defio;
struct scatterlist *sglist;
unsigned long frame_end;
unsigned long pan_offset;
wait_queue_head_t frame_end_wait;
struct completion vsync_completion;
};
struct sh_mobile_lcdc_priv {
void __iomem *base;
int irq;
atomic_t hw_usecnt;
struct device *dev;
struct clk *dot_clk;
unsigned long lddckr;
struct sh_mobile_lcdc_chan ch[2];
unsigned long saved_shared_regs[NR_SHARED_REGS];
int started;
};
static bool banked(int reg_nr)
{
switch (reg_nr) {
case LDMT1R:
case LDMT2R:
case LDMT3R:
case LDDFR:
case LDSM1R:
case LDSA1R:
case LDMLSR:
case LDHCNR:
case LDHSYNR:
case LDVLNR:
case LDVSYNR:
return true;
}
return false;
}
static void lcdc_write_chan(struct sh_mobile_lcdc_chan *chan,
int reg_nr, unsigned long data)
{
iowrite32(data, chan->lcdc->base + chan->reg_offs[reg_nr]);
if (banked(reg_nr))
iowrite32(data, chan->lcdc->base + chan->reg_offs[reg_nr] +
SIDE_B_OFFSET);
}
static void lcdc_write_chan_mirror(struct sh_mobile_lcdc_chan *chan,
int reg_nr, unsigned long data)
{
iowrite32(data, chan->lcdc->base + chan->reg_offs[reg_nr] +
MIRROR_OFFSET);
}
static unsigned long lcdc_read_chan(struct sh_mobile_lcdc_chan *chan,
int reg_nr)
{
return ioread32(chan->lcdc->base + chan->reg_offs[reg_nr]);
}
static void lcdc_write(struct sh_mobile_lcdc_priv *priv,
unsigned long reg_offs, unsigned long data)
{
iowrite32(data, priv->base + reg_offs);
}
static unsigned long lcdc_read(struct sh_mobile_lcdc_priv *priv,
unsigned long reg_offs)
{
return ioread32(priv->base + reg_offs);
}
static void lcdc_wait_bit(struct sh_mobile_lcdc_priv *priv,
unsigned long reg_offs,
unsigned long mask, unsigned long until)
{
while ((lcdc_read(priv, reg_offs) & mask) != until)
cpu_relax();
}
static int lcdc_chan_is_sublcd(struct sh_mobile_lcdc_chan *chan)
{
return chan->cfg.chan == LCDC_CHAN_SUBLCD;
}
static void lcdc_sys_write_index(void *handle, unsigned long data)
{
struct sh_mobile_lcdc_chan *ch = handle;
lcdc_write(ch->lcdc, _LDDWD0R, data | 0x10000000);
lcdc_wait_bit(ch->lcdc, _LDSR, 2, 0);
lcdc_write(ch->lcdc, _LDDWAR, 1 | (lcdc_chan_is_sublcd(ch) ? 2 : 0));
lcdc_wait_bit(ch->lcdc, _LDSR, 2, 0);
}
static void lcdc_sys_write_data(void *handle, unsigned long data)
{
struct sh_mobile_lcdc_chan *ch = handle;
lcdc_write(ch->lcdc, _LDDWD0R, data | 0x11000000);
lcdc_wait_bit(ch->lcdc, _LDSR, 2, 0);
lcdc_write(ch->lcdc, _LDDWAR, 1 | (lcdc_chan_is_sublcd(ch) ? 2 : 0));
lcdc_wait_bit(ch->lcdc, _LDSR, 2, 0);
}
static unsigned long lcdc_sys_read_data(void *handle)
{
struct sh_mobile_lcdc_chan *ch = handle;
lcdc_write(ch->lcdc, _LDDRDR, 0x01000000);
lcdc_wait_bit(ch->lcdc, _LDSR, 2, 0);
lcdc_write(ch->lcdc, _LDDRAR, 1 | (lcdc_chan_is_sublcd(ch) ? 2 : 0));
udelay(1);
lcdc_wait_bit(ch->lcdc, _LDSR, 2, 0);
return lcdc_read(ch->lcdc, _LDDRDR) & 0x3ffff;
}
struct sh_mobile_lcdc_sys_bus_ops sh_mobile_lcdc_sys_bus_ops = {
lcdc_sys_write_index,
lcdc_sys_write_data,
lcdc_sys_read_data,
};
static void sh_mobile_lcdc_clk_on(struct sh_mobile_lcdc_priv *priv)
{
if (atomic_inc_and_test(&priv->hw_usecnt)) {
pm_runtime_get_sync(priv->dev);
if (priv->dot_clk)
clk_enable(priv->dot_clk);
}
}
static void sh_mobile_lcdc_clk_off(struct sh_mobile_lcdc_priv *priv)
{
if (atomic_sub_return(1, &priv->hw_usecnt) == -1) {
if (priv->dot_clk)
clk_disable(priv->dot_clk);
pm_runtime_put(priv->dev);
}
}
static int sh_mobile_lcdc_sginit(struct fb_info *info,
struct list_head *pagelist)
{
struct sh_mobile_lcdc_chan *ch = info->par;
unsigned int nr_pages_max = info->fix.smem_len >> PAGE_SHIFT;
struct page *page;
int nr_pages = 0;
sg_init_table(ch->sglist, nr_pages_max);
list_for_each_entry(page, pagelist, lru)
sg_set_page(&ch->sglist[nr_pages++], page, PAGE_SIZE, 0);
return nr_pages;
}
static void sh_mobile_lcdc_deferred_io(struct fb_info *info,
struct list_head *pagelist)
{
struct sh_mobile_lcdc_chan *ch = info->par;
struct sh_mobile_lcdc_board_cfg *bcfg = &ch->cfg.board_cfg;
/* enable clocks before accessing hardware */
sh_mobile_lcdc_clk_on(ch->lcdc);
/*
* It's possible to get here without anything on the pagelist via
* sh_mobile_lcdc_deferred_io_touch() or via a userspace fsync()
* invocation. In the former case, the acceleration routines are
* stepped in to when using the framebuffer console causing the
* workqueue to be scheduled without any dirty pages on the list.
*
* Despite this, a panel update is still needed given that the
* acceleration routines have their own methods for writing in
* that still need to be updated.
*
* The fsync() and empty pagelist case could be optimized for,
* but we don't bother, as any application exhibiting such
* behaviour is fundamentally broken anyways.
*/
if (!list_empty(pagelist)) {
unsigned int nr_pages = sh_mobile_lcdc_sginit(info, pagelist);
/* trigger panel update */
dma_map_sg(info->dev, ch->sglist, nr_pages, DMA_TO_DEVICE);
if (bcfg->start_transfer)
bcfg->start_transfer(bcfg->board_data, ch,
&sh_mobile_lcdc_sys_bus_ops);
lcdc_write_chan(ch, LDSM2R, 1);
dma_unmap_sg(info->dev, ch->sglist, nr_pages, DMA_TO_DEVICE);
} else {
if (bcfg->start_transfer)
bcfg->start_transfer(bcfg->board_data, ch,
&sh_mobile_lcdc_sys_bus_ops);
lcdc_write_chan(ch, LDSM2R, 1);
}
}
static void sh_mobile_lcdc_deferred_io_touch(struct fb_info *info)
{
struct fb_deferred_io *fbdefio = info->fbdefio;
if (fbdefio)
schedule_delayed_work(&info->deferred_work, fbdefio->delay);
}
static irqreturn_t sh_mobile_lcdc_irq(int irq, void *data)
{
struct sh_mobile_lcdc_priv *priv = data;
struct sh_mobile_lcdc_chan *ch;
unsigned long tmp;
unsigned long ldintr;
int is_sub;
int k;
/* acknowledge interrupt */
ldintr = tmp = lcdc_read(priv, _LDINTR);
/*
* disable further VSYNC End IRQs, preserve all other enabled IRQs,
* write 0 to bits 0-6 to ack all triggered IRQs.
*/
tmp &= 0xffffff00 & ~LDINTR_VEE;
lcdc_write(priv, _LDINTR, tmp);
/* figure out if this interrupt is for main or sub lcd */
is_sub = (lcdc_read(priv, _LDSR) & (1 << 10)) ? 1 : 0;
/* wake up channel and disable clocks */
for (k = 0; k < ARRAY_SIZE(priv->ch); k++) {
ch = &priv->ch[k];
if (!ch->enabled)
continue;
/* Frame Start */
if (ldintr & LDINTR_FS) {
if (is_sub == lcdc_chan_is_sublcd(ch)) {
ch->frame_end = 1;
wake_up(&ch->frame_end_wait);
sh_mobile_lcdc_clk_off(priv);
}
}
/* VSYNC End */
if (ldintr & LDINTR_VES)
complete(&ch->vsync_completion);
}
return IRQ_HANDLED;
}
static void sh_mobile_lcdc_start_stop(struct sh_mobile_lcdc_priv *priv,
int start)
{
unsigned long tmp = lcdc_read(priv, _LDCNT2R);
int k;
/* start or stop the lcdc */
if (start)
lcdc_write(priv, _LDCNT2R, tmp | START_LCDC);
else
lcdc_write(priv, _LDCNT2R, tmp & ~START_LCDC);
/* wait until power is applied/stopped on all channels */
for (k = 0; k < ARRAY_SIZE(priv->ch); k++)
if (lcdc_read(priv, _LDCNT2R) & priv->ch[k].enabled)
while (1) {
tmp = lcdc_read_chan(&priv->ch[k], LDPMR) & 3;
if (start && tmp == 3)
break;
if (!start && tmp == 0)
break;
cpu_relax();
}
if (!start)
lcdc_write(priv, _LDDCKSTPR, 1); /* stop dotclock */
}
static int sh_mobile_lcdc_start(struct sh_mobile_lcdc_priv *priv)
{
struct sh_mobile_lcdc_chan *ch;
struct fb_videomode *lcd_cfg;
struct sh_mobile_lcdc_board_cfg *board_cfg;
unsigned long tmp;
int k, m;
int ret = 0;
/* enable clocks before accessing the hardware */
for (k = 0; k < ARRAY_SIZE(priv->ch); k++)
if (priv->ch[k].enabled)
sh_mobile_lcdc_clk_on(priv);
/* reset */
lcdc_write(priv, _LDCNT2R, lcdc_read(priv, _LDCNT2R) | LCDC_RESET);
lcdc_wait_bit(priv, _LDCNT2R, LCDC_RESET, 0);
/* enable LCDC channels */
tmp = lcdc_read(priv, _LDCNT2R);
tmp |= priv->ch[0].enabled;
tmp |= priv->ch[1].enabled;
lcdc_write(priv, _LDCNT2R, tmp);
/* read data from external memory, avoid using the BEU for now */
lcdc_write(priv, _LDCNT2R, lcdc_read(priv, _LDCNT2R) & ~DISPLAY_BEU);
/* stop the lcdc first */
sh_mobile_lcdc_start_stop(priv, 0);
/* configure clocks */
tmp = priv->lddckr;
for (k = 0; k < ARRAY_SIZE(priv->ch); k++) {
ch = &priv->ch[k];
if (!priv->ch[k].enabled)
continue;
m = ch->cfg.clock_divider;
if (!m)
continue;
if (m == 1)
m = 1 << 6;
tmp |= m << (lcdc_chan_is_sublcd(ch) ? 8 : 0);
lcdc_write_chan(ch, LDDCKPAT1R, 0x00000000);
lcdc_write_chan(ch, LDDCKPAT2R, (1 << (m/2)) - 1);
}
lcdc_write(priv, _LDDCKR, tmp);
/* start dotclock again */
lcdc_write(priv, _LDDCKSTPR, 0);
lcdc_wait_bit(priv, _LDDCKSTPR, ~0, 0);
/* interrupts are disabled to begin with */
lcdc_write(priv, _LDINTR, 0);
for (k = 0; k < ARRAY_SIZE(priv->ch); k++) {
ch = &priv->ch[k];
lcd_cfg = &ch->cfg.lcd_cfg;
if (!ch->enabled)
continue;
tmp = ch->ldmt1r_value;
tmp |= (lcd_cfg->sync & FB_SYNC_VERT_HIGH_ACT) ? 0 : 1 << 28;
tmp |= (lcd_cfg->sync & FB_SYNC_HOR_HIGH_ACT) ? 0 : 1 << 27;
tmp |= (ch->cfg.flags & LCDC_FLAGS_DWPOL) ? 1 << 26 : 0;
tmp |= (ch->cfg.flags & LCDC_FLAGS_DIPOL) ? 1 << 25 : 0;
tmp |= (ch->cfg.flags & LCDC_FLAGS_DAPOL) ? 1 << 24 : 0;
tmp |= (ch->cfg.flags & LCDC_FLAGS_HSCNT) ? 1 << 17 : 0;
tmp |= (ch->cfg.flags & LCDC_FLAGS_DWCNT) ? 1 << 16 : 0;
lcdc_write_chan(ch, LDMT1R, tmp);
/* setup SYS bus */
lcdc_write_chan(ch, LDMT2R, ch->cfg.sys_bus_cfg.ldmt2r);
lcdc_write_chan(ch, LDMT3R, ch->cfg.sys_bus_cfg.ldmt3r);
/* horizontal configuration */
tmp = lcd_cfg->xres + lcd_cfg->hsync_len;
tmp += lcd_cfg->left_margin;
tmp += lcd_cfg->right_margin;
tmp /= 8; /* HTCN */
tmp |= (lcd_cfg->xres / 8) << 16; /* HDCN */
lcdc_write_chan(ch, LDHCNR, tmp);
tmp = lcd_cfg->xres;
tmp += lcd_cfg->right_margin;
tmp /= 8; /* HSYNP */
tmp |= (lcd_cfg->hsync_len / 8) << 16; /* HSYNW */
lcdc_write_chan(ch, LDHSYNR, tmp);
/* power supply */
lcdc_write_chan(ch, LDPMR, 0);
/* vertical configuration */
tmp = lcd_cfg->yres + lcd_cfg->vsync_len;
tmp += lcd_cfg->upper_margin;
tmp += lcd_cfg->lower_margin; /* VTLN */
tmp |= lcd_cfg->yres << 16; /* VDLN */
lcdc_write_chan(ch, LDVLNR, tmp);
tmp = lcd_cfg->yres;
tmp += lcd_cfg->lower_margin; /* VSYNP */
tmp |= lcd_cfg->vsync_len << 16; /* VSYNW */
lcdc_write_chan(ch, LDVSYNR, tmp);
board_cfg = &ch->cfg.board_cfg;
if (board_cfg->setup_sys)
ret = board_cfg->setup_sys(board_cfg->board_data, ch,
&sh_mobile_lcdc_sys_bus_ops);
if (ret)
return ret;
}
/* word and long word swap */
lcdc_write(priv, _LDDDSR, lcdc_read(priv, _LDDDSR) | 6);
for (k = 0; k < ARRAY_SIZE(priv->ch); k++) {
ch = &priv->ch[k];
if (!priv->ch[k].enabled)
continue;
/* set bpp format in PKF[4:0] */
tmp = lcdc_read_chan(ch, LDDFR);
tmp &= ~(0x0001001f);
tmp |= (ch->info->var.bits_per_pixel == 16) ? 3 : 0;
lcdc_write_chan(ch, LDDFR, tmp);
/* point out our frame buffer */
lcdc_write_chan(ch, LDSA1R, ch->info->fix.smem_start);
/* set line size */
lcdc_write_chan(ch, LDMLSR, ch->info->fix.line_length);
/* setup deferred io if SYS bus */
tmp = ch->cfg.sys_bus_cfg.deferred_io_msec;
if (ch->ldmt1r_value & (1 << 12) && tmp) {
ch->defio.deferred_io = sh_mobile_lcdc_deferred_io;
ch->defio.delay = msecs_to_jiffies(tmp);
ch->info->fbdefio = &ch->defio;
fb_deferred_io_init(ch->info);
/* one-shot mode */
lcdc_write_chan(ch, LDSM1R, 1);
/* enable "Frame End Interrupt Enable" bit */
lcdc_write(priv, _LDINTR, LDINTR_FE);
} else {
/* continuous read mode */
lcdc_write_chan(ch, LDSM1R, 0);
}
}
/* display output */
lcdc_write(priv, _LDCNT1R, LCDC_ENABLE);
/* start the lcdc */
sh_mobile_lcdc_start_stop(priv, 1);
priv->started = 1;
/* tell the board code to enable the panel */
for (k = 0; k < ARRAY_SIZE(priv->ch); k++) {
ch = &priv->ch[k];
if (!ch->enabled)
continue;
board_cfg = &ch->cfg.board_cfg;
if (board_cfg->display_on)
board_cfg->display_on(board_cfg->board_data);
}
return 0;
}
static void sh_mobile_lcdc_stop(struct sh_mobile_lcdc_priv *priv)
{
struct sh_mobile_lcdc_chan *ch;
struct sh_mobile_lcdc_board_cfg *board_cfg;
int k;
/* clean up deferred io and ask board code to disable panel */
for (k = 0; k < ARRAY_SIZE(priv->ch); k++) {
ch = &priv->ch[k];
if (!ch->enabled)
continue;
/* deferred io mode:
* flush frame, and wait for frame end interrupt
* clean up deferred io and enable clock
*/
if (ch->info->fbdefio) {
ch->frame_end = 0;
schedule_delayed_work(&ch->info->deferred_work, 0);
wait_event(ch->frame_end_wait, ch->frame_end);
fb_deferred_io_cleanup(ch->info);
ch->info->fbdefio = NULL;
sh_mobile_lcdc_clk_on(priv);
}
board_cfg = &ch->cfg.board_cfg;
if (board_cfg->display_off)
board_cfg->display_off(board_cfg->board_data);
}
/* stop the lcdc */
if (priv->started) {
sh_mobile_lcdc_start_stop(priv, 0);
priv->started = 0;
}
/* stop clocks */
for (k = 0; k < ARRAY_SIZE(priv->ch); k++)
if (priv->ch[k].enabled)
sh_mobile_lcdc_clk_off(priv);
}
static int sh_mobile_lcdc_check_interface(struct sh_mobile_lcdc_chan *ch)
{
int ifm, miftyp;
switch (ch->cfg.interface_type) {
case RGB8: ifm = 0; miftyp = 0; break;
case RGB9: ifm = 0; miftyp = 4; break;
case RGB12A: ifm = 0; miftyp = 5; break;
case RGB12B: ifm = 0; miftyp = 6; break;
case RGB16: ifm = 0; miftyp = 7; break;
case RGB18: ifm = 0; miftyp = 10; break;
case RGB24: ifm = 0; miftyp = 11; break;
case SYS8A: ifm = 1; miftyp = 0; break;
case SYS8B: ifm = 1; miftyp = 1; break;
case SYS8C: ifm = 1; miftyp = 2; break;
case SYS8D: ifm = 1; miftyp = 3; break;
case SYS9: ifm = 1; miftyp = 4; break;
case SYS12: ifm = 1; miftyp = 5; break;
case SYS16A: ifm = 1; miftyp = 7; break;
case SYS16B: ifm = 1; miftyp = 8; break;
case SYS16C: ifm = 1; miftyp = 9; break;
case SYS18: ifm = 1; miftyp = 10; break;
case SYS24: ifm = 1; miftyp = 11; break;
default: goto bad;
}
/* SUBLCD only supports SYS interface */
if (lcdc_chan_is_sublcd(ch)) {
if (ifm == 0)
goto bad;
else
ifm = 0;
}
ch->ldmt1r_value = (ifm << 12) | miftyp;
return 0;
bad:
return -EINVAL;
}
static int sh_mobile_lcdc_setup_clocks(struct platform_device *pdev,
int clock_source,
struct sh_mobile_lcdc_priv *priv)
{
char *str;
int icksel;
switch (clock_source) {
case LCDC_CLK_BUS: str = "bus_clk"; icksel = 0; break;
case LCDC_CLK_PERIPHERAL: str = "peripheral_clk"; icksel = 1; break;
case LCDC_CLK_EXTERNAL: str = NULL; icksel = 2; break;
default:
return -EINVAL;
}
priv->lddckr = icksel << 16;
if (str) {
priv->dot_clk = clk_get(&pdev->dev, str);
if (IS_ERR(priv->dot_clk)) {
dev_err(&pdev->dev, "cannot get dot clock %s\n", str);
return PTR_ERR(priv->dot_clk);
}
}
atomic_set(&priv->hw_usecnt, -1);
/* Runtime PM support involves two step for this driver:
* 1) Enable Runtime PM
* 2) Force Runtime PM Resume since hardware is accessed from probe()
*/
priv->dev = &pdev->dev;
pm_runtime_enable(priv->dev);
pm_runtime_resume(priv->dev);
return 0;
}
static int sh_mobile_lcdc_setcolreg(u_int regno,
u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
u32 *palette = info->pseudo_palette;
if (regno >= PALETTE_NR)
return -EINVAL;
/* only FB_VISUAL_TRUECOLOR supported */
red >>= 16 - info->var.red.length;
green >>= 16 - info->var.green.length;
blue >>= 16 - info->var.blue.length;
transp >>= 16 - info->var.transp.length;
palette[regno] = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset) |
(transp << info->var.transp.offset);
return 0;
}
static struct fb_fix_screeninfo sh_mobile_lcdc_fix = {
.id = "SH Mobile LCDC",
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_TRUECOLOR,
.accel = FB_ACCEL_NONE,
.xpanstep = 0,
.ypanstep = 1,
.ywrapstep = 0,
};
static void sh_mobile_lcdc_fillrect(struct fb_info *info,
const struct fb_fillrect *rect)
{
sys_fillrect(info, rect);
sh_mobile_lcdc_deferred_io_touch(info);
}
static void sh_mobile_lcdc_copyarea(struct fb_info *info,
const struct fb_copyarea *area)
{
sys_copyarea(info, area);
sh_mobile_lcdc_deferred_io_touch(info);
}
static void sh_mobile_lcdc_imageblit(struct fb_info *info,
const struct fb_image *image)
{
sys_imageblit(info, image);
sh_mobile_lcdc_deferred_io_touch(info);
}
static int sh_mobile_fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct sh_mobile_lcdc_chan *ch = info->par;
struct sh_mobile_lcdc_priv *priv = ch->lcdc;
unsigned long ldrcntr;
unsigned long new_pan_offset;
new_pan_offset = (var->yoffset * info->fix.line_length) +
(var->xoffset * (info->var.bits_per_pixel / 8));
if (new_pan_offset == ch->pan_offset)
return 0; /* No change, do nothing */
ldrcntr = lcdc_read(priv, _LDRCNTR);
/* Set the source address for the next refresh */
lcdc_write_chan_mirror(ch, LDSA1R, ch->dma_handle + new_pan_offset);
if (lcdc_chan_is_sublcd(ch))
lcdc_write(ch->lcdc, _LDRCNTR, ldrcntr ^ LDRCNTR_SRS);
else
lcdc_write(ch->lcdc, _LDRCNTR, ldrcntr ^ LDRCNTR_MRS);
ch->pan_offset = new_pan_offset;
sh_mobile_lcdc_deferred_io_touch(info);
return 0;
}
static int sh_mobile_wait_for_vsync(struct fb_info *info)
{
struct sh_mobile_lcdc_chan *ch = info->par;
unsigned long ldintr;
int ret;
/* Enable VSync End interrupt */
ldintr = lcdc_read(ch->lcdc, _LDINTR);
ldintr |= LDINTR_VEE;
lcdc_write(ch->lcdc, _LDINTR, ldintr);
ret = wait_for_completion_interruptible_timeout(&ch->vsync_completion,
msecs_to_jiffies(100));
if (!ret)
return -ETIMEDOUT;
return 0;
}
static int sh_mobile_ioctl(struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
int retval;
switch (cmd) {
case FBIO_WAITFORVSYNC:
retval = sh_mobile_wait_for_vsync(info);
break;
default:
retval = -ENOIOCTLCMD;
break;
}
return retval;
}
static struct fb_ops sh_mobile_lcdc_ops = {
.owner = THIS_MODULE,
.fb_setcolreg = sh_mobile_lcdc_setcolreg,
.fb_read = fb_sys_read,
.fb_write = fb_sys_write,
.fb_fillrect = sh_mobile_lcdc_fillrect,
.fb_copyarea = sh_mobile_lcdc_copyarea,
.fb_imageblit = sh_mobile_lcdc_imageblit,
.fb_pan_display = sh_mobile_fb_pan_display,
.fb_ioctl = sh_mobile_ioctl,
};
static int sh_mobile_lcdc_set_bpp(struct fb_var_screeninfo *var, int bpp)
{
switch (bpp) {
case 16: /* PKF[4:0] = 00011 - RGB 565 */
var->red.offset = 11;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 6;
var->blue.offset = 0;
var->blue.length = 5;
var->transp.offset = 0;
var->transp.length = 0;
break;
case 32: /* PKF[4:0] = 00000 - RGB 888
* sh7722 pdf says 00RRGGBB but reality is GGBB00RR
* this may be because LDDDSR has word swap enabled..
*/
var->red.offset = 0;
var->red.length = 8;
var->green.offset = 24;
var->green.length = 8;
var->blue.offset = 16;
var->blue.length = 8;
var->transp.offset = 0;
var->transp.length = 0;
break;
default:
return -EINVAL;
}
var->bits_per_pixel = bpp;
var->red.msb_right = 0;
var->green.msb_right = 0;
var->blue.msb_right = 0;
var->transp.msb_right = 0;
return 0;
}
static int sh_mobile_lcdc_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
sh_mobile_lcdc_stop(platform_get_drvdata(pdev));
return 0;
}
static int sh_mobile_lcdc_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
return sh_mobile_lcdc_start(platform_get_drvdata(pdev));
}
static int sh_mobile_lcdc_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct sh_mobile_lcdc_priv *p = platform_get_drvdata(pdev);
struct sh_mobile_lcdc_chan *ch;
int k, n;
/* save per-channel registers */
for (k = 0; k < ARRAY_SIZE(p->ch); k++) {
ch = &p->ch[k];
if (!ch->enabled)
continue;
for (n = 0; n < NR_CH_REGS; n++)
ch->saved_ch_regs[n] = lcdc_read_chan(ch, n);
}
/* save shared registers */
for (n = 0; n < NR_SHARED_REGS; n++)
p->saved_shared_regs[n] = lcdc_read(p, lcdc_shared_regs[n]);
/* turn off LCDC hardware */
lcdc_write(p, _LDCNT1R, 0);
return 0;
}
static int sh_mobile_lcdc_runtime_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct sh_mobile_lcdc_priv *p = platform_get_drvdata(pdev);
struct sh_mobile_lcdc_chan *ch;
int k, n;
/* restore per-channel registers */
for (k = 0; k < ARRAY_SIZE(p->ch); k++) {
ch = &p->ch[k];
if (!ch->enabled)
continue;
for (n = 0; n < NR_CH_REGS; n++)
lcdc_write_chan(ch, n, ch->saved_ch_regs[n]);
}
/* restore shared registers */
for (n = 0; n < NR_SHARED_REGS; n++)
lcdc_write(p, lcdc_shared_regs[n], p->saved_shared_regs[n]);
return 0;
}
static const struct dev_pm_ops sh_mobile_lcdc_dev_pm_ops = {
.suspend = sh_mobile_lcdc_suspend,
.resume = sh_mobile_lcdc_resume,
.runtime_suspend = sh_mobile_lcdc_runtime_suspend,
.runtime_resume = sh_mobile_lcdc_runtime_resume,
};
static int sh_mobile_lcdc_remove(struct platform_device *pdev);
static int __devinit sh_mobile_lcdc_probe(struct platform_device *pdev)
{
struct fb_info *info;
struct sh_mobile_lcdc_priv *priv;
struct sh_mobile_lcdc_info *pdata;
struct sh_mobile_lcdc_chan_cfg *cfg;
struct resource *res;
int error;
void *buf;
int i, j;
if (!pdev->dev.platform_data) {
dev_err(&pdev->dev, "no platform data defined\n");
return -EINVAL;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
i = platform_get_irq(pdev, 0);
if (!res || i < 0) {
dev_err(&pdev->dev, "cannot get platform resources\n");
return -ENOENT;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(&pdev->dev, "cannot allocate device data\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, priv);
error = request_irq(i, sh_mobile_lcdc_irq, IRQF_DISABLED,
dev_name(&pdev->dev), priv);
if (error) {
dev_err(&pdev->dev, "unable to request irq\n");
goto err1;
}
priv->irq = i;
pdata = pdev->dev.platform_data;
j = 0;
for (i = 0; i < ARRAY_SIZE(pdata->ch); i++) {
priv->ch[j].lcdc = priv;
memcpy(&priv->ch[j].cfg, &pdata->ch[i], sizeof(pdata->ch[i]));
error = sh_mobile_lcdc_check_interface(&priv->ch[j]);
if (error) {
dev_err(&pdev->dev, "unsupported interface type\n");
goto err1;
}
init_waitqueue_head(&priv->ch[j].frame_end_wait);
init_completion(&priv->ch[j].vsync_completion);
priv->ch[j].pan_offset = 0;
switch (pdata->ch[i].chan) {
case LCDC_CHAN_MAINLCD:
priv->ch[j].enabled = 1 << 1;
priv->ch[j].reg_offs = lcdc_offs_mainlcd;
j++;
break;
case LCDC_CHAN_SUBLCD:
priv->ch[j].enabled = 1 << 2;
priv->ch[j].reg_offs = lcdc_offs_sublcd;
j++;
break;
}
}
if (!j) {
dev_err(&pdev->dev, "no channels defined\n");
error = -EINVAL;
goto err1;
}
error = sh_mobile_lcdc_setup_clocks(pdev, pdata->clock_source, priv);
if (error) {
dev_err(&pdev->dev, "unable to setup clocks\n");
goto err1;
}
priv->base = ioremap_nocache(res->start, (res->end - res->start) + 1);
for (i = 0; i < j; i++) {
cfg = &priv->ch[i].cfg;
priv->ch[i].info = framebuffer_alloc(0, &pdev->dev);
if (!priv->ch[i].info) {
dev_err(&pdev->dev, "unable to allocate fb_info\n");
error = -ENOMEM;
break;
}
info = priv->ch[i].info;
info->fbops = &sh_mobile_lcdc_ops;
info->var.xres = info->var.xres_virtual = cfg->lcd_cfg.xres;
info->var.yres = cfg->lcd_cfg.yres;
/* Default Y virtual resolution is 2x panel size */
info->var.yres_virtual = info->var.yres * 2;
info->var.width = cfg->lcd_size_cfg.width;
info->var.height = cfg->lcd_size_cfg.height;
info->var.activate = FB_ACTIVATE_NOW;
error = sh_mobile_lcdc_set_bpp(&info->var, cfg->bpp);
if (error)
break;
info->fix = sh_mobile_lcdc_fix;
info->fix.line_length = cfg->lcd_cfg.xres * (cfg->bpp / 8);
info->fix.smem_len = info->fix.line_length *
info->var.yres_virtual;
buf = dma_alloc_coherent(&pdev->dev, info->fix.smem_len,
&priv->ch[i].dma_handle, GFP_KERNEL);
if (!buf) {
dev_err(&pdev->dev, "unable to allocate buffer\n");
error = -ENOMEM;
break;
}
info->pseudo_palette = &priv->ch[i].pseudo_palette;
info->flags = FBINFO_FLAG_DEFAULT;
error = fb_alloc_cmap(&info->cmap, PALETTE_NR, 0);
if (error < 0) {
dev_err(&pdev->dev, "unable to allocate cmap\n");
dma_free_coherent(&pdev->dev, info->fix.smem_len,
buf, priv->ch[i].dma_handle);
break;
}
memset(buf, 0, info->fix.smem_len);
info->fix.smem_start = priv->ch[i].dma_handle;
info->screen_base = buf;
info->device = &pdev->dev;
info->par = &priv->ch[i];
}
if (error)
goto err1;
error = sh_mobile_lcdc_start(priv);
if (error) {
dev_err(&pdev->dev, "unable to start hardware\n");
goto err1;
}
for (i = 0; i < j; i++) {
struct sh_mobile_lcdc_chan *ch = priv->ch + i;
info = ch->info;
if (info->fbdefio) {
ch->sglist = vmalloc(sizeof(struct scatterlist) *
info->fix.smem_len >> PAGE_SHIFT);
if (!ch->sglist) {
dev_err(&pdev->dev, "cannot allocate sglist\n");
goto err1;
}
}
error = register_framebuffer(info);
if (error < 0)
goto err1;
dev_info(info->dev,
"registered %s/%s as %dx%d %dbpp.\n",
pdev->name,
(ch->cfg.chan == LCDC_CHAN_MAINLCD) ?
"mainlcd" : "sublcd",
(int) ch->cfg.lcd_cfg.xres,
(int) ch->cfg.lcd_cfg.yres,
ch->cfg.bpp);
/* deferred io mode: disable clock to save power */
if (info->fbdefio)
sh_mobile_lcdc_clk_off(priv);
}
return 0;
err1:
sh_mobile_lcdc_remove(pdev);
return error;
}
static int sh_mobile_lcdc_remove(struct platform_device *pdev)
{
struct sh_mobile_lcdc_priv *priv = platform_get_drvdata(pdev);
struct fb_info *info;
int i;
for (i = 0; i < ARRAY_SIZE(priv->ch); i++)
if (priv->ch[i].info && priv->ch[i].info->dev)
unregister_framebuffer(priv->ch[i].info);
sh_mobile_lcdc_stop(priv);
for (i = 0; i < ARRAY_SIZE(priv->ch); i++) {
info = priv->ch[i].info;
if (!info || !info->device)
continue;
if (priv->ch[i].sglist)
vfree(priv->ch[i].sglist);
dma_free_coherent(&pdev->dev, info->fix.smem_len,
info->screen_base, priv->ch[i].dma_handle);
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
if (priv->dot_clk)
clk_put(priv->dot_clk);
if (priv->dev)
pm_runtime_disable(priv->dev);
if (priv->base)
iounmap(priv->base);
if (priv->irq)
free_irq(priv->irq, priv);
kfree(priv);
return 0;
}
static struct platform_driver sh_mobile_lcdc_driver = {
.driver = {
.name = "sh_mobile_lcdc_fb",
.owner = THIS_MODULE,
.pm = &sh_mobile_lcdc_dev_pm_ops,
},
.probe = sh_mobile_lcdc_probe,
.remove = sh_mobile_lcdc_remove,
};
static int __init sh_mobile_lcdc_init(void)
{
return platform_driver_register(&sh_mobile_lcdc_driver);
}
static void __exit sh_mobile_lcdc_exit(void)
{
platform_driver_unregister(&sh_mobile_lcdc_driver);
}
module_init(sh_mobile_lcdc_init);
module_exit(sh_mobile_lcdc_exit);
MODULE_DESCRIPTION("SuperH Mobile LCDC Framebuffer driver");
MODULE_AUTHOR("Magnus Damm <damm@opensource.se>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dev-elixir/hx_wt88047 | drivers/pinctrl/pinconf-generic.c | 762 | 7300 | /*
* Core driver for the generic pin config portions of the pin control subsystem
*
* Copyright (C) 2011 ST-Ericsson SA
* Written on behalf of Linaro for ST-Ericsson
*
* Author: Linus Walleij <linus.walleij@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) "generic pinconfig core: " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinconf.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <linux/of.h>
#include "core.h"
#include "pinconf.h"
#ifdef CONFIG_DEBUG_FS
struct pin_config_item {
const enum pin_config_param param;
const char * const display;
const char * const format;
};
#define PCONFDUMP(a, b, c) { .param = a, .display = b, .format = c }
static struct pin_config_item conf_items[] = {
PCONFDUMP(PIN_CONFIG_BIAS_DISABLE, "input bias disabled", NULL),
PCONFDUMP(PIN_CONFIG_BIAS_HIGH_IMPEDANCE, "input bias high impedance", NULL),
PCONFDUMP(PIN_CONFIG_BIAS_BUS_HOLD, "input bias bus hold", NULL),
PCONFDUMP(PIN_CONFIG_BIAS_PULL_UP, "input bias pull up", NULL),
PCONFDUMP(PIN_CONFIG_BIAS_PULL_DOWN, "input bias pull down", NULL),
PCONFDUMP(PIN_CONFIG_BIAS_PULL_PIN_DEFAULT,
"input bias pull to pin specific state", NULL),
PCONFDUMP(PIN_CONFIG_DRIVE_PUSH_PULL, "output drive push pull", NULL),
PCONFDUMP(PIN_CONFIG_DRIVE_OPEN_DRAIN, "output drive open drain", NULL),
PCONFDUMP(PIN_CONFIG_DRIVE_OPEN_SOURCE, "output drive open source", NULL),
PCONFDUMP(PIN_CONFIG_DRIVE_STRENGTH, "output drive strength", "mA"),
PCONFDUMP(PIN_CONFIG_INPUT_ENABLE, "input enabled", NULL),
PCONFDUMP(PIN_CONFIG_INPUT_SCHMITT_ENABLE, "input schmitt enabled", NULL),
PCONFDUMP(PIN_CONFIG_INPUT_SCHMITT, "input schmitt trigger", NULL),
PCONFDUMP(PIN_CONFIG_INPUT_DEBOUNCE, "input debounce", "usec"),
PCONFDUMP(PIN_CONFIG_POWER_SOURCE, "pin power source", "selector"),
PCONFDUMP(PIN_CONFIG_SLEW_RATE, "slew rate", NULL),
PCONFDUMP(PIN_CONFIG_LOW_POWER_MODE, "pin low power", "mode"),
PCONFDUMP(PIN_CONFIG_OUTPUT, "pin output", "level"),
};
void pinconf_generic_dump_pin(struct pinctrl_dev *pctldev,
struct seq_file *s, unsigned pin)
{
const struct pinconf_ops *ops = pctldev->desc->confops;
int i;
if (!ops->is_generic)
return;
for (i = 0; i < ARRAY_SIZE(conf_items); i++) {
unsigned long config;
int ret;
/* We want to check out this parameter */
config = pinconf_to_config_packed(conf_items[i].param, 0);
ret = pin_config_get_for_pin(pctldev, pin, &config);
/* These are legal errors */
if (ret == -EINVAL || ret == -ENOTSUPP)
continue;
if (ret) {
seq_printf(s, "ERROR READING CONFIG SETTING %d ", i);
continue;
}
/* Space between multiple configs */
seq_puts(s, " ");
seq_puts(s, conf_items[i].display);
/* Print unit if available */
if (conf_items[i].format &&
pinconf_to_config_argument(config) != 0)
seq_printf(s, " (%u %s)",
pinconf_to_config_argument(config),
conf_items[i].format);
}
}
void pinconf_generic_dump_group(struct pinctrl_dev *pctldev,
struct seq_file *s, const char *gname)
{
const struct pinconf_ops *ops = pctldev->desc->confops;
int i;
if (!ops->is_generic)
return;
for (i = 0; i < ARRAY_SIZE(conf_items); i++) {
unsigned long config;
int ret;
/* We want to check out this parameter */
config = pinconf_to_config_packed(conf_items[i].param, 0);
ret = pin_config_group_get(dev_name(pctldev->dev), gname,
&config);
/* These are legal errors */
if (ret == -EINVAL || ret == -ENOTSUPP)
continue;
if (ret) {
seq_printf(s, "ERROR READING CONFIG SETTING %d ", i);
continue;
}
/* Space between multiple configs */
seq_puts(s, " ");
seq_puts(s, conf_items[i].display);
/* Print unit if available */
if (conf_items[i].format && config != 0)
seq_printf(s, " (%u %s)",
pinconf_to_config_argument(config),
conf_items[i].format);
}
}
void pinconf_generic_dump_config(struct pinctrl_dev *pctldev,
struct seq_file *s, unsigned long config)
{
int i;
for (i = 0; i < ARRAY_SIZE(conf_items); i++) {
if (pinconf_to_config_param(config) != conf_items[i].param)
continue;
seq_printf(s, "%s: 0x%x", conf_items[i].display,
pinconf_to_config_argument(config));
}
}
EXPORT_SYMBOL_GPL(pinconf_generic_dump_config);
#endif
#ifdef CONFIG_OF
struct pinconf_generic_dt_params {
const char * const property;
enum pin_config_param param;
u32 default_value;
};
static struct pinconf_generic_dt_params dt_params[] = {
{ "bias-disable", PIN_CONFIG_BIAS_DISABLE, 0 },
{ "bias-high-impedance", PIN_CONFIG_BIAS_HIGH_IMPEDANCE, 0 },
{ "bias-bus-hold", PIN_CONFIG_BIAS_BUS_HOLD, 0 },
{ "bias-pull-up", PIN_CONFIG_BIAS_PULL_UP, 1 },
{ "bias-pull-down", PIN_CONFIG_BIAS_PULL_DOWN, 1 },
{ "bias-pull-pin-default", PIN_CONFIG_BIAS_PULL_PIN_DEFAULT, 1 },
{ "drive-push-pull", PIN_CONFIG_DRIVE_PUSH_PULL, 0 },
{ "drive-open-drain", PIN_CONFIG_DRIVE_OPEN_DRAIN, 0 },
{ "drive-open-source", PIN_CONFIG_DRIVE_OPEN_SOURCE, 0 },
{ "drive-strength", PIN_CONFIG_DRIVE_STRENGTH, 0 },
{ "input-enable", PIN_CONFIG_INPUT_ENABLE, 1 },
{ "input-disable", PIN_CONFIG_INPUT_ENABLE, 0 },
{ "input-schmitt-enable", PIN_CONFIG_INPUT_SCHMITT_ENABLE, 1 },
{ "input-schmitt-disable", PIN_CONFIG_INPUT_SCHMITT_ENABLE, 0 },
{ "input-debounce", PIN_CONFIG_INPUT_DEBOUNCE, 0 },
{ "low-power-enable", PIN_CONFIG_LOW_POWER_MODE, 1 },
{ "low-power-disable", PIN_CONFIG_LOW_POWER_MODE, 0 },
{ "output-low", PIN_CONFIG_OUTPUT, 0, },
{ "output-high", PIN_CONFIG_OUTPUT, 1, },
{ "slew-rate", PIN_CONFIG_SLEW_RATE, 0},
};
/**
* pinconf_generic_parse_dt_config()
* parse the config properties into generic pinconfig values.
* @np: node containing the pinconfig properties
* @configs: array with nconfigs entries containing the generic pinconf values
* @nconfigs: umber of configurations
*/
int pinconf_generic_parse_dt_config(struct device_node *np,
unsigned long **configs,
unsigned int *nconfigs)
{
unsigned long *cfg;
unsigned int ncfg = 0;
int ret;
int i;
u32 val;
if (!np)
return -EINVAL;
/* allocate a temporary array big enough to hold one of each option */
cfg = kzalloc(sizeof(*cfg) * ARRAY_SIZE(dt_params), GFP_KERNEL);
if (!cfg)
return -ENOMEM;
for (i = 0; i < ARRAY_SIZE(dt_params); i++) {
struct pinconf_generic_dt_params *par = &dt_params[i];
ret = of_property_read_u32(np, par->property, &val);
/* property not found */
if (ret == -EINVAL)
continue;
/* use default value, when no value is specified */
if (ret)
val = par->default_value;
pr_debug("found %s with value %u\n", par->property, val);
cfg[ncfg] = pinconf_to_config_packed(par->param, val);
ncfg++;
}
ret = 0;
/* no configs found at all */
if (ncfg == 0) {
*configs = NULL;
*nconfigs = 0;
goto out;
}
/*
* Now limit the number of configs to the real number of
* found properties.
*/
*configs = kzalloc(ncfg * sizeof(unsigned long), GFP_KERNEL);
if (!*configs) {
ret = -ENOMEM;
goto out;
}
memcpy(*configs, cfg, ncfg * sizeof(unsigned long));
*nconfigs = ncfg;
out:
kfree(cfg);
return ret;
}
#endif
| gpl-2.0 |
jstotero/Old_Cucciolone | sound/core/info.c | 762 | 23542 | /*
* Information interface for ALSA driver
* 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 <linux/init.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/smp_lock.h>
#include <linux/string.h>
#include <sound/core.h>
#include <sound/minors.h>
#include <sound/info.h>
#include <sound/version.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include <stdarg.h>
/*
*
*/
#ifdef CONFIG_PROC_FS
int snd_info_check_reserved_words(const char *str)
{
static char *reserved[] =
{
"version",
"meminfo",
"memdebug",
"detect",
"devices",
"oss",
"cards",
"timers",
"synth",
"pcm",
"seq",
NULL
};
char **xstr = reserved;
while (*xstr) {
if (!strcmp(*xstr, str))
return 0;
xstr++;
}
if (!strncmp(str, "card", 4))
return 0;
return 1;
}
static DEFINE_MUTEX(info_mutex);
struct snd_info_private_data {
struct snd_info_buffer *rbuffer;
struct snd_info_buffer *wbuffer;
struct snd_info_entry *entry;
void *file_private_data;
};
static int snd_info_version_init(void);
static int snd_info_version_done(void);
static void snd_info_disconnect(struct snd_info_entry *entry);
/* resize the proc r/w buffer */
static int resize_info_buffer(struct snd_info_buffer *buffer,
unsigned int nsize)
{
char *nbuf;
nsize = PAGE_ALIGN(nsize);
nbuf = krealloc(buffer->buffer, nsize, GFP_KERNEL);
if (! nbuf)
return -ENOMEM;
buffer->buffer = nbuf;
buffer->len = nsize;
return 0;
}
/**
* snd_iprintf - printf on the procfs buffer
* @buffer: the procfs buffer
* @fmt: the printf format
*
* Outputs the string on the procfs buffer just like printf().
*
* Returns the size of output string.
*/
int snd_iprintf(struct snd_info_buffer *buffer, const char *fmt, ...)
{
va_list args;
int len, res;
int err = 0;
might_sleep();
if (buffer->stop || buffer->error)
return 0;
len = buffer->len - buffer->size;
va_start(args, fmt);
for (;;) {
va_list ap;
va_copy(ap, args);
res = vsnprintf(buffer->buffer + buffer->curr, len, fmt, ap);
va_end(ap);
if (res < len)
break;
err = resize_info_buffer(buffer, buffer->len + PAGE_SIZE);
if (err < 0)
break;
len = buffer->len - buffer->size;
}
va_end(args);
if (err < 0)
return err;
buffer->curr += res;
buffer->size += res;
return res;
}
EXPORT_SYMBOL(snd_iprintf);
/*
*/
static struct proc_dir_entry *snd_proc_root;
struct snd_info_entry *snd_seq_root;
EXPORT_SYMBOL(snd_seq_root);
#ifdef CONFIG_SND_OSSEMUL
struct snd_info_entry *snd_oss_root;
#endif
static void snd_remove_proc_entry(struct proc_dir_entry *parent,
struct proc_dir_entry *de)
{
if (de)
remove_proc_entry(de->name, parent);
}
static loff_t snd_info_entry_llseek(struct file *file, loff_t offset, int orig)
{
struct snd_info_private_data *data;
struct snd_info_entry *entry;
loff_t ret = -EINVAL, size;
data = file->private_data;
entry = data->entry;
mutex_lock(&entry->access);
if (entry->content == SNDRV_INFO_CONTENT_DATA &&
entry->c.ops->llseek) {
offset = entry->c.ops->llseek(entry,
data->file_private_data,
file, offset, orig);
goto out;
}
if (entry->content == SNDRV_INFO_CONTENT_DATA)
size = entry->size;
else
size = 0;
switch (orig) {
case SEEK_SET:
break;
case SEEK_CUR:
offset += file->f_pos;
break;
case SEEK_END:
if (!size)
goto out;
offset += size;
break;
default:
goto out;
}
if (offset < 0)
goto out;
if (size && offset > size)
offset = size;
file->f_pos = offset;
ret = offset;
out:
mutex_unlock(&entry->access);
return ret;
}
static ssize_t snd_info_entry_read(struct file *file, char __user *buffer,
size_t count, loff_t * offset)
{
struct snd_info_private_data *data;
struct snd_info_entry *entry;
struct snd_info_buffer *buf;
size_t size = 0;
loff_t pos;
data = file->private_data;
if (snd_BUG_ON(!data))
return -ENXIO;
pos = *offset;
if (pos < 0 || (long) pos != pos || (ssize_t) count < 0)
return -EIO;
if ((unsigned long) pos + (unsigned long) count < (unsigned long) pos)
return -EIO;
entry = data->entry;
switch (entry->content) {
case SNDRV_INFO_CONTENT_TEXT:
buf = data->rbuffer;
if (buf == NULL)
return -EIO;
if (pos >= buf->size)
return 0;
size = buf->size - pos;
size = min(count, size);
if (copy_to_user(buffer, buf->buffer + pos, size))
return -EFAULT;
break;
case SNDRV_INFO_CONTENT_DATA:
if (pos >= entry->size)
return 0;
if (entry->c.ops->read) {
size = entry->size - pos;
size = min(count, size);
size = entry->c.ops->read(entry,
data->file_private_data,
file, buffer, size, pos);
}
break;
}
if ((ssize_t) size > 0)
*offset = pos + size;
return size;
}
static ssize_t snd_info_entry_write(struct file *file, const char __user *buffer,
size_t count, loff_t * offset)
{
struct snd_info_private_data *data;
struct snd_info_entry *entry;
struct snd_info_buffer *buf;
ssize_t size = 0;
loff_t pos;
data = file->private_data;
if (snd_BUG_ON(!data))
return -ENXIO;
entry = data->entry;
pos = *offset;
if (pos < 0 || (long) pos != pos || (ssize_t) count < 0)
return -EIO;
if ((unsigned long) pos + (unsigned long) count < (unsigned long) pos)
return -EIO;
switch (entry->content) {
case SNDRV_INFO_CONTENT_TEXT:
buf = data->wbuffer;
if (buf == NULL)
return -EIO;
mutex_lock(&entry->access);
if (pos + count >= buf->len) {
if (resize_info_buffer(buf, pos + count)) {
mutex_unlock(&entry->access);
return -ENOMEM;
}
}
if (copy_from_user(buf->buffer + pos, buffer, count)) {
mutex_unlock(&entry->access);
return -EFAULT;
}
buf->size = pos + count;
mutex_unlock(&entry->access);
size = count;
break;
case SNDRV_INFO_CONTENT_DATA:
if (entry->c.ops->write && count > 0) {
size_t maxsize = entry->size - pos;
count = min(count, maxsize);
size = entry->c.ops->write(entry,
data->file_private_data,
file, buffer, count, pos);
}
break;
}
if ((ssize_t) size > 0)
*offset = pos + size;
return size;
}
static int snd_info_entry_open(struct inode *inode, struct file *file)
{
struct snd_info_entry *entry;
struct snd_info_private_data *data;
struct snd_info_buffer *buffer;
struct proc_dir_entry *p;
int mode, err;
mutex_lock(&info_mutex);
p = PDE(inode);
entry = p == NULL ? NULL : (struct snd_info_entry *)p->data;
if (entry == NULL || ! entry->p) {
mutex_unlock(&info_mutex);
return -ENODEV;
}
if (!try_module_get(entry->module)) {
err = -EFAULT;
goto __error1;
}
mode = file->f_flags & O_ACCMODE;
if (mode == O_RDONLY || mode == O_RDWR) {
if ((entry->content == SNDRV_INFO_CONTENT_DATA &&
entry->c.ops->read == NULL)) {
err = -ENODEV;
goto __error;
}
}
if (mode == O_WRONLY || mode == O_RDWR) {
if ((entry->content == SNDRV_INFO_CONTENT_DATA &&
entry->c.ops->write == NULL)) {
err = -ENODEV;
goto __error;
}
}
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (data == NULL) {
err = -ENOMEM;
goto __error;
}
data->entry = entry;
switch (entry->content) {
case SNDRV_INFO_CONTENT_TEXT:
if (mode == O_RDONLY || mode == O_RDWR) {
buffer = kzalloc(sizeof(*buffer), GFP_KERNEL);
if (buffer == NULL)
goto __nomem;
data->rbuffer = buffer;
buffer->len = PAGE_SIZE;
buffer->buffer = kmalloc(buffer->len, GFP_KERNEL);
if (buffer->buffer == NULL)
goto __nomem;
}
if (mode == O_WRONLY || mode == O_RDWR) {
buffer = kzalloc(sizeof(*buffer), GFP_KERNEL);
if (buffer == NULL)
goto __nomem;
data->wbuffer = buffer;
buffer->len = PAGE_SIZE;
buffer->buffer = kmalloc(buffer->len, GFP_KERNEL);
if (buffer->buffer == NULL)
goto __nomem;
}
break;
case SNDRV_INFO_CONTENT_DATA: /* data */
if (entry->c.ops->open) {
if ((err = entry->c.ops->open(entry, mode,
&data->file_private_data)) < 0) {
kfree(data);
goto __error;
}
}
break;
}
file->private_data = data;
mutex_unlock(&info_mutex);
if (entry->content == SNDRV_INFO_CONTENT_TEXT &&
(mode == O_RDONLY || mode == O_RDWR)) {
if (entry->c.text.read) {
mutex_lock(&entry->access);
entry->c.text.read(entry, data->rbuffer);
mutex_unlock(&entry->access);
}
}
return 0;
__nomem:
if (data->rbuffer) {
kfree(data->rbuffer->buffer);
kfree(data->rbuffer);
}
if (data->wbuffer) {
kfree(data->wbuffer->buffer);
kfree(data->wbuffer);
}
kfree(data);
err = -ENOMEM;
__error:
module_put(entry->module);
__error1:
mutex_unlock(&info_mutex);
return err;
}
static int snd_info_entry_release(struct inode *inode, struct file *file)
{
struct snd_info_entry *entry;
struct snd_info_private_data *data;
int mode;
mode = file->f_flags & O_ACCMODE;
data = file->private_data;
entry = data->entry;
switch (entry->content) {
case SNDRV_INFO_CONTENT_TEXT:
if (data->rbuffer) {
kfree(data->rbuffer->buffer);
kfree(data->rbuffer);
}
if (data->wbuffer) {
if (entry->c.text.write) {
entry->c.text.write(entry, data->wbuffer);
if (data->wbuffer->error) {
snd_printk(KERN_WARNING "data write error to %s (%i)\n",
entry->name,
data->wbuffer->error);
}
}
kfree(data->wbuffer->buffer);
kfree(data->wbuffer);
}
break;
case SNDRV_INFO_CONTENT_DATA:
if (entry->c.ops->release)
entry->c.ops->release(entry, mode,
data->file_private_data);
break;
}
module_put(entry->module);
kfree(data);
return 0;
}
static unsigned int snd_info_entry_poll(struct file *file, poll_table * wait)
{
struct snd_info_private_data *data;
struct snd_info_entry *entry;
unsigned int mask;
data = file->private_data;
if (data == NULL)
return 0;
entry = data->entry;
mask = 0;
switch (entry->content) {
case SNDRV_INFO_CONTENT_DATA:
if (entry->c.ops->poll)
return entry->c.ops->poll(entry,
data->file_private_data,
file, wait);
if (entry->c.ops->read)
mask |= POLLIN | POLLRDNORM;
if (entry->c.ops->write)
mask |= POLLOUT | POLLWRNORM;
break;
}
return mask;
}
static long snd_info_entry_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_info_private_data *data;
struct snd_info_entry *entry;
data = file->private_data;
if (data == NULL)
return 0;
entry = data->entry;
switch (entry->content) {
case SNDRV_INFO_CONTENT_DATA:
if (entry->c.ops->ioctl)
return entry->c.ops->ioctl(entry,
data->file_private_data,
file, cmd, arg);
break;
}
return -ENOTTY;
}
static int snd_info_entry_mmap(struct file *file, struct vm_area_struct *vma)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct snd_info_private_data *data;
struct snd_info_entry *entry;
data = file->private_data;
if (data == NULL)
return 0;
entry = data->entry;
switch (entry->content) {
case SNDRV_INFO_CONTENT_DATA:
if (entry->c.ops->mmap)
return entry->c.ops->mmap(entry,
data->file_private_data,
inode, file, vma);
break;
}
return -ENXIO;
}
static const struct file_operations snd_info_entry_operations =
{
.owner = THIS_MODULE,
.llseek = snd_info_entry_llseek,
.read = snd_info_entry_read,
.write = snd_info_entry_write,
.poll = snd_info_entry_poll,
.unlocked_ioctl = snd_info_entry_ioctl,
.mmap = snd_info_entry_mmap,
.open = snd_info_entry_open,
.release = snd_info_entry_release,
};
int __init snd_info_init(void)
{
struct proc_dir_entry *p;
p = create_proc_entry("asound", S_IFDIR | S_IRUGO | S_IXUGO, NULL);
if (p == NULL)
return -ENOMEM;
snd_proc_root = p;
#ifdef CONFIG_SND_OSSEMUL
{
struct snd_info_entry *entry;
if ((entry = snd_info_create_module_entry(THIS_MODULE, "oss", NULL)) == NULL)
return -ENOMEM;
entry->mode = S_IFDIR | S_IRUGO | S_IXUGO;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
snd_oss_root = entry;
}
#endif
#if defined(CONFIG_SND_SEQUENCER) || defined(CONFIG_SND_SEQUENCER_MODULE)
{
struct snd_info_entry *entry;
if ((entry = snd_info_create_module_entry(THIS_MODULE, "seq", NULL)) == NULL)
return -ENOMEM;
entry->mode = S_IFDIR | S_IRUGO | S_IXUGO;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
snd_seq_root = entry;
}
#endif
snd_info_version_init();
snd_minor_info_init();
snd_minor_info_oss_init();
snd_card_info_init();
return 0;
}
int __exit snd_info_done(void)
{
snd_card_info_done();
snd_minor_info_oss_done();
snd_minor_info_done();
snd_info_version_done();
if (snd_proc_root) {
#if defined(CONFIG_SND_SEQUENCER) || defined(CONFIG_SND_SEQUENCER_MODULE)
snd_info_free_entry(snd_seq_root);
#endif
#ifdef CONFIG_SND_OSSEMUL
snd_info_free_entry(snd_oss_root);
#endif
snd_remove_proc_entry(NULL, snd_proc_root);
}
return 0;
}
/*
*/
/*
* create a card proc file
* called from init.c
*/
int snd_info_card_create(struct snd_card *card)
{
char str[8];
struct snd_info_entry *entry;
if (snd_BUG_ON(!card))
return -ENXIO;
sprintf(str, "card%i", card->number);
if ((entry = snd_info_create_module_entry(card->module, str, NULL)) == NULL)
return -ENOMEM;
entry->mode = S_IFDIR | S_IRUGO | S_IXUGO;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
card->proc_root = entry;
return 0;
}
/*
* register the card proc file
* called from init.c
*/
int snd_info_card_register(struct snd_card *card)
{
struct proc_dir_entry *p;
if (snd_BUG_ON(!card))
return -ENXIO;
if (!strcmp(card->id, card->proc_root->name))
return 0;
p = proc_symlink(card->id, snd_proc_root, card->proc_root->name);
if (p == NULL)
return -ENOMEM;
card->proc_root_link = p;
return 0;
}
/*
* called on card->id change
*/
void snd_info_card_id_change(struct snd_card *card)
{
mutex_lock(&info_mutex);
if (card->proc_root_link) {
snd_remove_proc_entry(snd_proc_root, card->proc_root_link);
card->proc_root_link = NULL;
}
if (strcmp(card->id, card->proc_root->name))
card->proc_root_link = proc_symlink(card->id,
snd_proc_root,
card->proc_root->name);
mutex_unlock(&info_mutex);
}
/*
* de-register the card proc file
* called from init.c
*/
void snd_info_card_disconnect(struct snd_card *card)
{
if (!card)
return;
mutex_lock(&info_mutex);
if (card->proc_root_link) {
snd_remove_proc_entry(snd_proc_root, card->proc_root_link);
card->proc_root_link = NULL;
}
if (card->proc_root)
snd_info_disconnect(card->proc_root);
mutex_unlock(&info_mutex);
}
/*
* release the card proc file resources
* called from init.c
*/
int snd_info_card_free(struct snd_card *card)
{
if (!card)
return 0;
snd_info_free_entry(card->proc_root);
card->proc_root = NULL;
return 0;
}
/**
* snd_info_get_line - read one line from the procfs buffer
* @buffer: the procfs buffer
* @line: the buffer to store
* @len: the max. buffer size - 1
*
* Reads one line from the buffer and stores the string.
*
* Returns zero if successful, or 1 if error or EOF.
*/
int snd_info_get_line(struct snd_info_buffer *buffer, char *line, int len)
{
int c = -1;
if (len <= 0 || buffer->stop || buffer->error)
return 1;
while (--len > 0) {
c = buffer->buffer[buffer->curr++];
if (c == '\n') {
if (buffer->curr >= buffer->size)
buffer->stop = 1;
break;
}
*line++ = c;
if (buffer->curr >= buffer->size) {
buffer->stop = 1;
break;
}
}
while (c != '\n' && !buffer->stop) {
c = buffer->buffer[buffer->curr++];
if (buffer->curr >= buffer->size)
buffer->stop = 1;
}
*line = '\0';
return 0;
}
EXPORT_SYMBOL(snd_info_get_line);
/**
* snd_info_get_str - parse a string token
* @dest: the buffer to store the string token
* @src: the original string
* @len: the max. length of token - 1
*
* Parses the original string and copy a token to the given
* string buffer.
*
* Returns the updated pointer of the original string so that
* it can be used for the next call.
*/
const char *snd_info_get_str(char *dest, const char *src, int len)
{
int c;
while (*src == ' ' || *src == '\t')
src++;
if (*src == '"' || *src == '\'') {
c = *src++;
while (--len > 0 && *src && *src != c) {
*dest++ = *src++;
}
if (*src == c)
src++;
} else {
while (--len > 0 && *src && *src != ' ' && *src != '\t') {
*dest++ = *src++;
}
}
*dest = 0;
while (*src == ' ' || *src == '\t')
src++;
return src;
}
EXPORT_SYMBOL(snd_info_get_str);
/**
* snd_info_create_entry - create an info entry
* @name: the proc file name
*
* Creates an info entry with the given file name and initializes as
* the default state.
*
* Usually called from other functions such as
* snd_info_create_card_entry().
*
* Returns the pointer of the new instance, or NULL on failure.
*/
static struct snd_info_entry *snd_info_create_entry(const char *name)
{
struct snd_info_entry *entry;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (entry == NULL)
return NULL;
entry->name = kstrdup(name, GFP_KERNEL);
if (entry->name == NULL) {
kfree(entry);
return NULL;
}
entry->mode = S_IFREG | S_IRUGO;
entry->content = SNDRV_INFO_CONTENT_TEXT;
mutex_init(&entry->access);
INIT_LIST_HEAD(&entry->children);
INIT_LIST_HEAD(&entry->list);
return entry;
}
/**
* snd_info_create_module_entry - create an info entry for the given module
* @module: the module pointer
* @name: the file name
* @parent: the parent directory
*
* Creates a new info entry and assigns it to the given module.
*
* Returns the pointer of the new instance, or NULL on failure.
*/
struct snd_info_entry *snd_info_create_module_entry(struct module * module,
const char *name,
struct snd_info_entry *parent)
{
struct snd_info_entry *entry = snd_info_create_entry(name);
if (entry) {
entry->module = module;
entry->parent = parent;
}
return entry;
}
EXPORT_SYMBOL(snd_info_create_module_entry);
/**
* snd_info_create_card_entry - create an info entry for the given card
* @card: the card instance
* @name: the file name
* @parent: the parent directory
*
* Creates a new info entry and assigns it to the given card.
*
* Returns the pointer of the new instance, or NULL on failure.
*/
struct snd_info_entry *snd_info_create_card_entry(struct snd_card *card,
const char *name,
struct snd_info_entry * parent)
{
struct snd_info_entry *entry = snd_info_create_entry(name);
if (entry) {
entry->module = card->module;
entry->card = card;
entry->parent = parent;
}
return entry;
}
EXPORT_SYMBOL(snd_info_create_card_entry);
static void snd_info_disconnect(struct snd_info_entry *entry)
{
struct list_head *p, *n;
struct proc_dir_entry *root;
list_for_each_safe(p, n, &entry->children) {
snd_info_disconnect(list_entry(p, struct snd_info_entry, list));
}
if (! entry->p)
return;
list_del_init(&entry->list);
root = entry->parent == NULL ? snd_proc_root : entry->parent->p;
snd_BUG_ON(!root);
snd_remove_proc_entry(root, entry->p);
entry->p = NULL;
}
static int snd_info_dev_free_entry(struct snd_device *device)
{
struct snd_info_entry *entry = device->device_data;
snd_info_free_entry(entry);
return 0;
}
static int snd_info_dev_register_entry(struct snd_device *device)
{
struct snd_info_entry *entry = device->device_data;
return snd_info_register(entry);
}
/**
* snd_card_proc_new - create an info entry for the given card
* @card: the card instance
* @name: the file name
* @entryp: the pointer to store the new info entry
*
* Creates a new info entry and assigns it to the given card.
* Unlike snd_info_create_card_entry(), this function registers the
* info entry as an ALSA device component, so that it can be
* unregistered/released without explicit call.
* Also, you don't have to register this entry via snd_info_register(),
* since this will be registered by snd_card_register() automatically.
*
* The parent is assumed as card->proc_root.
*
* For releasing this entry, use snd_device_free() instead of
* snd_info_free_entry().
*
* Returns zero if successful, or a negative error code on failure.
*/
int snd_card_proc_new(struct snd_card *card, const char *name,
struct snd_info_entry **entryp)
{
static struct snd_device_ops ops = {
.dev_free = snd_info_dev_free_entry,
.dev_register = snd_info_dev_register_entry,
/* disconnect is done via snd_info_card_disconnect() */
};
struct snd_info_entry *entry;
int err;
entry = snd_info_create_card_entry(card, name, card->proc_root);
if (! entry)
return -ENOMEM;
if ((err = snd_device_new(card, SNDRV_DEV_INFO, entry, &ops)) < 0) {
snd_info_free_entry(entry);
return err;
}
if (entryp)
*entryp = entry;
return 0;
}
EXPORT_SYMBOL(snd_card_proc_new);
/**
* snd_info_free_entry - release the info entry
* @entry: the info entry
*
* Releases the info entry. Don't call this after registered.
*/
void snd_info_free_entry(struct snd_info_entry * entry)
{
if (entry == NULL)
return;
if (entry->p) {
mutex_lock(&info_mutex);
snd_info_disconnect(entry);
mutex_unlock(&info_mutex);
}
kfree(entry->name);
if (entry->private_free)
entry->private_free(entry);
kfree(entry);
}
EXPORT_SYMBOL(snd_info_free_entry);
/**
* snd_info_register - register the info entry
* @entry: the info entry
*
* Registers the proc info entry.
*
* Returns zero if successful, or a negative error code on failure.
*/
int snd_info_register(struct snd_info_entry * entry)
{
struct proc_dir_entry *root, *p = NULL;
if (snd_BUG_ON(!entry))
return -ENXIO;
root = entry->parent == NULL ? snd_proc_root : entry->parent->p;
mutex_lock(&info_mutex);
p = create_proc_entry(entry->name, entry->mode, root);
if (!p) {
mutex_unlock(&info_mutex);
return -ENOMEM;
}
if (!S_ISDIR(entry->mode))
p->proc_fops = &snd_info_entry_operations;
p->size = entry->size;
p->data = entry;
entry->p = p;
if (entry->parent)
list_add_tail(&entry->list, &entry->parent->children);
mutex_unlock(&info_mutex);
return 0;
}
EXPORT_SYMBOL(snd_info_register);
/*
*/
static struct snd_info_entry *snd_info_version_entry;
static void snd_info_version_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
{
snd_iprintf(buffer,
"Advanced Linux Sound Architecture Driver Version "
CONFIG_SND_VERSION CONFIG_SND_DATE ".\n"
);
}
static int __init snd_info_version_init(void)
{
struct snd_info_entry *entry;
entry = snd_info_create_module_entry(THIS_MODULE, "version", NULL);
if (entry == NULL)
return -ENOMEM;
entry->c.text.read = snd_info_version_read;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
snd_info_version_entry = entry;
return 0;
}
static int __exit snd_info_version_done(void)
{
snd_info_free_entry(snd_info_version_entry);
return 0;
}
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.