repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
Pesach85/PH85-KERNEL | arch/um/drivers/umcast_kern.c | 7719 | 4711 | /*
* user-mode-linux networking multicast transport
* Copyright (C) 2001 by Harald Welte <laforge@gnumonks.org>
* Copyright (C) 2001 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
*
* based on the existing uml-networking code, which is
* Copyright (C) 2001 Lennert Buytenhek (buytenh@gnu.org) and
* James Leu (jleu@mindspring.net).
* Copyright (C) 2001 by various other people who didn't put their name here.
*
* Licensed under the GPL.
*/
#include "linux/init.h"
#include <linux/netdevice.h>
#include "umcast.h"
#include "net_kern.h"
struct umcast_init {
char *addr;
int lport;
int rport;
int ttl;
bool unicast;
};
static void umcast_init(struct net_device *dev, void *data)
{
struct uml_net_private *pri;
struct umcast_data *dpri;
struct umcast_init *init = data;
pri = netdev_priv(dev);
dpri = (struct umcast_data *) pri->user;
dpri->addr = init->addr;
dpri->lport = init->lport;
dpri->rport = init->rport;
dpri->unicast = init->unicast;
dpri->ttl = init->ttl;
dpri->dev = dev;
if (dpri->unicast) {
printk(KERN_INFO "ucast backend address: %s:%u listen port: "
"%u\n", dpri->addr, dpri->rport, dpri->lport);
} else {
printk(KERN_INFO "mcast backend multicast address: %s:%u, "
"TTL:%u\n", dpri->addr, dpri->lport, dpri->ttl);
}
}
static int umcast_read(int fd, struct sk_buff *skb, struct uml_net_private *lp)
{
return net_recvfrom(fd, skb_mac_header(skb),
skb->dev->mtu + ETH_HEADER_OTHER);
}
static int umcast_write(int fd, struct sk_buff *skb, struct uml_net_private *lp)
{
return umcast_user_write(fd, skb->data, skb->len,
(struct umcast_data *) &lp->user);
}
static const struct net_kern_info umcast_kern_info = {
.init = umcast_init,
.protocol = eth_protocol,
.read = umcast_read,
.write = umcast_write,
};
static int mcast_setup(char *str, char **mac_out, void *data)
{
struct umcast_init *init = data;
char *port_str = NULL, *ttl_str = NULL, *remain;
char *last;
*init = ((struct umcast_init)
{ .addr = "239.192.168.1",
.lport = 1102,
.ttl = 1 });
remain = split_if_spec(str, mac_out, &init->addr, &port_str, &ttl_str,
NULL);
if (remain != NULL) {
printk(KERN_ERR "mcast_setup - Extra garbage on "
"specification : '%s'\n", remain);
return 0;
}
if (port_str != NULL) {
init->lport = simple_strtoul(port_str, &last, 10);
if ((*last != '\0') || (last == port_str)) {
printk(KERN_ERR "mcast_setup - Bad port : '%s'\n",
port_str);
return 0;
}
}
if (ttl_str != NULL) {
init->ttl = simple_strtoul(ttl_str, &last, 10);
if ((*last != '\0') || (last == ttl_str)) {
printk(KERN_ERR "mcast_setup - Bad ttl : '%s'\n",
ttl_str);
return 0;
}
}
init->unicast = false;
init->rport = init->lport;
printk(KERN_INFO "Configured mcast device: %s:%u-%u\n", init->addr,
init->lport, init->ttl);
return 1;
}
static int ucast_setup(char *str, char **mac_out, void *data)
{
struct umcast_init *init = data;
char *lport_str = NULL, *rport_str = NULL, *remain;
char *last;
*init = ((struct umcast_init)
{ .addr = "",
.lport = 1102,
.rport = 1102 });
remain = split_if_spec(str, mac_out, &init->addr,
&lport_str, &rport_str, NULL);
if (remain != NULL) {
printk(KERN_ERR "ucast_setup - Extra garbage on "
"specification : '%s'\n", remain);
return 0;
}
if (lport_str != NULL) {
init->lport = simple_strtoul(lport_str, &last, 10);
if ((*last != '\0') || (last == lport_str)) {
printk(KERN_ERR "ucast_setup - Bad listen port : "
"'%s'\n", lport_str);
return 0;
}
}
if (rport_str != NULL) {
init->rport = simple_strtoul(rport_str, &last, 10);
if ((*last != '\0') || (last == rport_str)) {
printk(KERN_ERR "ucast_setup - Bad remote port : "
"'%s'\n", rport_str);
return 0;
}
}
init->unicast = true;
printk(KERN_INFO "Configured ucast device: :%u -> %s:%u\n",
init->lport, init->addr, init->rport);
return 1;
}
static struct transport mcast_transport = {
.list = LIST_HEAD_INIT(mcast_transport.list),
.name = "mcast",
.setup = mcast_setup,
.user = &umcast_user_info,
.kern = &umcast_kern_info,
.private_size = sizeof(struct umcast_data),
.setup_size = sizeof(struct umcast_init),
};
static struct transport ucast_transport = {
.list = LIST_HEAD_INIT(ucast_transport.list),
.name = "ucast",
.setup = ucast_setup,
.user = &umcast_user_info,
.kern = &umcast_kern_info,
.private_size = sizeof(struct umcast_data),
.setup_size = sizeof(struct umcast_init),
};
static int register_umcast(void)
{
register_transport(&mcast_transport);
register_transport(&ucast_transport);
return 0;
}
late_initcall(register_umcast);
| gpl-2.0 |
CandyDevices/kernel_motorola_msm8226 | drivers/scsi/scsicam.c | 7975 | 7910 | /*
* scsicam.c - SCSI CAM support functions, use for HDIO_GETGEO, etc.
*
* Copyright 1993, 1994 Drew Eckhardt
* Visionary Computing
* (Unix and Linux consulting and custom programming)
* drew@Colorado.EDU
* +1 (303) 786-7975
*
* For more information, please consult the SCSI-CAM draft.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/genhd.h>
#include <linux/kernel.h>
#include <linux/blkdev.h>
#include <asm/unaligned.h>
#include <scsi/scsicam.h>
static int setsize(unsigned long capacity, unsigned int *cyls, unsigned int *hds,
unsigned int *secs);
/**
* scsi_bios_ptable - Read PC partition table out of first sector of device.
* @dev: from this device
*
* Description: Reads the first sector from the device and returns %0x42 bytes
* starting at offset %0x1be.
* Returns: partition table in kmalloc(GFP_KERNEL) memory, or NULL on error.
*/
unsigned char *scsi_bios_ptable(struct block_device *dev)
{
unsigned char *res = kmalloc(66, GFP_KERNEL);
if (res) {
struct block_device *bdev = dev->bd_contains;
Sector sect;
void *data = read_dev_sector(bdev, 0, §);
if (data) {
memcpy(res, data + 0x1be, 66);
put_dev_sector(sect);
} else {
kfree(res);
res = NULL;
}
}
return res;
}
EXPORT_SYMBOL(scsi_bios_ptable);
/**
* scsicam_bios_param - Determine geometry of a disk in cylinders/heads/sectors.
* @bdev: which device
* @capacity: size of the disk in sectors
* @ip: return value: ip[0]=heads, ip[1]=sectors, ip[2]=cylinders
*
* Description : determine the BIOS mapping/geometry used for a drive in a
* SCSI-CAM system, storing the results in ip as required
* by the HDIO_GETGEO ioctl().
*
* Returns : -1 on failure, 0 on success.
*/
int scsicam_bios_param(struct block_device *bdev, sector_t capacity, int *ip)
{
unsigned char *p;
u64 capacity64 = capacity; /* Suppress gcc warning */
int ret;
p = scsi_bios_ptable(bdev);
if (!p)
return -1;
/* try to infer mapping from partition table */
ret = scsi_partsize(p, (unsigned long)capacity, (unsigned int *)ip + 2,
(unsigned int *)ip + 0, (unsigned int *)ip + 1);
kfree(p);
if (ret == -1 && capacity64 < (1ULL << 32)) {
/* pick some standard mapping with at most 1024 cylinders,
and at most 62 sectors per track - this works up to
7905 MB */
ret = setsize((unsigned long)capacity, (unsigned int *)ip + 2,
(unsigned int *)ip + 0, (unsigned int *)ip + 1);
}
/* if something went wrong, then apparently we have to return
a geometry with more than 1024 cylinders */
if (ret || ip[0] > 255 || ip[1] > 63) {
if ((capacity >> 11) > 65534) {
ip[0] = 255;
ip[1] = 63;
} else {
ip[0] = 64;
ip[1] = 32;
}
if (capacity > 65535*63*255)
ip[2] = 65535;
else
ip[2] = (unsigned long)capacity / (ip[0] * ip[1]);
}
return 0;
}
EXPORT_SYMBOL(scsicam_bios_param);
/**
* scsi_partsize - Parse cylinders/heads/sectors from PC partition table
* @buf: partition table, see scsi_bios_ptable()
* @capacity: size of the disk in sectors
* @cyls: put cylinders here
* @hds: put heads here
* @secs: put sectors here
*
* Description: determine the BIOS mapping/geometry used to create the partition
* table, storing the results in *cyls, *hds, and *secs
*
* Returns: -1 on failure, 0 on success.
*/
int scsi_partsize(unsigned char *buf, unsigned long capacity,
unsigned int *cyls, unsigned int *hds, unsigned int *secs)
{
struct partition *p = (struct partition *)buf, *largest = NULL;
int i, largest_cyl;
int cyl, ext_cyl, end_head, end_cyl, end_sector;
unsigned int logical_end, physical_end, ext_physical_end;
if (*(unsigned short *) (buf + 64) == 0xAA55) {
for (largest_cyl = -1, i = 0; i < 4; ++i, ++p) {
if (!p->sys_ind)
continue;
#ifdef DEBUG
printk("scsicam_bios_param : partition %d has system \n",
i);
#endif
cyl = p->cyl + ((p->sector & 0xc0) << 2);
if (cyl > largest_cyl) {
largest_cyl = cyl;
largest = p;
}
}
}
if (largest) {
end_cyl = largest->end_cyl + ((largest->end_sector & 0xc0) << 2);
end_head = largest->end_head;
end_sector = largest->end_sector & 0x3f;
if (end_head + 1 == 0 || end_sector == 0)
return -1;
#ifdef DEBUG
printk("scsicam_bios_param : end at h = %d, c = %d, s = %d\n",
end_head, end_cyl, end_sector);
#endif
physical_end = end_cyl * (end_head + 1) * end_sector +
end_head * end_sector + end_sector;
/* This is the actual _sector_ number at the end */
logical_end = get_unaligned(&largest->start_sect)
+ get_unaligned(&largest->nr_sects);
/* This is for >1023 cylinders */
ext_cyl = (logical_end - (end_head * end_sector + end_sector))
/ (end_head + 1) / end_sector;
ext_physical_end = ext_cyl * (end_head + 1) * end_sector +
end_head * end_sector + end_sector;
#ifdef DEBUG
printk("scsicam_bios_param : logical_end=%d physical_end=%d ext_physical_end=%d ext_cyl=%d\n"
,logical_end, physical_end, ext_physical_end, ext_cyl);
#endif
if ((logical_end == physical_end) ||
(end_cyl == 1023 && ext_physical_end == logical_end)) {
*secs = end_sector;
*hds = end_head + 1;
*cyls = capacity / ((end_head + 1) * end_sector);
return 0;
}
#ifdef DEBUG
printk("scsicam_bios_param : logical (%u) != physical (%u)\n",
logical_end, physical_end);
#endif
}
return -1;
}
EXPORT_SYMBOL(scsi_partsize);
/*
* Function : static int setsize(unsigned long capacity,unsigned int *cyls,
* unsigned int *hds, unsigned int *secs);
*
* Purpose : to determine a near-optimal int 0x13 mapping for a
* SCSI disk in terms of lost space of size capacity, storing
* the results in *cyls, *hds, and *secs.
*
* Returns : -1 on failure, 0 on success.
*
* Extracted from
*
* WORKING X3T9.2
* DRAFT 792D
* see http://www.t10.org/ftp/t10/drafts/cam/cam-r12b.pdf
*
* Revision 6
* 10-MAR-94
* Information technology -
* SCSI-2 Common access method
* transport and SCSI interface module
*
* ANNEX A :
*
* setsize() converts a read capacity value to int 13h
* head-cylinder-sector requirements. It minimizes the value for
* number of heads and maximizes the number of cylinders. This
* will support rather large disks before the number of heads
* will not fit in 4 bits (or 6 bits). This algorithm also
* minimizes the number of sectors that will be unused at the end
* of the disk while allowing for very large disks to be
* accommodated. This algorithm does not use physical geometry.
*/
static int setsize(unsigned long capacity, unsigned int *cyls, unsigned int *hds,
unsigned int *secs)
{
unsigned int rv = 0;
unsigned long heads, sectors, cylinders, temp;
cylinders = 1024L; /* Set number of cylinders to max */
sectors = 62L; /* Maximize sectors per track */
temp = cylinders * sectors; /* Compute divisor for heads */
heads = capacity / temp; /* Compute value for number of heads */
if (capacity % temp) { /* If no remainder, done! */
heads++; /* Else, increment number of heads */
temp = cylinders * heads; /* Compute divisor for sectors */
sectors = capacity / temp; /* Compute value for sectors per
track */
if (capacity % temp) { /* If no remainder, done! */
sectors++; /* Else, increment number of sectors */
temp = heads * sectors; /* Compute divisor for cylinders */
cylinders = capacity / temp; /* Compute number of cylinders */
}
}
if (cylinders == 0)
rv = (unsigned) -1; /* Give error if 0 cylinders */
*cyls = (unsigned int) cylinders; /* Stuff return values */
*secs = (unsigned int) sectors;
*hds = (unsigned int) heads;
return (rv);
}
| gpl-2.0 |
mrjaydee82/SinLessKernelNew | drivers/isdn/hisax/st5481_b.c | 9511 | 9957 | /*
* Driver for ST5481 USB ISDN modem
*
* Author Frode Isaksen
* Copyright 2001 by Frode Isaksen <fisaksen@bewan.com>
* 2001 by Kai Germaschewski <kai.germaschewski@gmx.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/usb.h>
#include <linux/netdevice.h>
#include <linux/bitrev.h>
#include "st5481.h"
static inline void B_L1L2(struct st5481_bcs *bcs, int pr, void *arg)
{
struct hisax_if *ifc = (struct hisax_if *) &bcs->b_if;
ifc->l1l2(ifc, pr, arg);
}
/*
* Encode and transmit next frame.
*/
static void usb_b_out(struct st5481_bcs *bcs, int buf_nr)
{
struct st5481_b_out *b_out = &bcs->b_out;
struct st5481_adapter *adapter = bcs->adapter;
struct urb *urb;
unsigned int packet_size, offset;
int len, buf_size, bytes_sent;
int i;
struct sk_buff *skb;
if (test_and_set_bit(buf_nr, &b_out->busy)) {
DBG(4, "ep %d urb %d busy", (bcs->channel + 1) * 2, buf_nr);
return;
}
urb = b_out->urb[buf_nr];
// Adjust isoc buffer size according to flow state
if (b_out->flow_event & (OUT_DOWN | OUT_UNDERRUN)) {
buf_size = NUM_ISO_PACKETS_B * SIZE_ISO_PACKETS_B_OUT + B_FLOW_ADJUST;
packet_size = SIZE_ISO_PACKETS_B_OUT + B_FLOW_ADJUST;
DBG(4, "B%d,adjust flow,add %d bytes", bcs->channel + 1, B_FLOW_ADJUST);
} else if (b_out->flow_event & OUT_UP) {
buf_size = NUM_ISO_PACKETS_B * SIZE_ISO_PACKETS_B_OUT - B_FLOW_ADJUST;
packet_size = SIZE_ISO_PACKETS_B_OUT - B_FLOW_ADJUST;
DBG(4, "B%d,adjust flow,remove %d bytes", bcs->channel + 1, B_FLOW_ADJUST);
} else {
buf_size = NUM_ISO_PACKETS_B * SIZE_ISO_PACKETS_B_OUT;
packet_size = 8;
}
b_out->flow_event = 0;
len = 0;
while (len < buf_size) {
if ((skb = b_out->tx_skb)) {
DBG_SKB(0x100, skb);
DBG(4, "B%d,len=%d", bcs->channel + 1, skb->len);
if (bcs->mode == L1_MODE_TRANS) {
bytes_sent = buf_size - len;
if (skb->len < bytes_sent)
bytes_sent = skb->len;
{ /* swap tx bytes to get hearable audio data */
register unsigned char *src = skb->data;
register unsigned char *dest = urb->transfer_buffer + len;
register unsigned int count;
for (count = 0; count < bytes_sent; count++)
*dest++ = bitrev8(*src++);
}
len += bytes_sent;
} else {
len += isdnhdlc_encode(&b_out->hdlc_state,
skb->data, skb->len, &bytes_sent,
urb->transfer_buffer + len, buf_size-len);
}
skb_pull(skb, bytes_sent);
if (!skb->len) {
// Frame sent
b_out->tx_skb = NULL;
B_L1L2(bcs, PH_DATA | CONFIRM, (void *)(unsigned long) skb->truesize);
dev_kfree_skb_any(skb);
/* if (!(bcs->tx_skb = skb_dequeue(&bcs->sq))) { */
/* st5481B_sched_event(bcs, B_XMTBUFREADY); */
/* } */
}
} else {
if (bcs->mode == L1_MODE_TRANS) {
memset(urb->transfer_buffer + len, 0xff, buf_size-len);
len = buf_size;
} else {
// Send flags
len += isdnhdlc_encode(&b_out->hdlc_state,
NULL, 0, &bytes_sent,
urb->transfer_buffer + len, buf_size-len);
}
}
}
// Prepare the URB
for (i = 0, offset = 0; offset < len; i++) {
urb->iso_frame_desc[i].offset = offset;
urb->iso_frame_desc[i].length = packet_size;
offset += packet_size;
packet_size = SIZE_ISO_PACKETS_B_OUT;
}
urb->transfer_buffer_length = len;
urb->number_of_packets = i;
urb->dev = adapter->usb_dev;
DBG_ISO_PACKET(0x200, urb);
SUBMIT_URB(urb, GFP_NOIO);
}
/*
* Start transferring (flags or data) on the B channel, since
* FIFO counters has been set to a non-zero value.
*/
static void st5481B_start_xfer(void *context)
{
struct st5481_bcs *bcs = context;
DBG(4, "B%d", bcs->channel + 1);
// Start transmitting (flags or data) on B channel
usb_b_out(bcs, 0);
usb_b_out(bcs, 1);
}
/*
* If the adapter has only 2 LEDs, the green
* LED will blink with a rate depending
* on the number of channels opened.
*/
static void led_blink(struct st5481_adapter *adapter)
{
u_char leds = adapter->leds;
// 50 frames/sec for each channel
if (++adapter->led_counter % 50) {
return;
}
if (adapter->led_counter % 100) {
leds |= GREEN_LED;
} else {
leds &= ~GREEN_LED;
}
st5481_usb_device_ctrl_msg(adapter, GPIO_OUT, leds, NULL, NULL);
}
static void usb_b_out_complete(struct urb *urb)
{
struct st5481_bcs *bcs = urb->context;
struct st5481_b_out *b_out = &bcs->b_out;
struct st5481_adapter *adapter = bcs->adapter;
int buf_nr;
buf_nr = get_buf_nr(b_out->urb, urb);
test_and_clear_bit(buf_nr, &b_out->busy);
if (unlikely(urb->status < 0)) {
switch (urb->status) {
case -ENOENT:
case -ESHUTDOWN:
case -ECONNRESET:
DBG(4, "urb killed status %d", urb->status);
return; // Give up
default:
WARNING("urb status %d", urb->status);
if (b_out->busy == 0) {
st5481_usb_pipe_reset(adapter, (bcs->channel + 1) * 2 | USB_DIR_OUT, NULL, NULL);
}
break;
}
}
usb_b_out(bcs, buf_nr);
if (adapter->number_of_leds == 2)
led_blink(adapter);
}
/*
* Start or stop the transfer on the B channel.
*/
static void st5481B_mode(struct st5481_bcs *bcs, int mode)
{
struct st5481_b_out *b_out = &bcs->b_out;
struct st5481_adapter *adapter = bcs->adapter;
DBG(4, "B%d,mode=%d", bcs->channel + 1, mode);
if (bcs->mode == mode)
return;
bcs->mode = mode;
// Cancel all USB transfers on this B channel
usb_unlink_urb(b_out->urb[0]);
usb_unlink_urb(b_out->urb[1]);
b_out->busy = 0;
st5481_in_mode(&bcs->b_in, mode);
if (bcs->mode != L1_MODE_NULL) {
// Open the B channel
if (bcs->mode != L1_MODE_TRANS) {
u32 features = HDLC_BITREVERSE;
if (bcs->mode == L1_MODE_HDLC_56K)
features |= HDLC_56KBIT;
isdnhdlc_out_init(&b_out->hdlc_state, features);
}
st5481_usb_pipe_reset(adapter, (bcs->channel + 1) * 2, NULL, NULL);
// Enable B channel interrupts
st5481_usb_device_ctrl_msg(adapter, FFMSK_B1 + (bcs->channel * 2),
OUT_UP + OUT_DOWN + OUT_UNDERRUN, NULL, NULL);
// Enable B channel FIFOs
st5481_usb_device_ctrl_msg(adapter, OUT_B1_COUNTER+(bcs->channel * 2), 32, st5481B_start_xfer, bcs);
if (adapter->number_of_leds == 4) {
if (bcs->channel == 0) {
adapter->leds |= B1_LED;
} else {
adapter->leds |= B2_LED;
}
}
} else {
// Disble B channel interrupts
st5481_usb_device_ctrl_msg(adapter, FFMSK_B1+(bcs->channel * 2), 0, NULL, NULL);
// Disable B channel FIFOs
st5481_usb_device_ctrl_msg(adapter, OUT_B1_COUNTER+(bcs->channel * 2), 0, NULL, NULL);
if (adapter->number_of_leds == 4) {
if (bcs->channel == 0) {
adapter->leds &= ~B1_LED;
} else {
adapter->leds &= ~B2_LED;
}
} else {
st5481_usb_device_ctrl_msg(adapter, GPIO_OUT, adapter->leds, NULL, NULL);
}
if (b_out->tx_skb) {
dev_kfree_skb_any(b_out->tx_skb);
b_out->tx_skb = NULL;
}
}
}
static int st5481_setup_b_out(struct st5481_bcs *bcs)
{
struct usb_device *dev = bcs->adapter->usb_dev;
struct usb_interface *intf;
struct usb_host_interface *altsetting = NULL;
struct usb_host_endpoint *endpoint;
struct st5481_b_out *b_out = &bcs->b_out;
DBG(4, "");
intf = usb_ifnum_to_if(dev, 0);
if (intf)
altsetting = usb_altnum_to_altsetting(intf, 3);
if (!altsetting)
return -ENXIO;
// Allocate URBs and buffers for the B channel out
endpoint = &altsetting->endpoint[EP_B1_OUT - 1 + bcs->channel * 2];
DBG(4, "endpoint address=%02x,packet size=%d",
endpoint->desc.bEndpointAddress, le16_to_cpu(endpoint->desc.wMaxPacketSize));
// Allocate memory for 8000bytes/sec + extra bytes if underrun
return st5481_setup_isocpipes(b_out->urb, dev,
usb_sndisocpipe(dev, endpoint->desc.bEndpointAddress),
NUM_ISO_PACKETS_B, SIZE_ISO_PACKETS_B_OUT,
NUM_ISO_PACKETS_B * SIZE_ISO_PACKETS_B_OUT + B_FLOW_ADJUST,
usb_b_out_complete, bcs);
}
static void st5481_release_b_out(struct st5481_bcs *bcs)
{
struct st5481_b_out *b_out = &bcs->b_out;
DBG(4, "");
st5481_release_isocpipes(b_out->urb);
}
int st5481_setup_b(struct st5481_bcs *bcs)
{
int retval;
DBG(4, "");
retval = st5481_setup_b_out(bcs);
if (retval)
goto err;
bcs->b_in.bufsize = HSCX_BUFMAX;
bcs->b_in.num_packets = NUM_ISO_PACKETS_B;
bcs->b_in.packet_size = SIZE_ISO_PACKETS_B_IN;
bcs->b_in.ep = (bcs->channel ? EP_B2_IN : EP_B1_IN) | USB_DIR_IN;
bcs->b_in.counter = bcs->channel ? IN_B2_COUNTER : IN_B1_COUNTER;
bcs->b_in.adapter = bcs->adapter;
bcs->b_in.hisax_if = &bcs->b_if.ifc;
retval = st5481_setup_in(&bcs->b_in);
if (retval)
goto err_b_out;
return 0;
err_b_out:
st5481_release_b_out(bcs);
err:
return retval;
}
/*
* Release buffers and URBs for the B channels
*/
void st5481_release_b(struct st5481_bcs *bcs)
{
DBG(4, "");
st5481_release_in(&bcs->b_in);
st5481_release_b_out(bcs);
}
/*
* st5481_b_l2l1 is the entry point for upper layer routines that want to
* transmit on the B channel. PH_DATA | REQUEST is a normal packet that
* we either start transmitting (if idle) or queue (if busy).
* PH_PULL | REQUEST can be called to request a callback message
* (PH_PULL | CONFIRM)
* once the link is idle. After a "pull" callback, the upper layer
* routines can use PH_PULL | INDICATION to send data.
*/
void st5481_b_l2l1(struct hisax_if *ifc, int pr, void *arg)
{
struct st5481_bcs *bcs = ifc->priv;
struct sk_buff *skb = arg;
long mode;
DBG(4, "");
switch (pr) {
case PH_DATA | REQUEST:
BUG_ON(bcs->b_out.tx_skb);
bcs->b_out.tx_skb = skb;
break;
case PH_ACTIVATE | REQUEST:
mode = (long) arg;
DBG(4, "B%d,PH_ACTIVATE_REQUEST %ld", bcs->channel + 1, mode);
st5481B_mode(bcs, mode);
B_L1L2(bcs, PH_ACTIVATE | INDICATION, NULL);
break;
case PH_DEACTIVATE | REQUEST:
DBG(4, "B%d,PH_DEACTIVATE_REQUEST", bcs->channel + 1);
st5481B_mode(bcs, L1_MODE_NULL);
B_L1L2(bcs, PH_DEACTIVATE | INDICATION, NULL);
break;
default:
WARNING("pr %#x\n", pr);
}
}
| gpl-2.0 |
PsychoGame/android_kernel_lge_msm8974-caf | arch/sh/kernel/asm-offsets.c | 11815 | 2670 | /*
* This program is used to generate definitions needed by
* assembly language modules.
*
* We use the technique used in the OSF Mach kernel code:
* generate asm statements containing #defines,
* compile this file to assembler, and then extract the
* #defines from the assembly-language output.
*/
#include <linux/stddef.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/kbuild.h>
#include <linux/suspend.h>
#include <asm/thread_info.h>
#include <asm/suspend.h>
int main(void)
{
/* offsets into the thread_info struct */
DEFINE(TI_TASK, offsetof(struct thread_info, task));
DEFINE(TI_EXEC_DOMAIN, offsetof(struct thread_info, exec_domain));
DEFINE(TI_FLAGS, offsetof(struct thread_info, flags));
DEFINE(TI_CPU, offsetof(struct thread_info, cpu));
DEFINE(TI_PRE_COUNT, offsetof(struct thread_info, preempt_count));
DEFINE(TI_RESTART_BLOCK,offsetof(struct thread_info, restart_block));
DEFINE(TI_SIZE, sizeof(struct thread_info));
#ifdef CONFIG_HIBERNATION
DEFINE(PBE_ADDRESS, offsetof(struct pbe, address));
DEFINE(PBE_ORIG_ADDRESS, offsetof(struct pbe, orig_address));
DEFINE(PBE_NEXT, offsetof(struct pbe, next));
DEFINE(SWSUSP_ARCH_REGS_SIZE, sizeof(struct swsusp_arch_regs));
#endif
DEFINE(SH_SLEEP_MODE, offsetof(struct sh_sleep_data, mode));
DEFINE(SH_SLEEP_SF_PRE, offsetof(struct sh_sleep_data, sf_pre));
DEFINE(SH_SLEEP_SF_POST, offsetof(struct sh_sleep_data, sf_post));
DEFINE(SH_SLEEP_RESUME, offsetof(struct sh_sleep_data, resume));
DEFINE(SH_SLEEP_VBR, offsetof(struct sh_sleep_data, vbr));
DEFINE(SH_SLEEP_SPC, offsetof(struct sh_sleep_data, spc));
DEFINE(SH_SLEEP_SR, offsetof(struct sh_sleep_data, sr));
DEFINE(SH_SLEEP_SP, offsetof(struct sh_sleep_data, sp));
DEFINE(SH_SLEEP_BASE_ADDR, offsetof(struct sh_sleep_data, addr));
DEFINE(SH_SLEEP_BASE_DATA, offsetof(struct sh_sleep_data, data));
DEFINE(SH_SLEEP_REG_STBCR, offsetof(struct sh_sleep_regs, stbcr));
DEFINE(SH_SLEEP_REG_BAR, offsetof(struct sh_sleep_regs, bar));
DEFINE(SH_SLEEP_REG_PTEH, offsetof(struct sh_sleep_regs, pteh));
DEFINE(SH_SLEEP_REG_PTEL, offsetof(struct sh_sleep_regs, ptel));
DEFINE(SH_SLEEP_REG_TTB, offsetof(struct sh_sleep_regs, ttb));
DEFINE(SH_SLEEP_REG_TEA, offsetof(struct sh_sleep_regs, tea));
DEFINE(SH_SLEEP_REG_MMUCR, offsetof(struct sh_sleep_regs, mmucr));
DEFINE(SH_SLEEP_REG_PTEA, offsetof(struct sh_sleep_regs, ptea));
DEFINE(SH_SLEEP_REG_PASCR, offsetof(struct sh_sleep_regs, pascr));
DEFINE(SH_SLEEP_REG_IRMCR, offsetof(struct sh_sleep_regs, irmcr));
DEFINE(SH_SLEEP_REG_CCR, offsetof(struct sh_sleep_regs, ccr));
DEFINE(SH_SLEEP_REG_RAMCR, offsetof(struct sh_sleep_regs, ramcr));
return 0;
}
| gpl-2.0 |
AOSPXS/kernel_sony_msm8x60 | drivers/media/dvb/b2c2/flexcop-dma.c | 14375 | 4316 | /*
* Linux driver for digital TV devices equipped with B2C2 FlexcopII(b)/III
* flexcop-dma.c - configuring and controlling the DMA of the FlexCop
* see flexcop.c for copyright information
*/
#include "flexcop.h"
int flexcop_dma_allocate(struct pci_dev *pdev,
struct flexcop_dma *dma, u32 size)
{
u8 *tcpu;
dma_addr_t tdma = 0;
if (size % 2) {
err("dma buffersize has to be even.");
return -EINVAL;
}
if ((tcpu = pci_alloc_consistent(pdev, size, &tdma)) != NULL) {
dma->pdev = pdev;
dma->cpu_addr0 = tcpu;
dma->dma_addr0 = tdma;
dma->cpu_addr1 = tcpu + size/2;
dma->dma_addr1 = tdma + size/2;
dma->size = size/2;
return 0;
}
return -ENOMEM;
}
EXPORT_SYMBOL(flexcop_dma_allocate);
void flexcop_dma_free(struct flexcop_dma *dma)
{
pci_free_consistent(dma->pdev, dma->size*2,
dma->cpu_addr0, dma->dma_addr0);
memset(dma,0,sizeof(struct flexcop_dma));
}
EXPORT_SYMBOL(flexcop_dma_free);
int flexcop_dma_config(struct flexcop_device *fc,
struct flexcop_dma *dma,
flexcop_dma_index_t dma_idx)
{
flexcop_ibi_value v0x0,v0x4,v0xc;
v0x0.raw = v0x4.raw = v0xc.raw = 0;
v0x0.dma_0x0.dma_address0 = dma->dma_addr0 >> 2;
v0xc.dma_0xc.dma_address1 = dma->dma_addr1 >> 2;
v0x4.dma_0x4_write.dma_addr_size = dma->size / 4;
if ((dma_idx & FC_DMA_1) == dma_idx) {
fc->write_ibi_reg(fc,dma1_000,v0x0);
fc->write_ibi_reg(fc,dma1_004,v0x4);
fc->write_ibi_reg(fc,dma1_00c,v0xc);
} else if ((dma_idx & FC_DMA_2) == dma_idx) {
fc->write_ibi_reg(fc,dma2_010,v0x0);
fc->write_ibi_reg(fc,dma2_014,v0x4);
fc->write_ibi_reg(fc,dma2_01c,v0xc);
} else {
err("either DMA1 or DMA2 can be configured within one "
"flexcop_dma_config call.");
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(flexcop_dma_config);
/* start the DMA transfers, but not the DMA IRQs */
int flexcop_dma_xfer_control(struct flexcop_device *fc,
flexcop_dma_index_t dma_idx,
flexcop_dma_addr_index_t index,
int onoff)
{
flexcop_ibi_value v0x0,v0xc;
flexcop_ibi_register r0x0,r0xc;
if ((dma_idx & FC_DMA_1) == dma_idx) {
r0x0 = dma1_000;
r0xc = dma1_00c;
} else if ((dma_idx & FC_DMA_2) == dma_idx) {
r0x0 = dma2_010;
r0xc = dma2_01c;
} else {
err("either transfer DMA1 or DMA2 can be started within one "
"flexcop_dma_xfer_control call.");
return -EINVAL;
}
v0x0 = fc->read_ibi_reg(fc,r0x0);
v0xc = fc->read_ibi_reg(fc,r0xc);
deb_rdump("reg: %03x: %x\n",r0x0,v0x0.raw);
deb_rdump("reg: %03x: %x\n",r0xc,v0xc.raw);
if (index & FC_DMA_SUBADDR_0)
v0x0.dma_0x0.dma_0start = onoff;
if (index & FC_DMA_SUBADDR_1)
v0xc.dma_0xc.dma_1start = onoff;
fc->write_ibi_reg(fc,r0x0,v0x0);
fc->write_ibi_reg(fc,r0xc,v0xc);
deb_rdump("reg: %03x: %x\n",r0x0,v0x0.raw);
deb_rdump("reg: %03x: %x\n",r0xc,v0xc.raw);
return 0;
}
EXPORT_SYMBOL(flexcop_dma_xfer_control);
static int flexcop_dma_remap(struct flexcop_device *fc,
flexcop_dma_index_t dma_idx,
int onoff)
{
flexcop_ibi_register r = (dma_idx & FC_DMA_1) ? dma1_00c : dma2_01c;
flexcop_ibi_value v = fc->read_ibi_reg(fc,r);
deb_info("%s\n",__func__);
v.dma_0xc.remap_enable = onoff;
fc->write_ibi_reg(fc,r,v);
return 0;
}
int flexcop_dma_control_size_irq(struct flexcop_device *fc,
flexcop_dma_index_t no,
int onoff)
{
flexcop_ibi_value v = fc->read_ibi_reg(fc,ctrl_208);
if (no & FC_DMA_1)
v.ctrl_208.DMA1_IRQ_Enable_sig = onoff;
if (no & FC_DMA_2)
v.ctrl_208.DMA2_IRQ_Enable_sig = onoff;
fc->write_ibi_reg(fc,ctrl_208,v);
return 0;
}
EXPORT_SYMBOL(flexcop_dma_control_size_irq);
int flexcop_dma_control_timer_irq(struct flexcop_device *fc,
flexcop_dma_index_t no,
int onoff)
{
flexcop_ibi_value v = fc->read_ibi_reg(fc,ctrl_208);
if (no & FC_DMA_1)
v.ctrl_208.DMA1_Timer_Enable_sig = onoff;
if (no & FC_DMA_2)
v.ctrl_208.DMA2_Timer_Enable_sig = onoff;
fc->write_ibi_reg(fc,ctrl_208,v);
return 0;
}
EXPORT_SYMBOL(flexcop_dma_control_timer_irq);
/* 1 cycles = 1.97 msec */
int flexcop_dma_config_timer(struct flexcop_device *fc,
flexcop_dma_index_t dma_idx, u8 cycles)
{
flexcop_ibi_register r = (dma_idx & FC_DMA_1) ? dma1_004 : dma2_014;
flexcop_ibi_value v = fc->read_ibi_reg(fc,r);
flexcop_dma_remap(fc,dma_idx,0);
deb_info("%s\n",__func__);
v.dma_0x4_write.dmatimer = cycles;
fc->write_ibi_reg(fc,r,v);
return 0;
}
EXPORT_SYMBOL(flexcop_dma_config_timer);
| gpl-2.0 |
tzlaine/gcc | gcc/testsuite/gcc.dg/ipa/ipa-icf-37.c | 40 | 1050 | /* { dg-do compile } */
/* { dg-options "-O2 -fdump-ipa-icf" } */
static int a;
static int b;
static const int c = 2;
static const int d = 2;
static char * e = "test";
static char * f = "test";
static int g[3]={1,2,3};
static int h[3]={1,2,3};
static const int *i=&c;
static const int *j=&c;
static const int *k=&d;
int t(int tt)
{
switch (tt)
{
case 1: return a;
case 2: return b;
case 3: return c;
case 4: return d;
case 5: return e[1];
case 6: return f[1];
case 7: return g[1];
case 8: return h[1];
case 9: return i[0];
case 10: return j[0];
case 11: return k[0];
}
}
/* { dg-final { scan-ipa-dump "Equal symbols: 5" "icf" } } */
/* { dg-final { scan-ipa-dump "Semantic equality hit:b->a" "icf" } } */
/* { dg-final { scan-ipa-dump "Semantic equality hit:d->c" "icf" } } */
/* { dg-final { scan-ipa-dump "Semantic equality hit:f->e" "icf" } } */
/* { dg-final { scan-ipa-dump "Semantic equality hit:h->g" "icf" } } */
/* { dg-final { scan-ipa-dump "Semantic equality hit:j->i" "icf" } } */
| gpl-2.0 |
SomethingExplosive/android_kernel_samsung_manta | drivers/media/video/exynos/fimc-lite/fimc-lite-core.c | 40 | 54696 | /*
* Register interface file for Samsung Camera Interface (FIMC-Lite) driver
*
* Copyright (c) 2011 Samsung Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
#include <mach/videonode.h>
#include <media/exynos_mc.h>
#endif
#include "fimc-lite-core.h"
#define MODULE_NAME "exynos-fimc-lite"
#define DEFAULT_FLITE_SINK_WIDTH 800
#define DEFAULT_FLITE_SINK_HEIGHT 480
#define CAMIF_TOP_CLK "camif_top"
static struct flite_fmt flite_formats[] = {
{
.name = "YUV422 8-bit 1 plane(UYVY)",
.pixelformat = V4L2_PIX_FMT_UYVY,
.depth = { 16 },
.code = V4L2_MBUS_FMT_UYVY8_2X8,
.fmt_reg = FLITE_REG_CIGCTRL_YUV422_1P,
.is_yuv = 1,
}, {
.name = "YUV422 8-bit 1 plane(VYUY)",
.pixelformat = V4L2_PIX_FMT_VYUY,
.depth = { 16 },
.code = V4L2_MBUS_FMT_VYUY8_2X8,
.fmt_reg = FLITE_REG_CIGCTRL_YUV422_1P,
.is_yuv = 1,
}, {
.name = "YUV422 8-bit 1 plane(YUYV)",
.pixelformat = V4L2_PIX_FMT_YUYV,
.depth = { 16 },
.code = V4L2_MBUS_FMT_YUYV8_2X8,
.fmt_reg = FLITE_REG_CIGCTRL_YUV422_1P,
.is_yuv = 1,
}, {
.name = "YUV422 8-bit 1 plane(YVYU)",
.pixelformat = V4L2_PIX_FMT_YVYU,
.depth = { 16 },
.code = V4L2_MBUS_FMT_YVYU8_2X8,
.fmt_reg = FLITE_REG_CIGCTRL_YUV422_1P,
.is_yuv = 1,
}, {
.name = "RAW8(GRBG)",
.pixelformat = V4L2_PIX_FMT_SGRBG8,
.depth = { 8 },
.code = V4L2_MBUS_FMT_SGRBG8_1X8,
.fmt_reg = FLITE_REG_CIGCTRL_RAW8,
.is_yuv = 0,
}, {
.name = "RAW10(GRBG)",
.pixelformat = V4L2_PIX_FMT_SGRBG10,
.depth = { 10 },
.code = V4L2_MBUS_FMT_SGRBG10_1X10,
.fmt_reg = FLITE_REG_CIGCTRL_RAW10,
.is_yuv = 0,
}, {
.name = "RAW12(GRBG)",
.pixelformat = V4L2_PIX_FMT_SGRBG12,
.depth = { 12 },
.code = V4L2_MBUS_FMT_SGRBG12_1X12,
.fmt_reg = FLITE_REG_CIGCTRL_RAW12,
.is_yuv = 0,
}, {
.name = "User Defined(JPEG)",
.code = V4L2_MBUS_FMT_JPEG_1X8,
.depth = { 8 },
.fmt_reg = FLITE_REG_CIGCTRL_USER(1),
.is_yuv = 0,
},
};
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
static struct flite_variant variant = {
.max_w = 8192,
.max_h = 8192,
.align_win_offs_w = 2,
.align_out_w = 8,
.align_out_offs_w = 8,
};
static struct flite_fmt *get_format(int index)
{
return &flite_formats[index];
}
static struct flite_fmt *find_format(u32 *pixelformat, u32 *mbus_code, int index)
{
struct flite_fmt *fmt, *def_fmt = NULL;
unsigned int i;
if (index >= ARRAY_SIZE(flite_formats))
return NULL;
for (i = 0; i < ARRAY_SIZE(flite_formats); ++i) {
fmt = get_format(i);
if (pixelformat && fmt->pixelformat == *pixelformat)
return fmt;
if (mbus_code && fmt->code == *mbus_code)
return fmt;
if (index == i)
def_fmt = fmt;
}
return def_fmt;
}
#endif
inline struct flite_fmt const *find_flite_format(struct v4l2_mbus_framefmt *mf)
{
int num_fmt = ARRAY_SIZE(flite_formats);
while (num_fmt--)
if (mf->code == flite_formats[num_fmt].code)
break;
if (num_fmt < 0)
return NULL;
return &flite_formats[num_fmt];
}
static int flite_s_mbus_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct flite_fmt const *f_fmt = find_flite_format(mf);
struct flite_frame *f_frame = &flite->s_frame;
flite_dbg("w: %d, h: %d", mf->width, mf->height);
if (unlikely(!f_fmt)) {
flite_err("f_fmt is null");
return -EINVAL;
}
flite->mbus_fmt = *mf;
/*
* These are the datas from fimc
* If you want to crop the image, you can use s_crop
*/
f_frame->o_width = mf->width;
f_frame->o_height = mf->height;
f_frame->width = mf->width;
f_frame->height = mf->height;
f_frame->offs_h = 0;
f_frame->offs_v = 0;
return 0;
}
static int flite_g_mbus_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
mf = &flite->mbus_fmt;
return 0;
}
static int flite_subdev_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *cc)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct flite_frame *f;
f = &flite->s_frame;
cc->bounds.left = 0;
cc->bounds.top = 0;
cc->bounds.width = f->o_width;
cc->bounds.height = f->o_height;
cc->defrect = cc->bounds;
return 0;
}
static int flite_subdev_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *crop)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct flite_frame *f;
f = &flite->s_frame;
crop->c.left = f->offs_h;
crop->c.top = f->offs_v;
crop->c.width = f->width;
crop->c.height = f->height;
return 0;
}
static int flite_subdev_s_crop(struct v4l2_subdev *sd, struct v4l2_crop *crop)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct flite_frame *f;
f = &flite->s_frame;
if (crop->c.left + crop->c.width > f->o_width) {
flite_err("Unsupported crop width");
return -EINVAL;
}
if (crop->c.top + crop->c.height > f->o_height) {
flite_err("Unsupported crop height");
return -EINVAL;
}
f->width = crop->c.width;
f->height = crop->c.height;
f->offs_h = crop->c.left;
f->offs_v = crop->c.top;
flite_dbg("width : %d, height : %d, offs_h : %d, off_v : %dn",
f->width, f->height, f->offs_h, f->offs_v);
return 0;
}
static int flite_s_stream(struct v4l2_subdev *sd, int enable)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
u32 index = flite->pdata->active_cam_index;
struct s3c_platform_camera *cam = NULL;
u32 int_src = 0;
unsigned long flags;
int ret = 0;
if (!(flite->output & FLITE_OUTPUT_MEM)) {
if (enable)
flite_hw_reset(flite);
cam = flite->pdata->cam[index];
}
spin_lock_irqsave(&flite->slock, flags);
if (test_bit(FLITE_ST_SUSPEND, &flite->state))
goto s_stream_unlock;
if (enable) {
flite_hw_set_cam_channel(flite);
flite_hw_set_cam_source_size(flite);
if (!(flite->output & FLITE_OUTPUT_MEM)) {
flite_info("@local out start@");
flite_hw_set_camera_type(flite, cam);
flite_hw_set_config_irq(flite, cam);
if (IS_ERR_OR_NULL(cam)) {
flite_err("cam is null");
goto s_stream_unlock;
}
if (cam->use_isp)
flite_hw_set_output_dma(flite, false);
int_src = FLITE_REG_CIGCTRL_IRQ_OVFEN0_ENABLE |
FLITE_REG_CIGCTRL_IRQ_LASTEN0_ENABLE |
FLITE_REG_CIGCTRL_IRQ_ENDEN0_DISABLE |
FLITE_REG_CIGCTRL_IRQ_STARTEN0_DISABLE;
} else {
flite_info("@mem out start@");
flite_hw_set_sensor_type(flite);
flite_hw_set_inverse_polarity(flite);
set_bit(FLITE_ST_PEND, &flite->state);
flite_hw_set_output_dma(flite, true);
int_src = FLITE_REG_CIGCTRL_IRQ_OVFEN0_ENABLE |
FLITE_REG_CIGCTRL_IRQ_LASTEN0_ENABLE |
FLITE_REG_CIGCTRL_IRQ_ENDEN0_ENABLE |
FLITE_REG_CIGCTRL_IRQ_STARTEN0_DISABLE;
flite_hw_set_out_order(flite);
flite_hw_set_output_size(flite);
flite_hw_set_dma_offset(flite);
}
ret = flite_hw_set_source_format(flite);
if (unlikely(ret < 0))
goto s_stream_unlock;
flite_hw_set_interrupt_source(flite, int_src);
flite_hw_set_window_offset(flite);
flite_hw_set_capture_start(flite);
set_bit(FLITE_ST_STREAM, &flite->state);
} else {
if (test_bit(FLITE_ST_STREAM, &flite->state)) {
flite_hw_set_capture_stop(flite);
spin_unlock_irqrestore(&flite->slock, flags);
ret = wait_event_timeout(flite->irq_queue,
!test_bit(FLITE_ST_STREAM, &flite->state), HZ/20); /* 50 ms */
if (unlikely(!ret)) {
v4l2_err(sd, "wait timeout\n");
ret = -EBUSY;
}
return ret;
} else {
goto s_stream_unlock;
}
}
s_stream_unlock:
spin_unlock_irqrestore(&flite->slock, flags);
return ret;
}
static irqreturn_t flite_irq_handler(int irq, void *priv)
{
struct flite_dev *flite = priv;
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
struct flite_buffer *buf;
#endif
u32 int_src = 0;
flite_hw_get_int_src(flite, &int_src);
flite_hw_clear_irq(flite);
spin_lock(&flite->slock);
switch (int_src & FLITE_REG_CISTATUS_IRQ_MASK) {
case FLITE_REG_CISTATUS_IRQ_SRC_OVERFLOW:
clear_bit(FLITE_ST_RUN, &flite->state);
flite_err("overflow generated");
break;
case FLITE_REG_CISTATUS_IRQ_SRC_LASTCAPEND:
flite_hw_set_last_capture_end_clear(flite);
flite_info("last capture end");
clear_bit(FLITE_ST_STREAM, &flite->state);
wake_up(&flite->irq_queue);
break;
case FLITE_REG_CISTATUS_IRQ_SRC_FRMSTART:
flite_dbg("frame start");
break;
case FLITE_REG_CISTATUS_IRQ_SRC_FRMEND:
set_bit(FLITE_ST_RUN, &flite->state);
flite_dbg("frame end");
break;
}
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
if (flite->output & FLITE_OUTPUT_MEM) {
if (!list_empty(&flite->active_buf_q)) {
buf = active_queue_pop(flite);
if (!test_bit(FLITE_ST_RUN, &flite->state)) {
flite_info("error interrupt");
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
goto unlock;
}
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_DONE);
flite_dbg("done_index : %d", buf->vb.v4l2_buf.index);
}
if (!list_empty(&flite->pending_buf_q)) {
buf = pending_queue_pop(flite);
flite_hw_set_output_addr(flite, &buf->paddr,
buf->vb.v4l2_buf.index);
active_queue_add(flite, buf);
}
if (flite->active_buf_cnt == 0) {
clear_bit(FLITE_ST_RUN, &flite->state);
}
}
unlock:
#endif
spin_unlock(&flite->slock);
return IRQ_HANDLED;
}
static int flite_runtime_resume(struct device *dev);
static int flite_runtime_suspend(struct device *dev);
static int flite_s_power(struct v4l2_subdev *sd, int on)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
int ret = 0;
if (on) {
#ifdef CONFIG_PM_RUNTIME
pm_runtime_get_sync(&flite->pdev->dev);
#else
flite_runtime_resume(&flite->pdev->dev);
#endif
set_bit(FLITE_ST_POWER, &flite->state);
} else {
#ifdef CONFIG_PM_RUNTIME
pm_runtime_put_sync(&flite->pdev->dev);
#else
flite_runtime_suspend(&flite->pdev->dev);
#endif
clear_bit(FLITE_ST_POWER, &flite->state);
}
return ret;
}
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
static int flite_subdev_enum_mbus_code(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_mbus_code_enum *code)
{
if (code->index >= ARRAY_SIZE(flite_formats))
return -EINVAL;
code->code = flite_formats[code->index].code;
return 0;
}
static struct v4l2_mbus_framefmt *__flite_get_format(
struct flite_dev *flite, struct v4l2_subdev_fh *fh,
u32 pad, enum v4l2_subdev_format_whence which)
{
if (which == V4L2_SUBDEV_FORMAT_TRY)
return fh ? v4l2_subdev_get_try_format(fh, pad) : NULL;
else
return &flite->mbus_fmt;
}
static void flite_try_format(struct flite_dev *flite, struct v4l2_subdev_fh *fh,
struct v4l2_mbus_framefmt *fmt,
enum v4l2_subdev_format_whence which)
{
struct flite_fmt const *ffmt;
struct flite_frame *f = &flite->s_frame;
ffmt = find_flite_format(fmt);
if (ffmt == NULL)
ffmt = &flite_formats[1];
fmt->code = ffmt->code;
fmt->width = clamp_t(u32, fmt->width, 1, variant.max_w);
fmt->height = clamp_t(u32, fmt->height, 1, variant.max_h);
f->offs_h = f->offs_v = 0;
f->width = f->o_width = fmt->width;
f->height = f->o_height = fmt->height;
fmt->colorspace = V4L2_COLORSPACE_JPEG;
fmt->field = V4L2_FIELD_NONE;
}
static int flite_subdev_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *mf;
mf = __flite_get_format(flite, fh, fmt->pad, fmt->which);
if (mf == NULL) {
flite_err("__flite_get_format is null");
return -EINVAL;
}
fmt->format = *mf;
if (fmt->pad != FLITE_PAD_SINK) {
struct flite_frame *f = &flite->s_frame;
fmt->format.width = f->width;
fmt->format.height = f->height;
}
return 0;
}
static int flite_subdev_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *mf;
if (fmt->pad != FLITE_PAD_SINK)
return -EPERM;
mf = __flite_get_format(flite, fh, fmt->pad, fmt->which);
if (mf == NULL) {
flite_err("__flite_get_format is null");
return -EINVAL;
}
flite_try_format(flite, fh, &fmt->format, fmt->which);
*mf = fmt->format;
return 0;
}
static void flite_try_crop(struct flite_dev *flite, struct v4l2_subdev_crop *crop)
{
struct flite_frame *f_frame = flite_get_frame(flite, crop->pad);
u32 max_left = f_frame->o_width - crop->rect.width;
u32 max_top = f_frame->o_height - crop->rect.height;
u32 crop_max_w = f_frame->o_width - crop->rect.left;
u32 crop_max_h = f_frame->o_height - crop->rect.top;
crop->rect.left = clamp_t(u32, crop->rect.left, 0, max_left);
crop->rect.top = clamp_t(u32, crop->rect.top, 0, max_top);
crop->rect.width = clamp_t(u32, crop->rect.width, 2, crop_max_w);
crop->rect.height = clamp_t(u32, crop->rect.height, 1, crop_max_h);
}
static int __flite_get_crop(struct flite_dev *flite, struct v4l2_subdev_fh *fh,
unsigned int pad, enum v4l2_subdev_format_whence which,
struct v4l2_rect *crop)
{
struct flite_frame *frame = &flite->s_frame;
if (which == V4L2_SUBDEV_FORMAT_TRY) {
crop = v4l2_subdev_get_try_crop(fh, pad);
} else {
crop->left = frame->offs_h;
crop->top = frame->offs_v;
crop->width = frame->width;
crop->height = frame->height;
}
return 0;
}
static int flite_subdev_get_crop(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_crop *crop)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct v4l2_rect fcrop;
fcrop.left = fcrop.top = fcrop.width = fcrop.height = 0;
if (crop->pad != FLITE_PAD_SINK) {
flite_err("crop is supported only sink pad");
return -EINVAL;
}
__flite_get_crop(flite, fh, crop->pad, crop->which, &fcrop);
crop->rect = fcrop;
return 0;
}
static int flite_subdev_set_crop(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_crop *crop)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct flite_frame *f_frame = flite_get_frame(flite, crop->pad);
if (!(flite->output & FLITE_OUTPUT_MEM) && (crop->pad != FLITE_PAD_SINK)) {
flite_err("crop is supported only sink pad");
return -EINVAL;
}
flite_try_crop(flite, crop);
if (crop->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
f_frame->offs_h = crop->rect.left;
f_frame->offs_v = crop->rect.top;
f_frame->width = crop->rect.width;
f_frame->height = crop->rect.height;
}
return 0;
}
static int flite_init_formats(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
struct v4l2_subdev_format format;
struct flite_dev *flite = v4l2_get_subdevdata(sd);
if (!test_bit(FLITE_ST_SUBDEV_OPEN, &flite->state)) {
flite->s_frame.fmt = get_format(2);
memset(&format, 0, sizeof(format));
format.pad = FLITE_PAD_SINK;
format.which = fh ?
V4L2_SUBDEV_FORMAT_TRY : V4L2_SUBDEV_FORMAT_ACTIVE;
format.format.code = flite->s_frame.fmt->code;
format.format.width = DEFAULT_FLITE_SINK_WIDTH;
format.format.height = DEFAULT_FLITE_SINK_HEIGHT;
flite_subdev_set_fmt(sd, fh, &format);
flite->d_frame.fmt = get_format(2);
set_bit(FLITE_ST_SUBDEV_OPEN, &flite->state);
}
return 0;
}
static int flite_subdev_close(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh)
{
struct flite_dev *flite = v4l2_get_subdevdata(sd);
flite_info("");
clear_bit(FLITE_ST_SUBDEV_OPEN, &flite->state);
return 0;
}
static int flite_subdev_registered(struct v4l2_subdev *sd)
{
flite_dbg("");
return 0;
}
static void flite_subdev_unregistered(struct v4l2_subdev *sd)
{
flite_dbg("");
}
static const struct v4l2_subdev_internal_ops flite_v4l2_internal_ops = {
.open = flite_init_formats,
.close = flite_subdev_close,
.registered = flite_subdev_registered,
.unregistered = flite_subdev_unregistered,
};
static int flite_link_setup(struct media_entity *entity,
const struct media_pad *local,
const struct media_pad *remote, u32 flags)
{
struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
struct flite_dev *flite = v4l2_get_subdevdata(sd);
switch (local->index | media_entity_type(remote->entity)) {
case FLITE_PAD_SINK | MEDIA_ENT_T_V4L2_SUBDEV:
if (flags & MEDIA_LNK_FL_ENABLED) {
flite_info("sink link enabled");
if (flite->input != FLITE_INPUT_NONE) {
flite_err("link is busy");
return -EBUSY;
}
if (remote->index == CSIS_PAD_SOURCE)
flite->input = FLITE_INPUT_CSIS;
else
flite->input = FLITE_INPUT_SENSOR;
} else {
flite_info("sink link disabled");
flite->input = FLITE_INPUT_NONE;
}
break;
case FLITE_PAD_SOURCE_PREV | MEDIA_ENT_T_V4L2_SUBDEV: /* fall through */
case FLITE_PAD_SOURCE_CAMCORD | MEDIA_ENT_T_V4L2_SUBDEV:
if (flags & MEDIA_LNK_FL_ENABLED) {
flite_info("source link enabled");
flite->output |= FLITE_OUTPUT_GSC;
} else {
flite_info("source link disabled");
flite->output &= ~FLITE_OUTPUT_GSC;
}
break;
case FLITE_PAD_SOURCE_MEM | MEDIA_ENT_T_DEVNODE:
if (flags & MEDIA_LNK_FL_ENABLED) {
flite_info("source link enabled");
flite->output |= FLITE_OUTPUT_MEM;
} else {
flite_info("source link disabled");
flite->output &= ~FLITE_OUTPUT_MEM;
}
break;
default:
flite_err("ERR link");
return -EINVAL;
}
return 0;
}
static const struct media_entity_operations flite_media_ops = {
.link_setup = flite_link_setup,
};
static struct v4l2_subdev_pad_ops flite_pad_ops = {
.enum_mbus_code = flite_subdev_enum_mbus_code,
.get_fmt = flite_subdev_get_fmt,
.set_fmt = flite_subdev_set_fmt,
.get_crop = flite_subdev_get_crop,
.set_crop = flite_subdev_set_crop,
};
static void flite_pipeline_prepare(struct flite_dev *flite, struct media_entity *me)
{
struct media_entity_graph graph;
struct v4l2_subdev *sd;
media_entity_graph_walk_start(&graph, me);
while ((me = media_entity_graph_walk_next(&graph))) {
flite_info("me->name : %s", me->name);
if (media_entity_type(me) != MEDIA_ENT_T_V4L2_SUBDEV)
continue;
sd = media_entity_to_v4l2_subdev(me);
switch (sd->grp_id) {
case FLITE_GRP_ID:
flite->pipeline.flite = sd;
break;
case SENSOR_GRP_ID:
flite->pipeline.sensor = sd;
break;
case CSIS_GRP_ID:
flite->pipeline.csis = sd;
break;
default:
flite_warn("Another link's group id");
break;
}
}
flite_info("flite->pipeline.flite : 0x%p", flite->pipeline.flite);
flite_info("flite->pipeline.sensor : 0x%p", flite->pipeline.sensor);
flite_info("flite->pipeline.csis : 0x%p", flite->pipeline.csis);
}
static void flite_set_cam_clock(struct flite_dev *flite, bool on)
{
struct v4l2_subdev *sd = flite->pipeline.sensor;
clk_enable(flite->gsc_clk);
if (flite->pipeline.sensor) {
struct flite_sensor_info *s_info = v4l2_get_subdev_hostdata(sd);
on ? clk_enable(s_info->camclk) : clk_disable(s_info->camclk);
}
}
static int __subdev_set_power(struct v4l2_subdev *sd, int on)
{
int *use_count;
int ret;
if (sd == NULL)
return -ENXIO;
use_count = &sd->entity.use_count;
if (on && (*use_count)++ > 0)
return 0;
else if (!on && (*use_count == 0 || --(*use_count) > 0))
return 0;
ret = v4l2_subdev_call(sd, core, s_power, on);
return ret != -ENOIOCTLCMD ? ret : 0;
}
static int flite_pipeline_s_power(struct flite_dev *flite, int state)
{
int ret = 0;
if (!flite->pipeline.sensor)
return -ENXIO;
if (state) {
ret = __subdev_set_power(flite->pipeline.flite, 1);
if (ret && ret != -ENXIO)
return ret;
ret = __subdev_set_power(flite->pipeline.csis, 1);
if (ret && ret != -ENXIO)
return ret;
ret = __subdev_set_power(flite->pipeline.sensor, 1);
} else {
ret = __subdev_set_power(flite->pipeline.flite, 0);
if (ret && ret != -ENXIO)
return ret;
ret = __subdev_set_power(flite->pipeline.sensor, 0);
if (ret && ret != -ENXIO)
return ret;
ret = __subdev_set_power(flite->pipeline.csis, 0);
}
return ret == -ENXIO ? 0 : ret;
}
static int __flite_pipeline_initialize(struct flite_dev *flite,
struct media_entity *me, bool prep)
{
int ret = 0;
if (prep)
flite_pipeline_prepare(flite, me);
if (!flite->pipeline.sensor)
return -EINVAL;
flite_set_cam_clock(flite, true);
if (flite->pipeline.sensor)
ret = flite_pipeline_s_power(flite, 1);
return ret;
}
static int flite_pipeline_initialize(struct flite_dev *flite,
struct media_entity *me, bool prep)
{
int ret;
mutex_lock(&me->parent->graph_mutex);
ret = __flite_pipeline_initialize(flite, me, prep);
mutex_unlock(&me->parent->graph_mutex);
return ret;
}
static int flite_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct flite_dev *flite = ctrl_to_dev(ctrl);
switch (ctrl->id) {
case V4L2_CID_CACHEABLE:
user_to_drv(flite->flite_ctrls.cacheable, ctrl->val);
break;
default:
flite_err("unsupported ctrl id");
return -EINVAL;
}
return 0;
}
const struct v4l2_ctrl_ops flite_ctrl_ops = {
.s_ctrl = flite_s_ctrl,
};
static const struct v4l2_ctrl_config flite_custom_ctrl[] = {
{
.ops = &flite_ctrl_ops,
.id = V4L2_CID_CACHEABLE,
.name = "Set cacheable",
.type = V4L2_CTRL_TYPE_BOOLEAN,
.flags = V4L2_CTRL_FLAG_SLIDER,
.max = 1,
.def = true,
},
};
static int flite_ctrls_create(struct flite_dev *flite)
{
if (flite->ctrls_rdy)
return 0;
v4l2_ctrl_handler_init(&flite->ctrl_handler, FLITE_MAX_CTRL_NUM);
flite->flite_ctrls.cacheable = v4l2_ctrl_new_custom(&flite->ctrl_handler,
&flite_custom_ctrl[0], NULL);
flite->ctrls_rdy = flite->ctrl_handler.error == 0;
if (flite->ctrl_handler.error) {
int err = flite->ctrl_handler.error;
v4l2_ctrl_handler_free(&flite->ctrl_handler);
flite_err("Failed to flite control hander create");
return err;
}
return 0;
}
static void flite_ctrls_delete(struct flite_dev *flite)
{
if (flite->ctrls_rdy) {
v4l2_ctrl_handler_free(&flite->ctrl_handler);
flite->ctrls_rdy = false;
}
}
static int flite_open(struct file *file)
{
struct flite_dev *flite = video_drvdata(file);
int ret = v4l2_fh_open(file);
if (ret)
return ret;
if (test_bit(FLITE_ST_OPEN, &flite->state)) {
v4l2_fh_release(file);
return -EBUSY;
}
set_bit(FLITE_ST_OPEN, &flite->state);
if (++flite->refcnt == 1) {
ret = flite_pipeline_initialize(flite, &flite->vfd->entity, true);
if (ret < 0) {
flite_err("flite pipeline initialization failed\n");
goto err;
}
ret = flite_ctrls_create(flite);
if (ret) {
flite_err("failed to create controls\n");
goto err;
}
}
flite_info("pid: %d, state: 0x%lx", task_pid_nr(current), flite->state);
return 0;
err:
v4l2_fh_release(file);
clear_bit(FLITE_ST_OPEN, &flite->state);
return ret;
}
int __flite_pipeline_shutdown(struct flite_dev *flite)
{
int ret = 0;
if (flite->pipeline.sensor)
ret = flite_pipeline_s_power(flite, 0);
if (ret && ret != -ENXIO)
flite_set_cam_clock(flite, false);
flite->pipeline.flite = NULL;
flite->pipeline.csis = NULL;
flite->pipeline.sensor = NULL;
return ret == -ENXIO ? 0 : ret;
}
int flite_pipeline_shutdown(struct flite_dev *flite)
{
struct media_entity *me = &flite->vfd->entity;
int ret;
mutex_lock(&me->parent->graph_mutex);
ret = __flite_pipeline_shutdown(flite);
mutex_unlock(&me->parent->graph_mutex);
return ret;
}
static int flite_close(struct file *file)
{
struct flite_dev *flite = video_drvdata(file);
struct flite_buffer *buf;
flite_info("pid: %d, state: 0x%lx", task_pid_nr(current), flite->state);
if (--flite->refcnt == 0) {
clear_bit(FLITE_ST_OPEN, &flite->state);
flite_info("FIMC-LITE h/w disable control");
flite_hw_set_capture_stop(flite);
clear_bit(FLITE_ST_STREAM, &flite->state);
flite_pipeline_shutdown(flite);
clear_bit(FLITE_ST_SUSPEND, &flite->state);
}
if (flite->refcnt == 0) {
while (!list_empty(&flite->pending_buf_q)) {
flite_info("clean pending q");
buf = pending_queue_pop(flite);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
}
while (!list_empty(&flite->active_buf_q)) {
flite_info("clean active q");
buf = active_queue_pop(flite);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
}
vb2_queue_release(&flite->vbq);
flite_ctrls_delete(flite);
}
return v4l2_fh_release(file);
}
static unsigned int flite_poll(struct file *file,
struct poll_table_struct *wait)
{
struct flite_dev *flite = video_drvdata(file);
return vb2_poll(&flite->vbq, file, wait);
}
static int flite_mmap(struct file *file, struct vm_area_struct *vma)
{
struct flite_dev *flite = video_drvdata(file);
return vb2_mmap(&flite->vbq, vma);
}
/*
* videobuf2 operations
*/
int flite_pipeline_s_stream(struct flite_dev *flite, int on)
{
struct flite_pipeline *p = &flite->pipeline;
int ret = 0;
if (!p->sensor)
return -ENODEV;
if (on) {
ret = v4l2_subdev_call(p->flite, video, s_stream, 1);
if (ret < 0 && ret != -ENOIOCTLCMD)
return ret;
ret = v4l2_subdev_call(p->csis, video, s_stream, 1);
if (ret < 0 && ret != -ENOIOCTLCMD)
return ret;
ret = v4l2_subdev_call(p->sensor, video, s_stream, 1);
} else {
ret = v4l2_subdev_call(p->sensor, video, s_stream, 0);
if (ret < 0 && ret != -ENOIOCTLCMD)
return ret;
ret = v4l2_subdev_call(p->csis, video, s_stream, 0);
if (ret < 0 && ret != -ENOIOCTLCMD)
return ret;
ret = v4l2_subdev_call(p->flite, video, s_stream, 0);
}
return ret == -ENOIOCTLCMD ? 0 : ret;
}
static int flite_start_streaming(struct vb2_queue *q, unsigned int count)
{
struct flite_dev *flite = q->drv_priv;
flite->active_buf_cnt = 0;
flite->pending_buf_cnt = 0;
flite->mdev->is_flite_on= true;
if (!test_bit(FLITE_ST_STREAM, &flite->state)) {
if (!test_and_set_bit(FLITE_ST_PIPE_STREAM, &flite->state))
flite_pipeline_s_stream(flite, 1);
}
return 0;
}
static int flite_state_cleanup(struct flite_dev *flite)
{
unsigned long flags;
bool streaming;
spin_lock_irqsave(&flite->slock, flags);
streaming = flite->state & (1 << FLITE_ST_PIPE_STREAM);
flite->state &= ~(1 << FLITE_ST_RUN | 1 << FLITE_ST_STREAM |
1 << FLITE_ST_PIPE_STREAM | 1 << FLITE_ST_PEND);
set_bit(FLITE_ST_SUSPEND, &flite->state);
spin_unlock_irqrestore(&flite->slock, flags);
if (streaming)
return flite_pipeline_s_stream(flite, 0);
else
return 0;
}
static int flite_stop_capture(struct flite_dev *flite)
{
if (!flite_active(flite)) {
flite_warn("already stopped\n");
return 0;
}
flite_info("FIMC-Lite H/W disable control");
flite_hw_set_capture_stop(flite);
clear_bit(FLITE_ST_STREAM, &flite->state);
return flite_state_cleanup(flite);
}
static int flite_stop_streaming(struct vb2_queue *q)
{
struct flite_dev *flite = q->drv_priv;
if (!flite_active(flite))
return -EINVAL;
flite->mdev->is_flite_on= false;
return flite_stop_capture(flite);
}
static u32 get_plane_size(struct flite_frame *frame, unsigned int plane)
{
if (!frame) {
flite_err("frame is null");
return 0;
}
return frame->payload;
}
static int flite_queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
unsigned int *num_buffers, unsigned int *num_planes,
unsigned int sizes[], void *allocators[])
{
struct flite_dev *flite = vq->drv_priv;
struct flite_fmt *ffmt = flite->d_frame.fmt;
if (!ffmt)
return -EINVAL;
*num_planes = 1;
sizes[0] = get_plane_size(&flite->d_frame, 0);
allocators[0] = flite->alloc_ctx;
return 0;
}
static int flite_buf_prepare(struct vb2_buffer *vb)
{
struct vb2_queue *vq = vb->vb2_queue;
struct flite_dev *flite = vq->drv_priv;
struct flite_frame *frame = &flite->d_frame;
unsigned long size;
if (frame->fmt == NULL)
return -EINVAL;
size = frame->payload;
if (vb2_plane_size(vb, 0) < size) {
v4l2_err(flite->vfd, "User buffer too small (%ld < %ld)\n",
vb2_plane_size(vb, 0), size);
return -EINVAL;
}
vb2_set_plane_payload(vb, 0, size);
if (frame->cacheable)
flite->vb2->cache_flush(vb, 1);
return 0;
}
/* The color format (nr_comp, num_planes) must be already configured. */
int flite_prepare_addr(struct flite_dev *flite, struct vb2_buffer *vb,
struct flite_frame *frame, struct flite_addr *addr)
{
if (IS_ERR(vb) || IS_ERR(frame)) {
flite_err("Invalid argument");
return -EINVAL;
}
addr->y = flite->vb2->plane_addr(vb, 0);
flite_dbg("ADDR: y= 0x%X", addr->y);
return 0;
}
static void flite_buf_queue(struct vb2_buffer *vb)
{
struct flite_buffer *buf = container_of(vb, struct flite_buffer, vb);
struct flite_dev *flite = vb2_get_drv_priv(vb->vb2_queue);
int min_bufs;
unsigned long flags;
spin_lock_irqsave(&flite->slock, flags);
flite_prepare_addr(flite, &buf->vb, &flite->d_frame, &buf->paddr);
min_bufs = flite->reqbufs_cnt > 1 ? 2 : 1;
if (flite->active_buf_cnt < FLITE_MAX_OUT_BUFS) {
active_queue_add(flite, buf);
flite_hw_set_output_addr(flite, &buf->paddr, vb->v4l2_buf.index);
} else {
pending_queue_add(flite, buf);
}
if (vb2_is_streaming(&flite->vbq) &&
(flite->pending_buf_cnt >= min_bufs) &&
!test_bit(FLITE_ST_STREAM, &flite->state)) {
if (!test_and_set_bit(FLITE_ST_PIPE_STREAM, &flite->state)) {
spin_unlock_irqrestore(&flite->slock, flags);
flite_pipeline_s_stream(flite, 1);
return;
}
if (!test_bit(FLITE_ST_STREAM, &flite->state)) {
flite_info("G-Scaler h/w enable control");
flite_hw_set_capture_start(flite);
set_bit(FLITE_ST_STREAM, &flite->state);
}
}
spin_unlock_irqrestore(&flite->slock, flags);
return;
}
static struct vb2_ops flite_qops = {
.queue_setup = flite_queue_setup,
.buf_prepare = flite_buf_prepare,
.buf_queue = flite_buf_queue,
.wait_prepare = flite_unlock,
.wait_finish = flite_lock,
.start_streaming = flite_start_streaming,
.stop_streaming = flite_stop_streaming,
};
/*
* The video node ioctl operations
*/
static int flite_vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct flite_dev *flite = video_drvdata(file);
strncpy(cap->driver, flite->pdev->name, sizeof(cap->driver) - 1);
strncpy(cap->card, flite->pdev->name, sizeof(cap->card) - 1);
cap->bus_info[0] = 0;
cap->capabilities = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_CAPTURE_MPLANE;
return 0;
}
static int flite_enum_fmt_mplane(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct flite_fmt *fmt;
fmt = find_format(NULL, NULL, f->index);
if (!fmt)
return -EINVAL;
strncpy(f->description, fmt->name, sizeof(f->description) - 1);
f->pixelformat = fmt->pixelformat;
return 0;
}
static int flite_try_fmt_mplane(struct file *file, void *fh, struct v4l2_format *f)
{
struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp;
struct flite_fmt *fmt;
u32 max_w, max_h, mod_x, mod_y;
u32 min_w, min_h, tmp_w, tmp_h;
int i;
if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
return -EINVAL;
flite_dbg("user put w: %d, h: %d", pix_mp->width, pix_mp->height);
fmt = find_format(&pix_mp->pixelformat, NULL, 0);
if (!fmt) {
flite_err("pixelformat format (0x%X) invalid\n", pix_mp->pixelformat);
return -EINVAL;
}
max_w = variant.max_w;
max_h = variant.max_h;
min_w = min_h = mod_y = 0;
if (fmt->is_yuv)
mod_x = ffs(variant.align_out_w / 2) - 1;
else
mod_x = ffs(variant.align_out_w) - 1;
flite_dbg("mod_x: %d, mod_y: %d, max_w: %d, max_h = %d",
mod_x, mod_y, max_w, max_h);
/* To check if image size is modified to adjust parameter against
hardware abilities */
tmp_w = pix_mp->width;
tmp_h = pix_mp->height;
v4l_bound_align_image(&pix_mp->width, min_w, max_w, mod_x,
&pix_mp->height, min_h, max_h, mod_y, 0);
if (tmp_w != pix_mp->width || tmp_h != pix_mp->height)
flite_info("Image size has been modified from %dx%d to %dx%d",
tmp_w, tmp_h, pix_mp->width, pix_mp->height);
pix_mp->num_planes = 1;
for (i = 0; i < pix_mp->num_planes; ++i) {
int bpl = (pix_mp->width * fmt->depth[i]) >> 3;
pix_mp->plane_fmt[i].bytesperline = bpl;
pix_mp->plane_fmt[i].sizeimage = bpl * pix_mp->height;
flite_dbg("[%d]: bpl: %d, sizeimage: %d",
i, bpl, pix_mp->plane_fmt[i].sizeimage);
}
return 0;
}
void flite_set_frame_size(struct flite_frame *frame, int width, int height)
{
frame->o_width = width;
frame->o_height = height;
frame->width = width;
frame->height = height;
frame->offs_h = 0;
frame->offs_v = 0;
}
static int flite_s_fmt_mplane(struct file *file, void *fh, struct v4l2_format *f)
{
struct flite_dev *flite = video_drvdata(file);
struct flite_frame *frame;
struct v4l2_pix_format_mplane *pix;
int ret = 0;
ret = flite_try_fmt_mplane(file, fh, f);
if (ret)
return ret;
if (vb2_is_streaming(&flite->vbq)) {
flite_err("queue (%d) busy", f->type);
return -EBUSY;
}
frame = &flite->d_frame;
pix = &f->fmt.pix_mp;
frame->fmt = find_format(&pix->pixelformat, NULL, 0);
if (!frame->fmt)
return -EINVAL;
frame->payload = pix->plane_fmt[0].bytesperline * pix->height;
flite_set_frame_size(frame, pix->width, pix->height);
flite_info("f_w: %d, f_h: %d", frame->o_width, frame->o_height);
return 0;
}
static int flite_g_fmt_mplane(struct file *file, void *fh, struct v4l2_format *f)
{
struct flite_dev *flite = video_drvdata(file);
struct flite_frame *frame;
struct v4l2_pix_format_mplane *pix_mp;
int i;
if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
return -EINVAL;
frame = &flite->d_frame;
if (IS_ERR(frame))
return PTR_ERR(frame);
pix_mp = &f->fmt.pix_mp;
pix_mp->width = frame->o_width;
pix_mp->height = frame->o_height;
pix_mp->field = V4L2_FIELD_NONE;
pix_mp->pixelformat = frame->fmt->pixelformat;
pix_mp->colorspace = V4L2_COLORSPACE_JPEG;
pix_mp->num_planes = 1;
for (i = 0; i < pix_mp->num_planes; ++i) {
pix_mp->plane_fmt[i].bytesperline = (frame->o_width *
frame->fmt->depth[i]) / 8;
pix_mp->plane_fmt[i].sizeimage = pix_mp->plane_fmt[i].bytesperline *
frame->o_height;
}
return 0;
}
static int flite_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *reqbufs)
{
struct flite_dev *flite = video_drvdata(file);
struct flite_frame *frame;
int ret;
frame = &flite->d_frame;
frame->cacheable = flite->flite_ctrls.cacheable->val;
flite->vb2->set_cacheable(flite->alloc_ctx, frame->cacheable);
ret = vb2_reqbufs(&flite->vbq, reqbufs);
if (!ret)
flite->reqbufs_cnt = reqbufs->count;
return ret;
}
static int flite_querybuf(struct file *file, void *priv, struct v4l2_buffer *buf)
{
struct flite_dev *flite = video_drvdata(file);
return vb2_querybuf(&flite->vbq, buf);
}
static int flite_qbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
{
struct flite_dev *flite = video_drvdata(file);
return vb2_qbuf(&flite->vbq, buf);
}
static int flite_dqbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
{
struct flite_dev *flite = video_drvdata(file);
return vb2_dqbuf(&flite->vbq, buf, file->f_flags & O_NONBLOCK);
}
static int flite_link_validate(struct flite_dev *flite)
{
struct v4l2_subdev_format sink_fmt, src_fmt;
struct v4l2_subdev *sd;
struct media_pad *pad;
int ret;
/* Get the source pad connected with flite-video */
pad = media_entity_remote_source(&flite->vd_pad);
if (pad == NULL)
return -EPIPE;
/* Get the subdev of source pad */
sd = media_entity_to_v4l2_subdev(pad->entity);
while (1) {
/* Find sink pad of the subdev*/
pad = &sd->entity.pads[0];
if (!(pad->flags & MEDIA_PAD_FL_SINK))
break;
if (sd == flite->sd_flite) {
struct flite_frame *f = &flite->s_frame;
sink_fmt.format.width = f->o_width;
sink_fmt.format.height = f->o_height;
sink_fmt.format.code = f->fmt ? f->fmt->code : 0;
} else {
sink_fmt.pad = pad->index;
sink_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &sink_fmt);
if (ret < 0 && ret != -ENOIOCTLCMD) {
flite_err("failed %s subdev get_fmt", sd->name);
return -EPIPE;
}
}
flite_info("sink sd name : %s", sd->name);
/* Get the source pad connected with remote sink pad */
pad = media_entity_remote_source(pad);
if (pad == NULL ||
media_entity_type(pad->entity) != MEDIA_ENT_T_V4L2_SUBDEV)
break;
/* Get the subdev of source pad */
sd = media_entity_to_v4l2_subdev(pad->entity);
flite_info("source sd name : %s", sd->name);
src_fmt.pad = pad->index;
src_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &src_fmt);
if (ret < 0 && ret != -ENOIOCTLCMD) {
flite_err("failed %s subdev get_fmt", sd->name);
return -EPIPE;
}
flite_info("src_width : %d, src_height : %d, src_code : %d",
src_fmt.format.width, src_fmt.format.height,
src_fmt.format.code);
flite_info("sink_width : %d, sink_height : %d, sink_code : %d",
sink_fmt.format.width, sink_fmt.format.height,
sink_fmt.format.code);
if (src_fmt.format.width != sink_fmt.format.width ||
src_fmt.format.height != sink_fmt.format.height ||
src_fmt.format.code != sink_fmt.format.code) {
flite_err("mismatch sink and source");
return -EPIPE;
}
}
return 0;
}
static int flite_streamon(struct file *file, void *priv, enum v4l2_buf_type type)
{
struct flite_dev *flite = video_drvdata(file);
struct flite_pipeline *p = &flite->pipeline;
int ret;
if (flite_active(flite))
return -EBUSY;
if (p->sensor) {
media_entity_pipeline_start(&p->sensor->entity, p->pipe);
} else {
flite_err("Error pipeline");
return -EPIPE;
}
ret = flite_link_validate(flite);
if (ret)
return ret;
flite_hw_reset(flite);
return vb2_streamon(&flite->vbq, type);
}
static int flite_streamoff(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct flite_dev *flite = video_drvdata(file);
struct v4l2_subdev *sd = flite->pipeline.sensor;
int ret;
ret = vb2_streamoff(&flite->vbq, type);
if (ret == 0)
media_entity_pipeline_stop(&sd->entity);
return ret;
}
static int flite_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct flite_dev *flite = video_drvdata(file);
struct exynos_platform_flite *pdata = flite->pdata;
struct exynos_isp_info *isp_info;
if (i->index >= MAX_CAMIF_CLIENTS)
return -EINVAL;
isp_info = pdata->isp_info[i->index];
if (isp_info == NULL)
return -EINVAL;
i->type = V4L2_INPUT_TYPE_CAMERA;
strncpy(i->name, isp_info->board_info->type, 32);
return 0;
}
static int flite_s_input(struct file *file, void *priv, unsigned int i)
{
return i == 0 ? 0 : -EINVAL;
}
static int flite_g_input(struct file *file, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static const struct v4l2_ioctl_ops flite_capture_ioctl_ops = {
.vidioc_querycap = flite_vidioc_querycap,
.vidioc_enum_fmt_vid_cap_mplane = flite_enum_fmt_mplane,
.vidioc_try_fmt_vid_cap_mplane = flite_try_fmt_mplane,
.vidioc_s_fmt_vid_cap_mplane = flite_s_fmt_mplane,
.vidioc_g_fmt_vid_cap_mplane = flite_g_fmt_mplane,
.vidioc_reqbufs = flite_reqbufs,
.vidioc_querybuf = flite_querybuf,
.vidioc_qbuf = flite_qbuf,
.vidioc_dqbuf = flite_dqbuf,
.vidioc_streamon = flite_streamon,
.vidioc_streamoff = flite_streamoff,
.vidioc_enum_input = flite_enum_input,
.vidioc_s_input = flite_s_input,
.vidioc_g_input = flite_g_input,
};
static const struct v4l2_file_operations flite_fops = {
.owner = THIS_MODULE,
.open = flite_open,
.release = flite_close,
.poll = flite_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = flite_mmap,
};
static int flite_config_camclk(struct flite_dev *flite,
struct exynos_isp_info *isp_info, int i)
{
struct clk *camclk;
struct clk *srclk;
camclk = clk_get(&flite->pdev->dev, isp_info->cam_clk_name);
if (IS_ERR_OR_NULL(camclk)) {
flite_err("failed to get cam clk");
return -ENXIO;
}
flite->sensor[i].camclk = camclk;
srclk = clk_get(&flite->pdev->dev, isp_info->cam_srclk_name);
if (IS_ERR_OR_NULL(srclk)) {
clk_put(camclk);
flite_err("failed to get cam source clk\n");
return -ENXIO;
}
clk_set_parent(camclk, srclk);
clk_set_rate(camclk, isp_info->clk_frequency);
clk_put(srclk);
flite->gsc_clk = clk_get(&flite->pdev->dev, "gscl");
if (IS_ERR_OR_NULL(flite->gsc_clk)) {
flite_err("failed to get gscl clk");
return -ENXIO;
}
return 0;
}
static struct v4l2_subdev *flite_register_sensor(struct flite_dev *flite,
int i)
{
struct exynos_platform_flite *pdata = flite->pdata;
struct exynos_isp_info *isp_info = pdata->isp_info[i];
struct exynos_md *mdev = flite->mdev;
struct i2c_adapter *adapter;
struct v4l2_subdev *sd = NULL;
adapter = i2c_get_adapter(isp_info->i2c_bus_num);
if (!adapter)
return NULL;
sd = v4l2_i2c_new_subdev_board(&mdev->v4l2_dev, adapter,
isp_info->board_info, NULL);
if (IS_ERR_OR_NULL(sd)) {
v4l2_err(&mdev->v4l2_dev, "Failed to acquire subdev\n");
return NULL;
}
v4l2_set_subdev_hostdata(sd, &flite->sensor[i]);
sd->grp_id = SENSOR_GRP_ID;
v4l2_info(&mdev->v4l2_dev, "Registered sensor subdevice %s\n",
isp_info->board_info->type);
return sd;
}
static int flite_register_sensor_entities(struct flite_dev *flite)
{
struct exynos_platform_flite *pdata = flite->pdata;
u32 num_clients = pdata->num_clients;
int i;
for (i = 0; i < num_clients; i++) {
flite->sensor[i].pdata = pdata->isp_info[i];
flite->sensor[i].sd = flite_register_sensor(flite, i);
if (IS_ERR_OR_NULL(flite->sensor[i].sd)) {
flite_err("failed to get register sensor");
return -EINVAL;
}
flite->mdev->sensor_sd[i] = flite->sensor[i].sd;
}
return 0;
}
static int flite_create_subdev(struct flite_dev *flite, struct v4l2_subdev *sd)
{
struct v4l2_device *v4l2_dev;
int ret;
sd->flags = V4L2_SUBDEV_FL_HAS_DEVNODE;
flite->pads[FLITE_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
flite->pads[FLITE_PAD_SOURCE_PREV].flags = MEDIA_PAD_FL_SOURCE;
flite->pads[FLITE_PAD_SOURCE_CAMCORD].flags = MEDIA_PAD_FL_SOURCE;
flite->pads[FLITE_PAD_SOURCE_MEM].flags = MEDIA_PAD_FL_SOURCE;
ret = media_entity_init(&sd->entity, FLITE_PADS_NUM,
flite->pads, 0);
if (ret)
goto err_ent;
sd->internal_ops = &flite_v4l2_internal_ops;
sd->entity.ops = &flite_media_ops;
sd->grp_id = FLITE_GRP_ID;
v4l2_dev = &flite->mdev->v4l2_dev;
flite->mdev->flite_sd[flite->id] = sd;
ret = v4l2_device_register_subdev(v4l2_dev, sd);
if (ret)
goto err_sub;
flite_init_formats(sd, NULL);
return 0;
err_sub:
media_entity_cleanup(&sd->entity);
err_ent:
return ret;
}
static int flite_create_link(struct flite_dev *flite)
{
struct media_entity *source, *sink;
struct exynos_platform_flite *pdata = flite->pdata;
struct exynos_isp_info *isp_info;
u32 num_clients = pdata->num_clients;
int ret, i;
enum cam_port id;
/* FIMC-LITE-SUBDEV ------> FIMC-LITE-VIDEO (Always link enable) */
source = &flite->sd_flite->entity;
sink = &flite->vfd->entity;
if (source && sink) {
ret = media_entity_create_link(source, FLITE_PAD_SOURCE_MEM, sink,
0, 0);
if (ret) {
flite_err("failed link flite-subdev to flite-video\n");
return ret;
}
}
/* link sensor to mipi-csis */
for (i = 0; i < num_clients; i++) {
isp_info = pdata->isp_info[i];
id = isp_info->cam_port;
switch (isp_info->bus_type) {
case CAM_TYPE_ITU:
/* SENSOR ------> FIMC-LITE */
source = &flite->sensor[i].sd->entity;
sink = &flite->sd_flite->entity;
if (source && sink) {
ret = media_entity_create_link(source, 0,
sink, FLITE_PAD_SINK, 0);
if (ret) {
flite_err("failed link sensor to flite\n");
return ret;
}
}
break;
case CAM_TYPE_MIPI:
/* SENSOR ------> MIPI-CSI2 */
source = &flite->sensor[i].sd->entity;
sink = &flite->sd_csis->entity;
if (source && sink) {
ret = media_entity_create_link(source, 0,
sink, CSIS_PAD_SINK, 0);
if (ret) {
flite_err("failed link sensor to csis\n");
return ret;
}
}
/* MIPI-CSI2 ------> FIMC-LITE */
source = &flite->sd_csis->entity;
sink = &flite->sd_flite->entity;
if (source && sink) {
ret = media_entity_create_link(source,
CSIS_PAD_SOURCE,
sink, FLITE_PAD_SINK, 0);
if (ret) {
flite_err("failed link csis to flite\n");
return ret;
}
}
break;
}
}
flite->input = FLITE_INPUT_NONE;
flite->output = FLITE_OUTPUT_NONE;
return 0;
}
static int flite_register_video_device(struct flite_dev *flite)
{
struct video_device *vfd;
struct vb2_queue *q;
int ret = -ENOMEM;
vfd = video_device_alloc();
if (!vfd) {
printk("Failed to allocate video device\n");
return ret;
}
snprintf(vfd->name, sizeof(vfd->name), "%s", dev_name(&flite->pdev->dev));
vfd->fops = &flite_fops;
vfd->ioctl_ops = &flite_capture_ioctl_ops;
vfd->v4l2_dev = &flite->mdev->v4l2_dev;
vfd->minor = -1;
vfd->release = video_device_release;
vfd->lock = &flite->lock;
video_set_drvdata(vfd, flite);
flite->vfd = vfd;
flite->refcnt = 0;
flite->reqbufs_cnt = 0;
INIT_LIST_HEAD(&flite->active_buf_q);
INIT_LIST_HEAD(&flite->pending_buf_q);
q = &flite->vbq;
memset(q, 0, sizeof(*q));
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
q->io_modes = VB2_MMAP | VB2_USERPTR;
q->drv_priv = flite;
q->ops = &flite_qops;
q->mem_ops = flite->vb2->ops;
vb2_queue_init(q);
ret = video_register_device(vfd, VFL_TYPE_GRABBER,
EXYNOS_VIDEONODE_FLITE(flite->id));
if (ret) {
flite_err("failed to register video device");
goto err_vfd_alloc;
}
flite->vd_pad.flags = MEDIA_PAD_FL_SOURCE;
ret = media_entity_init(&vfd->entity, 1, &flite->vd_pad, 0);
if (ret) {
flite_err("failed to initialize entity");
goto err_unreg_video;
}
vfd->ctrl_handler = &flite->ctrl_handler;
flite_dbg("flite video-device driver registered as /dev/video%d", vfd->num);
return 0;
err_unreg_video:
video_unregister_device(vfd);
err_vfd_alloc:
video_device_release(vfd);
return ret;
}
static int flite_get_md_callback(struct device *dev, void *p)
{
struct exynos_md **md_list = p;
struct exynos_md *md = NULL;
md = dev_get_drvdata(dev);
if (md)
*(md_list + md->id) = md;
return 0; /* non-zero value stops iteration */
}
static struct exynos_md *flite_get_capture_md(enum mdev_node node)
{
struct device_driver *drv;
struct exynos_md *md[MDEV_MAX_NUM] = {NULL,};
int ret;
drv = driver_find(MDEV_MODULE_NAME, &platform_bus_type);
if (!drv)
return ERR_PTR(-ENODEV);
ret = driver_for_each_device(drv, NULL, &md[0],
flite_get_md_callback);
return ret ? NULL : md[node];
}
static void flite_destroy_subdev(struct flite_dev *flite)
{
struct v4l2_subdev *sd = flite->sd_flite;
if (!sd)
return;
media_entity_cleanup(&sd->entity);
v4l2_device_unregister_subdev(sd);
kfree(sd);
sd = NULL;
}
void flite_unregister_device(struct flite_dev *flite)
{
struct video_device *vfd = flite->vfd;
if (vfd) {
media_entity_cleanup(&vfd->entity);
/* Can also be called if video device was
not registered */
video_unregister_device(vfd);
}
flite_destroy_subdev(flite);
}
#endif
static int flite_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct v4l2_subdev *sd = platform_get_drvdata(pdev);
struct flite_dev *flite = v4l2_get_subdevdata(sd);
if (test_bit(FLITE_ST_STREAM, &flite->state))
flite_s_stream(sd, false);
if (test_bit(FLITE_ST_POWER, &flite->state))
flite_s_power(sd, false);
set_bit(FLITE_ST_SUSPEND, &flite->state);
return 0;
}
static int flite_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct v4l2_subdev *sd = platform_get_drvdata(pdev);
struct flite_dev *flite = v4l2_get_subdevdata(sd);
if (test_bit(FLITE_ST_POWER, &flite->state))
flite_s_power(sd, true);
if (test_bit(FLITE_ST_STREAM, &flite->state))
flite_s_stream(sd, true);
clear_bit(FLITE_ST_SUSPEND, &flite->state);
return 0;
}
static int flite_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct v4l2_subdev *sd = platform_get_drvdata(pdev);
struct flite_dev *flite = v4l2_get_subdevdata(sd);
unsigned long flags;
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
flite->vb2->suspend(flite->alloc_ctx);
clk_disable(flite->camif_clk);
#endif
spin_lock_irqsave(&flite->slock, flags);
set_bit(FLITE_ST_SUSPEND, &flite->state);
spin_unlock_irqrestore(&flite->slock, flags);
return 0;
}
static int flite_runtime_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct v4l2_subdev *sd = platform_get_drvdata(pdev);
struct flite_dev *flite = v4l2_get_subdevdata(sd);
unsigned long flags;
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
clk_enable(flite->camif_clk);
flite->vb2->resume(flite->alloc_ctx);
#endif
spin_lock_irqsave(&flite->slock, flags);
clear_bit(FLITE_ST_SUSPEND, &flite->state);
spin_unlock_irqrestore(&flite->slock, flags);
return 0;
}
static struct v4l2_subdev_core_ops flite_core_ops = {
.s_power = flite_s_power,
};
static struct v4l2_subdev_video_ops flite_video_ops = {
.g_mbus_fmt = flite_g_mbus_fmt,
.s_mbus_fmt = flite_s_mbus_fmt,
.s_stream = flite_s_stream,
.cropcap = flite_subdev_cropcap,
.g_crop = flite_subdev_g_crop,
.s_crop = flite_subdev_s_crop,
};
static struct v4l2_subdev_ops flite_subdev_ops = {
.core = &flite_core_ops,
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
.pad = &flite_pad_ops,
#endif
.video = &flite_video_ops,
};
static int flite_probe(struct platform_device *pdev)
{
struct resource *mem_res;
struct resource *regs_res;
struct flite_dev *flite;
struct v4l2_subdev *sd;
int ret = -ENODEV;
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
struct exynos_isp_info *isp_info;
int i;
#endif
if (!pdev->dev.platform_data) {
dev_err(&pdev->dev, "platform data is NULL\n");
return -EINVAL;
}
flite = kzalloc(sizeof(struct flite_dev), GFP_KERNEL);
if (!flite)
return -ENOMEM;
flite->pdev = pdev;
flite->pdata = pdev->dev.platform_data;
flite->id = pdev->id;
init_waitqueue_head(&flite->irq_queue);
spin_lock_init(&flite->slock);
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem_res) {
dev_err(&pdev->dev, "Failed to get io memory region\n");
goto err_flite;
}
regs_res = request_mem_region(mem_res->start, resource_size(mem_res),
pdev->name);
if (!regs_res) {
dev_err(&pdev->dev, "Failed to request io memory region\n");
goto err_resource;
}
flite->regs_res = regs_res;
flite->regs = ioremap(mem_res->start, resource_size(mem_res));
if (!flite->regs) {
dev_err(&pdev->dev, "Failed to remap io region\n");
goto err_reg_region;
}
flite->irq = platform_get_irq(pdev, 0);
if (flite->irq < 0) {
dev_err(&pdev->dev, "Failed to get irq\n");
goto err_reg_unmap;
}
ret = request_irq(flite->irq, flite_irq_handler, 0, dev_name(&pdev->dev), flite);
if (ret) {
dev_err(&pdev->dev, "request_irq failed\n");
goto err_reg_unmap;
}
sd = kzalloc(sizeof(*sd), GFP_KERNEL);
if (!sd)
goto err_irq;
v4l2_subdev_init(sd, &flite_subdev_ops);
snprintf(sd->name, sizeof(sd->name), "flite-subdev.%d", flite->id);
flite->sd_flite = sd;
v4l2_set_subdevdata(flite->sd_flite, flite);
if (soc_is_exynos4212() || soc_is_exynos4412())
v4l2_set_subdev_hostdata(sd, pdev);
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
#if defined(CONFIG_VIDEOBUF2_CMA_PHYS)
flite->vb2 = &flite_vb2_cma;
#elif defined(CONFIG_VIDEOBUF2_ION)
flite->vb2 = &flite_vb2_ion;
#endif
mutex_init(&flite->lock);
flite->mdev = flite_get_capture_md(MDEV_CAPTURE);
if (IS_ERR_OR_NULL(flite->mdev))
goto err_irq;
flite_dbg("mdev = 0x%08x", (u32)flite->mdev);
ret = flite_register_video_device(flite);
if (ret)
goto err_irq;
/* Get mipi-csis subdev ptr using mdev */
flite->sd_csis = flite->mdev->csis_sd[flite->id];
for (i = 0; i < flite->pdata->num_clients; i++) {
isp_info = flite->pdata->isp_info[i];
ret = flite_config_camclk(flite, isp_info, i);
if (ret) {
flite_err("failed setup cam clk");
goto err_vfd_alloc;
}
}
ret = flite_register_sensor_entities(flite);
if (ret) {
flite_err("failed register sensor entities");
goto err_clk;
}
ret = flite_create_subdev(flite, sd);
if (ret) {
flite_err("failed create subdev");
goto err_clk;
}
ret = flite_create_link(flite);
if (ret) {
flite_err("failed create link");
goto err_entity;
}
flite->alloc_ctx = flite->vb2->init(flite);
if (IS_ERR(flite->alloc_ctx)) {
ret = PTR_ERR(flite->alloc_ctx);
goto err_entity;
}
flite->camif_clk = clk_get(&flite->pdev->dev, CAMIF_TOP_CLK);
if (IS_ERR(flite->camif_clk)) {
flite_err("failed to get flite.%d clock", flite->id);
goto err_entity;
}
flite->mdev->is_flite_on= false;
#endif
platform_set_drvdata(flite->pdev, flite->sd_flite);
pm_runtime_enable(&pdev->dev);
flite_info("FIMC-LITE%d probe success", pdev->id);
return 0;
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
err_entity:
media_entity_cleanup(&sd->entity);
err_clk:
for (i = 0; i < flite->pdata->num_clients; i++)
clk_put(flite->sensor[i].camclk);
err_vfd_alloc:
media_entity_cleanup(&flite->vfd->entity);
video_device_release(flite->vfd);
#endif
err_irq:
free_irq(flite->irq, flite);
err_reg_unmap:
iounmap(flite->regs);
err_reg_region:
release_mem_region(regs_res->start, resource_size(regs_res));
err_resource:
release_resource(flite->regs_res);
kfree(flite->regs_res);
err_flite:
kfree(flite);
return ret;
}
static int flite_remove(struct platform_device *pdev)
{
struct v4l2_subdev *sd = platform_get_drvdata(pdev);
struct flite_dev *flite = v4l2_get_subdevdata(sd);
struct resource *res = flite->regs_res;
flite_s_power(flite->sd_flite, 0);
#if defined(CONFIG_MEDIA_CONTROLLER) && defined(CONFIG_ARCH_EXYNOS5)
flite_subdev_close(sd, NULL);
flite_unregister_device(flite);
flite->vb2->cleanup(flite->alloc_ctx);
#endif
pm_runtime_disable(&pdev->dev);
free_irq(flite->irq, flite);
iounmap(flite->regs);
release_mem_region(res->start, resource_size(res));
kfree(flite);
return 0;
}
static const struct dev_pm_ops flite_pm_ops = {
.suspend = flite_suspend,
.resume = flite_resume,
.runtime_suspend = flite_runtime_suspend,
.runtime_resume = flite_runtime_resume,
};
static struct platform_driver flite_driver = {
.probe = flite_probe,
.remove = __devexit_p(flite_remove),
.driver = {
.name = MODULE_NAME,
.owner = THIS_MODULE,
.pm = &flite_pm_ops,
}
};
static int __init flite_init(void)
{
int ret = platform_driver_register(&flite_driver);
if (ret)
flite_err("platform_driver_register failed: %d", ret);
return ret;
}
static void __exit flite_exit(void)
{
platform_driver_unregister(&flite_driver);
}
module_init(flite_init);
module_exit(flite_exit);
MODULE_AUTHOR("Sky Kang<sungchun.kang@samsung.com>");
MODULE_DESCRIPTION("Exynos FIMC-Lite driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
sigma-random/asuswrt-merlin | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/usb/Beceem_driver/src/Common/Arp.c | 40 | 3658 | /*
* Arp.c
*
*Copyright (C) 2010 Beceem Communications, Inc.
*
*This program is free software: you can redistribute it and/or modify
*it under the terms of the GNU General Public License version 2 as
*published by the Free Software Foundation.
*
*This program is distributed in the hope that it will be useful,but
*WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*See the GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program. If not, write to the Free Software Foundation, Inc.,
*51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
/**********************************************************************
* This file contains the routines for handling ARP PACKETS
***********************************************************************/
#include <headers.h>
#define ARP_PKT_SIZE 60
/* =========================================================================
* Function - reply_to_arp_request()
*
* Description - When this host tries to broadcast ARP request packet through
* the virtual interface (veth0), reply directly to upper layer.
* This function allocates a new skb for ARP reply packet,
* fills in the fields of the packet and then sends it to
* upper layer.
*
* Parameters - skb: Pointer to sk_buff structure of the ARP request pkt.
*
* Returns - None
* =========================================================================*/
VOID
reply_to_arp_request(struct sk_buff *skb)
{
PMINI_ADAPTER Adapter;
struct ArpHeader *pArpHdr = NULL;
struct ethhdr *pethhdr = NULL;
UCHAR uiIPHdr[4];
/* Check for valid skb */
if(skb == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Invalid skb: Cannot reply to ARP request\n");
return;
}
Adapter = GET_BCM_ADAPTER(skb->dev);
/* Print the ARP Request Packet */
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, ARP_RESP, DBG_LVL_ALL, "ARP Packet Dump :");
BCM_DEBUG_PRINT_BUFFER(Adapter,DBG_TYPE_TX, ARP_RESP, DBG_LVL_ALL, (PUCHAR)(skb->data), skb->len);
/*
* Extract the Ethernet Header and Arp Payload including Header
*/
pethhdr = (struct ethhdr *)skb->data;
pArpHdr = (struct ArpHeader *)(skb->data+ETH_HLEN);
if(Adapter->bETHCSEnabled)
{
if(memcmp(pethhdr->h_source, Adapter->dev->dev_addr, ETH_ALEN))
{
bcm_kfree_skb(skb);
return;
}
}
// Set the Ethernet Header First.
memcpy(pethhdr->h_dest, pethhdr->h_source, ETH_ALEN);
if(!memcmp(pethhdr->h_source, Adapter->dev->dev_addr, ETH_ALEN))
{
pethhdr->h_source[5]++;
}
/* Set the reply to ARP Reply */
pArpHdr->arp.ar_op = ntohs(ARPOP_REPLY);
/* Set the HW Address properly */
memcpy(pArpHdr->ar_sha, pethhdr->h_source, ETH_ALEN);
memcpy(pArpHdr->ar_tha, pethhdr->h_dest, ETH_ALEN);
// Swapping the IP Adddress
memcpy(uiIPHdr,pArpHdr->ar_sip,4);
memcpy(pArpHdr->ar_sip,pArpHdr->ar_tip,4);
memcpy(pArpHdr->ar_tip,uiIPHdr,4);
/* Print the ARP Reply Packet */
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, ARP_RESP, DBG_LVL_ALL, "ARP REPLY PACKET: ");
/* Send the Packet to upper layer */
BCM_DEBUG_PRINT_BUFFER(Adapter,DBG_TYPE_TX, ARP_RESP, DBG_LVL_ALL, (PUCHAR)(skb->data), skb->len);
skb->protocol = eth_type_trans(skb,skb->dev);
skb->pkt_type = PACKET_HOST;
// skb->mac.raw=skb->data+LEADER_SIZE;
skb_set_mac_header (skb, LEADER_SIZE);
netif_rx(skb);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, ARP_RESP, DBG_LVL_ALL, "<=============\n");
return;
}
| gpl-2.0 |
jyizheng/linux-3.16 | drivers/usb/serial/ftdi_sio.c | 40 | 90840 | /*
* USB FTDI SIO driver
*
* Copyright (C) 2009 - 2013
* Johan Hovold (jhovold@gmail.com)
* Copyright (C) 1999 - 2001
* Greg Kroah-Hartman (greg@kroah.com)
* Bill Ryder (bryder@sgi.com)
* Copyright (C) 2002
* Kuba Ober (kuba@mareimbrium.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.
*
* See Documentation/usb/usb-serial.txt for more information on using this
* driver
*
* See http://ftdi-usb-sio.sourceforge.net for up to date testing info
* and extra documentation
*
* Change entries from 2004 and earlier can be found in versions of this
* file in kernel versions prior to the 2.6.24 release.
*
*/
/* Bill Ryder - bryder@sgi.com - wrote the FTDI_SIO implementation */
/* Thanx to FTDI for so kindly providing details of the protocol required */
/* to talk to the device */
/* Thanx to gkh and the rest of the usb dev group for all code I have
assimilated :-) */
#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/spinlock.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/serial.h>
#include <linux/usb/serial.h>
#include "ftdi_sio.h"
#include "ftdi_sio_ids.h"
#define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com>, Bill Ryder <bryder@sgi.com>, Kuba Ober <kuba@mareimbrium.org>, Andreas Mohr, Johan Hovold <jhovold@gmail.com>"
#define DRIVER_DESC "USB FTDI Serial Converters Driver"
struct ftdi_private {
enum ftdi_chip_type chip_type;
/* type of device, either SIO or FT8U232AM */
int baud_base; /* baud base clock for divisor setting */
int custom_divisor; /* custom_divisor kludge, this is for
baud_base (different from what goes to the
chip!) */
__u16 last_set_data_urb_value ;
/* the last data state set - needed for doing
* a break
*/
int flags; /* some ASYNC_xxxx flags are supported */
unsigned long last_dtr_rts; /* saved modem control outputs */
char prev_status; /* Used for TIOCMIWAIT */
char transmit_empty; /* If transmitter is empty or not */
__u16 interface; /* FT2232C, FT2232H or FT4232H port interface
(0 for FT232/245) */
speed_t force_baud; /* if non-zero, force the baud rate to
this value */
int force_rtscts; /* if non-zero, force RTS-CTS to always
be enabled */
unsigned int latency; /* latency setting in use */
unsigned short max_packet_size;
struct mutex cfg_lock; /* Avoid mess by parallel calls of config ioctl() and change_speed() */
};
/* struct ftdi_sio_quirk is used by devices requiring special attention. */
struct ftdi_sio_quirk {
int (*probe)(struct usb_serial *);
/* Special settings for probed ports. */
void (*port_probe)(struct ftdi_private *);
};
static int ftdi_jtag_probe(struct usb_serial *serial);
static int ftdi_mtxorb_hack_setup(struct usb_serial *serial);
static int ftdi_NDI_device_setup(struct usb_serial *serial);
static int ftdi_stmclite_probe(struct usb_serial *serial);
static int ftdi_8u2232c_probe(struct usb_serial *serial);
static void ftdi_USB_UIRT_setup(struct ftdi_private *priv);
static void ftdi_HE_TIRA1_setup(struct ftdi_private *priv);
static struct ftdi_sio_quirk ftdi_jtag_quirk = {
.probe = ftdi_jtag_probe,
};
static struct ftdi_sio_quirk ftdi_mtxorb_hack_quirk = {
.probe = ftdi_mtxorb_hack_setup,
};
static struct ftdi_sio_quirk ftdi_NDI_device_quirk = {
.probe = ftdi_NDI_device_setup,
};
static struct ftdi_sio_quirk ftdi_USB_UIRT_quirk = {
.port_probe = ftdi_USB_UIRT_setup,
};
static struct ftdi_sio_quirk ftdi_HE_TIRA1_quirk = {
.port_probe = ftdi_HE_TIRA1_setup,
};
static struct ftdi_sio_quirk ftdi_stmclite_quirk = {
.probe = ftdi_stmclite_probe,
};
static struct ftdi_sio_quirk ftdi_8u2232c_quirk = {
.probe = ftdi_8u2232c_probe,
};
/*
* The 8U232AM has the same API as the sio except for:
* - it can support MUCH higher baudrates; up to:
* o 921600 for RS232 and 2000000 for RS422/485 at 48MHz
* o 230400 at 12MHz
* so .. 8U232AM's baudrate setting codes are different
* - it has a two byte status code.
* - it returns characters every 16ms (the FTDI does it every 40ms)
*
* the bcdDevice value is used to differentiate FT232BM and FT245BM from
* the earlier FT8U232AM and FT8U232BM. For now, include all known VID/PID
* combinations in both tables.
* FIXME: perhaps bcdDevice can also identify 12MHz FT8U232AM devices,
* but I don't know if those ever went into mass production. [Ian Abbott]
*/
/*
* Device ID not listed? Test it using
* /sys/bus/usb-serial/drivers/ftdi_sio/new_id and send a patch or report.
*/
static const struct usb_device_id id_table_combined[] = {
{ USB_DEVICE(FTDI_VID, FTDI_ZEITCONTROL_TAGTRACE_MIFARE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CTI_MINI_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CTI_NANO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_AMC232_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CANUSB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CANDAPTER_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_NXTCAM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_EV3CON_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_5_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_6_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCS_DEVICE_7_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USINT_CAT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USINT_WKEY_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USINT_RS232_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ACTZWAVE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IRTRANS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IPLUS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IPLUS2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DMX4ALL) },
{ USB_DEVICE(FTDI_VID, FTDI_SIO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_8U232AM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_8U232AM_ALT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_232RL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_8U2232C_PID) ,
.driver_info = (kernel_ulong_t)&ftdi_8u2232c_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_4232H_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_232H_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_FTX_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MICRO_CHAMELEON_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_RELAIS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_SNIFFER_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_THROTTLE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_GATEWAY_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_GBM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OPENDCC_GBM_BOOST_PID) },
{ USB_DEVICE(NEWPORT_VID, NEWPORT_AGILIS_PID) },
{ USB_DEVICE(NEWPORT_VID, NEWPORT_CONEX_CC_PID) },
{ USB_DEVICE(NEWPORT_VID, NEWPORT_CONEX_AGP_PID) },
{ USB_DEVICE(INTERBIOMETRICS_VID, INTERBIOMETRICS_IOBOARD_PID) },
{ USB_DEVICE(INTERBIOMETRICS_VID, INTERBIOMETRICS_MINI_IOBOARD_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SPROG_II) },
{ USB_DEVICE(FTDI_VID, FTDI_TAGSYS_LP101_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TAGSYS_P200X_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_LENZ_LIUSB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_632_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_634_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_547_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_633_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_631_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_635_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_640_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_XF_642_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DSS20_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_URBAN_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_URBAN_1_PID) },
{ USB_DEVICE(FTDI_NF_RIC_VID, FTDI_NF_RIC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_VNHCPCUSB_D_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_5_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_6_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_R2000KU_TRUE_RNG) },
{ USB_DEVICE(FTDI_VID, FTDI_VARDAAN_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0100_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0101_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0102_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0103_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0104_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0105_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0106_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0107_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0108_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0109_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_010F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0110_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0111_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0112_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0113_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0114_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0115_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0116_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0117_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0118_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0119_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_011F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0120_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0121_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0122_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0123_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0124_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0125_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0126_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0127_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0128_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0129_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012C_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_012F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0130_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0131_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0132_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0133_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0134_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0135_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0136_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0137_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0138_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0139_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_013F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0140_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0141_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0142_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0143_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0144_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0145_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0146_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0147_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0148_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0149_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_014F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0150_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0151_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0152_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0153_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0154_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0155_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0156_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0157_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0158_PID),
.driver_info = (kernel_ulong_t)&ftdi_mtxorb_hack_quirk },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0159_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_015F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0160_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0161_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0162_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0163_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0164_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0165_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0166_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0167_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0168_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0169_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_016F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0170_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0171_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0172_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0173_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0174_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0175_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0176_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0177_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0178_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0179_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_017F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0180_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0181_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0182_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0183_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0184_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0185_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0186_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0187_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0188_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0189_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_018F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0190_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0191_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0192_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0193_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0194_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0195_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0196_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0197_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0198_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_0199_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019A_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019B_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019C_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019D_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019E_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_019F_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01A9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01AF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01B9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01BF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01C9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01CF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01D9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01DF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01E9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01ED_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01EF_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F0_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F1_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F2_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F3_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F4_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F5_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F6_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F7_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F8_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01F9_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FA_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FB_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FC_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FD_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FE_PID) },
{ USB_DEVICE(MTXORB_VID, MTXORB_FTDI_RANGE_01FF_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PERLE_ULTRAPORT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PIEGROUP_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TNC_X_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_USBX_707_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2101_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2102_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2103_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2104_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2106_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2201_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2201_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2202_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2202_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2203_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2203_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_5_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_6_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_7_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_8_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_5_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_6_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_7_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_8_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_4_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_5_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_6_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_7_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_8_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803R_1_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803R_2_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803R_3_PID) },
{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803R_4_PID) },
{ USB_DEVICE(IDTECH_VID, IDTECH_IDT1221U_PID) },
{ USB_DEVICE(OCT_VID, OCT_US101_PID) },
{ USB_DEVICE(OCT_VID, OCT_DK201_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_HE_TIRA1_PID),
.driver_info = (kernel_ulong_t)&ftdi_HE_TIRA1_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_USB_UIRT_PID),
.driver_info = (kernel_ulong_t)&ftdi_USB_UIRT_quirk },
{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_1) },
{ USB_DEVICE(FTDI_VID, PROTEGO_R2X0) },
{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_3) },
{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_4) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E808_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E809_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80A_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80B_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80D_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80E_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80F_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E888_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E889_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88A_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88B_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88D_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88E_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88F_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UO100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UM100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UR100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_ALC8500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PYRAMID_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FHZ1000PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_US485_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PICPRO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PCMCIA_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PK1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_RS232MON_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_APP70_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PEDO_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_IBS_PROD_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TAVIR_STK500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TIAO_UMPA_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NT_ORIONLXM_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
/*
* ELV devices:
*/
{ USB_DEVICE(FTDI_ELV_VID, FTDI_ELV_WS300_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_USR_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_MSM1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_KL100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS550_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_EC3000_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS888_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_TWS550_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FEM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_CLI7000_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_PPS7330_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_TFM100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UDF77_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UIO88_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UAD8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UDA7_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_USI2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_T1100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_PCD200_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_ULA200_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_CSI8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_EM1000DL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_PCK100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_RFP500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FS20SIG_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UTP8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS300PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS444PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FHZ1300PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_EM1010PC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS500_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_HS485_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_UMS100_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_TFD128_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_FM3RX_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELV_WS777_PID) },
{ USB_DEVICE(FTDI_VID, LINX_SDMUSBQSS_PID) },
{ USB_DEVICE(FTDI_VID, LINX_MASTERDEVEL2_PID) },
{ USB_DEVICE(FTDI_VID, LINX_FUTURE_0_PID) },
{ USB_DEVICE(FTDI_VID, LINX_FUTURE_1_PID) },
{ USB_DEVICE(FTDI_VID, LINX_FUTURE_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU20_0_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU40_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSMACHX_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSLOAD_N_GO_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU64_4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CCSPRIME8_5_PID) },
{ USB_DEVICE(FTDI_VID, INSIDE_ACCESSO) },
{ USB_DEVICE(INTREPID_VID, INTREPID_VALUECAN_PID) },
{ USB_DEVICE(INTREPID_VID, INTREPID_NEOVI_PID) },
{ USB_DEVICE(FALCOM_VID, FALCOM_TWIST_PID) },
{ USB_DEVICE(FALCOM_VID, FALCOM_SAMBA_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SUUNTO_SPORTS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OCEANIC_PID) },
{ USB_DEVICE(TTI_VID, TTI_QL355P_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_RM_CANVIEW_PID) },
{ USB_DEVICE(ACTON_VID, ACTON_SPECTRAPRO_PID) },
{ USB_DEVICE(CONTEC_VID, CONTEC_COM1USBH_PID) },
{ USB_DEVICE(MITSUBISHI_VID, MITSUBISHI_FXUSB_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOPTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USPTL4_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2DR_2_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2DR_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOPTL4DR2_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_USOPTL4DR_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USB9F_2W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USB9F_4W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_232USB9M_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USBTB_2W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_485USBTB_4W_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_TTL5USB9M_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_TTL3USB9M_PID) },
{ USB_DEVICE(BANDB_VID, BANDB_ZZ_PROG1_USB_PID) },
{ USB_DEVICE(FTDI_VID, EVER_ECO_PRO_CDS) },
{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_3_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_0_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_1_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_2_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_3_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_4_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_5_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_6_PID) },
{ USB_DEVICE(FTDI_VID, XSENS_CONVERTER_7_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_OMNI1509) },
{ USB_DEVICE(MOBILITY_VID, MOBILITY_USB_SERIAL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ACTIVE_ROBOTS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_KW_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_YS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y6_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y8_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_IC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_DB9_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_RS232_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y9_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TERATRONIK_VCP_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TERATRONIK_D2XX_PID) },
{ USB_DEVICE(EVOLUTION_VID, EVOLUTION_ER1_PID) },
{ USB_DEVICE(EVOLUTION_VID, EVO_HYBRID_PID) },
{ USB_DEVICE(EVOLUTION_VID, EVO_RCM4_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ARTEMIS_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16C_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16HR_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16HRC_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ATIK_ATK16IC_PID) },
{ USB_DEVICE(KOBIL_VID, KOBIL_CONV_B1_PID) },
{ USB_DEVICE(KOBIL_VID, KOBIL_CONV_KAAN_PID) },
{ USB_DEVICE(POSIFLEX_VID, POSIFLEX_PP7000_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TTUSB_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ECLO_COM_1WIRE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_WESTREX_MODEL_777_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_WESTREX_MODEL_8900F_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PCDJ_DAC2_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_RRCIRKITS_LOCOBUFFER_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ASK_RDR400_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_NZR_SEM_USB_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_1_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_OPC_U_UC_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2C1_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2C2_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2D_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2VT_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2VR_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP4KVT_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP4KVR_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2KVT_PID) },
{ USB_DEVICE(ICOM_VID, ICOM_ID_RP2KVR_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ACG_HFDUAL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_YEI_SERVOCENTER31_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_THORLABS_PID) },
{ USB_DEVICE(TESTO_VID, TESTO_1_PID) },
{ USB_DEVICE(TESTO_VID, TESTO_3_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_GAMMA_SCOUT_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TACTRIX_OPENPORT_13M_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TACTRIX_OPENPORT_13S_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_TACTRIX_OPENPORT_13U_PID) },
{ USB_DEVICE(ELEKTOR_VID, ELEKTOR_FT323R_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_HUC_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_SPECTRA_SCU_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_FUTURE_2_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_FUTURE_3_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_NDI_AURORA_SCU_PID),
.driver_info = (kernel_ulong_t)&ftdi_NDI_device_quirk },
{ USB_DEVICE(TELLDUS_VID, TELLDUS_TELLSTICK_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_S03_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_59_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_57A_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_57B_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_29A_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_29B_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_29F_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_62B_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_S01_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_63_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_29C_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_81B_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_82B_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_K5D_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_K4Y_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_K5G_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_S05_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_60_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_61_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_62_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_63B_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_64_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_65_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_92_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_92D_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_W5R_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_A5R_PID) },
{ USB_DEVICE(RTSYSTEMS_VID, RTSYSTEMS_USB_PW1_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_MAXSTREAM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PHI_FISCO_PID) },
{ USB_DEVICE(TML_VID, TML_USB_SERIAL_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_ELSTER_UNICOM_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PROPOX_JTAGCABLEII_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_PROPOX_ISPCABLEIII_PID) },
{ USB_DEVICE(OLIMEX_VID, OLIMEX_ARM_USB_OCD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(OLIMEX_VID, OLIMEX_ARM_USB_OCD_H_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FIC_VID, FIC_NEO1973_DEBUG_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_OOCDLINK_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, LMI_LM3S_DEVEL_BOARD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, LMI_LM3S_EVAL_BOARD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, LMI_LM3S_ICDI_BOARD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_TURTELIZER_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(RATOC_VENDOR_ID, RATOC_PRODUCT_ID_USB60F) },
{ USB_DEVICE(FTDI_VID, FTDI_REU_TINY_PID) },
/* Papouch devices based on FTDI chip */
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB485_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_AP485_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB422_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB485_2_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_AP485_2_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB422_2_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB485S_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB485C_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_LEC_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SB232_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_TMU_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_IRAMP_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_DRAK5_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO8x8_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO4x4_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO2x2_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO10x1_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO30x3_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO60x3_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO2x16_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_QUIDO3x32_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_DRAK6_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_UPSUSB_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_MU_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_SIMUKEY_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_AD4USB_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_GMUX_PID) },
{ USB_DEVICE(PAPOUCH_VID, PAPOUCH_GMSR_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DOMINTELL_DGQG_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DOMINTELL_DUSB_PID) },
{ USB_DEVICE(ALTI2_VID, ALTI2_N3_PID) },
{ USB_DEVICE(FTDI_VID, DIEBOLD_BCS_SE923_PID) },
{ USB_DEVICE(ATMEL_VID, STK541_PID) },
{ USB_DEVICE(DE_VID, STB_PID) },
{ USB_DEVICE(DE_VID, WHT_PID) },
{ USB_DEVICE(ADI_VID, ADI_GNICE_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(ADI_VID, ADI_GNICEPLUS_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE_AND_INTERFACE_INFO(MICROCHIP_VID, MICROCHIP_USB_BOARD_PID,
USB_CLASS_VENDOR_SPEC,
USB_SUBCLASS_VENDOR_SPEC, 0x00) },
{ USB_DEVICE(JETI_VID, JETI_SPC1201_PID) },
{ USB_DEVICE(MARVELL_VID, MARVELL_SHEEVAPLUG_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(LARSENBRUSGAARD_VID, LB_ALTITRACK_PID) },
{ USB_DEVICE(GN_OTOMETRICS_VID, AURICAL_USB_PID) },
{ USB_DEVICE(FTDI_VID, PI_C865_PID) },
{ USB_DEVICE(FTDI_VID, PI_C857_PID) },
{ USB_DEVICE(PI_VID, PI_C866_PID) },
{ USB_DEVICE(PI_VID, PI_C663_PID) },
{ USB_DEVICE(PI_VID, PI_C725_PID) },
{ USB_DEVICE(PI_VID, PI_E517_PID) },
{ USB_DEVICE(PI_VID, PI_C863_PID) },
{ USB_DEVICE(PI_VID, PI_E861_PID) },
{ USB_DEVICE(PI_VID, PI_C867_PID) },
{ USB_DEVICE(PI_VID, PI_E609_PID) },
{ USB_DEVICE(PI_VID, PI_E709_PID) },
{ USB_DEVICE(PI_VID, PI_100F_PID) },
{ USB_DEVICE(PI_VID, PI_1011_PID) },
{ USB_DEVICE(PI_VID, PI_1012_PID) },
{ USB_DEVICE(PI_VID, PI_1013_PID) },
{ USB_DEVICE(PI_VID, PI_1014_PID) },
{ USB_DEVICE(PI_VID, PI_1015_PID) },
{ USB_DEVICE(PI_VID, PI_1016_PID) },
{ USB_DEVICE(KONDO_VID, KONDO_USB_SERIAL_PID) },
{ USB_DEVICE(BAYER_VID, BAYER_CONTOUR_CABLE_PID) },
{ USB_DEVICE(FTDI_VID, MARVELL_OPENRD_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, TI_XDS100V2_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, HAMEG_HO820_PID) },
{ USB_DEVICE(FTDI_VID, HAMEG_HO720_PID) },
{ USB_DEVICE(FTDI_VID, HAMEG_HO730_PID) },
{ USB_DEVICE(FTDI_VID, HAMEG_HO870_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_GENERIC_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_SR_RADIO_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_HD_RADIO_PID) },
{ USB_DEVICE(FTDI_VID, MJSG_XM_RADIO_PID) },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_ST_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_SLITE_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_SH2_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, XVERVE_SIGNALYZER_SH4_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, SEGWAY_RMP200_PID) },
{ USB_DEVICE(FTDI_VID, ACCESIO_COM4SM_PID) },
{ USB_DEVICE(IONICS_VID, IONICS_PLUGCOMPUTER_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_24_MASTER_WING_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_PC_WING_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_USB_DMX_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_MIDI_TIMECODE_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_MINI_WING_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_MAXI_WING_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_MEDIA_WING_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CHAMSYS_WING_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCIENCESCOPE_LOGBOOKML_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCIENCESCOPE_LS_LOGBOOK_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_SCIENCESCOPE_HS_LOGBOOK_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_CINTERION_MC55I_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_DOTEC_PID) },
{ USB_DEVICE(QIHARDWARE_VID, MILKYMISTONE_JTAGSERIAL_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(ST_VID, ST_STMCLT_2232_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(ST_VID, ST_STMCLT_4232_PID),
.driver_info = (kernel_ulong_t)&ftdi_stmclite_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_RF_R106) },
{ USB_DEVICE(FTDI_VID, FTDI_DISTORTEC_JTAG_LOCK_PICK_PID),
.driver_info = (kernel_ulong_t)&ftdi_jtag_quirk },
{ USB_DEVICE(FTDI_VID, FTDI_LUMEL_PD12_PID) },
/* Crucible Devices */
{ USB_DEVICE(FTDI_VID, FTDI_CT_COMET_PID) },
{ USB_DEVICE(FTDI_VID, FTDI_Z3X_PID) },
/* Cressi Devices */
{ USB_DEVICE(FTDI_VID, FTDI_CRESSI_PID) },
/* Brainboxes Devices */
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_VX_001_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_VX_012_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_VX_023_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_VX_034_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_101_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_1_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_2_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_3_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_4_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_5_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_6_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_7_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_160_8_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_257_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_279_1_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_279_2_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_279_3_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_279_4_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_313_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_324_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_346_1_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_346_2_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_357_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_606_1_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_606_2_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_606_3_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_701_1_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_701_2_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_842_1_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_842_2_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_842_3_PID) },
{ USB_DEVICE(BRAINBOXES_VID, BRAINBOXES_US_842_4_PID) },
/* Infineon Devices */
{ USB_DEVICE_INTERFACE_NUMBER(INFINEON_VID, INFINEON_TRIBOARD_PID, 1) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
static const char *ftdi_chip_name[] = {
[SIO] = "SIO", /* the serial part of FT8U100AX */
[FT8U232AM] = "FT8U232AM",
[FT232BM] = "FT232BM",
[FT2232C] = "FT2232C",
[FT232RL] = "FT232RL",
[FT2232H] = "FT2232H",
[FT4232H] = "FT4232H",
[FT232H] = "FT232H",
[FTX] = "FT-X"
};
/* Used for TIOCMIWAIT */
#define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
#define FTDI_STATUS_B1_MASK (FTDI_RS_BI)
/* End TIOCMIWAIT */
/* function prototypes for a FTDI serial converter */
static int ftdi_sio_probe(struct usb_serial *serial,
const struct usb_device_id *id);
static int ftdi_sio_port_probe(struct usb_serial_port *port);
static int ftdi_sio_port_remove(struct usb_serial_port *port);
static int ftdi_open(struct tty_struct *tty, struct usb_serial_port *port);
static void ftdi_dtr_rts(struct usb_serial_port *port, int on);
static void ftdi_process_read_urb(struct urb *urb);
static int ftdi_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size);
static void ftdi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old);
static int ftdi_tiocmget(struct tty_struct *tty);
static int ftdi_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear);
static int ftdi_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg);
static void ftdi_break_ctl(struct tty_struct *tty, int break_state);
static bool ftdi_tx_empty(struct usb_serial_port *port);
static int ftdi_get_modem_status(struct usb_serial_port *port,
unsigned char status[2]);
static unsigned short int ftdi_232am_baud_base_to_divisor(int baud, int base);
static unsigned short int ftdi_232am_baud_to_divisor(int baud);
static __u32 ftdi_232bm_baud_base_to_divisor(int baud, int base);
static __u32 ftdi_232bm_baud_to_divisor(int baud);
static __u32 ftdi_2232h_baud_base_to_divisor(int baud, int base);
static __u32 ftdi_2232h_baud_to_divisor(int baud);
static struct usb_serial_driver ftdi_sio_device = {
.driver = {
.owner = THIS_MODULE,
.name = "ftdi_sio",
},
.description = "FTDI USB Serial Device",
.id_table = id_table_combined,
.num_ports = 1,
.bulk_in_size = 512,
.bulk_out_size = 256,
.probe = ftdi_sio_probe,
.port_probe = ftdi_sio_port_probe,
.port_remove = ftdi_sio_port_remove,
.open = ftdi_open,
.dtr_rts = ftdi_dtr_rts,
.throttle = usb_serial_generic_throttle,
.unthrottle = usb_serial_generic_unthrottle,
.process_read_urb = ftdi_process_read_urb,
.prepare_write_buffer = ftdi_prepare_write_buffer,
.tiocmget = ftdi_tiocmget,
.tiocmset = ftdi_tiocmset,
.tiocmiwait = usb_serial_generic_tiocmiwait,
.get_icount = usb_serial_generic_get_icount,
.ioctl = ftdi_ioctl,
.set_termios = ftdi_set_termios,
.break_ctl = ftdi_break_ctl,
.tx_empty = ftdi_tx_empty,
};
static struct usb_serial_driver * const serial_drivers[] = {
&ftdi_sio_device, NULL
};
#define WDR_TIMEOUT 5000 /* default urb timeout */
#define WDR_SHORT_TIMEOUT 1000 /* shorter urb timeout */
/*
* ***************************************************************************
* Utility functions
* ***************************************************************************
*/
static unsigned short int ftdi_232am_baud_base_to_divisor(int baud, int base)
{
unsigned short int divisor;
/* divisor shifted 3 bits to the left */
int divisor3 = base / 2 / baud;
if ((divisor3 & 0x7) == 7)
divisor3++; /* round x.7/8 up to x+1 */
divisor = divisor3 >> 3;
divisor3 &= 0x7;
if (divisor3 == 1)
divisor |= 0xc000;
else if (divisor3 >= 4)
divisor |= 0x4000;
else if (divisor3 != 0)
divisor |= 0x8000;
else if (divisor == 1)
divisor = 0; /* special case for maximum baud rate */
return divisor;
}
static unsigned short int ftdi_232am_baud_to_divisor(int baud)
{
return ftdi_232am_baud_base_to_divisor(baud, 48000000);
}
static __u32 ftdi_232bm_baud_base_to_divisor(int baud, int base)
{
static const unsigned char divfrac[8] = { 0, 3, 2, 4, 1, 5, 6, 7 };
__u32 divisor;
/* divisor shifted 3 bits to the left */
int divisor3 = base / 2 / baud;
divisor = divisor3 >> 3;
divisor |= (__u32)divfrac[divisor3 & 0x7] << 14;
/* Deal with special cases for highest baud rates. */
if (divisor == 1)
divisor = 0;
else if (divisor == 0x4001)
divisor = 1;
return divisor;
}
static __u32 ftdi_232bm_baud_to_divisor(int baud)
{
return ftdi_232bm_baud_base_to_divisor(baud, 48000000);
}
static __u32 ftdi_2232h_baud_base_to_divisor(int baud, int base)
{
static const unsigned char divfrac[8] = { 0, 3, 2, 4, 1, 5, 6, 7 };
__u32 divisor;
int divisor3;
/* hi-speed baud rate is 10-bit sampling instead of 16-bit */
divisor3 = base * 8 / (baud * 10);
divisor = divisor3 >> 3;
divisor |= (__u32)divfrac[divisor3 & 0x7] << 14;
/* Deal with special cases for highest baud rates. */
if (divisor == 1)
divisor = 0;
else if (divisor == 0x4001)
divisor = 1;
/*
* Set this bit to turn off a divide by 2.5 on baud rate generator
* This enables baud rates up to 12Mbaud but cannot reach below 1200
* baud with this bit set
*/
divisor |= 0x00020000;
return divisor;
}
static __u32 ftdi_2232h_baud_to_divisor(int baud)
{
return ftdi_2232h_baud_base_to_divisor(baud, 120000000);
}
#define set_mctrl(port, set) update_mctrl((port), (set), 0)
#define clear_mctrl(port, clear) update_mctrl((port), 0, (clear))
static int update_mctrl(struct usb_serial_port *port, unsigned int set,
unsigned int clear)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct device *dev = &port->dev;
unsigned urb_value;
int rv;
if (((set | clear) & (TIOCM_DTR | TIOCM_RTS)) == 0) {
dev_dbg(dev, "%s - DTR|RTS not being set|cleared\n", __func__);
return 0; /* no change */
}
clear &= ~set; /* 'set' takes precedence over 'clear' */
urb_value = 0;
if (clear & TIOCM_DTR)
urb_value |= FTDI_SIO_SET_DTR_LOW;
if (clear & TIOCM_RTS)
urb_value |= FTDI_SIO_SET_RTS_LOW;
if (set & TIOCM_DTR)
urb_value |= FTDI_SIO_SET_DTR_HIGH;
if (set & TIOCM_RTS)
urb_value |= FTDI_SIO_SET_RTS_HIGH;
rv = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_MODEM_CTRL_REQUEST,
FTDI_SIO_SET_MODEM_CTRL_REQUEST_TYPE,
urb_value, priv->interface,
NULL, 0, WDR_TIMEOUT);
if (rv < 0) {
dev_dbg(dev, "%s Error from MODEM_CTRL urb: DTR %s, RTS %s\n",
__func__,
(set & TIOCM_DTR) ? "HIGH" : (clear & TIOCM_DTR) ? "LOW" : "unchanged",
(set & TIOCM_RTS) ? "HIGH" : (clear & TIOCM_RTS) ? "LOW" : "unchanged");
rv = usb_translate_errors(rv);
} else {
dev_dbg(dev, "%s - DTR %s, RTS %s\n", __func__,
(set & TIOCM_DTR) ? "HIGH" : (clear & TIOCM_DTR) ? "LOW" : "unchanged",
(set & TIOCM_RTS) ? "HIGH" : (clear & TIOCM_RTS) ? "LOW" : "unchanged");
/* FIXME: locking on last_dtr_rts */
priv->last_dtr_rts = (priv->last_dtr_rts & ~clear) | set;
}
return rv;
}
static __u32 get_ftdi_divisor(struct tty_struct *tty,
struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct device *dev = &port->dev;
__u32 div_value = 0;
int div_okay = 1;
int baud;
/*
* The logic involved in setting the baudrate can be cleanly split into
* 3 steps.
* 1. Standard baud rates are set in tty->termios->c_cflag
* 2. If these are not enough, you can set any speed using alt_speed as
* follows:
* - set tty->termios->c_cflag speed to B38400
* - set your real speed in tty->alt_speed; it gets ignored when
* alt_speed==0, (or)
* - call TIOCSSERIAL ioctl with (struct serial_struct) set as
* follows:
* flags & ASYNC_SPD_MASK == ASYNC_SPD_[HI, VHI, SHI, WARP],
* this just sets alt_speed to (HI: 57600, VHI: 115200,
* SHI: 230400, WARP: 460800)
* ** Steps 1, 2 are done courtesy of tty_get_baud_rate
* 3. You can also set baud rate by setting custom divisor as follows
* - set tty->termios->c_cflag speed to B38400
* - call TIOCSSERIAL ioctl with (struct serial_struct) set as
* follows:
* o flags & ASYNC_SPD_MASK == ASYNC_SPD_CUST
* o custom_divisor set to baud_base / your_new_baudrate
* ** Step 3 is done courtesy of code borrowed from serial.c
* I should really spend some time and separate + move this common
* code to serial.c, it is replicated in nearly every serial driver
* you see.
*/
/* 1. Get the baud rate from the tty settings, this observes
alt_speed hack */
baud = tty_get_baud_rate(tty);
dev_dbg(dev, "%s - tty_get_baud_rate reports speed %d\n", __func__, baud);
/* 2. Observe async-compatible custom_divisor hack, update baudrate
if needed */
if (baud == 38400 &&
((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) &&
(priv->custom_divisor)) {
baud = priv->baud_base / priv->custom_divisor;
dev_dbg(dev, "%s - custom divisor %d sets baud rate to %d\n",
__func__, priv->custom_divisor, baud);
}
/* 3. Convert baudrate to device-specific divisor */
if (!baud)
baud = 9600;
switch (priv->chip_type) {
case SIO: /* SIO chip */
switch (baud) {
case 300: div_value = ftdi_sio_b300; break;
case 600: div_value = ftdi_sio_b600; break;
case 1200: div_value = ftdi_sio_b1200; break;
case 2400: div_value = ftdi_sio_b2400; break;
case 4800: div_value = ftdi_sio_b4800; break;
case 9600: div_value = ftdi_sio_b9600; break;
case 19200: div_value = ftdi_sio_b19200; break;
case 38400: div_value = ftdi_sio_b38400; break;
case 57600: div_value = ftdi_sio_b57600; break;
case 115200: div_value = ftdi_sio_b115200; break;
} /* baud */
if (div_value == 0) {
dev_dbg(dev, "%s - Baudrate (%d) requested is not supported\n",
__func__, baud);
div_value = ftdi_sio_b9600;
baud = 9600;
div_okay = 0;
}
break;
case FT8U232AM: /* 8U232AM chip */
if (baud <= 3000000) {
div_value = ftdi_232am_baud_to_divisor(baud);
} else {
dev_dbg(dev, "%s - Baud rate too high!\n", __func__);
baud = 9600;
div_value = ftdi_232am_baud_to_divisor(9600);
div_okay = 0;
}
break;
case FT232BM: /* FT232BM chip */
case FT2232C: /* FT2232C chip */
case FT232RL: /* FT232RL chip */
case FTX: /* FT-X series */
if (baud <= 3000000) {
__u16 product_id = le16_to_cpu(
port->serial->dev->descriptor.idProduct);
if (((FTDI_NDI_HUC_PID == product_id) ||
(FTDI_NDI_SPECTRA_SCU_PID == product_id) ||
(FTDI_NDI_FUTURE_2_PID == product_id) ||
(FTDI_NDI_FUTURE_3_PID == product_id) ||
(FTDI_NDI_AURORA_SCU_PID == product_id)) &&
(baud == 19200)) {
baud = 1200000;
}
div_value = ftdi_232bm_baud_to_divisor(baud);
} else {
dev_dbg(dev, "%s - Baud rate too high!\n", __func__);
div_value = ftdi_232bm_baud_to_divisor(9600);
div_okay = 0;
baud = 9600;
}
break;
case FT2232H: /* FT2232H chip */
case FT4232H: /* FT4232H chip */
case FT232H: /* FT232H chip */
if ((baud <= 12000000) && (baud >= 1200)) {
div_value = ftdi_2232h_baud_to_divisor(baud);
} else if (baud < 1200) {
div_value = ftdi_232bm_baud_to_divisor(baud);
} else {
dev_dbg(dev, "%s - Baud rate too high!\n", __func__);
div_value = ftdi_232bm_baud_to_divisor(9600);
div_okay = 0;
baud = 9600;
}
break;
} /* priv->chip_type */
if (div_okay) {
dev_dbg(dev, "%s - Baud rate set to %d (divisor 0x%lX) on chip %s\n",
__func__, baud, (unsigned long)div_value,
ftdi_chip_name[priv->chip_type]);
}
tty_encode_baud_rate(tty, baud, baud);
return div_value;
}
static int change_speed(struct tty_struct *tty, struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
__u16 urb_value;
__u16 urb_index;
__u32 urb_index_value;
int rv;
urb_index_value = get_ftdi_divisor(tty, port);
urb_value = (__u16)urb_index_value;
urb_index = (__u16)(urb_index_value >> 16);
if ((priv->chip_type == FT2232C) || (priv->chip_type == FT2232H) ||
(priv->chip_type == FT4232H) || (priv->chip_type == FT232H)) {
/* Probably the BM type needs the MSB of the encoded fractional
* divider also moved like for the chips above. Any infos? */
urb_index = (__u16)((urb_index << 8) | priv->interface);
}
rv = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_BAUDRATE_REQUEST,
FTDI_SIO_SET_BAUDRATE_REQUEST_TYPE,
urb_value, urb_index,
NULL, 0, WDR_SHORT_TIMEOUT);
return rv;
}
static int write_latency_timer(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_device *udev = port->serial->dev;
int rv;
int l = priv->latency;
if (priv->flags & ASYNC_LOW_LATENCY)
l = 1;
dev_dbg(&port->dev, "%s: setting latency timer = %i\n", __func__, l);
rv = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
FTDI_SIO_SET_LATENCY_TIMER_REQUEST,
FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,
l, priv->interface,
NULL, 0, WDR_TIMEOUT);
if (rv < 0)
dev_err(&port->dev, "Unable to write latency timer: %i\n", rv);
return rv;
}
static int read_latency_timer(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_device *udev = port->serial->dev;
unsigned char *buf;
int rv;
buf = kmalloc(1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
rv = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
FTDI_SIO_GET_LATENCY_TIMER_REQUEST,
FTDI_SIO_GET_LATENCY_TIMER_REQUEST_TYPE,
0, priv->interface,
buf, 1, WDR_TIMEOUT);
if (rv < 0)
dev_err(&port->dev, "Unable to read latency timer: %i\n", rv);
else
priv->latency = buf[0];
kfree(buf);
return rv;
}
static int get_serial_info(struct usb_serial_port *port,
struct serial_struct __user *retinfo)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.flags = priv->flags;
tmp.baud_base = priv->baud_base;
tmp.custom_divisor = priv->custom_divisor;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int set_serial_info(struct tty_struct *tty,
struct usb_serial_port *port, struct serial_struct __user *newinfo)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct serial_struct new_serial;
struct ftdi_private old_priv;
if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
return -EFAULT;
mutex_lock(&priv->cfg_lock);
old_priv = *priv;
/* Do error checking and permission checking */
if (!capable(CAP_SYS_ADMIN)) {
if (((new_serial.flags & ~ASYNC_USR_MASK) !=
(priv->flags & ~ASYNC_USR_MASK))) {
mutex_unlock(&priv->cfg_lock);
return -EPERM;
}
priv->flags = ((priv->flags & ~ASYNC_USR_MASK) |
(new_serial.flags & ASYNC_USR_MASK));
priv->custom_divisor = new_serial.custom_divisor;
goto check_and_exit;
}
if (new_serial.baud_base != priv->baud_base) {
mutex_unlock(&priv->cfg_lock);
return -EINVAL;
}
/* Make the changes - these are privileged changes! */
priv->flags = ((priv->flags & ~ASYNC_FLAGS) |
(new_serial.flags & ASYNC_FLAGS));
priv->custom_divisor = new_serial.custom_divisor;
write_latency_timer(port);
check_and_exit:
if ((old_priv.flags & ASYNC_SPD_MASK) !=
(priv->flags & ASYNC_SPD_MASK)) {
if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI)
tty->alt_speed = 57600;
else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI)
tty->alt_speed = 115200;
else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI)
tty->alt_speed = 230400;
else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP)
tty->alt_speed = 460800;
else
tty->alt_speed = 0;
}
if (((old_priv.flags & ASYNC_SPD_MASK) !=
(priv->flags & ASYNC_SPD_MASK)) ||
(((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) &&
(old_priv.custom_divisor != priv->custom_divisor))) {
change_speed(tty, port);
mutex_unlock(&priv->cfg_lock);
}
else
mutex_unlock(&priv->cfg_lock);
return 0;
}
static int get_lsr_info(struct usb_serial_port *port,
struct serial_struct __user *retinfo)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
unsigned int result = 0;
if (!retinfo)
return -EFAULT;
if (priv->transmit_empty)
result = TIOCSER_TEMT;
if (copy_to_user(retinfo, &result, sizeof(unsigned int)))
return -EFAULT;
return 0;
}
/* Determine type of FTDI chip based on USB config and descriptor. */
static void ftdi_determine_type(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
struct usb_device *udev = serial->dev;
unsigned version;
unsigned interfaces;
/* Assume it is not the original SIO device for now. */
priv->baud_base = 48000000 / 2;
version = le16_to_cpu(udev->descriptor.bcdDevice);
interfaces = udev->actconfig->desc.bNumInterfaces;
dev_dbg(&port->dev, "%s: bcdDevice = 0x%x, bNumInterfaces = %u\n", __func__,
version, interfaces);
if (interfaces > 1) {
int inter;
/* Multiple interfaces.*/
if (version == 0x0800) {
priv->chip_type = FT4232H;
/* Hi-speed - baud clock runs at 120MHz */
priv->baud_base = 120000000 / 2;
} else if (version == 0x0700) {
priv->chip_type = FT2232H;
/* Hi-speed - baud clock runs at 120MHz */
priv->baud_base = 120000000 / 2;
} else
priv->chip_type = FT2232C;
/* Determine interface code. */
inter = serial->interface->altsetting->desc.bInterfaceNumber;
if (inter == 0) {
priv->interface = INTERFACE_A;
} else if (inter == 1) {
priv->interface = INTERFACE_B;
} else if (inter == 2) {
priv->interface = INTERFACE_C;
} else if (inter == 3) {
priv->interface = INTERFACE_D;
}
/* BM-type devices have a bug where bcdDevice gets set
* to 0x200 when iSerialNumber is 0. */
if (version < 0x500) {
dev_dbg(&port->dev,
"%s: something fishy - bcdDevice too low for multi-interface device\n",
__func__);
}
} else if (version < 0x200) {
/* Old device. Assume it's the original SIO. */
priv->chip_type = SIO;
priv->baud_base = 12000000 / 16;
} else if (version < 0x400) {
/* Assume it's an FT8U232AM (or FT8U245AM) */
/* (It might be a BM because of the iSerialNumber bug,
* but it will still work as an AM device.) */
priv->chip_type = FT8U232AM;
} else if (version < 0x600) {
/* Assume it's an FT232BM (or FT245BM) */
priv->chip_type = FT232BM;
} else if (version < 0x900) {
/* Assume it's an FT232RL */
priv->chip_type = FT232RL;
} else if (version < 0x1000) {
/* Assume it's an FT232H */
priv->chip_type = FT232H;
} else {
/* Assume it's an FT-X series device */
priv->chip_type = FTX;
}
dev_info(&udev->dev, "Detected %s\n", ftdi_chip_name[priv->chip_type]);
}
/* Determine the maximum packet size for the device. This depends on the chip
* type and the USB host capabilities. The value should be obtained from the
* device descriptor as the chip will use the appropriate values for the host.*/
static void ftdi_set_max_packet_size(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
struct usb_device *udev = serial->dev;
struct usb_interface *interface = serial->interface;
struct usb_endpoint_descriptor *ep_desc;
unsigned num_endpoints;
unsigned i;
num_endpoints = interface->cur_altsetting->desc.bNumEndpoints;
dev_info(&udev->dev, "Number of endpoints %d\n", num_endpoints);
if (!num_endpoints)
return;
/* NOTE: some customers have programmed FT232R/FT245R devices
* with an endpoint size of 0 - not good. In this case, we
* want to override the endpoint descriptor setting and use a
* value of 64 for wMaxPacketSize */
for (i = 0; i < num_endpoints; i++) {
dev_info(&udev->dev, "Endpoint %d MaxPacketSize %d\n", i+1,
interface->cur_altsetting->endpoint[i].desc.wMaxPacketSize);
ep_desc = &interface->cur_altsetting->endpoint[i].desc;
if (ep_desc->wMaxPacketSize == 0) {
ep_desc->wMaxPacketSize = cpu_to_le16(0x40);
dev_info(&udev->dev, "Overriding wMaxPacketSize on endpoint %d\n", i);
}
}
/* set max packet size based on descriptor */
priv->max_packet_size = usb_endpoint_maxp(ep_desc);
dev_info(&udev->dev, "Setting MaxPacketSize %d\n", priv->max_packet_size);
}
/*
* ***************************************************************************
* Sysfs Attribute
* ***************************************************************************
*/
static ssize_t latency_timer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct ftdi_private *priv = usb_get_serial_port_data(port);
if (priv->flags & ASYNC_LOW_LATENCY)
return sprintf(buf, "1\n");
else
return sprintf(buf, "%i\n", priv->latency);
}
/* Write a new value of the latency timer, in units of milliseconds. */
static ssize_t latency_timer_store(struct device *dev,
struct device_attribute *attr,
const char *valbuf, size_t count)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct ftdi_private *priv = usb_get_serial_port_data(port);
int v = simple_strtoul(valbuf, NULL, 10);
int rv;
priv->latency = v;
rv = write_latency_timer(port);
if (rv < 0)
return -EIO;
return count;
}
static DEVICE_ATTR_RW(latency_timer);
/* Write an event character directly to the FTDI register. The ASCII
value is in the low 8 bits, with the enable bit in the 9th bit. */
static ssize_t store_event_char(struct device *dev,
struct device_attribute *attr, const char *valbuf, size_t count)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct usb_device *udev = port->serial->dev;
int v = simple_strtoul(valbuf, NULL, 10);
int rv;
dev_dbg(&port->dev, "%s: setting event char = %i\n", __func__, v);
rv = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
FTDI_SIO_SET_EVENT_CHAR_REQUEST,
FTDI_SIO_SET_EVENT_CHAR_REQUEST_TYPE,
v, priv->interface,
NULL, 0, WDR_TIMEOUT);
if (rv < 0) {
dev_dbg(&port->dev, "Unable to write event character: %i\n", rv);
return -EIO;
}
return count;
}
static DEVICE_ATTR(event_char, S_IWUSR, NULL, store_event_char);
static int create_sysfs_attrs(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
int retval = 0;
/* XXX I've no idea if the original SIO supports the event_char
* sysfs parameter, so I'm playing it safe. */
if (priv->chip_type != SIO) {
dev_dbg(&port->dev, "sysfs attributes for %s\n", ftdi_chip_name[priv->chip_type]);
retval = device_create_file(&port->dev, &dev_attr_event_char);
if ((!retval) &&
(priv->chip_type == FT232BM ||
priv->chip_type == FT2232C ||
priv->chip_type == FT232RL ||
priv->chip_type == FT2232H ||
priv->chip_type == FT4232H ||
priv->chip_type == FT232H ||
priv->chip_type == FTX)) {
retval = device_create_file(&port->dev,
&dev_attr_latency_timer);
}
}
return retval;
}
static void remove_sysfs_attrs(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
/* XXX see create_sysfs_attrs */
if (priv->chip_type != SIO) {
device_remove_file(&port->dev, &dev_attr_event_char);
if (priv->chip_type == FT232BM ||
priv->chip_type == FT2232C ||
priv->chip_type == FT232RL ||
priv->chip_type == FT2232H ||
priv->chip_type == FT4232H ||
priv->chip_type == FT232H ||
priv->chip_type == FTX) {
device_remove_file(&port->dev, &dev_attr_latency_timer);
}
}
}
/*
* ***************************************************************************
* FTDI driver specific functions
* ***************************************************************************
*/
/* Probe function to check for special devices */
static int ftdi_sio_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
struct ftdi_sio_quirk *quirk =
(struct ftdi_sio_quirk *)id->driver_info;
if (quirk && quirk->probe) {
int ret = quirk->probe(serial);
if (ret != 0)
return ret;
}
usb_set_serial_data(serial, (void *)id->driver_info);
return 0;
}
static int ftdi_sio_port_probe(struct usb_serial_port *port)
{
struct ftdi_private *priv;
struct ftdi_sio_quirk *quirk = usb_get_serial_data(port->serial);
priv = kzalloc(sizeof(struct ftdi_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_init(&priv->cfg_lock);
priv->flags = ASYNC_LOW_LATENCY;
if (quirk && quirk->port_probe)
quirk->port_probe(priv);
usb_set_serial_port_data(port, priv);
ftdi_determine_type(port);
ftdi_set_max_packet_size(port);
if (read_latency_timer(port) < 0)
priv->latency = 16;
write_latency_timer(port);
create_sysfs_attrs(port);
return 0;
}
/* Setup for the USB-UIRT device, which requires hardwired
* baudrate (38400 gets mapped to 312500) */
/* Called from usbserial:serial_probe */
static void ftdi_USB_UIRT_setup(struct ftdi_private *priv)
{
priv->flags |= ASYNC_SPD_CUST;
priv->custom_divisor = 77;
priv->force_baud = 38400;
}
/* Setup for the HE-TIRA1 device, which requires hardwired
* baudrate (38400 gets mapped to 100000) and RTS-CTS enabled. */
static void ftdi_HE_TIRA1_setup(struct ftdi_private *priv)
{
priv->flags |= ASYNC_SPD_CUST;
priv->custom_divisor = 240;
priv->force_baud = 38400;
priv->force_rtscts = 1;
}
/*
* Module parameter to control latency timer for NDI FTDI-based USB devices.
* If this value is not set in /etc/modprobe.d/ its value will be set
* to 1ms.
*/
static int ndi_latency_timer = 1;
/* Setup for the NDI FTDI-based USB devices, which requires hardwired
* baudrate (19200 gets mapped to 1200000).
*
* Called from usbserial:serial_probe.
*/
static int ftdi_NDI_device_setup(struct usb_serial *serial)
{
struct usb_device *udev = serial->dev;
int latency = ndi_latency_timer;
if (latency == 0)
latency = 1;
if (latency > 99)
latency = 99;
dev_dbg(&udev->dev, "%s setting NDI device latency to %d\n", __func__, latency);
dev_info(&udev->dev, "NDI device with a latency value of %d\n", latency);
/* FIXME: errors are not returned */
usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
FTDI_SIO_SET_LATENCY_TIMER_REQUEST,
FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,
latency, 0, NULL, 0, WDR_TIMEOUT);
return 0;
}
/*
* First port on JTAG adaptors such as Olimex arm-usb-ocd or the FIC/OpenMoko
* Neo1973 Debug Board is reserved for JTAG interface and can be accessed from
* userspace using openocd.
*/
static int ftdi_jtag_probe(struct usb_serial *serial)
{
struct usb_device *udev = serial->dev;
struct usb_interface *interface = serial->interface;
if (interface == udev->actconfig->interface[0]) {
dev_info(&udev->dev,
"Ignoring serial port reserved for JTAG\n");
return -ENODEV;
}
return 0;
}
static int ftdi_8u2232c_probe(struct usb_serial *serial)
{
struct usb_device *udev = serial->dev;
if ((udev->manufacturer && !strcmp(udev->manufacturer, "CALAO Systems")) ||
(udev->product && !strcmp(udev->product, "BeagleBone/XDS100V2")))
return ftdi_jtag_probe(serial);
return 0;
}
/*
* First two ports on JTAG adaptors using an FT4232 such as STMicroelectronics's
* ST Micro Connect Lite are reserved for JTAG or other non-UART interfaces and
* can be accessed from userspace.
* The next two ports are enabled as UARTs by default, where port 2 is
* a conventional RS-232 UART.
*/
static int ftdi_stmclite_probe(struct usb_serial *serial)
{
struct usb_device *udev = serial->dev;
struct usb_interface *interface = serial->interface;
if (interface == udev->actconfig->interface[0] ||
interface == udev->actconfig->interface[1]) {
dev_info(&udev->dev, "Ignoring serial port reserved for JTAG\n");
return -ENODEV;
}
return 0;
}
/*
* The Matrix Orbital VK204-25-USB has an invalid IN endpoint.
* We have to correct it if we want to read from it.
*/
static int ftdi_mtxorb_hack_setup(struct usb_serial *serial)
{
struct usb_host_endpoint *ep = serial->dev->ep_in[1];
struct usb_endpoint_descriptor *ep_desc = &ep->desc;
if (ep->enabled && ep_desc->wMaxPacketSize == 0) {
ep_desc->wMaxPacketSize = cpu_to_le16(0x40);
dev_info(&serial->dev->dev,
"Fixing invalid wMaxPacketSize on read pipe\n");
}
return 0;
}
static int ftdi_sio_port_remove(struct usb_serial_port *port)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
remove_sysfs_attrs(port);
kfree(priv);
return 0;
}
static int ftdi_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_device *dev = port->serial->dev;
struct ftdi_private *priv = usb_get_serial_port_data(port);
/* No error checking for this (will get errors later anyway) */
/* See ftdi_sio.h for description of what is reset */
usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
FTDI_SIO_RESET_REQUEST, FTDI_SIO_RESET_REQUEST_TYPE,
FTDI_SIO_RESET_SIO,
priv->interface, NULL, 0, WDR_TIMEOUT);
/* Termios defaults are set by usb_serial_init. We don't change
port->tty->termios - this would lose speed settings, etc.
This is same behaviour as serial.c/rs_open() - Kuba */
/* ftdi_set_termios will send usb control messages */
if (tty)
ftdi_set_termios(tty, port, NULL);
return usb_serial_generic_open(tty, port);
}
static void ftdi_dtr_rts(struct usb_serial_port *port, int on)
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
/* Disable flow control */
if (!on) {
if (usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0, priv->interface, NULL, 0,
WDR_TIMEOUT) < 0) {
dev_err(&port->dev, "error from flowcontrol urb\n");
}
}
/* drop RTS and DTR */
if (on)
set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
else
clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
}
/* The SIO requires the first byte to have:
* B0 1
* B1 0
* B2..7 length of message excluding byte 0
*
* The new devices do not require this byte
*/
static int ftdi_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size)
{
struct ftdi_private *priv;
int count;
unsigned long flags;
priv = usb_get_serial_port_data(port);
if (priv->chip_type == SIO) {
unsigned char *buffer = dest;
int i, len, c;
count = 0;
spin_lock_irqsave(&port->lock, flags);
for (i = 0; i < size - 1; i += priv->max_packet_size) {
len = min_t(int, size - i, priv->max_packet_size) - 1;
c = kfifo_out(&port->write_fifo, &buffer[i + 1], len);
if (!c)
break;
port->icount.tx += c;
buffer[i] = (c << 2) + 1;
count += c + 1;
}
spin_unlock_irqrestore(&port->lock, flags);
} else {
count = kfifo_out_locked(&port->write_fifo, dest, size,
&port->lock);
port->icount.tx += count;
}
return count;
}
#define FTDI_RS_ERR_MASK (FTDI_RS_BI | FTDI_RS_PE | FTDI_RS_FE | FTDI_RS_OE)
static int ftdi_process_packet(struct usb_serial_port *port,
struct ftdi_private *priv, char *packet, int len)
{
int i;
char status;
char flag;
char *ch;
if (len < 2) {
dev_dbg(&port->dev, "malformed packet\n");
return 0;
}
/* Compare new line status to the old one, signal if different/
N.B. packet may be processed more than once, but differences
are only processed once. */
status = packet[0] & FTDI_STATUS_B0_MASK;
if (status != priv->prev_status) {
char diff_status = status ^ priv->prev_status;
if (diff_status & FTDI_RS0_CTS)
port->icount.cts++;
if (diff_status & FTDI_RS0_DSR)
port->icount.dsr++;
if (diff_status & FTDI_RS0_RI)
port->icount.rng++;
if (diff_status & FTDI_RS0_RLSD) {
struct tty_struct *tty;
port->icount.dcd++;
tty = tty_port_tty_get(&port->port);
if (tty)
usb_serial_handle_dcd_change(port, tty,
status & FTDI_RS0_RLSD);
tty_kref_put(tty);
}
wake_up_interruptible(&port->port.delta_msr_wait);
priv->prev_status = status;
}
flag = TTY_NORMAL;
if (packet[1] & FTDI_RS_ERR_MASK) {
/* Break takes precedence over parity, which takes precedence
* over framing errors */
if (packet[1] & FTDI_RS_BI) {
flag = TTY_BREAK;
port->icount.brk++;
usb_serial_handle_break(port);
} else if (packet[1] & FTDI_RS_PE) {
flag = TTY_PARITY;
port->icount.parity++;
} else if (packet[1] & FTDI_RS_FE) {
flag = TTY_FRAME;
port->icount.frame++;
}
/* Overrun is special, not associated with a char */
if (packet[1] & FTDI_RS_OE) {
port->icount.overrun++;
tty_insert_flip_char(&port->port, 0, TTY_OVERRUN);
}
}
/* save if the transmitter is empty or not */
if (packet[1] & FTDI_RS_TEMT)
priv->transmit_empty = 1;
else
priv->transmit_empty = 0;
len -= 2;
if (!len)
return 0; /* status only */
port->icount.rx += len;
ch = packet + 2;
if (port->port.console && port->sysrq) {
for (i = 0; i < len; i++, ch++) {
if (!usb_serial_handle_sysrq_char(port, *ch))
tty_insert_flip_char(&port->port, *ch, flag);
}
} else {
tty_insert_flip_string_fixed_flag(&port->port, ch, flag, len);
}
return len;
}
static void ftdi_process_read_urb(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct ftdi_private *priv = usb_get_serial_port_data(port);
char *data = (char *)urb->transfer_buffer;
int i;
int len;
int count = 0;
for (i = 0; i < urb->actual_length; i += priv->max_packet_size) {
len = min_t(int, urb->actual_length - i, priv->max_packet_size);
count += ftdi_process_packet(port, priv, &data[i], len);
}
if (count)
tty_flip_buffer_push(&port->port);
}
static void ftdi_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
struct ftdi_private *priv = usb_get_serial_port_data(port);
__u16 urb_value;
/* break_state = -1 to turn on break, and 0 to turn off break */
/* see drivers/char/tty_io.c to see it used */
/* last_set_data_urb_value NEVER has the break bit set in it */
if (break_state)
urb_value = priv->last_set_data_urb_value | FTDI_SIO_SET_BREAK;
else
urb_value = priv->last_set_data_urb_value;
if (usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
FTDI_SIO_SET_DATA_REQUEST,
FTDI_SIO_SET_DATA_REQUEST_TYPE,
urb_value , priv->interface,
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev, "%s FAILED to enable/disable break state (state was %d)\n",
__func__, break_state);
}
dev_dbg(&port->dev, "%s break state is %d - urb is %d\n", __func__,
break_state, urb_value);
}
static bool ftdi_tx_empty(struct usb_serial_port *port)
{
unsigned char buf[2];
int ret;
ret = ftdi_get_modem_status(port, buf);
if (ret == 2) {
if (!(buf[1] & FTDI_RS_TEMT))
return false;
}
return true;
}
/* old_termios contains the original termios settings and tty->termios contains
* the new setting to be used
* WARNING: set_termios calls this with old_termios in kernel space
*/
static void ftdi_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct usb_device *dev = port->serial->dev;
struct device *ddev = &port->dev;
struct ftdi_private *priv = usb_get_serial_port_data(port);
struct ktermios *termios = &tty->termios;
unsigned int cflag = termios->c_cflag;
__u16 urb_value; /* will hold the new flags */
/* Added for xon/xoff support */
unsigned int iflag = termios->c_iflag;
unsigned char vstop;
unsigned char vstart;
/* Force baud rate if this device requires it, unless it is set to
B0. */
if (priv->force_baud && ((termios->c_cflag & CBAUD) != B0)) {
dev_dbg(ddev, "%s: forcing baud rate for this device\n", __func__);
tty_encode_baud_rate(tty, priv->force_baud,
priv->force_baud);
}
/* Force RTS-CTS if this device requires it. */
if (priv->force_rtscts) {
dev_dbg(ddev, "%s: forcing rtscts for this device\n", __func__);
termios->c_cflag |= CRTSCTS;
}
/*
* All FTDI UART chips are limited to CS7/8. We shouldn't pretend to
* support CS5/6 and revert the CSIZE setting instead.
*
* CS5 however is used to control some smartcard readers which abuse
* this limitation to switch modes. Original FTDI chips fall back to
* eight data bits.
*
* TODO: Implement a quirk to only allow this with mentioned
* readers. One I know of (Argolis Smartreader V1)
* returns "USB smartcard server" as iInterface string.
* The vendor didn't bother with a custom VID/PID of
* course.
*/
if (C_CSIZE(tty) == CS6) {
dev_warn(ddev, "requested CSIZE setting not supported\n");
termios->c_cflag &= ~CSIZE;
if (old_termios)
termios->c_cflag |= old_termios->c_cflag & CSIZE;
else
termios->c_cflag |= CS8;
}
cflag = termios->c_cflag;
if (!old_termios)
goto no_skip;
if (old_termios->c_cflag == termios->c_cflag
&& old_termios->c_ispeed == termios->c_ispeed
&& old_termios->c_ospeed == termios->c_ospeed)
goto no_c_cflag_changes;
/* NOTE These routines can get interrupted by
ftdi_sio_read_bulk_callback - need to examine what this means -
don't see any problems yet */
if ((old_termios->c_cflag & (CSIZE|PARODD|PARENB|CMSPAR|CSTOPB)) ==
(termios->c_cflag & (CSIZE|PARODD|PARENB|CMSPAR|CSTOPB)))
goto no_data_parity_stop_changes;
no_skip:
/* Set number of data bits, parity, stop bits */
urb_value = 0;
urb_value |= (cflag & CSTOPB ? FTDI_SIO_SET_DATA_STOP_BITS_2 :
FTDI_SIO_SET_DATA_STOP_BITS_1);
if (cflag & PARENB) {
if (cflag & CMSPAR)
urb_value |= cflag & PARODD ?
FTDI_SIO_SET_DATA_PARITY_MARK :
FTDI_SIO_SET_DATA_PARITY_SPACE;
else
urb_value |= cflag & PARODD ?
FTDI_SIO_SET_DATA_PARITY_ODD :
FTDI_SIO_SET_DATA_PARITY_EVEN;
} else {
urb_value |= FTDI_SIO_SET_DATA_PARITY_NONE;
}
switch (cflag & CSIZE) {
case CS5:
dev_dbg(ddev, "Setting CS5 quirk\n");
break;
case CS7:
urb_value |= 7;
dev_dbg(ddev, "Setting CS7\n");
break;
default:
case CS8:
urb_value |= 8;
dev_dbg(ddev, "Setting CS8\n");
break;
}
/* This is needed by the break command since it uses the same command
- but is or'ed with this value */
priv->last_set_data_urb_value = urb_value;
if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_DATA_REQUEST,
FTDI_SIO_SET_DATA_REQUEST_TYPE,
urb_value , priv->interface,
NULL, 0, WDR_SHORT_TIMEOUT) < 0) {
dev_err(ddev, "%s FAILED to set databits/stopbits/parity\n",
__func__);
}
/* Now do the baudrate */
no_data_parity_stop_changes:
if ((cflag & CBAUD) == B0) {
/* Disable flow control */
if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0, priv->interface,
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(ddev, "%s error from disable flowcontrol urb\n",
__func__);
}
/* Drop RTS and DTR */
clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
} else {
/* set the baudrate determined before */
mutex_lock(&priv->cfg_lock);
if (change_speed(tty, port))
dev_err(ddev, "%s urb failed to set baudrate\n", __func__);
mutex_unlock(&priv->cfg_lock);
/* Ensure RTS and DTR are raised when baudrate changed from 0 */
if (old_termios && (old_termios->c_cflag & CBAUD) == B0)
set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
}
/* Set flow control */
/* Note device also supports DTR/CD (ugh) and Xon/Xoff in hardware */
no_c_cflag_changes:
if (cflag & CRTSCTS) {
dev_dbg(ddev, "%s Setting to CRTSCTS flow control\n", __func__);
if (usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0 , (FTDI_SIO_RTS_CTS_HS | priv->interface),
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(ddev, "urb failed to set to rts/cts flow control\n");
}
} else {
/*
* Xon/Xoff code
*
* Check the IXOFF status in the iflag component of the
* termios structure. If IXOFF is not set, the pre-xon/xoff
* code is executed.
*/
if (iflag & IXOFF) {
dev_dbg(ddev, "%s request to enable xonxoff iflag=%04x\n",
__func__, iflag);
/* Try to enable the XON/XOFF on the ftdi_sio
* Set the vstart and vstop -- could have been done up
* above where a lot of other dereferencing is done but
* that would be very inefficient as vstart and vstop
* are not always needed.
*/
vstart = termios->c_cc[VSTART];
vstop = termios->c_cc[VSTOP];
urb_value = (vstop << 8) | (vstart);
if (usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
urb_value , (FTDI_SIO_XON_XOFF_HS
| priv->interface),
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(&port->dev, "urb failed to set to "
"xon/xoff flow control\n");
}
} else {
/* else clause to only run if cflag ! CRTSCTS and iflag
* ! XOFF. CHECKME Assuming XON/XOFF handled by tty
* stack - not by device */
dev_dbg(ddev, "%s Turning off hardware flow control\n", __func__);
if (usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
FTDI_SIO_SET_FLOW_CTRL_REQUEST,
FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
0, priv->interface,
NULL, 0, WDR_TIMEOUT) < 0) {
dev_err(ddev, "urb failed to clear flow control\n");
}
}
}
}
/*
* Get modem-control status.
*
* Returns the number of status bytes retrieved (device dependant), or
* negative error code.
*/
static int ftdi_get_modem_status(struct usb_serial_port *port,
unsigned char status[2])
{
struct ftdi_private *priv = usb_get_serial_port_data(port);
unsigned char *buf;
int len;
int ret;
buf = kmalloc(2, GFP_KERNEL);
if (!buf)
return -ENOMEM;
/*
* The 8U232AM returns a two byte value (the SIO a 1 byte value) in
* the same format as the data returned from the in point.
*/
switch (priv->chip_type) {
case SIO:
len = 1;
break;
case FT8U232AM:
case FT232BM:
case FT2232C:
case FT232RL:
case FT2232H:
case FT4232H:
case FT232H:
case FTX:
len = 2;
break;
default:
ret = -EFAULT;
goto out;
}
ret = usb_control_msg(port->serial->dev,
usb_rcvctrlpipe(port->serial->dev, 0),
FTDI_SIO_GET_MODEM_STATUS_REQUEST,
FTDI_SIO_GET_MODEM_STATUS_REQUEST_TYPE,
0, priv->interface,
buf, len, WDR_TIMEOUT);
if (ret < 0) {
dev_err(&port->dev, "failed to get modem status: %d\n", ret);
ret = usb_translate_errors(ret);
goto out;
}
status[0] = buf[0];
if (ret > 1)
status[1] = buf[1];
else
status[1] = 0;
dev_dbg(&port->dev, "%s - 0x%02x%02x\n", __func__, status[0],
status[1]);
out:
kfree(buf);
return ret;
}
static int ftdi_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct ftdi_private *priv = usb_get_serial_port_data(port);
unsigned char buf[2];
int ret;
ret = ftdi_get_modem_status(port, buf);
if (ret < 0)
return ret;
ret = (buf[0] & FTDI_SIO_DSR_MASK ? TIOCM_DSR : 0) |
(buf[0] & FTDI_SIO_CTS_MASK ? TIOCM_CTS : 0) |
(buf[0] & FTDI_SIO_RI_MASK ? TIOCM_RI : 0) |
(buf[0] & FTDI_SIO_RLSD_MASK ? TIOCM_CD : 0) |
priv->last_dtr_rts;
return ret;
}
static int ftdi_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
return update_mctrl(port, set, clear);
}
static int ftdi_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
/* Based on code from acm.c and others */
switch (cmd) {
case TIOCGSERIAL: /* gets serial port data */
return get_serial_info(port,
(struct serial_struct __user *) arg);
case TIOCSSERIAL: /* sets serial port data */
return set_serial_info(tty, port,
(struct serial_struct __user *) arg);
case TIOCSERGETLSR:
return get_lsr_info(port, (struct serial_struct __user *)arg);
break;
default:
break;
}
return -ENOIOCTLCMD;
}
module_usb_serial_driver(serial_drivers, id_table_combined);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(ndi_latency_timer, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ndi_latency_timer, "NDI device latency timer override");
| gpl-2.0 |
loverszhaokai/gcc | gcc/testsuite/gcc.target/aarch64/advsimd-intrinsics/vcle.c | 40 | 2116 | #define INSN_NAME vcle
#define TEST_MSG "VCLE/VCLEQ"
#include "cmp_op.inc"
/* Expected results. */
VECT_VAR_DECL(expected,uint,8,8) [] = { 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x0 };
VECT_VAR_DECL(expected,uint,16,4) [] = { 0xffff, 0xffff, 0xffff, 0x0 };
VECT_VAR_DECL(expected,uint,32,2) [] = { 0xffffffff, 0x0 };
VECT_VAR_DECL(expected,uint,8,16) [] = { 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0x0, 0x0, 0x0 };
VECT_VAR_DECL(expected,uint,16,8) [] = { 0xffff, 0xffff, 0xffff, 0xffff,
0xffff, 0xffff, 0xffff, 0x0 };
VECT_VAR_DECL(expected,uint,32,4) [] = { 0xffffffff, 0xffffffff,
0xffffffff, 0x0 };
VECT_VAR_DECL(expected_uint,uint,8,8) [] = { 0xff, 0xff, 0xff, 0xff,
0x0, 0x0, 0x0, 0x0 };
VECT_VAR_DECL(expected_uint,uint,16,4) [] = { 0xffff, 0xffff, 0xffff, 0x0 };
VECT_VAR_DECL(expected_uint,uint,32,2) [] = { 0xffffffff, 0xffffffff };
VECT_VAR_DECL(expected_q_uint,uint,8,16) [] = { 0xff, 0xff, 0xff, 0xff,
0xff, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0 };
VECT_VAR_DECL(expected_q_uint,uint,16,8) [] = { 0xffff, 0xffff, 0xffff, 0xffff,
0xffff, 0xffff, 0xffff, 0x0 };
VECT_VAR_DECL(expected_q_uint,uint,32,4) [] = { 0xffffffff, 0xffffffff,
0xffffffff, 0x0 };
VECT_VAR_DECL(expected_float,uint,32,2) [] = { 0xffffffff, 0xffffffff };
VECT_VAR_DECL(expected_q_float,uint,32,4) [] = { 0xffffffff, 0xffffffff,
0xffffffff, 0x0 };
VECT_VAR_DECL(expected_uint2,uint,32,2) [] = { 0xffffffff, 0x0 };
VECT_VAR_DECL(expected_uint3,uint,32,2) [] = { 0xffffffff, 0xffffffff };
VECT_VAR_DECL(expected_uint4,uint,32,2) [] = { 0xffffffff, 0x0 };
VECT_VAR_DECL(expected_nan,uint,32,2) [] = { 0x0, 0x0 };
VECT_VAR_DECL(expected_mnan,uint,32,2) [] = { 0x0, 0x0 };
VECT_VAR_DECL(expected_nan2,uint,32,2) [] = { 0x0, 0x0 };
VECT_VAR_DECL(expected_inf,uint,32,2) [] = { 0xffffffff, 0xffffffff };
VECT_VAR_DECL(expected_minf,uint,32,2) [] = { 0x0, 0x0 };
VECT_VAR_DECL(expected_inf2,uint,32,2) [] = { 0x0, 0x0 };
VECT_VAR_DECL(expected_mzero,uint,32,2) [] = { 0xffffffff, 0xffffffff };
| gpl-2.0 |
TheBr0ken/vigor_aosp_kernel | net/wireless/reg.c | 296 | 61273 | /*
* Copyright 2002-2005, Instant802 Networks, Inc.
* Copyright 2005-2006, Devicescape Software, Inc.
* Copyright 2007 Johannes Berg <johannes@sipsolutions.net>
* Copyright 2008 Luis R. Rodriguez <lrodriguz@atheros.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.
*/
/**
* DOC: Wireless regulatory infrastructure
*
* The usual implementation is for a driver to read a device EEPROM to
* determine which regulatory domain it should be operating under, then
* looking up the allowable channels in a driver-local table and finally
* registering those channels in the wiphy structure.
*
* Another set of compliance enforcement is for drivers to use their
* own compliance limits which can be stored on the EEPROM. The host
* driver or firmware may ensure these are used.
*
* In addition to all this we provide an extra layer of regulatory
* conformance. For drivers which do not have any regulatory
* information CRDA provides the complete regulatory solution.
* For others it provides a community effort on further restrictions
* to enhance compliance.
*
* Note: When number of rules --> infinity we will not be able to
* index on alpha2 any more, instead we'll probably have to
* rely on some SHA1 checksum of the regdomain for example.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/random.h>
#include <linux/ctype.h>
#include <linux/nl80211.h>
#include <linux/platform_device.h>
#include <net/cfg80211.h>
#include "core.h"
#include "reg.h"
#include "regdb.h"
#include "nl80211.h"
#ifdef CONFIG_CFG80211_REG_DEBUG
#define REG_DBG_PRINT(format, args...) \
do { \
printk(KERN_DEBUG pr_fmt(format), ##args); \
} while (0)
#else
#define REG_DBG_PRINT(args...)
#endif
static struct regulatory_request core_request_world = {
.initiator = NL80211_REGDOM_SET_BY_CORE,
.alpha2[0] = '0',
.alpha2[1] = '0',
.intersect = false,
.processed = true,
.country_ie_env = ENVIRON_ANY,
};
/* Receipt of information from last regulatory request */
static struct regulatory_request *last_request = &core_request_world;
/* To trigger userspace events */
static struct platform_device *reg_pdev;
static struct device_type reg_device_type = {
.uevent = reg_device_uevent,
};
/*
* Central wireless core regulatory domains, we only need two,
* the current one and a world regulatory domain in case we have no
* information to give us an alpha2
*/
const struct ieee80211_regdomain *cfg80211_regdomain;
/*
* Protects static reg.c components:
* - cfg80211_world_regdom
* - cfg80211_regdom
* - last_request
*/
static DEFINE_MUTEX(reg_mutex);
static inline void assert_reg_lock(void)
{
lockdep_assert_held(®_mutex);
}
/* Used to queue up regulatory hints */
static LIST_HEAD(reg_requests_list);
static spinlock_t reg_requests_lock;
/* Used to queue up beacon hints for review */
static LIST_HEAD(reg_pending_beacons);
static spinlock_t reg_pending_beacons_lock;
/* Used to keep track of processed beacon hints */
static LIST_HEAD(reg_beacon_list);
struct reg_beacon {
struct list_head list;
struct ieee80211_channel chan;
};
static void reg_todo(struct work_struct *work);
static DECLARE_WORK(reg_work, reg_todo);
static void reg_timeout_work(struct work_struct *work);
static DECLARE_DELAYED_WORK(reg_timeout, reg_timeout_work);
/* We keep a static world regulatory domain in case of the absence of CRDA */
static const struct ieee80211_regdomain world_regdom = {
.n_reg_rules = 5,
.alpha2 = "00",
.reg_rules = {
/* IEEE 802.11b/g, channels 1..11 */
REG_RULE(2412-10, 2462+10, 40, 6, 20, 0),
/* IEEE 802.11b/g, channels 12..13. */
REG_RULE(2467-10, 2472+10, 40, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS),
/* IEEE 802.11 channel 14 - Only JP enables
* this and for 802.11b only */
REG_RULE(2484-10, 2484+10, 20, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS |
NL80211_RRF_NO_OFDM),
/* IEEE 802.11a, channel 36..48 */
REG_RULE(5180-10, 5240+10, 40, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS),
/* NB: 5260 MHz - 5700 MHz requies DFS */
/* IEEE 802.11a, channel 149..165 */
REG_RULE(5745-10, 5825+10, 40, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS),
}
};
static const struct ieee80211_regdomain *cfg80211_world_regdom =
&world_regdom;
static char *ieee80211_regdom = "00";
static char user_alpha2[2];
module_param(ieee80211_regdom, charp, 0444);
MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code");
static void reset_regdomains(bool full_reset)
{
/* avoid freeing static information or freeing something twice */
if (cfg80211_regdomain == cfg80211_world_regdom)
cfg80211_regdomain = NULL;
if (cfg80211_world_regdom == &world_regdom)
cfg80211_world_regdom = NULL;
if (cfg80211_regdomain == &world_regdom)
cfg80211_regdomain = NULL;
kfree(cfg80211_regdomain);
kfree(cfg80211_world_regdom);
cfg80211_world_regdom = &world_regdom;
cfg80211_regdomain = NULL;
if (!full_reset)
return;
if (last_request != &core_request_world)
kfree(last_request);
last_request = &core_request_world;
}
/*
* Dynamic world regulatory domain requested by the wireless
* core upon initialization
*/
static void update_world_regdomain(const struct ieee80211_regdomain *rd)
{
BUG_ON(!last_request);
reset_regdomains(false);
cfg80211_world_regdom = rd;
cfg80211_regdomain = rd;
}
bool is_world_regdom(const char *alpha2)
{
if (!alpha2)
return false;
if (alpha2[0] == '0' && alpha2[1] == '0')
return true;
return false;
}
static bool is_alpha2_set(const char *alpha2)
{
if (!alpha2)
return false;
if (alpha2[0] != 0 && alpha2[1] != 0)
return true;
return false;
}
static bool is_unknown_alpha2(const char *alpha2)
{
if (!alpha2)
return false;
/*
* Special case where regulatory domain was built by driver
* but a specific alpha2 cannot be determined
*/
if (alpha2[0] == '9' && alpha2[1] == '9')
return true;
return false;
}
static bool is_intersected_alpha2(const char *alpha2)
{
if (!alpha2)
return false;
/*
* Special case where regulatory domain is the
* result of an intersection between two regulatory domain
* structures
*/
if (alpha2[0] == '9' && alpha2[1] == '8')
return true;
return false;
}
static bool is_an_alpha2(const char *alpha2)
{
if (!alpha2)
return false;
if (isalpha(alpha2[0]) && isalpha(alpha2[1]))
return true;
return false;
}
static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y)
{
if (!alpha2_x || !alpha2_y)
return false;
if (alpha2_x[0] == alpha2_y[0] &&
alpha2_x[1] == alpha2_y[1])
return true;
return false;
}
static bool regdom_changes(const char *alpha2)
{
assert_cfg80211_lock();
if (!cfg80211_regdomain)
return true;
if (alpha2_equal(cfg80211_regdomain->alpha2, alpha2))
return false;
return true;
}
/*
* The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets
* you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER
* has ever been issued.
*/
static bool is_user_regdom_saved(void)
{
if (user_alpha2[0] == '9' && user_alpha2[1] == '7')
return false;
/* This would indicate a mistake on the design */
if (WARN((!is_world_regdom(user_alpha2) &&
!is_an_alpha2(user_alpha2)),
"Unexpected user alpha2: %c%c\n",
user_alpha2[0],
user_alpha2[1]))
return false;
return true;
}
static int reg_copy_regd(const struct ieee80211_regdomain **dst_regd,
const struct ieee80211_regdomain *src_regd)
{
struct ieee80211_regdomain *regd;
int size_of_regd = 0;
unsigned int i;
size_of_regd = sizeof(struct ieee80211_regdomain) +
((src_regd->n_reg_rules + 1) * sizeof(struct ieee80211_reg_rule));
regd = kzalloc(size_of_regd, GFP_KERNEL);
if (!regd)
return -ENOMEM;
memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain));
for (i = 0; i < src_regd->n_reg_rules; i++)
memcpy(®d->reg_rules[i], &src_regd->reg_rules[i],
sizeof(struct ieee80211_reg_rule));
*dst_regd = regd;
return 0;
}
#ifdef CONFIG_CFG80211_INTERNAL_REGDB
struct reg_regdb_search_request {
char alpha2[2];
struct list_head list;
};
static LIST_HEAD(reg_regdb_search_list);
static DEFINE_MUTEX(reg_regdb_search_mutex);
static void reg_regdb_search(struct work_struct *work)
{
struct reg_regdb_search_request *request;
const struct ieee80211_regdomain *curdom, *regdom;
int i, r;
bool set_reg = false;
mutex_lock(&cfg80211_mutex);
mutex_lock(®_regdb_search_mutex);
while (!list_empty(®_regdb_search_list)) {
request = list_first_entry(®_regdb_search_list,
struct reg_regdb_search_request,
list);
list_del(&request->list);
for (i=0; i<reg_regdb_size; i++) {
curdom = reg_regdb[i];
if (!memcmp(request->alpha2, curdom->alpha2, 2)) {
r = reg_copy_regd(®dom, curdom);
if (r)
break;
set_reg = true;
break;
}
}
kfree(request);
}
mutex_unlock(®_regdb_search_mutex);
if (set_reg)
set_regdom(regdom);
mutex_unlock(&cfg80211_mutex);
}
static DECLARE_WORK(reg_regdb_work, reg_regdb_search);
static void reg_regdb_query(const char *alpha2)
{
struct reg_regdb_search_request *request;
if (!alpha2)
return;
request = kzalloc(sizeof(struct reg_regdb_search_request), GFP_KERNEL);
if (!request)
return;
memcpy(request->alpha2, alpha2, 2);
mutex_lock(®_regdb_search_mutex);
list_add_tail(&request->list, ®_regdb_search_list);
mutex_unlock(®_regdb_search_mutex);
schedule_work(®_regdb_work);
}
/* Feel free to add any other sanity checks here */
static void reg_regdb_size_check(void)
{
/* We should ideally BUILD_BUG_ON() but then random builds would fail */
WARN_ONCE(!reg_regdb_size, "db.txt is empty, you should update it...");
}
#else
static inline void reg_regdb_size_check(void) {}
static inline void reg_regdb_query(const char *alpha2) {}
#endif /* CONFIG_CFG80211_INTERNAL_REGDB */
/*
* This lets us keep regulatory code which is updated on a regulatory
* basis in userspace. Country information is filled in by
* reg_device_uevent
*/
static int call_crda(const char *alpha2)
{
if (!is_world_regdom((char *) alpha2))
pr_info("Calling CRDA for country: %c%c\n",
alpha2[0], alpha2[1]);
else
pr_info("Calling CRDA to update world regulatory domain\n");
/* query internal regulatory database (if it exists) */
reg_regdb_query(alpha2);
return kobject_uevent(®_pdev->dev.kobj, KOBJ_CHANGE);
}
/* Used by nl80211 before kmalloc'ing our regulatory domain */
bool reg_is_valid_request(const char *alpha2)
{
assert_cfg80211_lock();
if (!last_request)
return false;
return alpha2_equal(last_request->alpha2, alpha2);
}
/* Sanity check on a regulatory rule */
static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule)
{
const struct ieee80211_freq_range *freq_range = &rule->freq_range;
u32 freq_diff;
if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0)
return false;
if (freq_range->start_freq_khz > freq_range->end_freq_khz)
return false;
freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
if (freq_range->end_freq_khz <= freq_range->start_freq_khz ||
freq_range->max_bandwidth_khz > freq_diff)
return false;
return true;
}
static bool is_valid_rd(const struct ieee80211_regdomain *rd)
{
const struct ieee80211_reg_rule *reg_rule = NULL;
unsigned int i;
if (!rd->n_reg_rules)
return false;
if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES))
return false;
for (i = 0; i < rd->n_reg_rules; i++) {
reg_rule = &rd->reg_rules[i];
if (!is_valid_reg_rule(reg_rule))
return false;
}
return true;
}
static bool reg_does_bw_fit(const struct ieee80211_freq_range *freq_range,
u32 center_freq_khz,
u32 bw_khz)
{
u32 start_freq_khz, end_freq_khz;
start_freq_khz = center_freq_khz - (bw_khz/2);
end_freq_khz = center_freq_khz + (bw_khz/2);
if (start_freq_khz >= freq_range->start_freq_khz &&
end_freq_khz <= freq_range->end_freq_khz)
return true;
return false;
}
/**
* freq_in_rule_band - tells us if a frequency is in a frequency band
* @freq_range: frequency rule we want to query
* @freq_khz: frequency we are inquiring about
*
* This lets us know if a specific frequency rule is or is not relevant to
* a specific frequency's band. Bands are device specific and artificial
* definitions (the "2.4 GHz band" and the "5 GHz band"), however it is
* safe for now to assume that a frequency rule should not be part of a
* frequency's band if the start freq or end freq are off by more than 2 GHz.
* This resolution can be lowered and should be considered as we add
* regulatory rule support for other "bands".
**/
static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range,
u32 freq_khz)
{
#define ONE_GHZ_IN_KHZ 1000000
if (abs(freq_khz - freq_range->start_freq_khz) <= (2 * ONE_GHZ_IN_KHZ))
return true;
if (abs(freq_khz - freq_range->end_freq_khz) <= (2 * ONE_GHZ_IN_KHZ))
return true;
return false;
#undef ONE_GHZ_IN_KHZ
}
/*
* Helper for regdom_intersect(), this does the real
* mathematical intersection fun
*/
static int reg_rules_intersect(
const struct ieee80211_reg_rule *rule1,
const struct ieee80211_reg_rule *rule2,
struct ieee80211_reg_rule *intersected_rule)
{
const struct ieee80211_freq_range *freq_range1, *freq_range2;
struct ieee80211_freq_range *freq_range;
const struct ieee80211_power_rule *power_rule1, *power_rule2;
struct ieee80211_power_rule *power_rule;
u32 freq_diff;
freq_range1 = &rule1->freq_range;
freq_range2 = &rule2->freq_range;
freq_range = &intersected_rule->freq_range;
power_rule1 = &rule1->power_rule;
power_rule2 = &rule2->power_rule;
power_rule = &intersected_rule->power_rule;
freq_range->start_freq_khz = max(freq_range1->start_freq_khz,
freq_range2->start_freq_khz);
freq_range->end_freq_khz = min(freq_range1->end_freq_khz,
freq_range2->end_freq_khz);
freq_range->max_bandwidth_khz = min(freq_range1->max_bandwidth_khz,
freq_range2->max_bandwidth_khz);
freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
if (freq_range->max_bandwidth_khz > freq_diff)
freq_range->max_bandwidth_khz = freq_diff;
power_rule->max_eirp = min(power_rule1->max_eirp,
power_rule2->max_eirp);
power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain,
power_rule2->max_antenna_gain);
intersected_rule->flags = (rule1->flags | rule2->flags);
if (!is_valid_reg_rule(intersected_rule))
return -EINVAL;
return 0;
}
/**
* regdom_intersect - do the intersection between two regulatory domains
* @rd1: first regulatory domain
* @rd2: second regulatory domain
*
* Use this function to get the intersection between two regulatory domains.
* Once completed we will mark the alpha2 for the rd as intersected, "98",
* as no one single alpha2 can represent this regulatory domain.
*
* Returns a pointer to the regulatory domain structure which will hold the
* resulting intersection of rules between rd1 and rd2. We will
* kzalloc() this structure for you.
*/
static struct ieee80211_regdomain *regdom_intersect(
const struct ieee80211_regdomain *rd1,
const struct ieee80211_regdomain *rd2)
{
int r, size_of_regd;
unsigned int x, y;
unsigned int num_rules = 0, rule_idx = 0;
const struct ieee80211_reg_rule *rule1, *rule2;
struct ieee80211_reg_rule *intersected_rule;
struct ieee80211_regdomain *rd;
/* This is just a dummy holder to help us count */
struct ieee80211_reg_rule irule;
/* Uses the stack temporarily for counter arithmetic */
intersected_rule = &irule;
memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule));
if (!rd1 || !rd2)
return NULL;
/*
* First we get a count of the rules we'll need, then we actually
* build them. This is to so we can malloc() and free() a
* regdomain once. The reason we use reg_rules_intersect() here
* is it will return -EINVAL if the rule computed makes no sense.
* All rules that do check out OK are valid.
*/
for (x = 0; x < rd1->n_reg_rules; x++) {
rule1 = &rd1->reg_rules[x];
for (y = 0; y < rd2->n_reg_rules; y++) {
rule2 = &rd2->reg_rules[y];
if (!reg_rules_intersect(rule1, rule2,
intersected_rule))
num_rules++;
memset(intersected_rule, 0,
sizeof(struct ieee80211_reg_rule));
}
}
if (!num_rules)
return NULL;
size_of_regd = sizeof(struct ieee80211_regdomain) +
((num_rules + 1) * sizeof(struct ieee80211_reg_rule));
rd = kzalloc(size_of_regd, GFP_KERNEL);
if (!rd)
return NULL;
for (x = 0; x < rd1->n_reg_rules; x++) {
rule1 = &rd1->reg_rules[x];
for (y = 0; y < rd2->n_reg_rules; y++) {
rule2 = &rd2->reg_rules[y];
/*
* This time around instead of using the stack lets
* write to the target rule directly saving ourselves
* a memcpy()
*/
intersected_rule = &rd->reg_rules[rule_idx];
r = reg_rules_intersect(rule1, rule2,
intersected_rule);
/*
* No need to memset here the intersected rule here as
* we're not using the stack anymore
*/
if (r)
continue;
rule_idx++;
}
}
if (rule_idx != num_rules) {
kfree(rd);
return NULL;
}
rd->n_reg_rules = num_rules;
rd->alpha2[0] = '9';
rd->alpha2[1] = '8';
return rd;
}
/*
* XXX: add support for the rest of enum nl80211_reg_rule_flags, we may
* want to just have the channel structure use these
*/
static u32 map_regdom_flags(u32 rd_flags)
{
u32 channel_flags = 0;
if (rd_flags & NL80211_RRF_PASSIVE_SCAN)
channel_flags |= IEEE80211_CHAN_PASSIVE_SCAN;
if (rd_flags & NL80211_RRF_NO_IBSS)
channel_flags |= IEEE80211_CHAN_NO_IBSS;
if (rd_flags & NL80211_RRF_DFS)
channel_flags |= IEEE80211_CHAN_RADAR;
return channel_flags;
}
static int freq_reg_info_regd(struct wiphy *wiphy,
u32 center_freq,
u32 desired_bw_khz,
const struct ieee80211_reg_rule **reg_rule,
const struct ieee80211_regdomain *custom_regd)
{
int i;
bool band_rule_found = false;
const struct ieee80211_regdomain *regd;
bool bw_fits = false;
if (!desired_bw_khz)
desired_bw_khz = MHZ_TO_KHZ(20);
regd = custom_regd ? custom_regd : cfg80211_regdomain;
/*
* Follow the driver's regulatory domain, if present, unless a country
* IE has been processed or a user wants to help complaince further
*/
if (!custom_regd &&
last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
last_request->initiator != NL80211_REGDOM_SET_BY_USER &&
wiphy->regd)
regd = wiphy->regd;
if (!regd)
return -EINVAL;
for (i = 0; i < regd->n_reg_rules; i++) {
const struct ieee80211_reg_rule *rr;
const struct ieee80211_freq_range *fr = NULL;
rr = ®d->reg_rules[i];
fr = &rr->freq_range;
/*
* We only need to know if one frequency rule was
* was in center_freq's band, that's enough, so lets
* not overwrite it once found
*/
if (!band_rule_found)
band_rule_found = freq_in_rule_band(fr, center_freq);
bw_fits = reg_does_bw_fit(fr,
center_freq,
desired_bw_khz);
if (band_rule_found && bw_fits) {
*reg_rule = rr;
return 0;
}
}
if (!band_rule_found)
return -ERANGE;
return -EINVAL;
}
int freq_reg_info(struct wiphy *wiphy,
u32 center_freq,
u32 desired_bw_khz,
const struct ieee80211_reg_rule **reg_rule)
{
assert_cfg80211_lock();
return freq_reg_info_regd(wiphy,
center_freq,
desired_bw_khz,
reg_rule,
NULL);
}
EXPORT_SYMBOL(freq_reg_info);
#ifdef CONFIG_CFG80211_REG_DEBUG
static const char *reg_initiator_name(enum nl80211_reg_initiator initiator)
{
switch (initiator) {
case NL80211_REGDOM_SET_BY_CORE:
return "Set by core";
case NL80211_REGDOM_SET_BY_USER:
return "Set by user";
case NL80211_REGDOM_SET_BY_DRIVER:
return "Set by driver";
case NL80211_REGDOM_SET_BY_COUNTRY_IE:
return "Set by country IE";
default:
WARN_ON(1);
return "Set by bug";
}
}
static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan,
u32 desired_bw_khz,
const struct ieee80211_reg_rule *reg_rule)
{
const struct ieee80211_power_rule *power_rule;
const struct ieee80211_freq_range *freq_range;
char max_antenna_gain[32];
power_rule = ®_rule->power_rule;
freq_range = ®_rule->freq_range;
if (!power_rule->max_antenna_gain)
snprintf(max_antenna_gain, 32, "N/A");
else
snprintf(max_antenna_gain, 32, "%d", power_rule->max_antenna_gain);
REG_DBG_PRINT("Updating information on frequency %d MHz "
"for a %d MHz width channel with regulatory rule:\n",
chan->center_freq,
KHZ_TO_MHZ(desired_bw_khz));
REG_DBG_PRINT("%d KHz - %d KHz @ KHz), (%s mBi, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
max_antenna_gain,
power_rule->max_eirp);
}
#else
static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan,
u32 desired_bw_khz,
const struct ieee80211_reg_rule *reg_rule)
{
return;
}
#endif
/*
* Note that right now we assume the desired channel bandwidth
* is always 20 MHz for each individual channel (HT40 uses 20 MHz
* per channel, the primary and the extension channel). To support
* smaller custom bandwidths such as 5 MHz or 10 MHz we'll need a
* new ieee80211_channel.target_bw and re run the regulatory check
* on the wiphy with the target_bw specified. Then we can simply use
* that below for the desired_bw_khz below.
*/
static void handle_channel(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator,
enum ieee80211_band band,
unsigned int chan_idx)
{
int r;
u32 flags, bw_flags = 0;
u32 desired_bw_khz = MHZ_TO_KHZ(20);
const struct ieee80211_reg_rule *reg_rule = NULL;
const struct ieee80211_power_rule *power_rule = NULL;
const struct ieee80211_freq_range *freq_range = NULL;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
struct wiphy *request_wiphy = NULL;
assert_cfg80211_lock();
request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
sband = wiphy->bands[band];
BUG_ON(chan_idx >= sband->n_channels);
chan = &sband->channels[chan_idx];
flags = chan->orig_flags;
r = freq_reg_info(wiphy,
MHZ_TO_KHZ(chan->center_freq),
desired_bw_khz,
®_rule);
if (r) {
/*
* We will disable all channels that do not match our
* received regulatory rule unless the hint is coming
* from a Country IE and the Country IE had no information
* about a band. The IEEE 802.11 spec allows for an AP
* to send only a subset of the regulatory rules allowed,
* so an AP in the US that only supports 2.4 GHz may only send
* a country IE with information for the 2.4 GHz band
* while 5 GHz is still supported.
*/
if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
r == -ERANGE)
return;
REG_DBG_PRINT("Disabling freq %d MHz\n", chan->center_freq);
chan->flags |= IEEE80211_CHAN_DISABLED;
return;
}
chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule);
power_rule = ®_rule->power_rule;
freq_range = ®_rule->freq_range;
if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40))
bw_flags = IEEE80211_CHAN_NO_HT40;
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
request_wiphy && request_wiphy == wiphy &&
request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
/*
* This guarantees the driver's requested regulatory domain
* will always be used as a base for further regulatory
* settings
*/
chan->flags = chan->orig_flags =
map_regdom_flags(reg_rule->flags) | bw_flags;
chan->max_antenna_gain = chan->orig_mag =
(int) MBI_TO_DBI(power_rule->max_antenna_gain);
chan->max_power = chan->orig_mpwr =
(int) MBM_TO_DBM(power_rule->max_eirp);
return;
}
chan->beacon_found = false;
chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags);
chan->max_antenna_gain = min(chan->orig_mag,
(int) MBI_TO_DBI(power_rule->max_antenna_gain));
if (chan->orig_mpwr)
chan->max_power = min(chan->orig_mpwr,
(int) MBM_TO_DBM(power_rule->max_eirp));
else
chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp);
}
static void handle_band(struct wiphy *wiphy,
enum ieee80211_band band,
enum nl80211_reg_initiator initiator)
{
unsigned int i;
struct ieee80211_supported_band *sband;
BUG_ON(!wiphy->bands[band]);
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++)
handle_channel(wiphy, initiator, band, i);
}
static bool ignore_reg_update(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
if (!last_request) {
REG_DBG_PRINT("Ignoring regulatory request %s since "
"last_request is not set\n",
reg_initiator_name(initiator));
return true;
}
if (initiator == NL80211_REGDOM_SET_BY_CORE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) {
REG_DBG_PRINT("Ignoring regulatory request %s "
"since the driver uses its own custom "
"regulatory domain ",
reg_initiator_name(initiator));
return true;
}
/*
* wiphy->regd will be set once the device has its own
* desired regulatory domain set
*/
if (wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY && !wiphy->regd &&
initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
!is_world_regdom(last_request->alpha2)) {
REG_DBG_PRINT("Ignoring regulatory request %s "
"since the driver requires its own regulaotry "
"domain to be set first",
reg_initiator_name(initiator));
return true;
}
return false;
}
static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)
{
struct cfg80211_registered_device *rdev;
list_for_each_entry(rdev, &cfg80211_rdev_list, list)
wiphy_update_regulatory(&rdev->wiphy, initiator);
}
static void handle_reg_beacon(struct wiphy *wiphy,
unsigned int chan_idx,
struct reg_beacon *reg_beacon)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
bool channel_changed = false;
struct ieee80211_channel chan_before;
assert_cfg80211_lock();
sband = wiphy->bands[reg_beacon->chan.band];
chan = &sband->channels[chan_idx];
if (likely(chan->center_freq != reg_beacon->chan.center_freq))
return;
if (chan->beacon_found)
return;
chan->beacon_found = true;
if (wiphy->flags & WIPHY_FLAG_DISABLE_BEACON_HINTS)
return;
chan_before.center_freq = chan->center_freq;
chan_before.flags = chan->flags;
if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN) {
chan->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
channel_changed = true;
}
if (chan->flags & IEEE80211_CHAN_NO_IBSS) {
chan->flags &= ~IEEE80211_CHAN_NO_IBSS;
channel_changed = true;
}
if (channel_changed)
nl80211_send_beacon_hint_event(wiphy, &chan_before, chan);
}
/*
* Called when a scan on a wiphy finds a beacon on
* new channel
*/
static void wiphy_update_new_beacon(struct wiphy *wiphy,
struct reg_beacon *reg_beacon)
{
unsigned int i;
struct ieee80211_supported_band *sband;
assert_cfg80211_lock();
if (!wiphy->bands[reg_beacon->chan.band])
return;
sband = wiphy->bands[reg_beacon->chan.band];
for (i = 0; i < sband->n_channels; i++)
handle_reg_beacon(wiphy, i, reg_beacon);
}
/*
* Called upon reg changes or a new wiphy is added
*/
static void wiphy_update_beacon_reg(struct wiphy *wiphy)
{
unsigned int i;
struct ieee80211_supported_band *sband;
struct reg_beacon *reg_beacon;
assert_cfg80211_lock();
if (list_empty(®_beacon_list))
return;
list_for_each_entry(reg_beacon, ®_beacon_list, list) {
if (!wiphy->bands[reg_beacon->chan.band])
continue;
sband = wiphy->bands[reg_beacon->chan.band];
for (i = 0; i < sband->n_channels; i++)
handle_reg_beacon(wiphy, i, reg_beacon);
}
}
static bool reg_is_world_roaming(struct wiphy *wiphy)
{
if (is_world_regdom(cfg80211_regdomain->alpha2) ||
(wiphy->regd && is_world_regdom(wiphy->regd->alpha2)))
return true;
if (last_request &&
last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY)
return true;
return false;
}
/* Reap the advantages of previously found beacons */
static void reg_process_beacons(struct wiphy *wiphy)
{
/*
* Means we are just firing up cfg80211, so no beacons would
* have been processed yet.
*/
if (!last_request)
return;
if (!reg_is_world_roaming(wiphy))
return;
wiphy_update_beacon_reg(wiphy);
}
static bool is_ht40_not_allowed(struct ieee80211_channel *chan)
{
if (!chan)
return true;
if (chan->flags & IEEE80211_CHAN_DISABLED)
return true;
/* This would happen when regulatory rules disallow HT40 completely */
if (IEEE80211_CHAN_NO_HT40 == (chan->flags & (IEEE80211_CHAN_NO_HT40)))
return true;
return false;
}
static void reg_process_ht_flags_channel(struct wiphy *wiphy,
enum ieee80211_band band,
unsigned int chan_idx)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *channel;
struct ieee80211_channel *channel_before = NULL, *channel_after = NULL;
unsigned int i;
assert_cfg80211_lock();
sband = wiphy->bands[band];
BUG_ON(chan_idx >= sband->n_channels);
channel = &sband->channels[chan_idx];
if (is_ht40_not_allowed(channel)) {
channel->flags |= IEEE80211_CHAN_NO_HT40;
return;
}
/*
* We need to ensure the extension channels exist to
* be able to use HT40- or HT40+, this finds them (or not)
*/
for (i = 0; i < sband->n_channels; i++) {
struct ieee80211_channel *c = &sband->channels[i];
if (c->center_freq == (channel->center_freq - 20))
channel_before = c;
if (c->center_freq == (channel->center_freq + 20))
channel_after = c;
}
/*
* Please note that this assumes target bandwidth is 20 MHz,
* if that ever changes we also need to change the below logic
* to include that as well.
*/
if (is_ht40_not_allowed(channel_before))
channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
else
channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS;
if (is_ht40_not_allowed(channel_after))
channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
else
channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS;
}
static void reg_process_ht_flags_band(struct wiphy *wiphy,
enum ieee80211_band band)
{
unsigned int i;
struct ieee80211_supported_band *sband;
BUG_ON(!wiphy->bands[band]);
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++)
reg_process_ht_flags_channel(wiphy, band, i);
}
static void reg_process_ht_flags(struct wiphy *wiphy)
{
enum ieee80211_band band;
if (!wiphy)
return;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (wiphy->bands[band])
reg_process_ht_flags_band(wiphy, band);
}
}
void wiphy_update_regulatory(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
enum ieee80211_band band;
if (ignore_reg_update(wiphy, initiator))
return;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (wiphy->bands[band])
handle_band(wiphy, band, initiator);
}
reg_process_beacons(wiphy);
reg_process_ht_flags(wiphy);
if (wiphy->reg_notifier)
wiphy->reg_notifier(wiphy, last_request);
}
static void handle_channel_custom(struct wiphy *wiphy,
enum ieee80211_band band,
unsigned int chan_idx,
const struct ieee80211_regdomain *regd)
{
int r;
u32 desired_bw_khz = MHZ_TO_KHZ(20);
u32 bw_flags = 0;
const struct ieee80211_reg_rule *reg_rule = NULL;
const struct ieee80211_power_rule *power_rule = NULL;
const struct ieee80211_freq_range *freq_range = NULL;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
assert_reg_lock();
sband = wiphy->bands[band];
BUG_ON(chan_idx >= sband->n_channels);
chan = &sband->channels[chan_idx];
r = freq_reg_info_regd(wiphy,
MHZ_TO_KHZ(chan->center_freq),
desired_bw_khz,
®_rule,
regd);
if (r) {
REG_DBG_PRINT("Disabling freq %d MHz as custom "
"regd has no rule that fits a %d MHz "
"wide channel\n",
chan->center_freq,
KHZ_TO_MHZ(desired_bw_khz));
chan->flags = IEEE80211_CHAN_DISABLED;
return;
}
chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule);
power_rule = ®_rule->power_rule;
freq_range = ®_rule->freq_range;
if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40))
bw_flags = IEEE80211_CHAN_NO_HT40;
chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags;
chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain);
chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp);
}
static void handle_band_custom(struct wiphy *wiphy, enum ieee80211_band band,
const struct ieee80211_regdomain *regd)
{
unsigned int i;
struct ieee80211_supported_band *sband;
BUG_ON(!wiphy->bands[band]);
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++)
handle_channel_custom(wiphy, band, i, regd);
}
/* Used by drivers prior to wiphy registration */
void wiphy_apply_custom_regulatory(struct wiphy *wiphy,
const struct ieee80211_regdomain *regd)
{
enum ieee80211_band band;
unsigned int bands_set = 0;
mutex_lock(®_mutex);
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!wiphy->bands[band])
continue;
handle_band_custom(wiphy, band, regd);
bands_set++;
}
mutex_unlock(®_mutex);
/*
* no point in calling this if it won't have any effect
* on your device's supportd bands.
*/
WARN_ON(!bands_set);
}
EXPORT_SYMBOL(wiphy_apply_custom_regulatory);
/*
* Return value which can be used by ignore_request() to indicate
* it has been determined we should intersect two regulatory domains
*/
#define REG_INTERSECT 1
/* This has the logic which determines when a new request
* should be ignored. */
static int ignore_request(struct wiphy *wiphy,
struct regulatory_request *pending_request)
{
struct wiphy *last_wiphy = NULL;
assert_cfg80211_lock();
/* All initial requests are respected */
if (!last_request)
return 0;
switch (pending_request->initiator) {
case NL80211_REGDOM_SET_BY_CORE:
return 0;
case NL80211_REGDOM_SET_BY_COUNTRY_IE:
last_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
if (unlikely(!is_an_alpha2(pending_request->alpha2)))
return -EINVAL;
if (last_request->initiator ==
NL80211_REGDOM_SET_BY_COUNTRY_IE) {
if (last_wiphy != wiphy) {
/*
* Two cards with two APs claiming different
* Country IE alpha2s. We could
* intersect them, but that seems unlikely
* to be correct. Reject second one for now.
*/
if (regdom_changes(pending_request->alpha2))
return -EOPNOTSUPP;
return -EALREADY;
}
/*
* Two consecutive Country IE hints on the same wiphy.
* This should be picked up early by the driver/stack
*/
if (WARN_ON(regdom_changes(pending_request->alpha2)))
return 0;
return -EALREADY;
}
return 0;
case NL80211_REGDOM_SET_BY_DRIVER:
if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE) {
if (regdom_changes(pending_request->alpha2))
return 0;
return -EALREADY;
}
/*
* This would happen if you unplug and plug your card
* back in or if you add a new device for which the previously
* loaded card also agrees on the regulatory domain.
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
!regdom_changes(pending_request->alpha2))
return -EALREADY;
return REG_INTERSECT;
case NL80211_REGDOM_SET_BY_USER:
if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)
return REG_INTERSECT;
/*
* If the user knows better the user should set the regdom
* to their country before the IE is picked up
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_USER &&
last_request->intersect)
return -EOPNOTSUPP;
/*
* Process user requests only after previous user/driver/core
* requests have been processed
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE ||
last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
last_request->initiator == NL80211_REGDOM_SET_BY_USER) {
if (regdom_changes(last_request->alpha2))
return -EAGAIN;
}
if (!regdom_changes(pending_request->alpha2))
return -EALREADY;
return 0;
}
return -EINVAL;
}
static void reg_set_request_processed(void)
{
bool need_more_processing = false;
last_request->processed = true;
spin_lock(®_requests_lock);
if (!list_empty(®_requests_list))
need_more_processing = true;
spin_unlock(®_requests_lock);
if (last_request->initiator == NL80211_REGDOM_SET_BY_USER)
cancel_delayed_work(®_timeout);
if (need_more_processing)
schedule_work(®_work);
}
/**
* __regulatory_hint - hint to the wireless core a regulatory domain
* @wiphy: if the hint comes from country information from an AP, this
* is required to be set to the wiphy that received the information
* @pending_request: the regulatory request currently being processed
*
* The Wireless subsystem can use this function to hint to the wireless core
* what it believes should be the current regulatory domain.
*
* Returns zero if all went fine, %-EALREADY if a regulatory domain had
* already been set or other standard error codes.
*
* Caller must hold &cfg80211_mutex and ®_mutex
*/
static int __regulatory_hint(struct wiphy *wiphy,
struct regulatory_request *pending_request)
{
bool intersect = false;
int r = 0;
assert_cfg80211_lock();
r = ignore_request(wiphy, pending_request);
if (r == REG_INTERSECT) {
if (pending_request->initiator ==
NL80211_REGDOM_SET_BY_DRIVER) {
r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain);
if (r) {
kfree(pending_request);
return r;
}
}
intersect = true;
} else if (r) {
/*
* If the regulatory domain being requested by the
* driver has already been set just copy it to the
* wiphy
*/
if (r == -EALREADY &&
pending_request->initiator ==
NL80211_REGDOM_SET_BY_DRIVER) {
r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain);
if (r) {
kfree(pending_request);
return r;
}
r = -EALREADY;
goto new_request;
}
kfree(pending_request);
return r;
}
new_request:
if (last_request != &core_request_world)
kfree(last_request);
last_request = pending_request;
last_request->intersect = intersect;
pending_request = NULL;
if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) {
user_alpha2[0] = last_request->alpha2[0];
user_alpha2[1] = last_request->alpha2[1];
}
/* When r == REG_INTERSECT we do need to call CRDA */
if (r < 0) {
/*
* Since CRDA will not be called in this case as we already
* have applied the requested regulatory domain before we just
* inform userspace we have processed the request
*/
if (r == -EALREADY) {
nl80211_send_reg_change_event(last_request);
reg_set_request_processed();
}
return r;
}
return call_crda(last_request->alpha2);
}
/* This processes *all* regulatory hints */
static void reg_process_hint(struct regulatory_request *reg_request)
{
int r = 0;
struct wiphy *wiphy = NULL;
enum nl80211_reg_initiator initiator = reg_request->initiator;
BUG_ON(!reg_request->alpha2);
if (wiphy_idx_valid(reg_request->wiphy_idx))
wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx);
if (reg_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
!wiphy) {
kfree(reg_request);
return;
}
r = __regulatory_hint(wiphy, reg_request);
/* This is required so that the orig_* parameters are saved */
if (r == -EALREADY && wiphy &&
wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
wiphy_update_regulatory(wiphy, initiator);
return;
}
/*
* We only time out user hints, given that they should be the only
* source of bogus requests.
*/
if (r != -EALREADY &&
reg_request->initiator == NL80211_REGDOM_SET_BY_USER)
schedule_delayed_work(®_timeout, msecs_to_jiffies(3142));
}
/*
* Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_*
* Regulatory hints come on a first come first serve basis and we
* must process each one atomically.
*/
static void reg_process_pending_hints(void)
{
struct regulatory_request *reg_request;
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
/* When last_request->processed becomes true this will be rescheduled */
if (last_request && !last_request->processed) {
REG_DBG_PRINT("Pending regulatory request, waiting "
"for it to be processed...");
goto out;
}
spin_lock(®_requests_lock);
if (list_empty(®_requests_list)) {
spin_unlock(®_requests_lock);
goto out;
}
reg_request = list_first_entry(®_requests_list,
struct regulatory_request,
list);
list_del_init(®_request->list);
spin_unlock(®_requests_lock);
reg_process_hint(reg_request);
out:
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
}
/* Processes beacon hints -- this has nothing to do with country IEs */
static void reg_process_pending_beacon_hints(void)
{
struct cfg80211_registered_device *rdev;
struct reg_beacon *pending_beacon, *tmp;
/*
* No need to hold the reg_mutex here as we just touch wiphys
* and do not read or access regulatory variables.
*/
mutex_lock(&cfg80211_mutex);
/* This goes through the _pending_ beacon list */
spin_lock_bh(®_pending_beacons_lock);
if (list_empty(®_pending_beacons)) {
spin_unlock_bh(®_pending_beacons_lock);
goto out;
}
list_for_each_entry_safe(pending_beacon, tmp,
®_pending_beacons, list) {
list_del_init(&pending_beacon->list);
/* Applies the beacon hint to current wiphys */
list_for_each_entry(rdev, &cfg80211_rdev_list, list)
wiphy_update_new_beacon(&rdev->wiphy, pending_beacon);
/* Remembers the beacon hint for new wiphys or reg changes */
list_add_tail(&pending_beacon->list, ®_beacon_list);
}
spin_unlock_bh(®_pending_beacons_lock);
out:
mutex_unlock(&cfg80211_mutex);
}
static void reg_todo(struct work_struct *work)
{
reg_process_pending_hints();
reg_process_pending_beacon_hints();
}
static void queue_regulatory_request(struct regulatory_request *request)
{
if (isalpha(request->alpha2[0]))
request->alpha2[0] = toupper(request->alpha2[0]);
if (isalpha(request->alpha2[1]))
request->alpha2[1] = toupper(request->alpha2[1]);
spin_lock(®_requests_lock);
list_add_tail(&request->list, ®_requests_list);
spin_unlock(®_requests_lock);
schedule_work(®_work);
}
/*
* Core regulatory hint -- happens during cfg80211_init()
* and when we restore regulatory settings.
*/
static int regulatory_hint_core(const char *alpha2)
{
struct regulatory_request *request;
request = kzalloc(sizeof(struct regulatory_request),
GFP_KERNEL);
if (!request)
return -ENOMEM;
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_CORE;
queue_regulatory_request(request);
return 0;
}
/* User hints */
int regulatory_hint_user(const char *alpha2)
{
struct regulatory_request *request;
BUG_ON(!alpha2);
request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
if (!request)
return -ENOMEM;
request->wiphy_idx = WIPHY_IDX_STALE;
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_USER;
queue_regulatory_request(request);
return 0;
}
/* Driver hints */
int regulatory_hint(struct wiphy *wiphy, const char *alpha2)
{
struct regulatory_request *request;
BUG_ON(!alpha2);
BUG_ON(!wiphy);
request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
if (!request)
return -ENOMEM;
request->wiphy_idx = get_wiphy_idx(wiphy);
/* Must have registered wiphy first */
BUG_ON(!wiphy_idx_valid(request->wiphy_idx));
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_DRIVER;
queue_regulatory_request(request);
return 0;
}
EXPORT_SYMBOL(regulatory_hint);
/*
* We hold wdev_lock() here so we cannot hold cfg80211_mutex() and
* therefore cannot iterate over the rdev list here.
*/
void regulatory_hint_11d(struct wiphy *wiphy,
enum ieee80211_band band,
u8 *country_ie,
u8 country_ie_len)
{
char alpha2[2];
enum environment_cap env = ENVIRON_ANY;
struct regulatory_request *request;
mutex_lock(®_mutex);
if (unlikely(!last_request))
goto out;
/* IE len must be evenly divisible by 2 */
if (country_ie_len & 0x01)
goto out;
if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN)
goto out;
alpha2[0] = country_ie[0];
alpha2[1] = country_ie[1];
if (country_ie[2] == 'I')
env = ENVIRON_INDOOR;
else if (country_ie[2] == 'O')
env = ENVIRON_OUTDOOR;
/*
* We will run this only upon a successful connection on cfg80211.
* We leave conflict resolution to the workqueue, where can hold
* cfg80211_mutex.
*/
if (likely(last_request->initiator ==
NL80211_REGDOM_SET_BY_COUNTRY_IE &&
wiphy_idx_valid(last_request->wiphy_idx)))
goto out;
request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
if (!request)
goto out;
request->wiphy_idx = get_wiphy_idx(wiphy);
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE;
request->country_ie_env = env;
mutex_unlock(®_mutex);
queue_regulatory_request(request);
return;
out:
mutex_unlock(®_mutex);
}
static void restore_alpha2(char *alpha2, bool reset_user)
{
/* indicates there is no alpha2 to consider for restoration */
alpha2[0] = '9';
alpha2[1] = '7';
/* The user setting has precedence over the module parameter */
if (is_user_regdom_saved()) {
/* Unless we're asked to ignore it and reset it */
if (reset_user) {
REG_DBG_PRINT("Restoring regulatory settings "
"including user preference\n");
user_alpha2[0] = '9';
user_alpha2[1] = '7';
/*
* If we're ignoring user settings, we still need to
* check the module parameter to ensure we put things
* back as they were for a full restore.
*/
if (!is_world_regdom(ieee80211_regdom)) {
REG_DBG_PRINT("Keeping preference on "
"module parameter ieee80211_regdom: %c%c\n",
ieee80211_regdom[0],
ieee80211_regdom[1]);
alpha2[0] = ieee80211_regdom[0];
alpha2[1] = ieee80211_regdom[1];
}
} else {
REG_DBG_PRINT("Restoring regulatory settings "
"while preserving user preference for: %c%c\n",
user_alpha2[0],
user_alpha2[1]);
alpha2[0] = user_alpha2[0];
alpha2[1] = user_alpha2[1];
}
} else if (!is_world_regdom(ieee80211_regdom)) {
REG_DBG_PRINT("Keeping preference on "
"module parameter ieee80211_regdom: %c%c\n",
ieee80211_regdom[0],
ieee80211_regdom[1]);
alpha2[0] = ieee80211_regdom[0];
alpha2[1] = ieee80211_regdom[1];
} else
REG_DBG_PRINT("Restoring regulatory settings\n");
}
/*
* Restoring regulatory settings involves ingoring any
* possibly stale country IE information and user regulatory
* settings if so desired, this includes any beacon hints
* learned as we could have traveled outside to another country
* after disconnection. To restore regulatory settings we do
* exactly what we did at bootup:
*
* - send a core regulatory hint
* - send a user regulatory hint if applicable
*
* Device drivers that send a regulatory hint for a specific country
* keep their own regulatory domain on wiphy->regd so that does does
* not need to be remembered.
*/
static void restore_regulatory_settings(bool reset_user)
{
char alpha2[2];
char world_alpha2[2];
struct reg_beacon *reg_beacon, *btmp;
struct regulatory_request *reg_request, *tmp;
LIST_HEAD(tmp_reg_req_list);
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
reset_regdomains(true);
restore_alpha2(alpha2, reset_user);
/*
* If there's any pending requests we simply
* stash them to a temporary pending queue and
* add then after we've restored regulatory
* settings.
*/
spin_lock(®_requests_lock);
if (!list_empty(®_requests_list)) {
list_for_each_entry_safe(reg_request, tmp,
®_requests_list, list) {
if (reg_request->initiator !=
NL80211_REGDOM_SET_BY_USER)
continue;
list_del(®_request->list);
list_add_tail(®_request->list, &tmp_reg_req_list);
}
}
spin_unlock(®_requests_lock);
/* Clear beacon hints */
spin_lock_bh(®_pending_beacons_lock);
if (!list_empty(®_pending_beacons)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_pending_beacons, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
spin_unlock_bh(®_pending_beacons_lock);
if (!list_empty(®_beacon_list)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_beacon_list, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
/* First restore to the basic regulatory settings */
cfg80211_regdomain = cfg80211_world_regdom;
world_alpha2[0] = cfg80211_regdomain->alpha2[0];
world_alpha2[1] = cfg80211_regdomain->alpha2[1];
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
regulatory_hint_core(world_alpha2);
/*
* This restores the ieee80211_regdom module parameter
* preference or the last user requested regulatory
* settings, user regulatory settings takes precedence.
*/
if (is_an_alpha2(alpha2))
regulatory_hint_user(user_alpha2);
if (list_empty(&tmp_reg_req_list))
return;
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
spin_lock(®_requests_lock);
list_for_each_entry_safe(reg_request, tmp, &tmp_reg_req_list, list) {
REG_DBG_PRINT("Adding request for country %c%c back "
"into the queue\n",
reg_request->alpha2[0],
reg_request->alpha2[1]);
list_del(®_request->list);
list_add_tail(®_request->list, ®_requests_list);
}
spin_unlock(®_requests_lock);
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
REG_DBG_PRINT("Kicking the queue\n");
schedule_work(®_work);
}
void regulatory_hint_disconnect(void)
{
REG_DBG_PRINT("All devices are disconnected, going to "
"restore regulatory settings\n");
restore_regulatory_settings(false);
}
static bool freq_is_chan_12_13_14(u16 freq)
{
if (freq == ieee80211_channel_to_frequency(12, IEEE80211_BAND_2GHZ) ||
freq == ieee80211_channel_to_frequency(13, IEEE80211_BAND_2GHZ) ||
freq == ieee80211_channel_to_frequency(14, IEEE80211_BAND_2GHZ))
return true;
return false;
}
int regulatory_hint_found_beacon(struct wiphy *wiphy,
struct ieee80211_channel *beacon_chan,
gfp_t gfp)
{
struct reg_beacon *reg_beacon;
if (likely((beacon_chan->beacon_found ||
(beacon_chan->flags & IEEE80211_CHAN_RADAR) ||
(beacon_chan->band == IEEE80211_BAND_2GHZ &&
!freq_is_chan_12_13_14(beacon_chan->center_freq)))))
return 0;
reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp);
if (!reg_beacon)
return -ENOMEM;
REG_DBG_PRINT("Found new beacon on "
"frequency: %d MHz (Ch %d) on %s\n",
beacon_chan->center_freq,
ieee80211_frequency_to_channel(beacon_chan->center_freq),
wiphy_name(wiphy));
memcpy(®_beacon->chan, beacon_chan,
sizeof(struct ieee80211_channel));
/*
* Since we can be called from BH or and non-BH context
* we must use spin_lock_bh()
*/
spin_lock_bh(®_pending_beacons_lock);
list_add_tail(®_beacon->list, ®_pending_beacons);
spin_unlock_bh(®_pending_beacons_lock);
schedule_work(®_work);
return 0;
}
static void print_rd_rules(const struct ieee80211_regdomain *rd)
{
unsigned int i;
const struct ieee80211_reg_rule *reg_rule = NULL;
const struct ieee80211_freq_range *freq_range = NULL;
const struct ieee80211_power_rule *power_rule = NULL;
pr_info(" (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)\n");
for (i = 0; i < rd->n_reg_rules; i++) {
reg_rule = &rd->reg_rules[i];
freq_range = ®_rule->freq_range;
power_rule = ®_rule->power_rule;
/*
* There may not be documentation for max antenna gain
* in certain regions
*/
if (power_rule->max_antenna_gain)
pr_info(" (%d KHz - %d KHz @ %d KHz), (%d mBi, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
freq_range->max_bandwidth_khz,
power_rule->max_antenna_gain,
power_rule->max_eirp);
else
pr_info(" (%d KHz - %d KHz @ %d KHz), (N/A, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
freq_range->max_bandwidth_khz,
power_rule->max_eirp);
}
}
static void print_regdomain(const struct ieee80211_regdomain *rd)
{
if (is_intersected_alpha2(rd->alpha2)) {
if (last_request->initiator ==
NL80211_REGDOM_SET_BY_COUNTRY_IE) {
struct cfg80211_registered_device *rdev;
rdev = cfg80211_rdev_by_wiphy_idx(
last_request->wiphy_idx);
if (rdev) {
pr_info("Current regulatory domain updated by AP to: %c%c\n",
rdev->country_ie_alpha2[0],
rdev->country_ie_alpha2[1]);
} else
pr_info("Current regulatory domain intersected:\n");
} else
pr_info("Current regulatory domain intersected:\n");
} else if (is_world_regdom(rd->alpha2))
pr_info("World regulatory domain updated:\n");
else {
if (is_unknown_alpha2(rd->alpha2))
pr_info("Regulatory domain changed to driver built-in settings (unknown country)\n");
else
pr_info("Regulatory domain changed to country: %c%c\n",
rd->alpha2[0], rd->alpha2[1]);
}
print_rd_rules(rd);
}
static void print_regdomain_info(const struct ieee80211_regdomain *rd)
{
pr_info("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]);
print_rd_rules(rd);
}
/* Takes ownership of rd only if it doesn't fail */
static int __set_regdom(const struct ieee80211_regdomain *rd)
{
const struct ieee80211_regdomain *intersected_rd = NULL;
struct cfg80211_registered_device *rdev = NULL;
struct wiphy *request_wiphy;
/* Some basic sanity checks first */
if (is_world_regdom(rd->alpha2)) {
if (WARN_ON(!reg_is_valid_request(rd->alpha2)))
return -EINVAL;
update_world_regdomain(rd);
return 0;
}
if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) &&
!is_unknown_alpha2(rd->alpha2))
return -EINVAL;
if (!last_request)
return -EINVAL;
/*
* Lets only bother proceeding on the same alpha2 if the current
* rd is non static (it means CRDA was present and was used last)
* and the pending request came in from a country IE
*/
if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
/*
* If someone else asked us to change the rd lets only bother
* checking if the alpha2 changes if CRDA was already called
*/
if (!regdom_changes(rd->alpha2))
return -EINVAL;
}
/*
* Now lets set the regulatory domain, update all driver channels
* and finally inform them of what we have done, in case they want
* to review or adjust their own settings based on their own
* internal EEPROM data
*/
if (WARN_ON(!reg_is_valid_request(rd->alpha2)))
return -EINVAL;
if (!is_valid_rd(rd)) {
pr_err("Invalid regulatory domain detected:\n");
print_regdomain_info(rd);
return -EINVAL;
}
request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
if (!request_wiphy &&
(last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)) {
schedule_delayed_work(®_timeout, 0);
return -ENODEV;
}
if (!last_request->intersect) {
int r;
if (last_request->initiator != NL80211_REGDOM_SET_BY_DRIVER) {
reset_regdomains(false);
cfg80211_regdomain = rd;
return 0;
}
/*
* For a driver hint, lets copy the regulatory domain the
* driver wanted to the wiphy to deal with conflicts
*/
/*
* Userspace could have sent two replies with only
* one kernel request.
*/
if (request_wiphy->regd)
return -EALREADY;
r = reg_copy_regd(&request_wiphy->regd, rd);
if (r)
return r;
reset_regdomains(false);
cfg80211_regdomain = rd;
return 0;
}
/* Intersection requires a bit more work */
if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
intersected_rd = regdom_intersect(rd, cfg80211_regdomain);
if (!intersected_rd)
return -EINVAL;
/*
* We can trash what CRDA provided now.
* However if a driver requested this specific regulatory
* domain we keep it for its private use
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER)
request_wiphy->regd = rd;
else
kfree(rd);
rd = NULL;
reset_regdomains(false);
cfg80211_regdomain = intersected_rd;
return 0;
}
if (!intersected_rd)
return -EINVAL;
rdev = wiphy_to_dev(request_wiphy);
rdev->country_ie_alpha2[0] = rd->alpha2[0];
rdev->country_ie_alpha2[1] = rd->alpha2[1];
rdev->env = last_request->country_ie_env;
BUG_ON(intersected_rd == rd);
kfree(rd);
rd = NULL;
reset_regdomains(false);
cfg80211_regdomain = intersected_rd;
return 0;
}
/*
* Use this call to set the current regulatory domain. Conflicts with
* multiple drivers can be ironed out later. Caller must've already
* kmalloc'd the rd structure. Caller must hold cfg80211_mutex
*/
int set_regdom(const struct ieee80211_regdomain *rd)
{
int r;
assert_cfg80211_lock();
mutex_lock(®_mutex);
/* Note that this doesn't update the wiphys, this is done below */
r = __set_regdom(rd);
if (r) {
kfree(rd);
mutex_unlock(®_mutex);
return r;
}
/* This would make this whole thing pointless */
if (!last_request->intersect)
BUG_ON(rd != cfg80211_regdomain);
/* update all wiphys now with the new established regulatory domain */
update_all_wiphy_regulatory(last_request->initiator);
print_regdomain(cfg80211_regdomain);
nl80211_send_reg_change_event(last_request);
reg_set_request_processed();
mutex_unlock(®_mutex);
return r;
}
#ifdef CONFIG_HOTPLUG
int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
if (last_request && !last_request->processed) {
if (add_uevent_var(env, "COUNTRY=%c%c",
last_request->alpha2[0],
last_request->alpha2[1]))
return -ENOMEM;
}
return 0;
}
#else
int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
return -ENODEV;
}
#endif /* CONFIG_HOTPLUG */
/* Caller must hold cfg80211_mutex */
void reg_device_remove(struct wiphy *wiphy)
{
struct wiphy *request_wiphy = NULL;
assert_cfg80211_lock();
mutex_lock(®_mutex);
kfree(wiphy->regd);
if (last_request)
request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
if (!request_wiphy || request_wiphy != wiphy)
goto out;
last_request->wiphy_idx = WIPHY_IDX_STALE;
last_request->country_ie_env = ENVIRON_ANY;
out:
mutex_unlock(®_mutex);
}
static void reg_timeout_work(struct work_struct *work)
{
REG_DBG_PRINT("Timeout while waiting for CRDA to reply, "
"restoring regulatory settings");
restore_regulatory_settings(true);
}
int __init regulatory_init(void)
{
int err = 0;
reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0);
if (IS_ERR(reg_pdev))
return PTR_ERR(reg_pdev);
reg_pdev->dev.type = ®_device_type;
spin_lock_init(®_requests_lock);
spin_lock_init(®_pending_beacons_lock);
reg_regdb_size_check();
cfg80211_regdomain = cfg80211_world_regdom;
user_alpha2[0] = '9';
user_alpha2[1] = '7';
/* We always try to get an update for the static regdomain */
err = regulatory_hint_core(cfg80211_regdomain->alpha2);
if (err) {
if (err == -ENOMEM)
return err;
/*
* N.B. kobject_uevent_env() can fail mainly for when we're out
* memory which is handled and propagated appropriately above
* but it can also fail during a netlink_broadcast() or during
* early boot for call_usermodehelper(). For now treat these
* errors as non-fatal.
*/
pr_err("kobject_uevent_env() was unable to call CRDA during init\n");
#ifdef CONFIG_CFG80211_REG_DEBUG
/* We want to find out exactly why when debugging */
WARN_ON(err);
#endif
}
/*
* Finally, if the user set the module parameter treat it
* as a user hint.
*/
if (!is_world_regdom(ieee80211_regdom))
regulatory_hint_user(ieee80211_regdom);
return 0;
}
void /* __init_or_exit */ regulatory_exit(void)
{
struct regulatory_request *reg_request, *tmp;
struct reg_beacon *reg_beacon, *btmp;
cancel_work_sync(®_work);
cancel_delayed_work_sync(®_timeout);
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
reset_regdomains(true);
dev_set_uevent_suppress(®_pdev->dev, true);
platform_device_unregister(reg_pdev);
spin_lock_bh(®_pending_beacons_lock);
if (!list_empty(®_pending_beacons)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_pending_beacons, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
spin_unlock_bh(®_pending_beacons_lock);
if (!list_empty(®_beacon_list)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_beacon_list, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
spin_lock(®_requests_lock);
if (!list_empty(®_requests_list)) {
list_for_each_entry_safe(reg_request, tmp,
®_requests_list, list) {
list_del(®_request->list);
kfree(reg_request);
}
}
spin_unlock(®_requests_lock);
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
}
| gpl-2.0 |
keshav143/xenified-PV-kernel | drivers/of/of_mdio.c | 552 | 4947 | /*
* OF helpers for the MDIO (Ethernet PHY) API
*
* Copyright (c) 2009 Secret Lab Technologies, Ltd.
*
* This file is released under the GPLv2
*
* This file provides helper functions for extracting PHY device information
* out of the OpenFirmware device tree and using it to populate an mii_bus.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/netdevice.h>
#include <linux/err.h>
#include <linux/phy.h>
#include <linux/of.h>
#include <linux/of_mdio.h>
#include <linux/module.h>
MODULE_AUTHOR("Grant Likely <grant.likely@secretlab.ca>");
MODULE_LICENSE("GPL");
/**
* of_mdiobus_register - Register mii_bus and create PHYs from the device tree
* @mdio: pointer to mii_bus structure
* @np: pointer to device_node of MDIO bus.
*
* This function registers the mii_bus structure and registers a phy_device
* for each child node of @np.
*/
int of_mdiobus_register(struct mii_bus *mdio, struct device_node *np)
{
struct phy_device *phy;
struct device_node *child;
int rc, i;
/* Mask out all PHYs from auto probing. Instead the PHYs listed in
* the device tree are populated after the bus has been registered */
mdio->phy_mask = ~0;
/* Clear all the IRQ properties */
if (mdio->irq)
for (i=0; i<PHY_MAX_ADDR; i++)
mdio->irq[i] = PHY_POLL;
/* Register the MDIO bus */
rc = mdiobus_register(mdio);
if (rc)
return rc;
/* Loop over the child nodes and register a phy_device for each one */
for_each_child_of_node(np, child) {
const u32 *addr;
int len;
/* A PHY must have a reg property in the range [0-31] */
addr = of_get_property(child, "reg", &len);
if (!addr || len < sizeof(*addr) || *addr >= 32 || *addr < 0) {
dev_err(&mdio->dev, "%s has invalid PHY address\n",
child->full_name);
continue;
}
if (mdio->irq) {
mdio->irq[*addr] = irq_of_parse_and_map(child, 0);
if (!mdio->irq[*addr])
mdio->irq[*addr] = PHY_POLL;
}
phy = get_phy_device(mdio, *addr);
if (!phy) {
dev_err(&mdio->dev, "error probing PHY at address %i\n",
*addr);
continue;
}
phy_scan_fixups(phy);
/* Associate the OF node with the device structure so it
* can be looked up later */
of_node_get(child);
dev_archdata_set_node(&phy->dev.archdata, child);
/* All data is now stored in the phy struct; register it */
rc = phy_device_register(phy);
if (rc) {
phy_device_free(phy);
of_node_put(child);
continue;
}
dev_dbg(&mdio->dev, "registered phy %s at address %i\n",
child->name, *addr);
}
return 0;
}
EXPORT_SYMBOL(of_mdiobus_register);
/* Helper function for of_phy_find_device */
static int of_phy_match(struct device *dev, void *phy_np)
{
return dev_archdata_get_node(&dev->archdata) == phy_np;
}
/**
* of_phy_find_device - Give a PHY node, find the phy_device
* @phy_np: Pointer to the phy's device tree node
*
* Returns a pointer to the phy_device.
*/
struct phy_device *of_phy_find_device(struct device_node *phy_np)
{
struct device *d;
if (!phy_np)
return NULL;
d = bus_find_device(&mdio_bus_type, NULL, phy_np, of_phy_match);
return d ? to_phy_device(d) : NULL;
}
EXPORT_SYMBOL(of_phy_find_device);
/**
* of_phy_connect - Connect to the phy described in the device tree
* @dev: pointer to net_device claiming the phy
* @phy_np: Pointer to device tree node for the PHY
* @hndlr: Link state callback for the network device
* @iface: PHY data interface type
*
* Returns a pointer to the phy_device if successfull. NULL otherwise
*/
struct phy_device *of_phy_connect(struct net_device *dev,
struct device_node *phy_np,
void (*hndlr)(struct net_device *), u32 flags,
phy_interface_t iface)
{
struct phy_device *phy = of_phy_find_device(phy_np);
if (!phy)
return NULL;
return phy_connect_direct(dev, phy, hndlr, flags, iface) ? NULL : phy;
}
EXPORT_SYMBOL(of_phy_connect);
/**
* of_phy_connect_fixed_link - Parse fixed-link property and return a dummy phy
* @dev: pointer to net_device claiming the phy
* @hndlr: Link state callback for the network device
* @iface: PHY data interface type
*
* This function is a temporary stop-gap and will be removed soon. It is
* only to support the fs_enet, ucc_geth and gianfar Ethernet drivers. Do
* not call this function from new drivers.
*/
struct phy_device *of_phy_connect_fixed_link(struct net_device *dev,
void (*hndlr)(struct net_device *),
phy_interface_t iface)
{
struct device_node *net_np;
char bus_id[MII_BUS_ID_SIZE + 3];
struct phy_device *phy;
const u32 *phy_id;
int sz;
if (!dev->dev.parent)
return NULL;
net_np = dev_archdata_get_node(&dev->dev.parent->archdata);
if (!net_np)
return NULL;
phy_id = of_get_property(net_np, "fixed-link", &sz);
if (!phy_id || sz < sizeof(*phy_id))
return NULL;
sprintf(bus_id, PHY_ID_FMT, "0", phy_id[0]);
phy = phy_connect(dev, bus_id, hndlr, 0, iface);
return IS_ERR(phy) ? NULL : phy;
}
EXPORT_SYMBOL(of_phy_connect_fixed_link);
| gpl-2.0 |
gauravds/linux | drivers/gpu/drm/nouveau/nvkm/subdev/fuse/nv50.c | 552 | 2358 | /*
* Copyright 2014 Martin Peres
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Martin Peres
*/
#include "priv.h"
struct nv50_fuse_priv {
struct nvkm_fuse base;
spinlock_t fuse_enable_lock;
};
static u32
nv50_fuse_rd32(struct nvkm_object *object, u64 addr)
{
struct nv50_fuse_priv *priv = (void *)object;
unsigned long flags;
u32 fuse_enable, val;
/* racy if another part of nvkm start writing to this reg */
spin_lock_irqsave(&priv->fuse_enable_lock, flags);
fuse_enable = nv_mask(priv, 0x1084, 0x800, 0x800);
val = nv_rd32(priv, 0x21000 + addr);
nv_wr32(priv, 0x1084, fuse_enable);
spin_unlock_irqrestore(&priv->fuse_enable_lock, flags);
return val;
}
static int
nv50_fuse_ctor(struct nvkm_object *parent, struct nvkm_object *engine,
struct nvkm_oclass *oclass, void *data, u32 size,
struct nvkm_object **pobject)
{
struct nv50_fuse_priv *priv;
int ret;
ret = nvkm_fuse_create(parent, engine, oclass, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
spin_lock_init(&priv->fuse_enable_lock);
return 0;
}
struct nvkm_oclass
nv50_fuse_oclass = {
.handle = NV_SUBDEV(FUSE, 0x50),
.ofuncs = &(struct nvkm_ofuncs) {
.ctor = nv50_fuse_ctor,
.dtor = _nvkm_fuse_dtor,
.init = _nvkm_fuse_init,
.fini = _nvkm_fuse_fini,
.rd32 = nv50_fuse_rd32,
},
};
| gpl-2.0 |
SkrilaxCZ/android_kernel_motorola_omap3-common | arch/cris/arch-v10/drivers/sync_serial.c | 552 | 43873 | /*
* Simple synchronous serial port driver for ETRAX 100LX.
*
* Synchronous serial ports are used for continuous streamed data like audio.
* The default setting for this driver is compatible with the STA 013 MP3
* decoder. The driver can easily be tuned to fit other audio encoder/decoders
* and SPI
*
* Copyright (c) 2001-2008 Axis Communications AB
*
* Author: Mikael Starvik, Johan Adolfsson
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/major.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/smp_lock.h>
#include <linux/timer.h>
#include <asm/irq.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <arch/svinto.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/sync_serial.h>
#include <arch/io_interface_mux.h>
/* The receiver is a bit tricky beacuse of the continuous stream of data.*/
/* */
/* Three DMA descriptors are linked together. Each DMA descriptor is */
/* responsible for port->bufchunk of a common buffer. */
/* */
/* +---------------------------------------------+ */
/* | +----------+ +----------+ +----------+ | */
/* +-> | Descr[0] |-->| Descr[1] |-->| Descr[2] |-+ */
/* +----------+ +----------+ +----------+ */
/* | | | */
/* v v v */
/* +-------------------------------------+ */
/* | BUFFER | */
/* +-------------------------------------+ */
/* |<- data_avail ->| */
/* readp writep */
/* */
/* If the application keeps up the pace readp will be right after writep.*/
/* If the application can't keep the pace we have to throw away data. */
/* The idea is that readp should be ready with the data pointed out by */
/* Descr[i] when the DMA has filled in Descr[i+1]. */
/* Otherwise we will discard */
/* the rest of the data pointed out by Descr1 and set readp to the start */
/* of Descr2 */
#define SYNC_SERIAL_MAJOR 125
/* IN_BUFFER_SIZE should be a multiple of 6 to make sure that 24 bit */
/* words can be handled */
#define IN_BUFFER_SIZE 12288
#define IN_DESCR_SIZE 256
#define NUM_IN_DESCR (IN_BUFFER_SIZE/IN_DESCR_SIZE)
#define OUT_BUFFER_SIZE 4096
#define DEFAULT_FRAME_RATE 0
#define DEFAULT_WORD_RATE 7
/* NOTE: Enabling some debug will likely cause overrun or underrun,
* especially if manual mode is use.
*/
#define DEBUG(x)
#define DEBUGREAD(x)
#define DEBUGWRITE(x)
#define DEBUGPOLL(x)
#define DEBUGRXINT(x)
#define DEBUGTXINT(x)
/* Define some macros to access ETRAX 100 registers */
#define SETF(var, reg, field, val) \
do { \
var = (var & ~IO_MASK_(reg##_, field##_)) | \
IO_FIELD_(reg##_, field##_, val); \
} while (0)
#define SETS(var, reg, field, val) \
do { \
var = (var & ~IO_MASK_(reg##_, field##_)) | \
IO_STATE_(reg##_, field##_, _##val); \
} while (0)
struct sync_port {
/* Etrax registers and bits*/
const volatile unsigned *const status;
volatile unsigned *const ctrl_data;
volatile unsigned *const output_dma_first;
volatile unsigned char *const output_dma_cmd;
volatile unsigned char *const output_dma_clr_irq;
volatile unsigned *const input_dma_first;
volatile unsigned char *const input_dma_cmd;
volatile unsigned *const input_dma_descr;
/* 8*4 */
volatile unsigned char *const input_dma_clr_irq;
volatile unsigned *const data_out;
const volatile unsigned *const data_in;
char data_avail_bit; /* In R_IRQ_MASK1_RD/SET/CLR */
char transmitter_ready_bit; /* In R_IRQ_MASK1_RD/SET/CLR */
char input_dma_descr_bit; /* In R_IRQ_MASK2_RD */
char output_dma_bit; /* In R_IRQ_MASK2_RD */
/* End of fields initialised in array */
char started; /* 1 if port has been started */
char port_nbr; /* Port 0 or 1 */
char busy; /* 1 if port is busy */
char enabled; /* 1 if port is enabled */
char use_dma; /* 1 if port uses dma */
char tr_running;
char init_irqs;
/* Register shadow */
unsigned int ctrl_data_shadow;
/* Remaining bytes for current transfer */
volatile unsigned int out_count;
/* Current position in out_buffer */
unsigned char *outp;
/* 16*4 */
/* Next byte to be read by application */
volatile unsigned char *volatile readp;
/* Next byte to be written by etrax */
volatile unsigned char *volatile writep;
unsigned int in_buffer_size;
unsigned int inbufchunk;
struct etrax_dma_descr out_descr __attribute__ ((aligned(32)));
struct etrax_dma_descr in_descr[NUM_IN_DESCR] __attribute__ ((aligned(32)));
unsigned char out_buffer[OUT_BUFFER_SIZE] __attribute__ ((aligned(32)));
unsigned char in_buffer[IN_BUFFER_SIZE]__attribute__ ((aligned(32)));
unsigned char flip[IN_BUFFER_SIZE] __attribute__ ((aligned(32)));
struct etrax_dma_descr *next_rx_desc;
struct etrax_dma_descr *prev_rx_desc;
int full;
wait_queue_head_t out_wait_q;
wait_queue_head_t in_wait_q;
};
static int etrax_sync_serial_init(void);
static void initialize_port(int portnbr);
static inline int sync_data_avail(struct sync_port *port);
static int sync_serial_open(struct inode *inode, struct file *file);
static int sync_serial_release(struct inode *inode, struct file *file);
static unsigned int sync_serial_poll(struct file *filp, poll_table *wait);
static int sync_serial_ioctl(struct inode *inode, struct file *file,
unsigned int cmd, unsigned long arg);
static ssize_t sync_serial_write(struct file *file, const char *buf,
size_t count, loff_t *ppos);
static ssize_t sync_serial_read(struct file *file, char *buf,
size_t count, loff_t *ppos);
#if ((defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT0) && \
defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL0_DMA)) || \
(defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT1) && \
defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL1_DMA)))
#define SYNC_SER_DMA
#endif
static void send_word(struct sync_port *port);
static void start_dma(struct sync_port *port, const char *data, int count);
static void start_dma_in(struct sync_port *port);
#ifdef SYNC_SER_DMA
static irqreturn_t tr_interrupt(int irq, void *dev_id);
static irqreturn_t rx_interrupt(int irq, void *dev_id);
#endif
#if ((defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT0) && \
!defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL0_DMA)) || \
(defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT1) && \
!defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL1_DMA)))
#define SYNC_SER_MANUAL
#endif
#ifdef SYNC_SER_MANUAL
static irqreturn_t manual_interrupt(int irq, void *dev_id);
#endif
/* The ports */
static struct sync_port ports[] = {
{
.status = R_SYNC_SERIAL1_STATUS,
.ctrl_data = R_SYNC_SERIAL1_CTRL,
.output_dma_first = R_DMA_CH8_FIRST,
.output_dma_cmd = R_DMA_CH8_CMD,
.output_dma_clr_irq = R_DMA_CH8_CLR_INTR,
.input_dma_first = R_DMA_CH9_FIRST,
.input_dma_cmd = R_DMA_CH9_CMD,
.input_dma_descr = R_DMA_CH9_DESCR,
.input_dma_clr_irq = R_DMA_CH9_CLR_INTR,
.data_out = R_SYNC_SERIAL1_TR_DATA,
.data_in = R_SYNC_SERIAL1_REC_DATA,
.data_avail_bit = IO_BITNR(R_IRQ_MASK1_RD, ser1_data),
.transmitter_ready_bit = IO_BITNR(R_IRQ_MASK1_RD, ser1_ready),
.input_dma_descr_bit = IO_BITNR(R_IRQ_MASK2_RD, dma9_descr),
.output_dma_bit = IO_BITNR(R_IRQ_MASK2_RD, dma8_eop),
.init_irqs = 1,
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL0_DMA)
.use_dma = 1,
#else
.use_dma = 0,
#endif
},
{
.status = R_SYNC_SERIAL3_STATUS,
.ctrl_data = R_SYNC_SERIAL3_CTRL,
.output_dma_first = R_DMA_CH4_FIRST,
.output_dma_cmd = R_DMA_CH4_CMD,
.output_dma_clr_irq = R_DMA_CH4_CLR_INTR,
.input_dma_first = R_DMA_CH5_FIRST,
.input_dma_cmd = R_DMA_CH5_CMD,
.input_dma_descr = R_DMA_CH5_DESCR,
.input_dma_clr_irq = R_DMA_CH5_CLR_INTR,
.data_out = R_SYNC_SERIAL3_TR_DATA,
.data_in = R_SYNC_SERIAL3_REC_DATA,
.data_avail_bit = IO_BITNR(R_IRQ_MASK1_RD, ser3_data),
.transmitter_ready_bit = IO_BITNR(R_IRQ_MASK1_RD, ser3_ready),
.input_dma_descr_bit = IO_BITNR(R_IRQ_MASK2_RD, dma5_descr),
.output_dma_bit = IO_BITNR(R_IRQ_MASK2_RD, dma4_eop),
.init_irqs = 1,
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL1_DMA)
.use_dma = 1,
#else
.use_dma = 0,
#endif
}
};
/* Register shadows */
static unsigned sync_serial_prescale_shadow;
#define NUMBER_OF_PORTS 2
static const struct file_operations sync_serial_fops = {
.owner = THIS_MODULE,
.write = sync_serial_write,
.read = sync_serial_read,
.poll = sync_serial_poll,
.ioctl = sync_serial_ioctl,
.open = sync_serial_open,
.release = sync_serial_release
};
static int __init etrax_sync_serial_init(void)
{
ports[0].enabled = 0;
ports[1].enabled = 0;
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT0)
if (cris_request_io_interface(if_sync_serial_1, "sync_ser1")) {
printk(KERN_CRIT "ETRAX100LX sync_serial: "
"Could not allocate IO group for port %d\n", 0);
return -EBUSY;
}
#endif
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT1)
if (cris_request_io_interface(if_sync_serial_3, "sync_ser3")) {
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT0)
cris_free_io_interface(if_sync_serial_1);
#endif
printk(KERN_CRIT "ETRAX100LX sync_serial: "
"Could not allocate IO group for port %d\n", 1);
return -EBUSY;
}
#endif
if (register_chrdev(SYNC_SERIAL_MAJOR, "sync serial",
&sync_serial_fops) < 0) {
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT1)
cris_free_io_interface(if_sync_serial_3);
#endif
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT0)
cris_free_io_interface(if_sync_serial_1);
#endif
printk("unable to get major for synchronous serial port\n");
return -EBUSY;
}
/* Deselect synchronous serial ports while configuring. */
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode1, async);
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode3, async);
*R_GEN_CONFIG_II = gen_config_ii_shadow;
/* Initialize Ports */
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT0)
ports[0].enabled = 1;
SETS(port_pb_i2c_shadow, R_PORT_PB_I2C, syncser1, ss1extra);
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode1, sync);
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL0_DMA)
ports[0].use_dma = 1;
#else
ports[0].use_dma = 0;
#endif
initialize_port(0);
#endif
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL_PORT1)
ports[1].enabled = 1;
SETS(port_pb_i2c_shadow, R_PORT_PB_I2C, syncser3, ss3extra);
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode3, sync);
#if defined(CONFIG_ETRAX_SYNCHRONOUS_SERIAL1_DMA)
ports[1].use_dma = 1;
#else
ports[1].use_dma = 0;
#endif
initialize_port(1);
#endif
*R_PORT_PB_I2C = port_pb_i2c_shadow; /* Use PB4/PB7 */
/* Set up timing */
*R_SYNC_SERIAL_PRESCALE = sync_serial_prescale_shadow = (
IO_STATE(R_SYNC_SERIAL_PRESCALE, clk_sel_u1, codec) |
IO_STATE(R_SYNC_SERIAL_PRESCALE, word_stb_sel_u1, external) |
IO_STATE(R_SYNC_SERIAL_PRESCALE, clk_sel_u3, codec) |
IO_STATE(R_SYNC_SERIAL_PRESCALE, word_stb_sel_u3, external) |
IO_STATE(R_SYNC_SERIAL_PRESCALE, prescaler, div4) |
IO_FIELD(R_SYNC_SERIAL_PRESCALE, frame_rate,
DEFAULT_FRAME_RATE) |
IO_FIELD(R_SYNC_SERIAL_PRESCALE, word_rate, DEFAULT_WORD_RATE) |
IO_STATE(R_SYNC_SERIAL_PRESCALE, warp_mode, normal));
/* Select synchronous ports */
*R_GEN_CONFIG_II = gen_config_ii_shadow;
printk(KERN_INFO "ETRAX 100LX synchronous serial port driver\n");
return 0;
}
static void __init initialize_port(int portnbr)
{
struct sync_port *port = &ports[portnbr];
DEBUG(printk(KERN_DEBUG "Init sync serial port %d\n", portnbr));
port->started = 0;
port->port_nbr = portnbr;
port->busy = 0;
port->tr_running = 0;
port->out_count = 0;
port->outp = port->out_buffer;
port->readp = port->flip;
port->writep = port->flip;
port->in_buffer_size = IN_BUFFER_SIZE;
port->inbufchunk = IN_DESCR_SIZE;
port->next_rx_desc = &port->in_descr[0];
port->prev_rx_desc = &port->in_descr[NUM_IN_DESCR-1];
port->prev_rx_desc->ctrl = d_eol;
init_waitqueue_head(&port->out_wait_q);
init_waitqueue_head(&port->in_wait_q);
port->ctrl_data_shadow =
IO_STATE(R_SYNC_SERIAL1_CTRL, tr_baud, c115k2Hz) |
IO_STATE(R_SYNC_SERIAL1_CTRL, mode, master_output) |
IO_STATE(R_SYNC_SERIAL1_CTRL, error, ignore) |
IO_STATE(R_SYNC_SERIAL1_CTRL, rec_enable, disable) |
IO_STATE(R_SYNC_SERIAL1_CTRL, f_synctype, normal) |
IO_STATE(R_SYNC_SERIAL1_CTRL, f_syncsize, word) |
IO_STATE(R_SYNC_SERIAL1_CTRL, f_sync, on) |
IO_STATE(R_SYNC_SERIAL1_CTRL, clk_mode, normal) |
IO_STATE(R_SYNC_SERIAL1_CTRL, clk_halt, stopped) |
IO_STATE(R_SYNC_SERIAL1_CTRL, bitorder, msb) |
IO_STATE(R_SYNC_SERIAL1_CTRL, tr_enable, disable) |
IO_STATE(R_SYNC_SERIAL1_CTRL, wordsize, size8bit) |
IO_STATE(R_SYNC_SERIAL1_CTRL, buf_empty, lmt_8) |
IO_STATE(R_SYNC_SERIAL1_CTRL, buf_full, lmt_8) |
IO_STATE(R_SYNC_SERIAL1_CTRL, flow_ctrl, enabled) |
IO_STATE(R_SYNC_SERIAL1_CTRL, clk_polarity, neg) |
IO_STATE(R_SYNC_SERIAL1_CTRL, frame_polarity, normal)|
IO_STATE(R_SYNC_SERIAL1_CTRL, status_polarity, inverted)|
IO_STATE(R_SYNC_SERIAL1_CTRL, clk_driver, normal) |
IO_STATE(R_SYNC_SERIAL1_CTRL, frame_driver, normal) |
IO_STATE(R_SYNC_SERIAL1_CTRL, status_driver, normal)|
IO_STATE(R_SYNC_SERIAL1_CTRL, def_out0, high);
if (port->use_dma)
port->ctrl_data_shadow |= IO_STATE(R_SYNC_SERIAL1_CTRL,
dma_enable, on);
else
port->ctrl_data_shadow |= IO_STATE(R_SYNC_SERIAL1_CTRL,
dma_enable, off);
*port->ctrl_data = port->ctrl_data_shadow;
}
static inline int sync_data_avail(struct sync_port *port)
{
int avail;
unsigned char *start;
unsigned char *end;
start = (unsigned char *)port->readp; /* cast away volatile */
end = (unsigned char *)port->writep; /* cast away volatile */
/* 0123456789 0123456789
* ----- - -----
* ^rp ^wp ^wp ^rp
*/
if (end >= start)
avail = end - start;
else
avail = port->in_buffer_size - (start - end);
return avail;
}
static inline int sync_data_avail_to_end(struct sync_port *port)
{
int avail;
unsigned char *start;
unsigned char *end;
start = (unsigned char *)port->readp; /* cast away volatile */
end = (unsigned char *)port->writep; /* cast away volatile */
/* 0123456789 0123456789
* ----- -----
* ^rp ^wp ^wp ^rp
*/
if (end >= start)
avail = end - start;
else
avail = port->flip + port->in_buffer_size - start;
return avail;
}
static int sync_serial_open(struct inode *inode, struct file *file)
{
int dev = MINOR(inode->i_rdev);
struct sync_port *port;
int mode;
int err = -EBUSY;
lock_kernel();
DEBUG(printk(KERN_DEBUG "Open sync serial port %d\n", dev));
if (dev < 0 || dev >= NUMBER_OF_PORTS || !ports[dev].enabled) {
DEBUG(printk(KERN_DEBUG "Invalid minor %d\n", dev));
err = -ENODEV;
goto out;
}
port = &ports[dev];
/* Allow open this device twice (assuming one reader and one writer) */
if (port->busy == 2) {
DEBUG(printk(KERN_DEBUG "Device is busy.. \n"));
goto out;
}
if (port->init_irqs) {
if (port->use_dma) {
if (port == &ports[0]) {
#ifdef SYNC_SER_DMA
if (request_irq(24, tr_interrupt, 0,
"synchronous serial 1 dma tr",
&ports[0])) {
printk(KERN_CRIT "Can't alloc "
"sync serial port 1 IRQ");
goto out;
} else if (request_irq(25, rx_interrupt, 0,
"synchronous serial 1 dma rx",
&ports[0])) {
free_irq(24, &port[0]);
printk(KERN_CRIT "Can't alloc "
"sync serial port 1 IRQ");
goto out;
} else if (cris_request_dma(8,
"synchronous serial 1 dma tr",
DMA_VERBOSE_ON_ERROR,
dma_ser1)) {
free_irq(24, &port[0]);
free_irq(25, &port[0]);
printk(KERN_CRIT "Can't alloc "
"sync serial port 1 "
"TX DMA channel");
goto out;
} else if (cris_request_dma(9,
"synchronous serial 1 dma rec",
DMA_VERBOSE_ON_ERROR,
dma_ser1)) {
cris_free_dma(8, NULL);
free_irq(24, &port[0]);
free_irq(25, &port[0]);
printk(KERN_CRIT "Can't alloc "
"sync serial port 1 "
"RX DMA channel");
goto out;
}
#endif
RESET_DMA(8); WAIT_DMA(8);
RESET_DMA(9); WAIT_DMA(9);
*R_DMA_CH8_CLR_INTR =
IO_STATE(R_DMA_CH8_CLR_INTR, clr_eop,
do) |
IO_STATE(R_DMA_CH8_CLR_INTR, clr_descr,
do);
*R_DMA_CH9_CLR_INTR =
IO_STATE(R_DMA_CH9_CLR_INTR, clr_eop,
do) |
IO_STATE(R_DMA_CH9_CLR_INTR, clr_descr,
do);
*R_IRQ_MASK2_SET =
IO_STATE(R_IRQ_MASK2_SET, dma8_eop,
set) |
IO_STATE(R_IRQ_MASK2_SET, dma9_descr,
set);
} else if (port == &ports[1]) {
#ifdef SYNC_SER_DMA
if (request_irq(20, tr_interrupt, 0,
"synchronous serial 3 dma tr",
&ports[1])) {
printk(KERN_CRIT "Can't alloc "
"sync serial port 3 IRQ");
goto out;
} else if (request_irq(21, rx_interrupt, 0,
"synchronous serial 3 dma rx",
&ports[1])) {
free_irq(20, &ports[1]);
printk(KERN_CRIT "Can't alloc "
"sync serial port 3 IRQ");
goto out;
} else if (cris_request_dma(4,
"synchronous serial 3 dma tr",
DMA_VERBOSE_ON_ERROR,
dma_ser3)) {
free_irq(21, &ports[1]);
free_irq(20, &ports[1]);
printk(KERN_CRIT "Can't alloc "
"sync serial port 3 "
"TX DMA channel");
goto out;
} else if (cris_request_dma(5,
"synchronous serial 3 dma rec",
DMA_VERBOSE_ON_ERROR,
dma_ser3)) {
cris_free_dma(4, NULL);
free_irq(21, &ports[1]);
free_irq(20, &ports[1]);
printk(KERN_CRIT "Can't alloc "
"sync serial port 3 "
"RX DMA channel");
goto out;
}
#endif
RESET_DMA(4); WAIT_DMA(4);
RESET_DMA(5); WAIT_DMA(5);
*R_DMA_CH4_CLR_INTR =
IO_STATE(R_DMA_CH4_CLR_INTR, clr_eop,
do) |
IO_STATE(R_DMA_CH4_CLR_INTR, clr_descr,
do);
*R_DMA_CH5_CLR_INTR =
IO_STATE(R_DMA_CH5_CLR_INTR, clr_eop,
do) |
IO_STATE(R_DMA_CH5_CLR_INTR, clr_descr,
do);
*R_IRQ_MASK2_SET =
IO_STATE(R_IRQ_MASK2_SET, dma4_eop,
set) |
IO_STATE(R_IRQ_MASK2_SET, dma5_descr,
set);
}
start_dma_in(port);
port->init_irqs = 0;
} else { /* !port->use_dma */
#ifdef SYNC_SER_MANUAL
if (port == &ports[0]) {
if (request_irq(8,
manual_interrupt,
IRQF_SHARED | IRQF_DISABLED,
"synchronous serial manual irq",
&ports[0])) {
printk(KERN_CRIT "Can't alloc "
"sync serial manual irq");
goto out;
}
} else if (port == &ports[1]) {
if (request_irq(8,
manual_interrupt,
IRQF_SHARED | IRQF_DISABLED,
"synchronous serial manual irq",
&ports[1])) {
printk(KERN_CRIT "Can't alloc "
"sync serial manual irq");
goto out;
}
}
port->init_irqs = 0;
#else
panic("sync_serial: Manual mode not supported.\n");
#endif /* SYNC_SER_MANUAL */
}
} /* port->init_irqs */
port->busy++;
/* Start port if we use it as input */
mode = IO_EXTRACT(R_SYNC_SERIAL1_CTRL, mode, port->ctrl_data_shadow);
if (mode == IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, mode, master_input) ||
mode == IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, mode, slave_input) ||
mode == IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, mode, master_bidir) ||
mode == IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, mode, slave_bidir)) {
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, clk_halt,
running);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, tr_enable,
enable);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, rec_enable,
enable);
port->started = 1;
*port->ctrl_data = port->ctrl_data_shadow;
if (!port->use_dma)
*R_IRQ_MASK1_SET = 1 << port->data_avail_bit;
DEBUG(printk(KERN_DEBUG "sser%d rec started\n", dev));
}
ret = 0;
out:
unlock_kernel();
return ret;
}
static int sync_serial_release(struct inode *inode, struct file *file)
{
int dev = MINOR(inode->i_rdev);
struct sync_port *port;
if (dev < 0 || dev >= NUMBER_OF_PORTS || !ports[dev].enabled) {
DEBUG(printk(KERN_DEBUG "Invalid minor %d\n", dev));
return -ENODEV;
}
port = &ports[dev];
if (port->busy)
port->busy--;
if (!port->busy)
*R_IRQ_MASK1_CLR = ((1 << port->data_avail_bit) |
(1 << port->transmitter_ready_bit));
return 0;
}
static unsigned int sync_serial_poll(struct file *file, poll_table *wait)
{
int dev = MINOR(file->f_dentry->d_inode->i_rdev);
unsigned int mask = 0;
struct sync_port *port;
DEBUGPOLL(static unsigned int prev_mask = 0);
port = &ports[dev];
poll_wait(file, &port->out_wait_q, wait);
poll_wait(file, &port->in_wait_q, wait);
/* Some room to write */
if (port->out_count < OUT_BUFFER_SIZE)
mask |= POLLOUT | POLLWRNORM;
/* At least an inbufchunk of data */
if (sync_data_avail(port) >= port->inbufchunk)
mask |= POLLIN | POLLRDNORM;
DEBUGPOLL(if (mask != prev_mask)
printk(KERN_DEBUG "sync_serial_poll: mask 0x%08X %s %s\n",
mask,
mask & POLLOUT ? "POLLOUT" : "",
mask & POLLIN ? "POLLIN" : "");
prev_mask = mask;
);
return mask;
}
static int sync_serial_ioctl(struct inode *inode, struct file *file,
unsigned int cmd, unsigned long arg)
{
int return_val = 0;
unsigned long flags;
int dev = MINOR(file->f_dentry->d_inode->i_rdev);
struct sync_port *port;
if (dev < 0 || dev >= NUMBER_OF_PORTS || !ports[dev].enabled) {
DEBUG(printk(KERN_DEBUG "Invalid minor %d\n", dev));
return -1;
}
port = &ports[dev];
local_irq_save(flags);
/* Disable port while changing config */
if (dev) {
if (port->use_dma) {
RESET_DMA(4); WAIT_DMA(4);
port->tr_running = 0;
port->out_count = 0;
port->outp = port->out_buffer;
*R_DMA_CH4_CLR_INTR =
IO_STATE(R_DMA_CH4_CLR_INTR, clr_eop, do) |
IO_STATE(R_DMA_CH4_CLR_INTR, clr_descr, do);
}
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode3, async);
} else {
if (port->use_dma) {
RESET_DMA(8); WAIT_DMA(8);
port->tr_running = 0;
port->out_count = 0;
port->outp = port->out_buffer;
*R_DMA_CH8_CLR_INTR =
IO_STATE(R_DMA_CH8_CLR_INTR, clr_eop, do) |
IO_STATE(R_DMA_CH8_CLR_INTR, clr_descr, do);
}
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode1, async);
}
*R_GEN_CONFIG_II = gen_config_ii_shadow;
local_irq_restore(flags);
switch (cmd) {
case SSP_SPEED:
if (GET_SPEED(arg) == CODEC) {
if (dev)
SETS(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, clk_sel_u3,
codec);
else
SETS(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, clk_sel_u1,
codec);
SETF(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, prescaler,
GET_FREQ(arg));
SETF(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, frame_rate,
GET_FRAME_RATE(arg));
SETF(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, word_rate,
GET_WORD_RATE(arg));
} else {
SETF(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
tr_baud, GET_SPEED(arg));
if (dev)
SETS(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, clk_sel_u3,
baudrate);
else
SETS(sync_serial_prescale_shadow,
R_SYNC_SERIAL_PRESCALE, clk_sel_u1,
baudrate);
}
break;
case SSP_MODE:
if (arg > 5)
return -EINVAL;
if (arg == MASTER_OUTPUT || arg == SLAVE_OUTPUT)
*R_IRQ_MASK1_CLR = 1 << port->data_avail_bit;
else if (!port->use_dma)
*R_IRQ_MASK1_SET = 1 << port->data_avail_bit;
SETF(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, mode, arg);
break;
case SSP_FRAME_SYNC:
if (arg & NORMAL_SYNC)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_synctype, normal);
else if (arg & EARLY_SYNC)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_synctype, early);
if (arg & BIT_SYNC)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_syncsize, bit);
else if (arg & WORD_SYNC)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_syncsize, word);
else if (arg & EXTENDED_SYNC)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_syncsize, extended);
if (arg & SYNC_ON)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_sync, on);
else if (arg & SYNC_OFF)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
f_sync, off);
if (arg & WORD_SIZE_8)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
wordsize, size8bit);
else if (arg & WORD_SIZE_12)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
wordsize, size12bit);
else if (arg & WORD_SIZE_16)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
wordsize, size16bit);
else if (arg & WORD_SIZE_24)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
wordsize, size24bit);
else if (arg & WORD_SIZE_32)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
wordsize, size32bit);
if (arg & BIT_ORDER_MSB)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
bitorder, msb);
else if (arg & BIT_ORDER_LSB)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
bitorder, lsb);
if (arg & FLOW_CONTROL_ENABLE)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
flow_ctrl, enabled);
else if (arg & FLOW_CONTROL_DISABLE)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
flow_ctrl, disabled);
if (arg & CLOCK_NOT_GATED)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_mode, normal);
else if (arg & CLOCK_GATED)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_mode, gated);
break;
case SSP_IPOLARITY:
/* NOTE!! negedge is considered NORMAL */
if (arg & CLOCK_NORMAL)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_polarity, neg);
else if (arg & CLOCK_INVERT)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_polarity, pos);
if (arg & FRAME_NORMAL)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
frame_polarity, normal);
else if (arg & FRAME_INVERT)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
frame_polarity, inverted);
if (arg & STATUS_NORMAL)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
status_polarity, normal);
else if (arg & STATUS_INVERT)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
status_polarity, inverted);
break;
case SSP_OPOLARITY:
if (arg & CLOCK_NORMAL)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_driver, normal);
else if (arg & CLOCK_INVERT)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_driver, inverted);
if (arg & FRAME_NORMAL)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
frame_driver, normal);
else if (arg & FRAME_INVERT)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
frame_driver, inverted);
if (arg & STATUS_NORMAL)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
status_driver, normal);
else if (arg & STATUS_INVERT)
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
status_driver, inverted);
break;
case SSP_SPI:
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, flow_ctrl,
disabled);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, bitorder,
msb);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, wordsize,
size8bit);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, f_sync, on);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, f_syncsize,
word);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, f_synctype,
normal);
if (arg & SPI_SLAVE) {
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
frame_polarity, inverted);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_polarity, neg);
SETF(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
mode, SLAVE_INPUT);
} else {
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
frame_driver, inverted);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
clk_driver, inverted);
SETF(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL,
mode, MASTER_OUTPUT);
}
break;
case SSP_INBUFCHUNK:
#if 0
if (arg > port->in_buffer_size/NUM_IN_DESCR)
return -EINVAL;
port->inbufchunk = arg;
/* Make sure in_buffer_size is a multiple of inbufchunk */
port->in_buffer_size =
(port->in_buffer_size/port->inbufchunk) *
port->inbufchunk;
DEBUG(printk(KERN_DEBUG "inbufchunk %i in_buffer_size: %i\n",
port->inbufchunk, port->in_buffer_size));
if (port->use_dma) {
if (port->port_nbr == 0) {
RESET_DMA(9);
WAIT_DMA(9);
} else {
RESET_DMA(5);
WAIT_DMA(5);
}
start_dma_in(port);
}
#endif
break;
default:
return_val = -1;
}
/* Make sure we write the config without interruption */
local_irq_save(flags);
/* Set config and enable port */
*port->ctrl_data = port->ctrl_data_shadow;
nop(); nop(); nop(); nop();
*R_SYNC_SERIAL_PRESCALE = sync_serial_prescale_shadow;
nop(); nop(); nop(); nop();
if (dev)
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode3, sync);
else
SETS(gen_config_ii_shadow, R_GEN_CONFIG_II, sermode1, sync);
*R_GEN_CONFIG_II = gen_config_ii_shadow;
/* Reset DMA. At readout from serial port the data could be shifted
* one byte if not resetting DMA.
*/
if (port->use_dma) {
if (port->port_nbr == 0) {
RESET_DMA(9);
WAIT_DMA(9);
} else {
RESET_DMA(5);
WAIT_DMA(5);
}
start_dma_in(port);
}
local_irq_restore(flags);
return return_val;
}
static ssize_t sync_serial_write(struct file *file, const char *buf,
size_t count, loff_t *ppos)
{
int dev = MINOR(file->f_dentry->d_inode->i_rdev);
DECLARE_WAITQUEUE(wait, current);
struct sync_port *port;
unsigned long flags;
unsigned long c, c1;
unsigned long free_outp;
unsigned long outp;
unsigned long out_buffer;
if (dev < 0 || dev >= NUMBER_OF_PORTS || !ports[dev].enabled) {
DEBUG(printk(KERN_DEBUG "Invalid minor %d\n", dev));
return -ENODEV;
}
port = &ports[dev];
DEBUGWRITE(printk(KERN_DEBUG "W d%d c %lu (%d/%d)\n",
port->port_nbr, count, port->out_count, OUT_BUFFER_SIZE));
/* Space to end of buffer */
/*
* out_buffer <c1>012345<- c ->OUT_BUFFER_SIZE
* outp^ +out_count
* ^free_outp
* out_buffer 45<- c ->0123OUT_BUFFER_SIZE
* +out_count outp^
* free_outp
*
*/
/* Read variables that may be updated by interrupts */
local_irq_save(flags);
if (count > OUT_BUFFER_SIZE - port->out_count)
count = OUT_BUFFER_SIZE - port->out_count;
outp = (unsigned long)port->outp;
free_outp = outp + port->out_count;
local_irq_restore(flags);
out_buffer = (unsigned long)port->out_buffer;
/* Find out where and how much to write */
if (free_outp >= out_buffer + OUT_BUFFER_SIZE)
free_outp -= OUT_BUFFER_SIZE;
if (free_outp >= outp)
c = out_buffer + OUT_BUFFER_SIZE - free_outp;
else
c = outp - free_outp;
if (c > count)
c = count;
DEBUGWRITE(printk(KERN_DEBUG "w op %08lX fop %08lX c %lu\n",
outp, free_outp, c));
if (copy_from_user((void *)free_outp, buf, c))
return -EFAULT;
if (c != count) {
buf += c;
c1 = count - c;
DEBUGWRITE(printk(KERN_DEBUG "w2 fi %lu c %lu c1 %lu\n",
free_outp-out_buffer, c, c1));
if (copy_from_user((void *)out_buffer, buf, c1))
return -EFAULT;
}
local_irq_save(flags);
port->out_count += count;
local_irq_restore(flags);
/* Make sure transmitter/receiver is running */
if (!port->started) {
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, clk_halt,
running);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, tr_enable,
enable);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, rec_enable,
enable);
port->started = 1;
}
*port->ctrl_data = port->ctrl_data_shadow;
if (file->f_flags & O_NONBLOCK) {
local_irq_save(flags);
if (!port->tr_running) {
if (!port->use_dma) {
/* Start sender by writing data */
send_word(port);
/* and enable transmitter ready IRQ */
*R_IRQ_MASK1_SET = 1 <<
port->transmitter_ready_bit;
} else
start_dma(port,
(unsigned char *volatile)port->outp, c);
}
local_irq_restore(flags);
DEBUGWRITE(printk(KERN_DEBUG "w d%d c %lu NB\n",
port->port_nbr, count));
return count;
}
/* Sleep until all sent */
add_wait_queue(&port->out_wait_q, &wait);
set_current_state(TASK_INTERRUPTIBLE);
local_irq_save(flags);
if (!port->tr_running) {
if (!port->use_dma) {
/* Start sender by writing data */
send_word(port);
/* and enable transmitter ready IRQ */
*R_IRQ_MASK1_SET = 1 << port->transmitter_ready_bit;
} else
start_dma(port, port->outp, c);
}
local_irq_restore(flags);
schedule();
set_current_state(TASK_RUNNING);
remove_wait_queue(&port->out_wait_q, &wait);
if (signal_pending(current))
return -EINTR;
DEBUGWRITE(printk(KERN_DEBUG "w d%d c %lu\n", port->port_nbr, count));
return count;
}
static ssize_t sync_serial_read(struct file *file, char *buf,
size_t count, loff_t *ppos)
{
int dev = MINOR(file->f_dentry->d_inode->i_rdev);
int avail;
struct sync_port *port;
unsigned char *start;
unsigned char *end;
unsigned long flags;
if (dev < 0 || dev >= NUMBER_OF_PORTS || !ports[dev].enabled) {
DEBUG(printk(KERN_DEBUG "Invalid minor %d\n", dev));
return -ENODEV;
}
port = &ports[dev];
DEBUGREAD(printk(KERN_DEBUG "R%d c %d ri %lu wi %lu /%lu\n",
dev, count, port->readp - port->flip,
port->writep - port->flip, port->in_buffer_size));
if (!port->started) {
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, clk_halt,
running);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, tr_enable,
enable);
SETS(port->ctrl_data_shadow, R_SYNC_SERIAL1_CTRL, rec_enable,
enable);
port->started = 1;
}
*port->ctrl_data = port->ctrl_data_shadow;
/* Calculate number of available bytes */
/* Save pointers to avoid that they are modified by interrupt */
local_irq_save(flags);
start = (unsigned char *)port->readp; /* cast away volatile */
end = (unsigned char *)port->writep; /* cast away volatile */
local_irq_restore(flags);
while (start == end && !port->full) {
/* No data */
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
interruptible_sleep_on(&port->in_wait_q);
if (signal_pending(current))
return -EINTR;
local_irq_save(flags);
start = (unsigned char *)port->readp; /* cast away volatile */
end = (unsigned char *)port->writep; /* cast away volatile */
local_irq_restore(flags);
}
/* Lazy read, never return wrapped data. */
if (port->full)
avail = port->in_buffer_size;
else if (end > start)
avail = end - start;
else
avail = port->flip + port->in_buffer_size - start;
count = count > avail ? avail : count;
if (copy_to_user(buf, start, count))
return -EFAULT;
/* Disable interrupts while updating readp */
local_irq_save(flags);
port->readp += count;
if (port->readp >= port->flip + port->in_buffer_size) /* Wrap? */
port->readp = port->flip;
port->full = 0;
local_irq_restore(flags);
DEBUGREAD(printk(KERN_DEBUG "r %d\n", count));
return count;
}
static void send_word(struct sync_port *port)
{
switch (IO_EXTRACT(R_SYNC_SERIAL1_CTRL, wordsize,
port->ctrl_data_shadow)) {
case IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, wordsize, size8bit):
port->out_count--;
*port->data_out = *port->outp++;
if (port->outp >= port->out_buffer + OUT_BUFFER_SIZE)
port->outp = port->out_buffer;
break;
case IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, wordsize, size12bit):
{
int data = (*port->outp++) << 8;
data |= *port->outp++;
port->out_count -= 2;
*port->data_out = data;
if (port->outp >= port->out_buffer + OUT_BUFFER_SIZE)
port->outp = port->out_buffer;
break;
}
case IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, wordsize, size16bit):
port->out_count -= 2;
*port->data_out = *(unsigned short *)port->outp;
port->outp += 2;
if (port->outp >= port->out_buffer + OUT_BUFFER_SIZE)
port->outp = port->out_buffer;
break;
case IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, wordsize, size24bit):
port->out_count -= 3;
*port->data_out = *(unsigned int *)port->outp;
port->outp += 3;
if (port->outp >= port->out_buffer + OUT_BUFFER_SIZE)
port->outp = port->out_buffer;
break;
case IO_STATE_VALUE(R_SYNC_SERIAL1_CTRL, wordsize, size32bit):
port->out_count -= 4;
*port->data_out = *(unsigned int *)port->outp;
port->outp += 4;
if (port->outp >= port->out_buffer + OUT_BUFFER_SIZE)
port->outp = port->out_buffer;
break;
}
}
static void start_dma(struct sync_port *port, const char *data, int count)
{
port->tr_running = 1;
port->out_descr.hw_len = 0;
port->out_descr.next = 0;
port->out_descr.ctrl = d_eol | d_eop; /* No d_wait to avoid glitches */
port->out_descr.sw_len = count;
port->out_descr.buf = virt_to_phys(data);
port->out_descr.status = 0;
*port->output_dma_first = virt_to_phys(&port->out_descr);
*port->output_dma_cmd = IO_STATE(R_DMA_CH0_CMD, cmd, start);
DEBUGTXINT(printk(KERN_DEBUG "dma %08lX c %d\n",
(unsigned long)data, count));
}
static void start_dma_in(struct sync_port *port)
{
int i;
unsigned long buf;
port->writep = port->flip;
if (port->writep > port->flip + port->in_buffer_size) {
panic("Offset too large in sync serial driver\n");
return;
}
buf = virt_to_phys(port->in_buffer);
for (i = 0; i < NUM_IN_DESCR; i++) {
port->in_descr[i].sw_len = port->inbufchunk;
port->in_descr[i].ctrl = d_int;
port->in_descr[i].next = virt_to_phys(&port->in_descr[i+1]);
port->in_descr[i].buf = buf;
port->in_descr[i].hw_len = 0;
port->in_descr[i].status = 0;
port->in_descr[i].fifo_len = 0;
buf += port->inbufchunk;
prepare_rx_descriptor(&port->in_descr[i]);
}
/* Link the last descriptor to the first */
port->in_descr[i-1].next = virt_to_phys(&port->in_descr[0]);
port->in_descr[i-1].ctrl |= d_eol;
port->next_rx_desc = &port->in_descr[0];
port->prev_rx_desc = &port->in_descr[NUM_IN_DESCR - 1];
*port->input_dma_first = virt_to_phys(port->next_rx_desc);
*port->input_dma_cmd = IO_STATE(R_DMA_CH0_CMD, cmd, start);
}
#ifdef SYNC_SER_DMA
static irqreturn_t tr_interrupt(int irq, void *dev_id)
{
unsigned long ireg = *R_IRQ_MASK2_RD;
struct etrax_dma_descr *descr;
unsigned int sentl;
int handled = 0;
int i;
for (i = 0; i < NUMBER_OF_PORTS; i++) {
struct sync_port *port = &ports[i];
if (!port->enabled || !port->use_dma)
continue;
/* IRQ active for the port? */
if (!(ireg & (1 << port->output_dma_bit)))
continue;
handled = 1;
/* Clear IRQ */
*port->output_dma_clr_irq =
IO_STATE(R_DMA_CH0_CLR_INTR, clr_eop, do) |
IO_STATE(R_DMA_CH0_CLR_INTR, clr_descr, do);
descr = &port->out_descr;
if (!(descr->status & d_stop))
sentl = descr->sw_len;
else
/* Otherwise find amount of data sent here */
sentl = descr->hw_len;
port->out_count -= sentl;
port->outp += sentl;
if (port->outp >= port->out_buffer + OUT_BUFFER_SIZE)
port->outp = port->out_buffer;
if (port->out_count) {
int c = port->out_buffer + OUT_BUFFER_SIZE - port->outp;
if (c > port->out_count)
c = port->out_count;
DEBUGTXINT(printk(KERN_DEBUG
"tx_int DMAWRITE %i %i\n", sentl, c));
start_dma(port, port->outp, c);
} else {
DEBUGTXINT(printk(KERN_DEBUG
"tx_int DMA stop %i\n", sentl));
port->tr_running = 0;
}
/* wake up the waiting process */
wake_up_interruptible(&port->out_wait_q);
}
return IRQ_RETVAL(handled);
} /* tr_interrupt */
static irqreturn_t rx_interrupt(int irq, void *dev_id)
{
unsigned long ireg = *R_IRQ_MASK2_RD;
int i;
int handled = 0;
for (i = 0; i < NUMBER_OF_PORTS; i++) {
struct sync_port *port = &ports[i];
if (!port->enabled || !port->use_dma)
continue;
if (!(ireg & (1 << port->input_dma_descr_bit)))
continue;
/* Descriptor interrupt */
handled = 1;
while (*port->input_dma_descr !=
virt_to_phys(port->next_rx_desc)) {
if (port->writep + port->inbufchunk > port->flip +
port->in_buffer_size) {
int first_size = port->flip +
port->in_buffer_size - port->writep;
memcpy(port->writep,
phys_to_virt(port->next_rx_desc->buf),
first_size);
memcpy(port->flip,
phys_to_virt(port->next_rx_desc->buf +
first_size),
port->inbufchunk - first_size);
port->writep = port->flip +
port->inbufchunk - first_size;
} else {
memcpy(port->writep,
phys_to_virt(port->next_rx_desc->buf),
port->inbufchunk);
port->writep += port->inbufchunk;
if (port->writep >= port->flip
+ port->in_buffer_size)
port->writep = port->flip;
}
if (port->writep == port->readp)
port->full = 1;
prepare_rx_descriptor(port->next_rx_desc);
port->next_rx_desc->ctrl |= d_eol;
port->prev_rx_desc->ctrl &= ~d_eol;
port->prev_rx_desc = phys_to_virt((unsigned)
port->next_rx_desc);
port->next_rx_desc = phys_to_virt((unsigned)
port->next_rx_desc->next);
/* Wake up the waiting process */
wake_up_interruptible(&port->in_wait_q);
*port->input_dma_cmd = IO_STATE(R_DMA_CH1_CMD,
cmd, restart);
/* DMA has reached end of descriptor */
*port->input_dma_clr_irq = IO_STATE(R_DMA_CH0_CLR_INTR,
clr_descr, do);
}
}
return IRQ_RETVAL(handled);
} /* rx_interrupt */
#endif /* SYNC_SER_DMA */
#ifdef SYNC_SER_MANUAL
static irqreturn_t manual_interrupt(int irq, void *dev_id)
{
int i;
int handled = 0;
for (i = 0; i < NUMBER_OF_PORTS; i++) {
struct sync_port *port = &ports[i];
if (!port->enabled || port->use_dma)
continue;
/* Data received? */
if (*R_IRQ_MASK1_RD & (1 << port->data_avail_bit)) {
handled = 1;
/* Read data */
switch (port->ctrl_data_shadow &
IO_MASK(R_SYNC_SERIAL1_CTRL, wordsize)) {
case IO_STATE(R_SYNC_SERIAL1_CTRL, wordsize, size8bit):
*port->writep++ =
*(volatile char *)port->data_in;
break;
case IO_STATE(R_SYNC_SERIAL1_CTRL, wordsize, size12bit):
{
int data = *(unsigned short *)port->data_in;
*port->writep = (data & 0x0ff0) >> 4;
*(port->writep + 1) = data & 0x0f;
port->writep += 2;
break;
}
case IO_STATE(R_SYNC_SERIAL1_CTRL, wordsize, size16bit):
*(unsigned short *)port->writep =
*(volatile unsigned short *)port->data_in;
port->writep += 2;
break;
case IO_STATE(R_SYNC_SERIAL1_CTRL, wordsize, size24bit):
*(unsigned int *)port->writep = *port->data_in;
port->writep += 3;
break;
case IO_STATE(R_SYNC_SERIAL1_CTRL, wordsize, size32bit):
*(unsigned int *)port->writep = *port->data_in;
port->writep += 4;
break;
}
/* Wrap? */
if (port->writep >= port->flip + port->in_buffer_size)
port->writep = port->flip;
if (port->writep == port->readp) {
/* Receive buffer overrun, discard oldest */
port->readp++;
/* Wrap? */
if (port->readp >= port->flip +
port->in_buffer_size)
port->readp = port->flip;
}
if (sync_data_avail(port) >= port->inbufchunk) {
/* Wake up application */
wake_up_interruptible(&port->in_wait_q);
}
}
/* Transmitter ready? */
if (*R_IRQ_MASK1_RD & (1 << port->transmitter_ready_bit)) {
if (port->out_count > 0) {
/* More data to send */
send_word(port);
} else {
/* Transmission finished */
/* Turn off IRQ */
*R_IRQ_MASK1_CLR = 1 <<
port->transmitter_ready_bit;
/* Wake up application */
wake_up_interruptible(&port->out_wait_q);
}
}
}
return IRQ_RETVAL(handled);
}
#endif
module_init(etrax_sync_serial_init);
| gpl-2.0 |
imoseyon/leanKernel-i500-gingerbread | drivers/input/mousedev.c | 808 | 26333 | /*
* Input driver to ExplorerPS/2 device driver module.
*
* Copyright (c) 1999-2002 Vojtech Pavlik
* Copyright (c) 2004 Dmitry Torokhov
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#define MOUSEDEV_MINOR_BASE 32
#define MOUSEDEV_MINORS 32
#define MOUSEDEV_MIX 31
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/random.h>
#include <linux/major.h>
#include <linux/device.h>
#ifdef CONFIG_INPUT_MOUSEDEV_PSAUX
#include <linux/miscdevice.h>
#endif
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION("Mouse (ExplorerPS/2) device interfaces");
MODULE_LICENSE("GPL");
#ifndef CONFIG_INPUT_MOUSEDEV_SCREEN_X
#define CONFIG_INPUT_MOUSEDEV_SCREEN_X 1024
#endif
#ifndef CONFIG_INPUT_MOUSEDEV_SCREEN_Y
#define CONFIG_INPUT_MOUSEDEV_SCREEN_Y 768
#endif
static int xres = CONFIG_INPUT_MOUSEDEV_SCREEN_X;
module_param(xres, uint, 0644);
MODULE_PARM_DESC(xres, "Horizontal screen resolution");
static int yres = CONFIG_INPUT_MOUSEDEV_SCREEN_Y;
module_param(yres, uint, 0644);
MODULE_PARM_DESC(yres, "Vertical screen resolution");
static unsigned tap_time = 200;
module_param(tap_time, uint, 0644);
MODULE_PARM_DESC(tap_time, "Tap time for touchpads in absolute mode (msecs)");
struct mousedev_hw_data {
int dx, dy, dz;
int x, y;
int abs_event;
unsigned long buttons;
};
struct mousedev {
int exist;
int open;
int minor;
struct input_handle handle;
wait_queue_head_t wait;
struct list_head client_list;
spinlock_t client_lock; /* protects client_list */
struct mutex mutex;
struct device dev;
struct list_head mixdev_node;
int mixdev_open;
struct mousedev_hw_data packet;
unsigned int pkt_count;
int old_x[4], old_y[4];
int frac_dx, frac_dy;
unsigned long touch;
};
enum mousedev_emul {
MOUSEDEV_EMUL_PS2,
MOUSEDEV_EMUL_IMPS,
MOUSEDEV_EMUL_EXPS
};
struct mousedev_motion {
int dx, dy, dz;
unsigned long buttons;
};
#define PACKET_QUEUE_LEN 16
struct mousedev_client {
struct fasync_struct *fasync;
struct mousedev *mousedev;
struct list_head node;
struct mousedev_motion packets[PACKET_QUEUE_LEN];
unsigned int head, tail;
spinlock_t packet_lock;
int pos_x, pos_y;
signed char ps2[6];
unsigned char ready, buffer, bufsiz;
unsigned char imexseq, impsseq;
enum mousedev_emul mode;
unsigned long last_buttons;
};
#define MOUSEDEV_SEQ_LEN 6
static unsigned char mousedev_imps_seq[] = { 0xf3, 200, 0xf3, 100, 0xf3, 80 };
static unsigned char mousedev_imex_seq[] = { 0xf3, 200, 0xf3, 200, 0xf3, 80 };
static struct input_handler mousedev_handler;
static struct mousedev *mousedev_table[MOUSEDEV_MINORS];
static DEFINE_MUTEX(mousedev_table_mutex);
static struct mousedev *mousedev_mix;
static LIST_HEAD(mousedev_mix_list);
static void mixdev_open_devices(void);
static void mixdev_close_devices(void);
#define fx(i) (mousedev->old_x[(mousedev->pkt_count - (i)) & 03])
#define fy(i) (mousedev->old_y[(mousedev->pkt_count - (i)) & 03])
static void mousedev_touchpad_event(struct input_dev *dev,
struct mousedev *mousedev,
unsigned int code, int value)
{
int size, tmp;
enum { FRACTION_DENOM = 128 };
switch (code) {
case ABS_X:
fx(0) = value;
if (mousedev->touch && mousedev->pkt_count >= 2) {
size = dev->absmax[ABS_X] - dev->absmin[ABS_X];
if (size == 0)
size = 256 * 2;
tmp = ((value - fx(2)) * 256 * FRACTION_DENOM) / size;
tmp += mousedev->frac_dx;
mousedev->packet.dx = tmp / FRACTION_DENOM;
mousedev->frac_dx =
tmp - mousedev->packet.dx * FRACTION_DENOM;
}
break;
case ABS_Y:
fy(0) = value;
if (mousedev->touch && mousedev->pkt_count >= 2) {
/* use X size to keep the same scale */
size = dev->absmax[ABS_X] - dev->absmin[ABS_X];
if (size == 0)
size = 256 * 2;
tmp = -((value - fy(2)) * 256 * FRACTION_DENOM) / size;
tmp += mousedev->frac_dy;
mousedev->packet.dy = tmp / FRACTION_DENOM;
mousedev->frac_dy = tmp -
mousedev->packet.dy * FRACTION_DENOM;
}
break;
}
}
static void mousedev_abs_event(struct input_dev *dev, struct mousedev *mousedev,
unsigned int code, int value)
{
int size;
switch (code) {
case ABS_X:
size = dev->absmax[ABS_X] - dev->absmin[ABS_X];
if (size == 0)
size = xres ? : 1;
if (value > dev->absmax[ABS_X])
value = dev->absmax[ABS_X];
if (value < dev->absmin[ABS_X])
value = dev->absmin[ABS_X];
mousedev->packet.x =
((value - dev->absmin[ABS_X]) * xres) / size;
mousedev->packet.abs_event = 1;
break;
case ABS_Y:
size = dev->absmax[ABS_Y] - dev->absmin[ABS_Y];
if (size == 0)
size = yres ? : 1;
if (value > dev->absmax[ABS_Y])
value = dev->absmax[ABS_Y];
if (value < dev->absmin[ABS_Y])
value = dev->absmin[ABS_Y];
mousedev->packet.y = yres -
((value - dev->absmin[ABS_Y]) * yres) / size;
mousedev->packet.abs_event = 1;
break;
}
}
static void mousedev_rel_event(struct mousedev *mousedev,
unsigned int code, int value)
{
switch (code) {
case REL_X:
mousedev->packet.dx += value;
break;
case REL_Y:
mousedev->packet.dy -= value;
break;
case REL_WHEEL:
mousedev->packet.dz -= value;
break;
}
}
static void mousedev_key_event(struct mousedev *mousedev,
unsigned int code, int value)
{
int index;
switch (code) {
case BTN_TOUCH:
case BTN_0:
case BTN_LEFT: index = 0; break;
case BTN_STYLUS:
case BTN_1:
case BTN_RIGHT: index = 1; break;
case BTN_2:
case BTN_FORWARD:
case BTN_STYLUS2:
case BTN_MIDDLE: index = 2; break;
case BTN_3:
case BTN_BACK:
case BTN_SIDE: index = 3; break;
case BTN_4:
case BTN_EXTRA: index = 4; break;
default: return;
}
if (value) {
set_bit(index, &mousedev->packet.buttons);
set_bit(index, &mousedev_mix->packet.buttons);
} else {
clear_bit(index, &mousedev->packet.buttons);
clear_bit(index, &mousedev_mix->packet.buttons);
}
}
static void mousedev_notify_readers(struct mousedev *mousedev,
struct mousedev_hw_data *packet)
{
struct mousedev_client *client;
struct mousedev_motion *p;
unsigned int new_head;
int wake_readers = 0;
rcu_read_lock();
list_for_each_entry_rcu(client, &mousedev->client_list, node) {
/* Just acquire the lock, interrupts already disabled */
spin_lock(&client->packet_lock);
p = &client->packets[client->head];
if (client->ready && p->buttons != mousedev->packet.buttons) {
new_head = (client->head + 1) % PACKET_QUEUE_LEN;
if (new_head != client->tail) {
p = &client->packets[client->head = new_head];
memset(p, 0, sizeof(struct mousedev_motion));
}
}
if (packet->abs_event) {
p->dx += packet->x - client->pos_x;
p->dy += packet->y - client->pos_y;
client->pos_x = packet->x;
client->pos_y = packet->y;
}
client->pos_x += packet->dx;
client->pos_x = client->pos_x < 0 ?
0 : (client->pos_x >= xres ? xres : client->pos_x);
client->pos_y += packet->dy;
client->pos_y = client->pos_y < 0 ?
0 : (client->pos_y >= yres ? yres : client->pos_y);
p->dx += packet->dx;
p->dy += packet->dy;
p->dz += packet->dz;
p->buttons = mousedev->packet.buttons;
if (p->dx || p->dy || p->dz ||
p->buttons != client->last_buttons)
client->ready = 1;
spin_unlock(&client->packet_lock);
if (client->ready) {
kill_fasync(&client->fasync, SIGIO, POLL_IN);
wake_readers = 1;
}
}
rcu_read_unlock();
if (wake_readers)
wake_up_interruptible(&mousedev->wait);
}
static void mousedev_touchpad_touch(struct mousedev *mousedev, int value)
{
if (!value) {
if (mousedev->touch &&
time_before(jiffies,
mousedev->touch + msecs_to_jiffies(tap_time))) {
/*
* Toggle left button to emulate tap.
* We rely on the fact that mousedev_mix always has 0
* motion packet so we won't mess current position.
*/
set_bit(0, &mousedev->packet.buttons);
set_bit(0, &mousedev_mix->packet.buttons);
mousedev_notify_readers(mousedev, &mousedev_mix->packet);
mousedev_notify_readers(mousedev_mix,
&mousedev_mix->packet);
clear_bit(0, &mousedev->packet.buttons);
clear_bit(0, &mousedev_mix->packet.buttons);
}
mousedev->touch = mousedev->pkt_count = 0;
mousedev->frac_dx = 0;
mousedev->frac_dy = 0;
} else if (!mousedev->touch)
mousedev->touch = jiffies;
}
static void mousedev_event(struct input_handle *handle,
unsigned int type, unsigned int code, int value)
{
struct mousedev *mousedev = handle->private;
switch (type) {
case EV_ABS:
/* Ignore joysticks */
if (test_bit(BTN_TRIGGER, handle->dev->keybit))
return;
if (test_bit(BTN_TOOL_FINGER, handle->dev->keybit))
mousedev_touchpad_event(handle->dev,
mousedev, code, value);
else
mousedev_abs_event(handle->dev, mousedev, code, value);
break;
case EV_REL:
mousedev_rel_event(mousedev, code, value);
break;
case EV_KEY:
if (value != 2) {
if (code == BTN_TOUCH &&
test_bit(BTN_TOOL_FINGER, handle->dev->keybit))
mousedev_touchpad_touch(mousedev, value);
else
mousedev_key_event(mousedev, code, value);
}
break;
case EV_SYN:
if (code == SYN_REPORT) {
if (mousedev->touch) {
mousedev->pkt_count++;
/*
* Input system eats duplicate events,
* but we need all of them to do correct
* averaging so apply present one forward
*/
fx(0) = fx(1);
fy(0) = fy(1);
}
mousedev_notify_readers(mousedev, &mousedev->packet);
mousedev_notify_readers(mousedev_mix, &mousedev->packet);
mousedev->packet.dx = mousedev->packet.dy =
mousedev->packet.dz = 0;
mousedev->packet.abs_event = 0;
}
break;
}
}
static int mousedev_fasync(int fd, struct file *file, int on)
{
struct mousedev_client *client = file->private_data;
return fasync_helper(fd, file, on, &client->fasync);
}
static void mousedev_free(struct device *dev)
{
struct mousedev *mousedev = container_of(dev, struct mousedev, dev);
input_put_device(mousedev->handle.dev);
kfree(mousedev);
}
static int mousedev_open_device(struct mousedev *mousedev)
{
int retval;
retval = mutex_lock_interruptible(&mousedev->mutex);
if (retval)
return retval;
if (mousedev->minor == MOUSEDEV_MIX)
mixdev_open_devices();
else if (!mousedev->exist)
retval = -ENODEV;
else if (!mousedev->open++) {
retval = input_open_device(&mousedev->handle);
if (retval)
mousedev->open--;
}
mutex_unlock(&mousedev->mutex);
return retval;
}
static void mousedev_close_device(struct mousedev *mousedev)
{
mutex_lock(&mousedev->mutex);
if (mousedev->minor == MOUSEDEV_MIX)
mixdev_close_devices();
else if (mousedev->exist && !--mousedev->open)
input_close_device(&mousedev->handle);
mutex_unlock(&mousedev->mutex);
}
/*
* Open all available devices so they can all be multiplexed in one.
* stream. Note that this function is called with mousedev_mix->mutex
* held.
*/
static void mixdev_open_devices(void)
{
struct mousedev *mousedev;
if (mousedev_mix->open++)
return;
list_for_each_entry(mousedev, &mousedev_mix_list, mixdev_node) {
if (!mousedev->mixdev_open) {
if (mousedev_open_device(mousedev))
continue;
mousedev->mixdev_open = 1;
}
}
}
/*
* Close all devices that were opened as part of multiplexed
* device. Note that this function is called with mousedev_mix->mutex
* held.
*/
static void mixdev_close_devices(void)
{
struct mousedev *mousedev;
if (--mousedev_mix->open)
return;
list_for_each_entry(mousedev, &mousedev_mix_list, mixdev_node) {
if (mousedev->mixdev_open) {
mousedev->mixdev_open = 0;
mousedev_close_device(mousedev);
}
}
}
static void mousedev_attach_client(struct mousedev *mousedev,
struct mousedev_client *client)
{
spin_lock(&mousedev->client_lock);
list_add_tail_rcu(&client->node, &mousedev->client_list);
spin_unlock(&mousedev->client_lock);
synchronize_rcu();
}
static void mousedev_detach_client(struct mousedev *mousedev,
struct mousedev_client *client)
{
spin_lock(&mousedev->client_lock);
list_del_rcu(&client->node);
spin_unlock(&mousedev->client_lock);
synchronize_rcu();
}
static int mousedev_release(struct inode *inode, struct file *file)
{
struct mousedev_client *client = file->private_data;
struct mousedev *mousedev = client->mousedev;
mousedev_detach_client(mousedev, client);
kfree(client);
mousedev_close_device(mousedev);
put_device(&mousedev->dev);
return 0;
}
static int mousedev_open(struct inode *inode, struct file *file)
{
struct mousedev_client *client;
struct mousedev *mousedev;
int error;
int i;
#ifdef CONFIG_INPUT_MOUSEDEV_PSAUX
if (imajor(inode) == MISC_MAJOR)
i = MOUSEDEV_MIX;
else
#endif
i = iminor(inode) - MOUSEDEV_MINOR_BASE;
if (i >= MOUSEDEV_MINORS)
return -ENODEV;
error = mutex_lock_interruptible(&mousedev_table_mutex);
if (error) {
return error;
}
mousedev = mousedev_table[i];
if (mousedev)
get_device(&mousedev->dev);
mutex_unlock(&mousedev_table_mutex);
if (!mousedev) {
return -ENODEV;
}
client = kzalloc(sizeof(struct mousedev_client), GFP_KERNEL);
if (!client) {
error = -ENOMEM;
goto err_put_mousedev;
}
spin_lock_init(&client->packet_lock);
client->pos_x = xres / 2;
client->pos_y = yres / 2;
client->mousedev = mousedev;
mousedev_attach_client(mousedev, client);
error = mousedev_open_device(mousedev);
if (error)
goto err_free_client;
file->private_data = client;
return 0;
err_free_client:
mousedev_detach_client(mousedev, client);
kfree(client);
err_put_mousedev:
put_device(&mousedev->dev);
return error;
}
static inline int mousedev_limit_delta(int delta, int limit)
{
return delta > limit ? limit : (delta < -limit ? -limit : delta);
}
static void mousedev_packet(struct mousedev_client *client,
signed char *ps2_data)
{
struct mousedev_motion *p = &client->packets[client->tail];
ps2_data[0] = 0x08 |
((p->dx < 0) << 4) | ((p->dy < 0) << 5) | (p->buttons & 0x07);
ps2_data[1] = mousedev_limit_delta(p->dx, 127);
ps2_data[2] = mousedev_limit_delta(p->dy, 127);
p->dx -= ps2_data[1];
p->dy -= ps2_data[2];
switch (client->mode) {
case MOUSEDEV_EMUL_EXPS:
ps2_data[3] = mousedev_limit_delta(p->dz, 7);
p->dz -= ps2_data[3];
ps2_data[3] = (ps2_data[3] & 0x0f) | ((p->buttons & 0x18) << 1);
client->bufsiz = 4;
break;
case MOUSEDEV_EMUL_IMPS:
ps2_data[0] |=
((p->buttons & 0x10) >> 3) | ((p->buttons & 0x08) >> 1);
ps2_data[3] = mousedev_limit_delta(p->dz, 127);
p->dz -= ps2_data[3];
client->bufsiz = 4;
break;
case MOUSEDEV_EMUL_PS2:
default:
ps2_data[0] |=
((p->buttons & 0x10) >> 3) | ((p->buttons & 0x08) >> 1);
p->dz = 0;
client->bufsiz = 3;
break;
}
if (!p->dx && !p->dy && !p->dz) {
if (client->tail == client->head) {
client->ready = 0;
client->last_buttons = p->buttons;
} else
client->tail = (client->tail + 1) % PACKET_QUEUE_LEN;
}
}
static void mousedev_generate_response(struct mousedev_client *client,
int command)
{
client->ps2[0] = 0xfa; /* ACK */
switch (command) {
case 0xeb: /* Poll */
mousedev_packet(client, &client->ps2[1]);
client->bufsiz++; /* account for leading ACK */
break;
case 0xf2: /* Get ID */
switch (client->mode) {
case MOUSEDEV_EMUL_PS2:
client->ps2[1] = 0;
break;
case MOUSEDEV_EMUL_IMPS:
client->ps2[1] = 3;
break;
case MOUSEDEV_EMUL_EXPS:
client->ps2[1] = 4;
break;
}
client->bufsiz = 2;
break;
case 0xe9: /* Get info */
client->ps2[1] = 0x60; client->ps2[2] = 3; client->ps2[3] = 200;
client->bufsiz = 4;
break;
case 0xff: /* Reset */
client->impsseq = client->imexseq = 0;
client->mode = MOUSEDEV_EMUL_PS2;
client->ps2[1] = 0xaa; client->ps2[2] = 0x00;
client->bufsiz = 3;
break;
default:
client->bufsiz = 1;
break;
}
client->buffer = client->bufsiz;
}
static ssize_t mousedev_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
struct mousedev_client *client = file->private_data;
unsigned char c;
unsigned int i;
for (i = 0; i < count; i++) {
if (get_user(c, buffer + i))
return -EFAULT;
spin_lock_irq(&client->packet_lock);
if (c == mousedev_imex_seq[client->imexseq]) {
if (++client->imexseq == MOUSEDEV_SEQ_LEN) {
client->imexseq = 0;
client->mode = MOUSEDEV_EMUL_EXPS;
}
} else
client->imexseq = 0;
if (c == mousedev_imps_seq[client->impsseq]) {
if (++client->impsseq == MOUSEDEV_SEQ_LEN) {
client->impsseq = 0;
client->mode = MOUSEDEV_EMUL_IMPS;
}
} else
client->impsseq = 0;
mousedev_generate_response(client, c);
spin_unlock_irq(&client->packet_lock);
}
kill_fasync(&client->fasync, SIGIO, POLL_IN);
wake_up_interruptible(&client->mousedev->wait);
return count;
}
static ssize_t mousedev_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct mousedev_client *client = file->private_data;
struct mousedev *mousedev = client->mousedev;
signed char data[sizeof(client->ps2)];
int retval = 0;
if (!client->ready && !client->buffer && mousedev->exist &&
(file->f_flags & O_NONBLOCK))
return -EAGAIN;
retval = wait_event_interruptible(mousedev->wait,
!mousedev->exist || client->ready || client->buffer);
if (retval)
return retval;
if (!mousedev->exist)
return -ENODEV;
spin_lock_irq(&client->packet_lock);
if (!client->buffer && client->ready) {
mousedev_packet(client, client->ps2);
client->buffer = client->bufsiz;
}
if (count > client->buffer)
count = client->buffer;
memcpy(data, client->ps2 + client->bufsiz - client->buffer, count);
client->buffer -= count;
spin_unlock_irq(&client->packet_lock);
if (copy_to_user(buffer, data, count))
return -EFAULT;
return count;
}
/* No kernel lock - fine */
static unsigned int mousedev_poll(struct file *file, poll_table *wait)
{
struct mousedev_client *client = file->private_data;
struct mousedev *mousedev = client->mousedev;
poll_wait(file, &mousedev->wait, wait);
return ((client->ready || client->buffer) ? (POLLIN | POLLRDNORM) : 0) |
(mousedev->exist ? 0 : (POLLHUP | POLLERR));
}
static const struct file_operations mousedev_fops = {
.owner = THIS_MODULE,
.read = mousedev_read,
.write = mousedev_write,
.poll = mousedev_poll,
.open = mousedev_open,
.release = mousedev_release,
.fasync = mousedev_fasync,
};
static int mousedev_install_chrdev(struct mousedev *mousedev)
{
mousedev_table[mousedev->minor] = mousedev;
return 0;
}
static void mousedev_remove_chrdev(struct mousedev *mousedev)
{
mutex_lock(&mousedev_table_mutex);
mousedev_table[mousedev->minor] = NULL;
mutex_unlock(&mousedev_table_mutex);
}
/*
* Mark device non-existent. This disables writes, ioctls and
* prevents new users from opening the device. Already posted
* blocking reads will stay, however new ones will fail.
*/
static void mousedev_mark_dead(struct mousedev *mousedev)
{
mutex_lock(&mousedev->mutex);
mousedev->exist = 0;
mutex_unlock(&mousedev->mutex);
}
/*
* Wake up users waiting for IO so they can disconnect from
* dead device.
*/
static void mousedev_hangup(struct mousedev *mousedev)
{
struct mousedev_client *client;
spin_lock(&mousedev->client_lock);
list_for_each_entry(client, &mousedev->client_list, node)
kill_fasync(&client->fasync, SIGIO, POLL_HUP);
spin_unlock(&mousedev->client_lock);
wake_up_interruptible(&mousedev->wait);
}
static void mousedev_cleanup(struct mousedev *mousedev)
{
struct input_handle *handle = &mousedev->handle;
mousedev_mark_dead(mousedev);
mousedev_hangup(mousedev);
mousedev_remove_chrdev(mousedev);
/* mousedev is marked dead so no one else accesses mousedev->open */
if (mousedev->open)
input_close_device(handle);
}
static struct mousedev *mousedev_create(struct input_dev *dev,
struct input_handler *handler,
int minor)
{
struct mousedev *mousedev;
int error;
mousedev = kzalloc(sizeof(struct mousedev), GFP_KERNEL);
if (!mousedev) {
error = -ENOMEM;
goto err_out;
}
INIT_LIST_HEAD(&mousedev->client_list);
INIT_LIST_HEAD(&mousedev->mixdev_node);
spin_lock_init(&mousedev->client_lock);
mutex_init(&mousedev->mutex);
lockdep_set_subclass(&mousedev->mutex,
minor == MOUSEDEV_MIX ? MOUSEDEV_MIX : 0);
init_waitqueue_head(&mousedev->wait);
if (minor == MOUSEDEV_MIX)
dev_set_name(&mousedev->dev, "mice");
else
dev_set_name(&mousedev->dev, "mouse%d", minor);
mousedev->minor = minor;
mousedev->exist = 1;
mousedev->handle.dev = input_get_device(dev);
mousedev->handle.name = dev_name(&mousedev->dev);
mousedev->handle.handler = handler;
mousedev->handle.private = mousedev;
mousedev->dev.class = &input_class;
if (dev)
mousedev->dev.parent = &dev->dev;
mousedev->dev.devt = MKDEV(INPUT_MAJOR, MOUSEDEV_MINOR_BASE + minor);
mousedev->dev.release = mousedev_free;
device_initialize(&mousedev->dev);
if (minor != MOUSEDEV_MIX) {
error = input_register_handle(&mousedev->handle);
if (error)
goto err_free_mousedev;
}
error = mousedev_install_chrdev(mousedev);
if (error)
goto err_unregister_handle;
error = device_add(&mousedev->dev);
if (error)
goto err_cleanup_mousedev;
return mousedev;
err_cleanup_mousedev:
mousedev_cleanup(mousedev);
err_unregister_handle:
if (minor != MOUSEDEV_MIX)
input_unregister_handle(&mousedev->handle);
err_free_mousedev:
put_device(&mousedev->dev);
err_out:
return ERR_PTR(error);
}
static void mousedev_destroy(struct mousedev *mousedev)
{
device_del(&mousedev->dev);
mousedev_cleanup(mousedev);
if (mousedev->minor != MOUSEDEV_MIX)
input_unregister_handle(&mousedev->handle);
put_device(&mousedev->dev);
}
static int mixdev_add_device(struct mousedev *mousedev)
{
int retval;
retval = mutex_lock_interruptible(&mousedev_mix->mutex);
if (retval)
return retval;
if (mousedev_mix->open) {
retval = mousedev_open_device(mousedev);
if (retval)
goto out;
mousedev->mixdev_open = 1;
}
get_device(&mousedev->dev);
list_add_tail(&mousedev->mixdev_node, &mousedev_mix_list);
out:
mutex_unlock(&mousedev_mix->mutex);
return retval;
}
static void mixdev_remove_device(struct mousedev *mousedev)
{
mutex_lock(&mousedev_mix->mutex);
if (mousedev->mixdev_open) {
mousedev->mixdev_open = 0;
mousedev_close_device(mousedev);
}
list_del_init(&mousedev->mixdev_node);
mutex_unlock(&mousedev_mix->mutex);
put_device(&mousedev->dev);
}
static int mousedev_connect(struct input_handler *handler,
struct input_dev *dev,
const struct input_device_id *id)
{
struct mousedev *mousedev;
int minor;
int error;
for (minor = 0; minor < MOUSEDEV_MINORS; minor++)
if (!mousedev_table[minor])
break;
if (minor == MOUSEDEV_MINORS) {
printk(KERN_ERR "mousedev: no more free mousedev devices\n");
return -ENFILE;
}
mousedev = mousedev_create(dev, handler, minor);
if (IS_ERR(mousedev))
return PTR_ERR(mousedev);
error = mixdev_add_device(mousedev);
if (error) {
mousedev_destroy(mousedev);
return error;
}
return 0;
}
static void mousedev_disconnect(struct input_handle *handle)
{
struct mousedev *mousedev = handle->private;
mixdev_remove_device(mousedev);
mousedev_destroy(mousedev);
}
static const struct input_device_id mousedev_ids[] = {
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
INPUT_DEVICE_ID_MATCH_KEYBIT |
INPUT_DEVICE_ID_MATCH_RELBIT,
.evbit = { BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) },
.keybit = { [BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) },
.relbit = { BIT_MASK(REL_X) | BIT_MASK(REL_Y) },
}, /* A mouse like device, at least one button,
two relative axes */
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
INPUT_DEVICE_ID_MATCH_RELBIT,
.evbit = { BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) },
.relbit = { BIT_MASK(REL_WHEEL) },
}, /* A separate scrollwheel */
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
INPUT_DEVICE_ID_MATCH_KEYBIT |
INPUT_DEVICE_ID_MATCH_ABSBIT,
.evbit = { BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) },
.keybit = { [BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH) },
.absbit = { BIT_MASK(ABS_X) | BIT_MASK(ABS_Y) },
}, /* A tablet like device, at least touch detection,
two absolute axes */
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
INPUT_DEVICE_ID_MATCH_KEYBIT |
INPUT_DEVICE_ID_MATCH_ABSBIT,
.evbit = { BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) },
.keybit = { [BIT_WORD(BTN_TOOL_FINGER)] =
BIT_MASK(BTN_TOOL_FINGER) },
.absbit = { BIT_MASK(ABS_X) | BIT_MASK(ABS_Y) |
BIT_MASK(ABS_PRESSURE) |
BIT_MASK(ABS_TOOL_WIDTH) },
}, /* A touchpad */
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
INPUT_DEVICE_ID_MATCH_KEYBIT |
INPUT_DEVICE_ID_MATCH_ABSBIT,
.evbit = { BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) },
.keybit = { [BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) },
.absbit = { BIT_MASK(ABS_X) | BIT_MASK(ABS_Y) },
}, /* Mouse-like device with absolute X and Y but ordinary
clicks, like hp ILO2 High Performance mouse */
{ }, /* Terminating entry */
};
MODULE_DEVICE_TABLE(input, mousedev_ids);
static struct input_handler mousedev_handler = {
.event = mousedev_event,
.connect = mousedev_connect,
.disconnect = mousedev_disconnect,
.fops = &mousedev_fops,
.minor = MOUSEDEV_MINOR_BASE,
.name = "mousedev",
.id_table = mousedev_ids,
};
#ifdef CONFIG_INPUT_MOUSEDEV_PSAUX
static struct miscdevice psaux_mouse = {
PSMOUSE_MINOR, "psaux", &mousedev_fops
};
static int psaux_registered;
#endif
static int __init mousedev_init(void)
{
int error;
mousedev_mix = mousedev_create(NULL, &mousedev_handler, MOUSEDEV_MIX);
if (IS_ERR(mousedev_mix))
return PTR_ERR(mousedev_mix);
error = input_register_handler(&mousedev_handler);
if (error) {
mousedev_destroy(mousedev_mix);
return error;
}
#ifdef CONFIG_INPUT_MOUSEDEV_PSAUX
error = misc_register(&psaux_mouse);
if (error)
printk(KERN_WARNING "mice: could not register psaux device, "
"error: %d\n", error);
else
psaux_registered = 1;
#endif
printk(KERN_INFO "mice: PS/2 mouse device common for all mice\n");
return 0;
}
static void __exit mousedev_exit(void)
{
#ifdef CONFIG_INPUT_MOUSEDEV_PSAUX
if (psaux_registered)
misc_deregister(&psaux_mouse);
#endif
input_unregister_handler(&mousedev_handler);
mousedev_destroy(mousedev_mix);
}
module_init(mousedev_init);
module_exit(mousedev_exit);
| gpl-2.0 |
sq210/android-kernel-samsung-dev | net/netfilter/nf_conntrack_proto_tcp.c | 808 | 45521 | /* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/timer.h>
#include <linux/module.h>
#include <linux/in.h>
#include <linux/tcp.h>
#include <linux/spinlock.h>
#include <linux/skbuff.h>
#include <linux/ipv6.h>
#include <net/ip6_checksum.h>
#include <asm/unaligned.h>
#include <net/tcp.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_ecache.h>
#include <net/netfilter/nf_log.h>
#include <net/netfilter/ipv4/nf_conntrack_ipv4.h>
#include <net/netfilter/ipv6/nf_conntrack_ipv6.h>
/* "Be conservative in what you do,
be liberal in what you accept from others."
If it's non-zero, we mark only out of window RST segments as INVALID. */
static int nf_ct_tcp_be_liberal __read_mostly = 0;
/* If it is set to zero, we disable picking up already established
connections. */
static int nf_ct_tcp_loose __read_mostly = 1;
/* Max number of the retransmitted packets without receiving an (acceptable)
ACK from the destination. If this number is reached, a shorter timer
will be started. */
static int nf_ct_tcp_max_retrans __read_mostly = 3;
/* FIXME: Examine ipfilter's timeouts and conntrack transitions more
closely. They're more complex. --RR */
static const char *const tcp_conntrack_names[] = {
"NONE",
"SYN_SENT",
"SYN_RECV",
"ESTABLISHED",
"FIN_WAIT",
"CLOSE_WAIT",
"LAST_ACK",
"TIME_WAIT",
"CLOSE",
"SYN_SENT2",
};
#define SECS * HZ
#define MINS * 60 SECS
#define HOURS * 60 MINS
#define DAYS * 24 HOURS
/* RFC1122 says the R2 limit should be at least 100 seconds.
Linux uses 15 packets as limit, which corresponds
to ~13-30min depending on RTO. */
static unsigned int nf_ct_tcp_timeout_max_retrans __read_mostly = 5 MINS;
static unsigned int nf_ct_tcp_timeout_unacknowledged __read_mostly = 5 MINS;
static unsigned int tcp_timeouts[TCP_CONNTRACK_MAX] __read_mostly = {
[TCP_CONNTRACK_SYN_SENT] = 2 MINS,
[TCP_CONNTRACK_SYN_RECV] = 60 SECS,
[TCP_CONNTRACK_ESTABLISHED] = 5 DAYS,
[TCP_CONNTRACK_FIN_WAIT] = 2 MINS,
[TCP_CONNTRACK_CLOSE_WAIT] = 60 SECS,
[TCP_CONNTRACK_LAST_ACK] = 30 SECS,
[TCP_CONNTRACK_TIME_WAIT] = 2 MINS,
[TCP_CONNTRACK_CLOSE] = 10 SECS,
[TCP_CONNTRACK_SYN_SENT2] = 2 MINS,
};
#define sNO TCP_CONNTRACK_NONE
#define sSS TCP_CONNTRACK_SYN_SENT
#define sSR TCP_CONNTRACK_SYN_RECV
#define sES TCP_CONNTRACK_ESTABLISHED
#define sFW TCP_CONNTRACK_FIN_WAIT
#define sCW TCP_CONNTRACK_CLOSE_WAIT
#define sLA TCP_CONNTRACK_LAST_ACK
#define sTW TCP_CONNTRACK_TIME_WAIT
#define sCL TCP_CONNTRACK_CLOSE
#define sS2 TCP_CONNTRACK_SYN_SENT2
#define sIV TCP_CONNTRACK_MAX
#define sIG TCP_CONNTRACK_IGNORE
/* What TCP flags are set from RST/SYN/FIN/ACK. */
enum tcp_bit_set {
TCP_SYN_SET,
TCP_SYNACK_SET,
TCP_FIN_SET,
TCP_ACK_SET,
TCP_RST_SET,
TCP_NONE_SET,
};
/*
* The TCP state transition table needs a few words...
*
* We are the man in the middle. All the packets go through us
* but might get lost in transit to the destination.
* It is assumed that the destinations can't receive segments
* we haven't seen.
*
* The checked segment is in window, but our windows are *not*
* equivalent with the ones of the sender/receiver. We always
* try to guess the state of the current sender.
*
* The meaning of the states are:
*
* NONE: initial state
* SYN_SENT: SYN-only packet seen
* SYN_SENT2: SYN-only packet seen from reply dir, simultaneous open
* SYN_RECV: SYN-ACK packet seen
* ESTABLISHED: ACK packet seen
* FIN_WAIT: FIN packet seen
* CLOSE_WAIT: ACK seen (after FIN)
* LAST_ACK: FIN seen (after FIN)
* TIME_WAIT: last ACK seen
* CLOSE: closed connection (RST)
*
* Packets marked as IGNORED (sIG):
* if they may be either invalid or valid
* and the receiver may send back a connection
* closing RST or a SYN/ACK.
*
* Packets marked as INVALID (sIV):
* if we regard them as truly invalid packets
*/
static const u8 tcp_conntracks[2][6][TCP_CONNTRACK_MAX] = {
{
/* ORIGINAL */
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*syn*/ { sSS, sSS, sIG, sIG, sIG, sIG, sIG, sSS, sSS, sS2 },
/*
* sNO -> sSS Initialize a new connection
* sSS -> sSS Retransmitted SYN
* sS2 -> sS2 Late retransmitted SYN
* sSR -> sIG
* sES -> sIG Error: SYNs in window outside the SYN_SENT state
* are errors. Receiver will reply with RST
* and close the connection.
* Or we are not in sync and hold a dead connection.
* sFW -> sIG
* sCW -> sIG
* sLA -> sIG
* sTW -> sSS Reopened connection (RFC 1122).
* sCL -> sSS
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*synack*/ { sIV, sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIG, sSR },
/*
* sNO -> sIV Too late and no reason to do anything
* sSS -> sIV Client can't send SYN and then SYN/ACK
* sS2 -> sSR SYN/ACK sent to SYN2 in simultaneous open
* sSR -> sIG
* sES -> sIG Error: SYNs in window outside the SYN_SENT state
* are errors. Receiver will reply with RST
* and close the connection.
* Or we are not in sync and hold a dead connection.
* sFW -> sIG
* sCW -> sIG
* sLA -> sIG
* sTW -> sIG
* sCL -> sIG
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*fin*/ { sIV, sIV, sFW, sFW, sLA, sLA, sLA, sTW, sCL, sIV },
/*
* sNO -> sIV Too late and no reason to do anything...
* sSS -> sIV Client migth not send FIN in this state:
* we enforce waiting for a SYN/ACK reply first.
* sS2 -> sIV
* sSR -> sFW Close started.
* sES -> sFW
* sFW -> sLA FIN seen in both directions, waiting for
* the last ACK.
* Migth be a retransmitted FIN as well...
* sCW -> sLA
* sLA -> sLA Retransmitted FIN. Remain in the same state.
* sTW -> sTW
* sCL -> sCL
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*ack*/ { sES, sIV, sES, sES, sCW, sCW, sTW, sTW, sCL, sIV },
/*
* sNO -> sES Assumed.
* sSS -> sIV ACK is invalid: we haven't seen a SYN/ACK yet.
* sS2 -> sIV
* sSR -> sES Established state is reached.
* sES -> sES :-)
* sFW -> sCW Normal close request answered by ACK.
* sCW -> sCW
* sLA -> sTW Last ACK detected.
* sTW -> sTW Retransmitted last ACK. Remain in the same state.
* sCL -> sCL
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*rst*/ { sIV, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL },
/*none*/ { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }
},
{
/* REPLY */
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*syn*/ { sIV, sS2, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sS2 },
/*
* sNO -> sIV Never reached.
* sSS -> sS2 Simultaneous open
* sS2 -> sS2 Retransmitted simultaneous SYN
* sSR -> sIV Invalid SYN packets sent by the server
* sES -> sIV
* sFW -> sIV
* sCW -> sIV
* sLA -> sIV
* sTW -> sIV Reopened connection, but server may not do it.
* sCL -> sIV
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*synack*/ { sIV, sSR, sSR, sIG, sIG, sIG, sIG, sIG, sIG, sSR },
/*
* sSS -> sSR Standard open.
* sS2 -> sSR Simultaneous open
* sSR -> sSR Retransmitted SYN/ACK.
* sES -> sIG Late retransmitted SYN/ACK?
* sFW -> sIG Might be SYN/ACK answering ignored SYN
* sCW -> sIG
* sLA -> sIG
* sTW -> sIG
* sCL -> sIG
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*fin*/ { sIV, sIV, sFW, sFW, sLA, sLA, sLA, sTW, sCL, sIV },
/*
* sSS -> sIV Server might not send FIN in this state.
* sS2 -> sIV
* sSR -> sFW Close started.
* sES -> sFW
* sFW -> sLA FIN seen in both directions.
* sCW -> sLA
* sLA -> sLA Retransmitted FIN.
* sTW -> sTW
* sCL -> sCL
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*ack*/ { sIV, sIG, sSR, sES, sCW, sCW, sTW, sTW, sCL, sIG },
/*
* sSS -> sIG Might be a half-open connection.
* sS2 -> sIG
* sSR -> sSR Might answer late resent SYN.
* sES -> sES :-)
* sFW -> sCW Normal close request answered by ACK.
* sCW -> sCW
* sLA -> sTW Last ACK detected.
* sTW -> sTW Retransmitted last ACK.
* sCL -> sCL
*/
/* sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2 */
/*rst*/ { sIV, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL },
/*none*/ { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }
}
};
static bool tcp_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff,
struct nf_conntrack_tuple *tuple)
{
const struct tcphdr *hp;
struct tcphdr _hdr;
/* Actually only need first 8 bytes. */
hp = skb_header_pointer(skb, dataoff, 8, &_hdr);
if (hp == NULL)
return false;
tuple->src.u.tcp.port = hp->source;
tuple->dst.u.tcp.port = hp->dest;
return true;
}
static bool tcp_invert_tuple(struct nf_conntrack_tuple *tuple,
const struct nf_conntrack_tuple *orig)
{
tuple->src.u.tcp.port = orig->dst.u.tcp.port;
tuple->dst.u.tcp.port = orig->src.u.tcp.port;
return true;
}
/* Print out the per-protocol part of the tuple. */
static int tcp_print_tuple(struct seq_file *s,
const struct nf_conntrack_tuple *tuple)
{
return seq_printf(s, "sport=%hu dport=%hu ",
ntohs(tuple->src.u.tcp.port),
ntohs(tuple->dst.u.tcp.port));
}
/* Print out the private part of the conntrack. */
static int tcp_print_conntrack(struct seq_file *s, struct nf_conn *ct)
{
enum tcp_conntrack state;
spin_lock_bh(&ct->lock);
state = ct->proto.tcp.state;
spin_unlock_bh(&ct->lock);
return seq_printf(s, "%s ", tcp_conntrack_names[state]);
}
static unsigned int get_conntrack_index(const struct tcphdr *tcph)
{
if (tcph->rst) return TCP_RST_SET;
else if (tcph->syn) return (tcph->ack ? TCP_SYNACK_SET : TCP_SYN_SET);
else if (tcph->fin) return TCP_FIN_SET;
else if (tcph->ack) return TCP_ACK_SET;
else return TCP_NONE_SET;
}
/* TCP connection tracking based on 'Real Stateful TCP Packet Filtering
in IP Filter' by Guido van Rooij.
http://www.nluug.nl/events/sane2000/papers.html
http://www.iae.nl/users/guido/papers/tcp_filtering.ps.gz
The boundaries and the conditions are changed according to RFC793:
the packet must intersect the window (i.e. segments may be
after the right or before the left edge) and thus receivers may ACK
segments after the right edge of the window.
td_maxend = max(sack + max(win,1)) seen in reply packets
td_maxwin = max(max(win, 1)) + (sack - ack) seen in sent packets
td_maxwin += seq + len - sender.td_maxend
if seq + len > sender.td_maxend
td_end = max(seq + len) seen in sent packets
I. Upper bound for valid data: seq <= sender.td_maxend
II. Lower bound for valid data: seq + len >= sender.td_end - receiver.td_maxwin
III. Upper bound for valid (s)ack: sack <= receiver.td_end
IV. Lower bound for valid (s)ack: sack >= receiver.td_end - MAXACKWINDOW
where sack is the highest right edge of sack block found in the packet
or ack in the case of packet without SACK option.
The upper bound limit for a valid (s)ack is not ignored -
we doesn't have to deal with fragments.
*/
static inline __u32 segment_seq_plus_len(__u32 seq,
size_t len,
unsigned int dataoff,
const struct tcphdr *tcph)
{
/* XXX Should I use payload length field in IP/IPv6 header ?
* - YK */
return (seq + len - dataoff - tcph->doff*4
+ (tcph->syn ? 1 : 0) + (tcph->fin ? 1 : 0));
}
/* Fixme: what about big packets? */
#define MAXACKWINCONST 66000
#define MAXACKWINDOW(sender) \
((sender)->td_maxwin > MAXACKWINCONST ? (sender)->td_maxwin \
: MAXACKWINCONST)
/*
* Simplified tcp_parse_options routine from tcp_input.c
*/
static void tcp_options(const struct sk_buff *skb,
unsigned int dataoff,
const struct tcphdr *tcph,
struct ip_ct_tcp_state *state)
{
unsigned char buff[(15 * 4) - sizeof(struct tcphdr)];
const unsigned char *ptr;
int length = (tcph->doff*4) - sizeof(struct tcphdr);
if (!length)
return;
ptr = skb_header_pointer(skb, dataoff + sizeof(struct tcphdr),
length, buff);
BUG_ON(ptr == NULL);
state->td_scale =
state->flags = 0;
while (length > 0) {
int opcode=*ptr++;
int opsize;
switch (opcode) {
case TCPOPT_EOL:
return;
case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
length--;
continue;
default:
opsize=*ptr++;
if (opsize < 2) /* "silly options" */
return;
if (opsize > length)
break; /* don't parse partial options */
if (opcode == TCPOPT_SACK_PERM
&& opsize == TCPOLEN_SACK_PERM)
state->flags |= IP_CT_TCP_FLAG_SACK_PERM;
else if (opcode == TCPOPT_WINDOW
&& opsize == TCPOLEN_WINDOW) {
state->td_scale = *(u_int8_t *)ptr;
if (state->td_scale > 14) {
/* See RFC1323 */
state->td_scale = 14;
}
state->flags |=
IP_CT_TCP_FLAG_WINDOW_SCALE;
}
ptr += opsize - 2;
length -= opsize;
}
}
}
static void tcp_sack(const struct sk_buff *skb, unsigned int dataoff,
const struct tcphdr *tcph, __u32 *sack)
{
unsigned char buff[(15 * 4) - sizeof(struct tcphdr)];
const unsigned char *ptr;
int length = (tcph->doff*4) - sizeof(struct tcphdr);
__u32 tmp;
if (!length)
return;
ptr = skb_header_pointer(skb, dataoff + sizeof(struct tcphdr),
length, buff);
BUG_ON(ptr == NULL);
/* Fast path for timestamp-only option */
if (length == TCPOLEN_TSTAMP_ALIGNED*4
&& *(__be32 *)ptr == htonl((TCPOPT_NOP << 24)
| (TCPOPT_NOP << 16)
| (TCPOPT_TIMESTAMP << 8)
| TCPOLEN_TIMESTAMP))
return;
while (length > 0) {
int opcode = *ptr++;
int opsize, i;
switch (opcode) {
case TCPOPT_EOL:
return;
case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
length--;
continue;
default:
opsize = *ptr++;
if (opsize < 2) /* "silly options" */
return;
if (opsize > length)
break; /* don't parse partial options */
if (opcode == TCPOPT_SACK
&& opsize >= (TCPOLEN_SACK_BASE
+ TCPOLEN_SACK_PERBLOCK)
&& !((opsize - TCPOLEN_SACK_BASE)
% TCPOLEN_SACK_PERBLOCK)) {
for (i = 0;
i < (opsize - TCPOLEN_SACK_BASE);
i += TCPOLEN_SACK_PERBLOCK) {
tmp = get_unaligned_be32((__be32 *)(ptr+i)+1);
if (after(tmp, *sack))
*sack = tmp;
}
return;
}
ptr += opsize - 2;
length -= opsize;
}
}
}
#ifdef CONFIG_NF_NAT_NEEDED
static inline s16 nat_offset(const struct nf_conn *ct,
enum ip_conntrack_dir dir,
u32 seq)
{
typeof(nf_ct_nat_offset) get_offset = rcu_dereference(nf_ct_nat_offset);
return get_offset != NULL ? get_offset(ct, dir, seq) : 0;
}
#define NAT_OFFSET(pf, ct, dir, seq) \
(pf == NFPROTO_IPV4 ? nat_offset(ct, dir, seq) : 0)
#else
#define NAT_OFFSET(pf, ct, dir, seq) 0
#endif
static bool tcp_in_window(const struct nf_conn *ct,
struct ip_ct_tcp *state,
enum ip_conntrack_dir dir,
unsigned int index,
const struct sk_buff *skb,
unsigned int dataoff,
const struct tcphdr *tcph,
u_int8_t pf)
{
struct net *net = nf_ct_net(ct);
struct ip_ct_tcp_state *sender = &state->seen[dir];
struct ip_ct_tcp_state *receiver = &state->seen[!dir];
const struct nf_conntrack_tuple *tuple = &ct->tuplehash[dir].tuple;
__u32 seq, ack, sack, end, win, swin;
s16 receiver_offset;
bool res;
/*
* Get the required data from the packet.
*/
seq = ntohl(tcph->seq);
ack = sack = ntohl(tcph->ack_seq);
win = ntohs(tcph->window);
end = segment_seq_plus_len(seq, skb->len, dataoff, tcph);
if (receiver->flags & IP_CT_TCP_FLAG_SACK_PERM)
tcp_sack(skb, dataoff, tcph, &sack);
/* Take into account NAT sequence number mangling */
receiver_offset = NAT_OFFSET(pf, ct, !dir, ack - 1);
ack -= receiver_offset;
sack -= receiver_offset;
pr_debug("tcp_in_window: START\n");
pr_debug("tcp_in_window: ");
nf_ct_dump_tuple(tuple);
pr_debug("seq=%u ack=%u+(%d) sack=%u+(%d) win=%u end=%u\n",
seq, ack, receiver_offset, sack, receiver_offset, win, end);
pr_debug("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
"receiver end=%u maxend=%u maxwin=%u scale=%i\n",
sender->td_end, sender->td_maxend, sender->td_maxwin,
sender->td_scale,
receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
receiver->td_scale);
if (sender->td_maxwin == 0) {
/*
* Initialize sender data.
*/
if (tcph->syn) {
/*
* SYN-ACK in reply to a SYN
* or SYN from reply direction in simultaneous open.
*/
sender->td_end =
sender->td_maxend = end;
sender->td_maxwin = (win == 0 ? 1 : win);
tcp_options(skb, dataoff, tcph, sender);
/*
* RFC 1323:
* Both sides must send the Window Scale option
* to enable window scaling in either direction.
*/
if (!(sender->flags & IP_CT_TCP_FLAG_WINDOW_SCALE
&& receiver->flags & IP_CT_TCP_FLAG_WINDOW_SCALE))
sender->td_scale =
receiver->td_scale = 0;
if (!tcph->ack)
/* Simultaneous open */
return true;
} else {
/*
* We are in the middle of a connection,
* its history is lost for us.
* Let's try to use the data from the packet.
*/
sender->td_end = end;
sender->td_maxwin = (win == 0 ? 1 : win);
sender->td_maxend = end + sender->td_maxwin;
}
} else if (((state->state == TCP_CONNTRACK_SYN_SENT
&& dir == IP_CT_DIR_ORIGINAL)
|| (state->state == TCP_CONNTRACK_SYN_RECV
&& dir == IP_CT_DIR_REPLY))
&& after(end, sender->td_end)) {
/*
* RFC 793: "if a TCP is reinitialized ... then it need
* not wait at all; it must only be sure to use sequence
* numbers larger than those recently used."
*/
sender->td_end =
sender->td_maxend = end;
sender->td_maxwin = (win == 0 ? 1 : win);
tcp_options(skb, dataoff, tcph, sender);
}
if (!(tcph->ack)) {
/*
* If there is no ACK, just pretend it was set and OK.
*/
ack = sack = receiver->td_end;
} else if (((tcp_flag_word(tcph) & (TCP_FLAG_ACK|TCP_FLAG_RST)) ==
(TCP_FLAG_ACK|TCP_FLAG_RST))
&& (ack == 0)) {
/*
* Broken TCP stacks, that set ACK in RST packets as well
* with zero ack value.
*/
ack = sack = receiver->td_end;
}
if (seq == end
&& (!tcph->rst
|| (seq == 0 && state->state == TCP_CONNTRACK_SYN_SENT)))
/*
* Packets contains no data: we assume it is valid
* and check the ack value only.
* However RST segments are always validated by their
* SEQ number, except when seq == 0 (reset sent answering
* SYN.
*/
seq = end = sender->td_end;
pr_debug("tcp_in_window: ");
nf_ct_dump_tuple(tuple);
pr_debug("seq=%u ack=%u+(%d) sack=%u+(%d) win=%u end=%u\n",
seq, ack, receiver_offset, sack, receiver_offset, win, end);
pr_debug("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
"receiver end=%u maxend=%u maxwin=%u scale=%i\n",
sender->td_end, sender->td_maxend, sender->td_maxwin,
sender->td_scale,
receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
receiver->td_scale);
pr_debug("tcp_in_window: I=%i II=%i III=%i IV=%i\n",
before(seq, sender->td_maxend + 1),
after(end, sender->td_end - receiver->td_maxwin - 1),
before(sack, receiver->td_end + 1),
after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1));
if (before(seq, sender->td_maxend + 1) &&
after(end, sender->td_end - receiver->td_maxwin - 1) &&
before(sack, receiver->td_end + 1) &&
after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1)) {
/*
* Take into account window scaling (RFC 1323).
*/
if (!tcph->syn)
win <<= sender->td_scale;
/*
* Update sender data.
*/
swin = win + (sack - ack);
if (sender->td_maxwin < swin)
sender->td_maxwin = swin;
if (after(end, sender->td_end)) {
sender->td_end = end;
sender->flags |= IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED;
}
if (tcph->ack) {
if (!(sender->flags & IP_CT_TCP_FLAG_MAXACK_SET)) {
sender->td_maxack = ack;
sender->flags |= IP_CT_TCP_FLAG_MAXACK_SET;
} else if (after(ack, sender->td_maxack))
sender->td_maxack = ack;
}
/*
* Update receiver data.
*/
if (after(end, sender->td_maxend))
receiver->td_maxwin += end - sender->td_maxend;
if (after(sack + win, receiver->td_maxend - 1)) {
receiver->td_maxend = sack + win;
if (win == 0)
receiver->td_maxend++;
}
if (ack == receiver->td_end)
receiver->flags &= ~IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED;
/*
* Check retransmissions.
*/
if (index == TCP_ACK_SET) {
if (state->last_dir == dir
&& state->last_seq == seq
&& state->last_ack == ack
&& state->last_end == end
&& state->last_win == win)
state->retrans++;
else {
state->last_dir = dir;
state->last_seq = seq;
state->last_ack = ack;
state->last_end = end;
state->last_win = win;
state->retrans = 0;
}
}
res = true;
} else {
res = false;
if (sender->flags & IP_CT_TCP_FLAG_BE_LIBERAL ||
nf_ct_tcp_be_liberal)
res = true;
if (!res && LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: %s ",
before(seq, sender->td_maxend + 1) ?
after(end, sender->td_end - receiver->td_maxwin - 1) ?
before(sack, receiver->td_end + 1) ?
after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1) ? "BUG"
: "ACK is under the lower bound (possible overly delayed ACK)"
: "ACK is over the upper bound (ACKed data not seen yet)"
: "SEQ is under the lower bound (already ACKed data retransmitted)"
: "SEQ is over the upper bound (over the window of the receiver)");
}
pr_debug("tcp_in_window: res=%u sender end=%u maxend=%u maxwin=%u "
"receiver end=%u maxend=%u maxwin=%u\n",
res, sender->td_end, sender->td_maxend, sender->td_maxwin,
receiver->td_end, receiver->td_maxend, receiver->td_maxwin);
return res;
}
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECE 0x40
#define TH_CWR 0x80
/* table of valid flag combinations - PUSH, ECE and CWR are always valid */
static const u8 tcp_valid_flags[(TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG) + 1] =
{
[TH_SYN] = 1,
[TH_SYN|TH_URG] = 1,
[TH_SYN|TH_ACK] = 1,
[TH_RST] = 1,
[TH_RST|TH_ACK] = 1,
[TH_FIN|TH_ACK] = 1,
[TH_FIN|TH_ACK|TH_URG] = 1,
[TH_ACK] = 1,
[TH_ACK|TH_URG] = 1,
};
/* Protect conntrack agaist broken packets. Code taken from ipt_unclean.c. */
static int tcp_error(struct net *net, struct nf_conn *tmpl,
struct sk_buff *skb,
unsigned int dataoff,
enum ip_conntrack_info *ctinfo,
u_int8_t pf,
unsigned int hooknum)
{
const struct tcphdr *th;
struct tcphdr _tcph;
unsigned int tcplen = skb->len - dataoff;
u_int8_t tcpflags;
/* Smaller that minimal TCP header? */
th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
if (th == NULL) {
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: short packet ");
return -NF_ACCEPT;
}
/* Not whole TCP header or malformed packet */
if (th->doff*4 < sizeof(struct tcphdr) || tcplen < th->doff*4) {
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: truncated/malformed packet ");
return -NF_ACCEPT;
}
/* Checksum invalid? Ignore.
* We skip checking packets on the outgoing path
* because the checksum is assumed to be correct.
*/
/* FIXME: Source route IP option packets --RR */
if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
nf_checksum(skb, hooknum, dataoff, IPPROTO_TCP, pf)) {
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: bad TCP checksum ");
return -NF_ACCEPT;
}
/* Check TCP flags. */
tcpflags = (((u_int8_t *)th)[13] & ~(TH_ECE|TH_CWR|TH_PUSH));
if (!tcp_valid_flags[tcpflags]) {
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: invalid TCP flag combination ");
return -NF_ACCEPT;
}
return NF_ACCEPT;
}
/* Returns verdict for packet, or -1 for invalid. */
static int tcp_packet(struct nf_conn *ct,
const struct sk_buff *skb,
unsigned int dataoff,
enum ip_conntrack_info ctinfo,
u_int8_t pf,
unsigned int hooknum)
{
struct net *net = nf_ct_net(ct);
struct nf_conntrack_tuple *tuple;
enum tcp_conntrack new_state, old_state;
enum ip_conntrack_dir dir;
const struct tcphdr *th;
struct tcphdr _tcph;
unsigned long timeout;
unsigned int index;
th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
BUG_ON(th == NULL);
spin_lock_bh(&ct->lock);
old_state = ct->proto.tcp.state;
dir = CTINFO2DIR(ctinfo);
index = get_conntrack_index(th);
new_state = tcp_conntracks[dir][index][old_state];
tuple = &ct->tuplehash[dir].tuple;
switch (new_state) {
case TCP_CONNTRACK_SYN_SENT:
if (old_state < TCP_CONNTRACK_TIME_WAIT)
break;
/* RFC 1122: "When a connection is closed actively,
* it MUST linger in TIME-WAIT state for a time 2xMSL
* (Maximum Segment Lifetime). However, it MAY accept
* a new SYN from the remote TCP to reopen the connection
* directly from TIME-WAIT state, if..."
* We ignore the conditions because we are in the
* TIME-WAIT state anyway.
*
* Handle aborted connections: we and the server
* think there is an existing connection but the client
* aborts it and starts a new one.
*/
if (((ct->proto.tcp.seen[dir].flags
| ct->proto.tcp.seen[!dir].flags)
& IP_CT_TCP_FLAG_CLOSE_INIT)
|| (ct->proto.tcp.last_dir == dir
&& ct->proto.tcp.last_index == TCP_RST_SET)) {
/* Attempt to reopen a closed/aborted connection.
* Delete this connection and look up again. */
spin_unlock_bh(&ct->lock);
/* Only repeat if we can actually remove the timer.
* Destruction may already be in progress in process
* context and we must give it a chance to terminate.
*/
if (nf_ct_kill(ct))
return -NF_REPEAT;
return NF_DROP;
}
/* Fall through */
case TCP_CONNTRACK_IGNORE:
/* Ignored packets:
*
* Our connection entry may be out of sync, so ignore
* packets which may signal the real connection between
* the client and the server.
*
* a) SYN in ORIGINAL
* b) SYN/ACK in REPLY
* c) ACK in reply direction after initial SYN in original.
*
* If the ignored packet is invalid, the receiver will send
* a RST we'll catch below.
*/
if (index == TCP_SYNACK_SET
&& ct->proto.tcp.last_index == TCP_SYN_SET
&& ct->proto.tcp.last_dir != dir
&& ntohl(th->ack_seq) == ct->proto.tcp.last_end) {
/* b) This SYN/ACK acknowledges a SYN that we earlier
* ignored as invalid. This means that the client and
* the server are both in sync, while the firewall is
* not. We get in sync from the previously annotated
* values.
*/
old_state = TCP_CONNTRACK_SYN_SENT;
new_state = TCP_CONNTRACK_SYN_RECV;
ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_end =
ct->proto.tcp.last_end;
ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_maxend =
ct->proto.tcp.last_end;
ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_maxwin =
ct->proto.tcp.last_win == 0 ?
1 : ct->proto.tcp.last_win;
ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_scale =
ct->proto.tcp.last_wscale;
ct->proto.tcp.seen[ct->proto.tcp.last_dir].flags =
ct->proto.tcp.last_flags;
memset(&ct->proto.tcp.seen[dir], 0,
sizeof(struct ip_ct_tcp_state));
break;
}
ct->proto.tcp.last_index = index;
ct->proto.tcp.last_dir = dir;
ct->proto.tcp.last_seq = ntohl(th->seq);
ct->proto.tcp.last_end =
segment_seq_plus_len(ntohl(th->seq), skb->len, dataoff, th);
ct->proto.tcp.last_win = ntohs(th->window);
/* a) This is a SYN in ORIGINAL. The client and the server
* may be in sync but we are not. In that case, we annotate
* the TCP options and let the packet go through. If it is a
* valid SYN packet, the server will reply with a SYN/ACK, and
* then we'll get in sync. Otherwise, the server ignores it. */
if (index == TCP_SYN_SET && dir == IP_CT_DIR_ORIGINAL) {
struct ip_ct_tcp_state seen = {};
ct->proto.tcp.last_flags =
ct->proto.tcp.last_wscale = 0;
tcp_options(skb, dataoff, th, &seen);
if (seen.flags & IP_CT_TCP_FLAG_WINDOW_SCALE) {
ct->proto.tcp.last_flags |=
IP_CT_TCP_FLAG_WINDOW_SCALE;
ct->proto.tcp.last_wscale = seen.td_scale;
}
if (seen.flags & IP_CT_TCP_FLAG_SACK_PERM) {
ct->proto.tcp.last_flags |=
IP_CT_TCP_FLAG_SACK_PERM;
}
}
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: invalid packet ignored ");
return NF_ACCEPT;
case TCP_CONNTRACK_MAX:
/* Invalid packet */
pr_debug("nf_ct_tcp: Invalid dir=%i index=%u ostate=%u\n",
dir, get_conntrack_index(th), old_state);
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: invalid state ");
return -NF_ACCEPT;
case TCP_CONNTRACK_CLOSE:
if (index == TCP_RST_SET
&& (ct->proto.tcp.seen[!dir].flags & IP_CT_TCP_FLAG_MAXACK_SET)
&& before(ntohl(th->seq), ct->proto.tcp.seen[!dir].td_maxack)) {
/* Invalid RST */
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_TCP))
nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
"nf_ct_tcp: invalid RST ");
return -NF_ACCEPT;
}
if (index == TCP_RST_SET
&& ((test_bit(IPS_SEEN_REPLY_BIT, &ct->status)
&& ct->proto.tcp.last_index == TCP_SYN_SET)
|| (!test_bit(IPS_ASSURED_BIT, &ct->status)
&& ct->proto.tcp.last_index == TCP_ACK_SET))
&& ntohl(th->ack_seq) == ct->proto.tcp.last_end) {
/* RST sent to invalid SYN or ACK we had let through
* at a) and c) above:
*
* a) SYN was in window then
* c) we hold a half-open connection.
*
* Delete our connection entry.
* We skip window checking, because packet might ACK
* segments we ignored. */
goto in_window;
}
/* Just fall through */
default:
/* Keep compilers happy. */
break;
}
if (!tcp_in_window(ct, &ct->proto.tcp, dir, index,
skb, dataoff, th, pf)) {
spin_unlock_bh(&ct->lock);
return -NF_ACCEPT;
}
in_window:
/* From now on we have got in-window packets */
ct->proto.tcp.last_index = index;
ct->proto.tcp.last_dir = dir;
pr_debug("tcp_conntracks: ");
nf_ct_dump_tuple(tuple);
pr_debug("syn=%i ack=%i fin=%i rst=%i old=%i new=%i\n",
(th->syn ? 1 : 0), (th->ack ? 1 : 0),
(th->fin ? 1 : 0), (th->rst ? 1 : 0),
old_state, new_state);
ct->proto.tcp.state = new_state;
if (old_state != new_state
&& new_state == TCP_CONNTRACK_FIN_WAIT)
ct->proto.tcp.seen[dir].flags |= IP_CT_TCP_FLAG_CLOSE_INIT;
if (ct->proto.tcp.retrans >= nf_ct_tcp_max_retrans &&
tcp_timeouts[new_state] > nf_ct_tcp_timeout_max_retrans)
timeout = nf_ct_tcp_timeout_max_retrans;
else if ((ct->proto.tcp.seen[0].flags | ct->proto.tcp.seen[1].flags) &
IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED &&
tcp_timeouts[new_state] > nf_ct_tcp_timeout_unacknowledged)
timeout = nf_ct_tcp_timeout_unacknowledged;
else
timeout = tcp_timeouts[new_state];
spin_unlock_bh(&ct->lock);
if (new_state != old_state)
nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
if (!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
/* If only reply is a RST, we can consider ourselves not to
have an established connection: this is a fairly common
problem case, so we can delete the conntrack
immediately. --RR */
if (th->rst) {
nf_ct_kill_acct(ct, ctinfo, skb);
return NF_ACCEPT;
}
} else if (!test_bit(IPS_ASSURED_BIT, &ct->status)
&& (old_state == TCP_CONNTRACK_SYN_RECV
|| old_state == TCP_CONNTRACK_ESTABLISHED)
&& new_state == TCP_CONNTRACK_ESTABLISHED) {
/* Set ASSURED if we see see valid ack in ESTABLISHED
after SYN_RECV or a valid answer for a picked up
connection. */
set_bit(IPS_ASSURED_BIT, &ct->status);
nf_conntrack_event_cache(IPCT_ASSURED, ct);
}
nf_ct_refresh_acct(ct, ctinfo, skb, timeout);
return NF_ACCEPT;
}
/* Called when a new connection for this protocol found. */
static bool tcp_new(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff)
{
enum tcp_conntrack new_state;
const struct tcphdr *th;
struct tcphdr _tcph;
const struct ip_ct_tcp_state *sender = &ct->proto.tcp.seen[0];
const struct ip_ct_tcp_state *receiver = &ct->proto.tcp.seen[1];
th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
BUG_ON(th == NULL);
/* Don't need lock here: this conntrack not in circulation yet */
new_state
= tcp_conntracks[0][get_conntrack_index(th)]
[TCP_CONNTRACK_NONE];
/* Invalid: delete conntrack */
if (new_state >= TCP_CONNTRACK_MAX) {
pr_debug("nf_ct_tcp: invalid new deleting.\n");
return false;
}
if (new_state == TCP_CONNTRACK_SYN_SENT) {
/* SYN packet */
ct->proto.tcp.seen[0].td_end =
segment_seq_plus_len(ntohl(th->seq), skb->len,
dataoff, th);
ct->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
if (ct->proto.tcp.seen[0].td_maxwin == 0)
ct->proto.tcp.seen[0].td_maxwin = 1;
ct->proto.tcp.seen[0].td_maxend =
ct->proto.tcp.seen[0].td_end;
tcp_options(skb, dataoff, th, &ct->proto.tcp.seen[0]);
ct->proto.tcp.seen[1].flags = 0;
} else if (nf_ct_tcp_loose == 0) {
/* Don't try to pick up connections. */
return false;
} else {
/*
* We are in the middle of a connection,
* its history is lost for us.
* Let's try to use the data from the packet.
*/
ct->proto.tcp.seen[0].td_end =
segment_seq_plus_len(ntohl(th->seq), skb->len,
dataoff, th);
ct->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
if (ct->proto.tcp.seen[0].td_maxwin == 0)
ct->proto.tcp.seen[0].td_maxwin = 1;
ct->proto.tcp.seen[0].td_maxend =
ct->proto.tcp.seen[0].td_end +
ct->proto.tcp.seen[0].td_maxwin;
ct->proto.tcp.seen[0].td_scale = 0;
/* We assume SACK and liberal window checking to handle
* window scaling */
ct->proto.tcp.seen[0].flags =
ct->proto.tcp.seen[1].flags = IP_CT_TCP_FLAG_SACK_PERM |
IP_CT_TCP_FLAG_BE_LIBERAL;
}
ct->proto.tcp.seen[1].td_end = 0;
ct->proto.tcp.seen[1].td_maxend = 0;
ct->proto.tcp.seen[1].td_maxwin = 0;
ct->proto.tcp.seen[1].td_scale = 0;
/* tcp_packet will set them */
ct->proto.tcp.state = TCP_CONNTRACK_NONE;
ct->proto.tcp.last_index = TCP_NONE_SET;
pr_debug("tcp_new: sender end=%u maxend=%u maxwin=%u scale=%i "
"receiver end=%u maxend=%u maxwin=%u scale=%i\n",
sender->td_end, sender->td_maxend, sender->td_maxwin,
sender->td_scale,
receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
receiver->td_scale);
return true;
}
#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nfnetlink_conntrack.h>
static int tcp_to_nlattr(struct sk_buff *skb, struct nlattr *nla,
struct nf_conn *ct)
{
struct nlattr *nest_parms;
struct nf_ct_tcp_flags tmp = {};
spin_lock_bh(&ct->lock);
nest_parms = nla_nest_start(skb, CTA_PROTOINFO_TCP | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_STATE, ct->proto.tcp.state);
NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_WSCALE_ORIGINAL,
ct->proto.tcp.seen[0].td_scale);
NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_WSCALE_REPLY,
ct->proto.tcp.seen[1].td_scale);
tmp.flags = ct->proto.tcp.seen[0].flags;
NLA_PUT(skb, CTA_PROTOINFO_TCP_FLAGS_ORIGINAL,
sizeof(struct nf_ct_tcp_flags), &tmp);
tmp.flags = ct->proto.tcp.seen[1].flags;
NLA_PUT(skb, CTA_PROTOINFO_TCP_FLAGS_REPLY,
sizeof(struct nf_ct_tcp_flags), &tmp);
spin_unlock_bh(&ct->lock);
nla_nest_end(skb, nest_parms);
return 0;
nla_put_failure:
spin_unlock_bh(&ct->lock);
return -1;
}
static const struct nla_policy tcp_nla_policy[CTA_PROTOINFO_TCP_MAX+1] = {
[CTA_PROTOINFO_TCP_STATE] = { .type = NLA_U8 },
[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] = { .type = NLA_U8 },
[CTA_PROTOINFO_TCP_WSCALE_REPLY] = { .type = NLA_U8 },
[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL] = { .len = sizeof(struct nf_ct_tcp_flags) },
[CTA_PROTOINFO_TCP_FLAGS_REPLY] = { .len = sizeof(struct nf_ct_tcp_flags) },
};
static int nlattr_to_tcp(struct nlattr *cda[], struct nf_conn *ct)
{
struct nlattr *pattr = cda[CTA_PROTOINFO_TCP];
struct nlattr *tb[CTA_PROTOINFO_TCP_MAX+1];
int err;
/* updates could not contain anything about the private
* protocol info, in that case skip the parsing */
if (!pattr)
return 0;
err = nla_parse_nested(tb, CTA_PROTOINFO_TCP_MAX, pattr, tcp_nla_policy);
if (err < 0)
return err;
if (tb[CTA_PROTOINFO_TCP_STATE] &&
nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]) >= TCP_CONNTRACK_MAX)
return -EINVAL;
spin_lock_bh(&ct->lock);
if (tb[CTA_PROTOINFO_TCP_STATE])
ct->proto.tcp.state = nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]);
if (tb[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]) {
struct nf_ct_tcp_flags *attr =
nla_data(tb[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]);
ct->proto.tcp.seen[0].flags &= ~attr->mask;
ct->proto.tcp.seen[0].flags |= attr->flags & attr->mask;
}
if (tb[CTA_PROTOINFO_TCP_FLAGS_REPLY]) {
struct nf_ct_tcp_flags *attr =
nla_data(tb[CTA_PROTOINFO_TCP_FLAGS_REPLY]);
ct->proto.tcp.seen[1].flags &= ~attr->mask;
ct->proto.tcp.seen[1].flags |= attr->flags & attr->mask;
}
if (tb[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] &&
tb[CTA_PROTOINFO_TCP_WSCALE_REPLY] &&
ct->proto.tcp.seen[0].flags & IP_CT_TCP_FLAG_WINDOW_SCALE &&
ct->proto.tcp.seen[1].flags & IP_CT_TCP_FLAG_WINDOW_SCALE) {
ct->proto.tcp.seen[0].td_scale =
nla_get_u8(tb[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL]);
ct->proto.tcp.seen[1].td_scale =
nla_get_u8(tb[CTA_PROTOINFO_TCP_WSCALE_REPLY]);
}
spin_unlock_bh(&ct->lock);
return 0;
}
static int tcp_nlattr_size(void)
{
return nla_total_size(0) /* CTA_PROTOINFO_TCP */
+ nla_policy_len(tcp_nla_policy, CTA_PROTOINFO_TCP_MAX + 1);
}
static int tcp_nlattr_tuple_size(void)
{
return nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
}
#endif
#ifdef CONFIG_SYSCTL
static unsigned int tcp_sysctl_table_users;
static struct ctl_table_header *tcp_sysctl_header;
static struct ctl_table tcp_sysctl_table[] = {
{
.procname = "nf_conntrack_tcp_timeout_syn_sent",
.data = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_syn_recv",
.data = &tcp_timeouts[TCP_CONNTRACK_SYN_RECV],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_established",
.data = &tcp_timeouts[TCP_CONNTRACK_ESTABLISHED],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_fin_wait",
.data = &tcp_timeouts[TCP_CONNTRACK_FIN_WAIT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_close_wait",
.data = &tcp_timeouts[TCP_CONNTRACK_CLOSE_WAIT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_last_ack",
.data = &tcp_timeouts[TCP_CONNTRACK_LAST_ACK],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_time_wait",
.data = &tcp_timeouts[TCP_CONNTRACK_TIME_WAIT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_close",
.data = &tcp_timeouts[TCP_CONNTRACK_CLOSE],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_max_retrans",
.data = &nf_ct_tcp_timeout_max_retrans,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_timeout_unacknowledged",
.data = &nf_ct_tcp_timeout_unacknowledged,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_tcp_loose",
.data = &nf_ct_tcp_loose,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "nf_conntrack_tcp_be_liberal",
.data = &nf_ct_tcp_be_liberal,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "nf_conntrack_tcp_max_retrans",
.data = &nf_ct_tcp_max_retrans,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
static struct ctl_table tcp_compat_sysctl_table[] = {
{
.procname = "ip_conntrack_tcp_timeout_syn_sent",
.data = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_syn_sent2",
.data = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT2],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_syn_recv",
.data = &tcp_timeouts[TCP_CONNTRACK_SYN_RECV],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_established",
.data = &tcp_timeouts[TCP_CONNTRACK_ESTABLISHED],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_fin_wait",
.data = &tcp_timeouts[TCP_CONNTRACK_FIN_WAIT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_close_wait",
.data = &tcp_timeouts[TCP_CONNTRACK_CLOSE_WAIT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_last_ack",
.data = &tcp_timeouts[TCP_CONNTRACK_LAST_ACK],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_time_wait",
.data = &tcp_timeouts[TCP_CONNTRACK_TIME_WAIT],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_close",
.data = &tcp_timeouts[TCP_CONNTRACK_CLOSE],
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_timeout_max_retrans",
.data = &nf_ct_tcp_timeout_max_retrans,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "ip_conntrack_tcp_loose",
.data = &nf_ct_tcp_loose,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "ip_conntrack_tcp_be_liberal",
.data = &nf_ct_tcp_be_liberal,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "ip_conntrack_tcp_max_retrans",
.data = &nf_ct_tcp_max_retrans,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
#endif /* CONFIG_NF_CONNTRACK_PROC_COMPAT */
#endif /* CONFIG_SYSCTL */
struct nf_conntrack_l4proto nf_conntrack_l4proto_tcp4 __read_mostly =
{
.l3proto = PF_INET,
.l4proto = IPPROTO_TCP,
.name = "tcp",
.pkt_to_tuple = tcp_pkt_to_tuple,
.invert_tuple = tcp_invert_tuple,
.print_tuple = tcp_print_tuple,
.print_conntrack = tcp_print_conntrack,
.packet = tcp_packet,
.new = tcp_new,
.error = tcp_error,
#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
.to_nlattr = tcp_to_nlattr,
.nlattr_size = tcp_nlattr_size,
.from_nlattr = nlattr_to_tcp,
.tuple_to_nlattr = nf_ct_port_tuple_to_nlattr,
.nlattr_to_tuple = nf_ct_port_nlattr_to_tuple,
.nlattr_tuple_size = tcp_nlattr_tuple_size,
.nla_policy = nf_ct_port_nla_policy,
#endif
#ifdef CONFIG_SYSCTL
.ctl_table_users = &tcp_sysctl_table_users,
.ctl_table_header = &tcp_sysctl_header,
.ctl_table = tcp_sysctl_table,
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
.ctl_compat_table = tcp_compat_sysctl_table,
#endif
#endif
};
EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_tcp4);
struct nf_conntrack_l4proto nf_conntrack_l4proto_tcp6 __read_mostly =
{
.l3proto = PF_INET6,
.l4proto = IPPROTO_TCP,
.name = "tcp",
.pkt_to_tuple = tcp_pkt_to_tuple,
.invert_tuple = tcp_invert_tuple,
.print_tuple = tcp_print_tuple,
.print_conntrack = tcp_print_conntrack,
.packet = tcp_packet,
.new = tcp_new,
.error = tcp_error,
#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
.to_nlattr = tcp_to_nlattr,
.nlattr_size = tcp_nlattr_size,
.from_nlattr = nlattr_to_tcp,
.tuple_to_nlattr = nf_ct_port_tuple_to_nlattr,
.nlattr_to_tuple = nf_ct_port_nlattr_to_tuple,
.nlattr_tuple_size = tcp_nlattr_tuple_size,
.nla_policy = nf_ct_port_nla_policy,
#endif
#ifdef CONFIG_SYSCTL
.ctl_table_users = &tcp_sysctl_table_users,
.ctl_table_header = &tcp_sysctl_header,
.ctl_table = tcp_sysctl_table,
#endif
};
EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_tcp6);
| gpl-2.0 |
leeymcj/linuxrk-tk1 | arch/arm/kernel/perf_event_v6.c | 1576 | 21767 | /*
* ARMv6 Performance counter handling code.
*
* Copyright (C) 2009 picoChip Designs, Ltd., Jamie Iles
*
* ARMv6 has 2 configurable performance counters and a single cycle counter.
* They all share a single reset bit but can be written to zero so we can use
* that for a reset.
*
* The counters can't be individually enabled or disabled so when we remove
* one event and replace it with another we could get spurious counts from the
* wrong event. However, we can take advantage of the fact that the
* performance counters can export events to the event bus, and the event bus
* itself can be monitored. This requires that we *don't* export the events to
* the event bus. The procedure for disabling a configurable counter is:
* - change the counter to count the ETMEXTOUT[0] signal (0x20). This
* effectively stops the counter from counting.
* - disable the counter's interrupt generation (each counter has it's
* own interrupt enable bit).
* Once stopped, the counter value can be written as 0 to reset.
*
* To enable a counter:
* - enable the counter's interrupt generation.
* - set the new event type.
*
* Note: the dedicated cycle counter only counts cycles and can't be
* enabled/disabled independently of the others. When we want to disable the
* cycle counter, we have to just disable the interrupt reporting and start
* ignoring that counter. When re-enabling, we have to reset the value and
* enable the interrupt.
*/
#if defined(CONFIG_CPU_V6) || defined(CONFIG_CPU_V6K)
enum armv6_perf_types {
ARMV6_PERFCTR_ICACHE_MISS = 0x0,
ARMV6_PERFCTR_IBUF_STALL = 0x1,
ARMV6_PERFCTR_DDEP_STALL = 0x2,
ARMV6_PERFCTR_ITLB_MISS = 0x3,
ARMV6_PERFCTR_DTLB_MISS = 0x4,
ARMV6_PERFCTR_BR_EXEC = 0x5,
ARMV6_PERFCTR_BR_MISPREDICT = 0x6,
ARMV6_PERFCTR_INSTR_EXEC = 0x7,
ARMV6_PERFCTR_DCACHE_HIT = 0x9,
ARMV6_PERFCTR_DCACHE_ACCESS = 0xA,
ARMV6_PERFCTR_DCACHE_MISS = 0xB,
ARMV6_PERFCTR_DCACHE_WBACK = 0xC,
ARMV6_PERFCTR_SW_PC_CHANGE = 0xD,
ARMV6_PERFCTR_MAIN_TLB_MISS = 0xF,
ARMV6_PERFCTR_EXPL_D_ACCESS = 0x10,
ARMV6_PERFCTR_LSU_FULL_STALL = 0x11,
ARMV6_PERFCTR_WBUF_DRAINED = 0x12,
ARMV6_PERFCTR_CPU_CYCLES = 0xFF,
ARMV6_PERFCTR_NOP = 0x20,
};
enum armv6_counters {
ARMV6_CYCLE_COUNTER = 0,
ARMV6_COUNTER0,
ARMV6_COUNTER1,
};
/*
* The hardware events that we support. We do support cache operations but
* we have harvard caches and no way to combine instruction and data
* accesses/misses in hardware.
*/
static const unsigned armv6_perf_map[PERF_COUNT_HW_MAX] = {
[PERF_COUNT_HW_CPU_CYCLES] = ARMV6_PERFCTR_CPU_CYCLES,
[PERF_COUNT_HW_INSTRUCTIONS] = ARMV6_PERFCTR_INSTR_EXEC,
[PERF_COUNT_HW_CACHE_REFERENCES] = HW_OP_UNSUPPORTED,
[PERF_COUNT_HW_CACHE_MISSES] = HW_OP_UNSUPPORTED,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = ARMV6_PERFCTR_BR_EXEC,
[PERF_COUNT_HW_BRANCH_MISSES] = ARMV6_PERFCTR_BR_MISPREDICT,
[PERF_COUNT_HW_BUS_CYCLES] = HW_OP_UNSUPPORTED,
[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = ARMV6_PERFCTR_IBUF_STALL,
[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = ARMV6_PERFCTR_LSU_FULL_STALL,
};
static const unsigned armv6_perf_cache_map[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] = {
[C(L1D)] = {
/*
* The performance counters don't differentiate between read
* and write accesses/misses so this isn't strictly correct,
* but it's the best we can do. Writes and reads get
* combined.
*/
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = ARMV6_PERFCTR_DCACHE_ACCESS,
[C(RESULT_MISS)] = ARMV6_PERFCTR_DCACHE_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = ARMV6_PERFCTR_DCACHE_ACCESS,
[C(RESULT_MISS)] = ARMV6_PERFCTR_DCACHE_MISS,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6_PERFCTR_ICACHE_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(DTLB)] = {
/*
* The ARM performance counters can count micro DTLB misses,
* micro ITLB misses and main TLB misses. There isn't an event
* for TLB misses, so use the micro misses here and if users
* want the main TLB misses they can use a raw counter.
*/
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6_PERFCTR_DTLB_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6_PERFCTR_DTLB_MISS,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6_PERFCTR_ITLB_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6_PERFCTR_ITLB_MISS,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(NODE)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
};
enum armv6mpcore_perf_types {
ARMV6MPCORE_PERFCTR_ICACHE_MISS = 0x0,
ARMV6MPCORE_PERFCTR_IBUF_STALL = 0x1,
ARMV6MPCORE_PERFCTR_DDEP_STALL = 0x2,
ARMV6MPCORE_PERFCTR_ITLB_MISS = 0x3,
ARMV6MPCORE_PERFCTR_DTLB_MISS = 0x4,
ARMV6MPCORE_PERFCTR_BR_EXEC = 0x5,
ARMV6MPCORE_PERFCTR_BR_NOTPREDICT = 0x6,
ARMV6MPCORE_PERFCTR_BR_MISPREDICT = 0x7,
ARMV6MPCORE_PERFCTR_INSTR_EXEC = 0x8,
ARMV6MPCORE_PERFCTR_DCACHE_RDACCESS = 0xA,
ARMV6MPCORE_PERFCTR_DCACHE_RDMISS = 0xB,
ARMV6MPCORE_PERFCTR_DCACHE_WRACCESS = 0xC,
ARMV6MPCORE_PERFCTR_DCACHE_WRMISS = 0xD,
ARMV6MPCORE_PERFCTR_DCACHE_EVICTION = 0xE,
ARMV6MPCORE_PERFCTR_SW_PC_CHANGE = 0xF,
ARMV6MPCORE_PERFCTR_MAIN_TLB_MISS = 0x10,
ARMV6MPCORE_PERFCTR_EXPL_MEM_ACCESS = 0x11,
ARMV6MPCORE_PERFCTR_LSU_FULL_STALL = 0x12,
ARMV6MPCORE_PERFCTR_WBUF_DRAINED = 0x13,
ARMV6MPCORE_PERFCTR_CPU_CYCLES = 0xFF,
};
/*
* The hardware events that we support. We do support cache operations but
* we have harvard caches and no way to combine instruction and data
* accesses/misses in hardware.
*/
static const unsigned armv6mpcore_perf_map[PERF_COUNT_HW_MAX] = {
[PERF_COUNT_HW_CPU_CYCLES] = ARMV6MPCORE_PERFCTR_CPU_CYCLES,
[PERF_COUNT_HW_INSTRUCTIONS] = ARMV6MPCORE_PERFCTR_INSTR_EXEC,
[PERF_COUNT_HW_CACHE_REFERENCES] = HW_OP_UNSUPPORTED,
[PERF_COUNT_HW_CACHE_MISSES] = HW_OP_UNSUPPORTED,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = ARMV6MPCORE_PERFCTR_BR_EXEC,
[PERF_COUNT_HW_BRANCH_MISSES] = ARMV6MPCORE_PERFCTR_BR_MISPREDICT,
[PERF_COUNT_HW_BUS_CYCLES] = HW_OP_UNSUPPORTED,
[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = ARMV6MPCORE_PERFCTR_IBUF_STALL,
[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = ARMV6MPCORE_PERFCTR_LSU_FULL_STALL,
};
static const unsigned armv6mpcore_perf_cache_map[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] =
ARMV6MPCORE_PERFCTR_DCACHE_RDACCESS,
[C(RESULT_MISS)] =
ARMV6MPCORE_PERFCTR_DCACHE_RDMISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] =
ARMV6MPCORE_PERFCTR_DCACHE_WRACCESS,
[C(RESULT_MISS)] =
ARMV6MPCORE_PERFCTR_DCACHE_WRMISS,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6MPCORE_PERFCTR_ICACHE_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(DTLB)] = {
/*
* The ARM performance counters can count micro DTLB misses,
* micro ITLB misses and main TLB misses. There isn't an event
* for TLB misses, so use the micro misses here and if users
* want the main TLB misses they can use a raw counter.
*/
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6MPCORE_PERFCTR_DTLB_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6MPCORE_PERFCTR_DTLB_MISS,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6MPCORE_PERFCTR_ITLB_MISS,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = ARMV6MPCORE_PERFCTR_ITLB_MISS,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
[C(NODE)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
},
},
};
static inline unsigned long
armv6_pmcr_read(void)
{
u32 val;
asm volatile("mrc p15, 0, %0, c15, c12, 0" : "=r"(val));
return val;
}
static inline void
armv6_pmcr_write(unsigned long val)
{
asm volatile("mcr p15, 0, %0, c15, c12, 0" : : "r"(val));
}
#define ARMV6_PMCR_ENABLE (1 << 0)
#define ARMV6_PMCR_CTR01_RESET (1 << 1)
#define ARMV6_PMCR_CCOUNT_RESET (1 << 2)
#define ARMV6_PMCR_CCOUNT_DIV (1 << 3)
#define ARMV6_PMCR_COUNT0_IEN (1 << 4)
#define ARMV6_PMCR_COUNT1_IEN (1 << 5)
#define ARMV6_PMCR_CCOUNT_IEN (1 << 6)
#define ARMV6_PMCR_COUNT0_OVERFLOW (1 << 8)
#define ARMV6_PMCR_COUNT1_OVERFLOW (1 << 9)
#define ARMV6_PMCR_CCOUNT_OVERFLOW (1 << 10)
#define ARMV6_PMCR_EVT_COUNT0_SHIFT 20
#define ARMV6_PMCR_EVT_COUNT0_MASK (0xFF << ARMV6_PMCR_EVT_COUNT0_SHIFT)
#define ARMV6_PMCR_EVT_COUNT1_SHIFT 12
#define ARMV6_PMCR_EVT_COUNT1_MASK (0xFF << ARMV6_PMCR_EVT_COUNT1_SHIFT)
#define ARMV6_PMCR_OVERFLOWED_MASK \
(ARMV6_PMCR_COUNT0_OVERFLOW | ARMV6_PMCR_COUNT1_OVERFLOW | \
ARMV6_PMCR_CCOUNT_OVERFLOW)
static inline int
armv6_pmcr_has_overflowed(unsigned long pmcr)
{
return pmcr & ARMV6_PMCR_OVERFLOWED_MASK;
}
static inline int
armv6_pmcr_counter_has_overflowed(unsigned long pmcr,
enum armv6_counters counter)
{
int ret = 0;
if (ARMV6_CYCLE_COUNTER == counter)
ret = pmcr & ARMV6_PMCR_CCOUNT_OVERFLOW;
else if (ARMV6_COUNTER0 == counter)
ret = pmcr & ARMV6_PMCR_COUNT0_OVERFLOW;
else if (ARMV6_COUNTER1 == counter)
ret = pmcr & ARMV6_PMCR_COUNT1_OVERFLOW;
else
WARN_ONCE(1, "invalid counter number (%d)\n", counter);
return ret;
}
static inline u32 armv6pmu_read_counter(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
int counter = hwc->idx;
unsigned long value = 0;
if (ARMV6_CYCLE_COUNTER == counter)
asm volatile("mrc p15, 0, %0, c15, c12, 1" : "=r"(value));
else if (ARMV6_COUNTER0 == counter)
asm volatile("mrc p15, 0, %0, c15, c12, 2" : "=r"(value));
else if (ARMV6_COUNTER1 == counter)
asm volatile("mrc p15, 0, %0, c15, c12, 3" : "=r"(value));
else
WARN_ONCE(1, "invalid counter number (%d)\n", counter);
return value;
}
static inline void armv6pmu_write_counter(struct perf_event *event, u32 value)
{
struct hw_perf_event *hwc = &event->hw;
int counter = hwc->idx;
if (ARMV6_CYCLE_COUNTER == counter)
asm volatile("mcr p15, 0, %0, c15, c12, 1" : : "r"(value));
else if (ARMV6_COUNTER0 == counter)
asm volatile("mcr p15, 0, %0, c15, c12, 2" : : "r"(value));
else if (ARMV6_COUNTER1 == counter)
asm volatile("mcr p15, 0, %0, c15, c12, 3" : : "r"(value));
else
WARN_ONCE(1, "invalid counter number (%d)\n", counter);
}
static void armv6pmu_enable_event(struct perf_event *event)
{
unsigned long val, mask, evt, flags;
struct arm_pmu *cpu_pmu = to_arm_pmu(event->pmu);
struct hw_perf_event *hwc = &event->hw;
struct pmu_hw_events *events = cpu_pmu->get_hw_events();
int idx = hwc->idx;
if (ARMV6_CYCLE_COUNTER == idx) {
mask = 0;
evt = ARMV6_PMCR_CCOUNT_IEN;
} else if (ARMV6_COUNTER0 == idx) {
mask = ARMV6_PMCR_EVT_COUNT0_MASK;
evt = (hwc->config_base << ARMV6_PMCR_EVT_COUNT0_SHIFT) |
ARMV6_PMCR_COUNT0_IEN;
} else if (ARMV6_COUNTER1 == idx) {
mask = ARMV6_PMCR_EVT_COUNT1_MASK;
evt = (hwc->config_base << ARMV6_PMCR_EVT_COUNT1_SHIFT) |
ARMV6_PMCR_COUNT1_IEN;
} else {
WARN_ONCE(1, "invalid counter number (%d)\n", idx);
return;
}
/*
* Mask out the current event and set the counter to count the event
* that we're interested in.
*/
raw_spin_lock_irqsave(&events->pmu_lock, flags);
val = armv6_pmcr_read();
val &= ~mask;
val |= evt;
armv6_pmcr_write(val);
raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}
static irqreturn_t
armv6pmu_handle_irq(int irq_num,
void *dev)
{
unsigned long pmcr = armv6_pmcr_read();
struct perf_sample_data data;
struct arm_pmu *cpu_pmu = (struct arm_pmu *)dev;
struct pmu_hw_events *cpuc = cpu_pmu->get_hw_events();
struct pt_regs *regs;
int idx;
if (!armv6_pmcr_has_overflowed(pmcr))
return IRQ_NONE;
regs = get_irq_regs();
/*
* The interrupts are cleared by writing the overflow flags back to
* the control register. All of the other bits don't have any effect
* if they are rewritten, so write the whole value back.
*/
armv6_pmcr_write(pmcr);
for (idx = 0; idx < cpu_pmu->num_events; ++idx) {
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc;
/* Ignore if we don't have an event. */
if (!event)
continue;
/*
* We have a single interrupt for all counters. Check that
* each counter has overflowed before we process it.
*/
if (!armv6_pmcr_counter_has_overflowed(pmcr, idx))
continue;
hwc = &event->hw;
armpmu_event_update(event);
perf_sample_data_init(&data, 0, hwc->last_period);
if (!armpmu_event_set_period(event))
continue;
if (perf_event_overflow(event, &data, regs))
cpu_pmu->disable(event);
}
/*
* Handle the pending perf events.
*
* Note: this call *must* be run with interrupts disabled. For
* platforms that can have the PMU interrupts raised as an NMI, this
* will not work.
*/
irq_work_run();
return IRQ_HANDLED;
}
static void armv6pmu_start(struct arm_pmu *cpu_pmu)
{
unsigned long flags, val;
struct pmu_hw_events *events = cpu_pmu->get_hw_events();
raw_spin_lock_irqsave(&events->pmu_lock, flags);
val = armv6_pmcr_read();
val |= ARMV6_PMCR_ENABLE;
armv6_pmcr_write(val);
raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}
static void armv6pmu_stop(struct arm_pmu *cpu_pmu)
{
unsigned long flags, val;
struct pmu_hw_events *events = cpu_pmu->get_hw_events();
raw_spin_lock_irqsave(&events->pmu_lock, flags);
val = armv6_pmcr_read();
val &= ~ARMV6_PMCR_ENABLE;
armv6_pmcr_write(val);
raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}
static int
armv6pmu_get_event_idx(struct pmu_hw_events *cpuc,
struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
/* Always place a cycle counter into the cycle counter. */
if (ARMV6_PERFCTR_CPU_CYCLES == hwc->config_base) {
if (test_and_set_bit(ARMV6_CYCLE_COUNTER, cpuc->used_mask))
return -EAGAIN;
return ARMV6_CYCLE_COUNTER;
} else {
/*
* For anything other than a cycle counter, try and use
* counter0 and counter1.
*/
if (!test_and_set_bit(ARMV6_COUNTER1, cpuc->used_mask))
return ARMV6_COUNTER1;
if (!test_and_set_bit(ARMV6_COUNTER0, cpuc->used_mask))
return ARMV6_COUNTER0;
/* The counters are all in use. */
return -EAGAIN;
}
}
static void armv6pmu_disable_event(struct perf_event *event)
{
unsigned long val, mask, evt, flags;
struct arm_pmu *cpu_pmu = to_arm_pmu(event->pmu);
struct hw_perf_event *hwc = &event->hw;
struct pmu_hw_events *events = cpu_pmu->get_hw_events();
int idx = hwc->idx;
if (ARMV6_CYCLE_COUNTER == idx) {
mask = ARMV6_PMCR_CCOUNT_IEN;
evt = 0;
} else if (ARMV6_COUNTER0 == idx) {
mask = ARMV6_PMCR_COUNT0_IEN | ARMV6_PMCR_EVT_COUNT0_MASK;
evt = ARMV6_PERFCTR_NOP << ARMV6_PMCR_EVT_COUNT0_SHIFT;
} else if (ARMV6_COUNTER1 == idx) {
mask = ARMV6_PMCR_COUNT1_IEN | ARMV6_PMCR_EVT_COUNT1_MASK;
evt = ARMV6_PERFCTR_NOP << ARMV6_PMCR_EVT_COUNT1_SHIFT;
} else {
WARN_ONCE(1, "invalid counter number (%d)\n", idx);
return;
}
/*
* Mask out the current event and set the counter to count the number
* of ETM bus signal assertion cycles. The external reporting should
* be disabled and so this should never increment.
*/
raw_spin_lock_irqsave(&events->pmu_lock, flags);
val = armv6_pmcr_read();
val &= ~mask;
val |= evt;
armv6_pmcr_write(val);
raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}
static void armv6mpcore_pmu_disable_event(struct perf_event *event)
{
unsigned long val, mask, flags, evt = 0;
struct arm_pmu *cpu_pmu = to_arm_pmu(event->pmu);
struct hw_perf_event *hwc = &event->hw;
struct pmu_hw_events *events = cpu_pmu->get_hw_events();
int idx = hwc->idx;
if (ARMV6_CYCLE_COUNTER == idx) {
mask = ARMV6_PMCR_CCOUNT_IEN;
} else if (ARMV6_COUNTER0 == idx) {
mask = ARMV6_PMCR_COUNT0_IEN;
} else if (ARMV6_COUNTER1 == idx) {
mask = ARMV6_PMCR_COUNT1_IEN;
} else {
WARN_ONCE(1, "invalid counter number (%d)\n", idx);
return;
}
/*
* Unlike UP ARMv6, we don't have a way of stopping the counters. We
* simply disable the interrupt reporting.
*/
raw_spin_lock_irqsave(&events->pmu_lock, flags);
val = armv6_pmcr_read();
val &= ~mask;
val |= evt;
armv6_pmcr_write(val);
raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}
static int armv6_map_event(struct perf_event *event)
{
return armpmu_map_event(event, &armv6_perf_map,
&armv6_perf_cache_map, 0xFF);
}
static int armv6pmu_init(struct arm_pmu *cpu_pmu)
{
cpu_pmu->name = "v6";
cpu_pmu->handle_irq = armv6pmu_handle_irq;
cpu_pmu->enable = armv6pmu_enable_event;
cpu_pmu->disable = armv6pmu_disable_event;
cpu_pmu->read_counter = armv6pmu_read_counter;
cpu_pmu->write_counter = armv6pmu_write_counter;
cpu_pmu->get_event_idx = armv6pmu_get_event_idx;
cpu_pmu->start = armv6pmu_start;
cpu_pmu->stop = armv6pmu_stop;
cpu_pmu->map_event = armv6_map_event;
cpu_pmu->num_events = 3;
cpu_pmu->max_period = (1LLU << 32) - 1;
return 0;
}
/*
* ARMv6mpcore is almost identical to single core ARMv6 with the exception
* that some of the events have different enumerations and that there is no
* *hack* to stop the programmable counters. To stop the counters we simply
* disable the interrupt reporting and update the event. When unthrottling we
* reset the period and enable the interrupt reporting.
*/
static int armv6mpcore_map_event(struct perf_event *event)
{
return armpmu_map_event(event, &armv6mpcore_perf_map,
&armv6mpcore_perf_cache_map, 0xFF);
}
static int armv6mpcore_pmu_init(struct arm_pmu *cpu_pmu)
{
cpu_pmu->name = "v6mpcore";
cpu_pmu->handle_irq = armv6pmu_handle_irq;
cpu_pmu->enable = armv6pmu_enable_event;
cpu_pmu->disable = armv6mpcore_pmu_disable_event;
cpu_pmu->read_counter = armv6pmu_read_counter;
cpu_pmu->write_counter = armv6pmu_write_counter;
cpu_pmu->get_event_idx = armv6pmu_get_event_idx;
cpu_pmu->start = armv6pmu_start;
cpu_pmu->stop = armv6pmu_stop;
cpu_pmu->map_event = armv6mpcore_map_event;
cpu_pmu->num_events = 3;
cpu_pmu->max_period = (1LLU << 32) - 1;
return 0;
}
#else
static int armv6pmu_init(struct arm_pmu *cpu_pmu)
{
return -ENODEV;
}
static int armv6mpcore_pmu_init(struct arm_pmu *cpu_pmu)
{
return -ENODEV;
}
#endif /* CONFIG_CPU_V6 || CONFIG_CPU_V6K */
| gpl-2.0 |
GusBricker/surfacepro2-kernel | drivers/staging/tidspbridge/core/dsp-clock.c | 1576 | 8878 | /*
* clk.c
*
* DSP-BIOS Bridge driver support functions for TI OMAP processors.
*
* Clock and Timer services.
*
* Copyright (C) 2005-2006 Texas Instruments, Inc.
*
* This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#define L4_34XX_BASE 0x48000000
#include <linux/types.h>
/* ----------------------------------- Host OS */
#include <dspbridge/host_os.h>
#include <plat/dmtimer.h>
#include <linux/platform_data/asoc-ti-mcbsp.h>
/* ----------------------------------- DSP/BIOS Bridge */
#include <dspbridge/dbdefs.h>
#include <dspbridge/drv.h>
#include <dspbridge/dev.h>
#include "_tiomap.h"
/* ----------------------------------- This */
#include <dspbridge/clk.h>
/* ----------------------------------- Defines, Data Structures, Typedefs */
#define OMAP_SSI_OFFSET 0x58000
#define OMAP_SSI_SIZE 0x1000
#define OMAP_SSI_SYSCONFIG_OFFSET 0x10
#define SSI_AUTOIDLE (1 << 0)
#define SSI_SIDLE_SMARTIDLE (2 << 3)
#define SSI_MIDLE_NOIDLE (1 << 12)
/* Clk types requested by the dsp */
#define IVA2_CLK 0
#define GPT_CLK 1
#define WDT_CLK 2
#define MCBSP_CLK 3
#define SSI_CLK 4
/* Bridge GPT id (1 - 4), DM Timer id (5 - 8) */
#define DMT_ID(id) ((id) + 4)
#define DM_TIMER_CLOCKS 4
/* Bridge MCBSP id (6 - 10), OMAP Mcbsp id (0 - 4) */
#define MCBSP_ID(id) ((id) - 6)
static struct omap_dm_timer *timer[4];
struct clk *iva2_clk;
struct dsp_ssi {
struct clk *sst_fck;
struct clk *ssr_fck;
struct clk *ick;
};
static struct dsp_ssi ssi;
static u32 dsp_clocks;
static inline u32 is_dsp_clk_active(u32 clk, u8 id)
{
return clk & (1 << id);
}
static inline void set_dsp_clk_active(u32 *clk, u8 id)
{
*clk |= (1 << id);
}
static inline void set_dsp_clk_inactive(u32 *clk, u8 id)
{
*clk &= ~(1 << id);
}
static s8 get_clk_type(u8 id)
{
s8 type;
if (id == DSP_CLK_IVA2)
type = IVA2_CLK;
else if (id <= DSP_CLK_GPT8)
type = GPT_CLK;
else if (id == DSP_CLK_WDT3)
type = WDT_CLK;
else if (id <= DSP_CLK_MCBSP5)
type = MCBSP_CLK;
else if (id == DSP_CLK_SSI)
type = SSI_CLK;
else
type = -1;
return type;
}
/*
* ======== dsp_clk_exit ========
* Purpose:
* Cleanup CLK module.
*/
void dsp_clk_exit(void)
{
int i;
dsp_clock_disable_all(dsp_clocks);
for (i = 0; i < DM_TIMER_CLOCKS; i++)
omap_dm_timer_free(timer[i]);
clk_unprepare(iva2_clk);
clk_put(iva2_clk);
clk_unprepare(ssi.sst_fck);
clk_put(ssi.sst_fck);
clk_unprepare(ssi.ssr_fck);
clk_put(ssi.ssr_fck);
clk_unprepare(ssi.ick);
clk_put(ssi.ick);
}
/*
* ======== dsp_clk_init ========
* Purpose:
* Initialize CLK module.
*/
void dsp_clk_init(void)
{
static struct platform_device dspbridge_device;
int i, id;
dspbridge_device.dev.bus = &platform_bus_type;
for (i = 0, id = 5; i < DM_TIMER_CLOCKS; i++, id++)
timer[i] = omap_dm_timer_request_specific(id);
iva2_clk = clk_get(&dspbridge_device.dev, "iva2_ck");
if (IS_ERR(iva2_clk))
dev_err(bridge, "failed to get iva2 clock %p\n", iva2_clk);
else
clk_prepare(iva2_clk);
ssi.sst_fck = clk_get(&dspbridge_device.dev, "ssi_sst_fck");
ssi.ssr_fck = clk_get(&dspbridge_device.dev, "ssi_ssr_fck");
ssi.ick = clk_get(&dspbridge_device.dev, "ssi_ick");
if (IS_ERR(ssi.sst_fck) || IS_ERR(ssi.ssr_fck) || IS_ERR(ssi.ick)) {
dev_err(bridge, "failed to get ssi: sst %p, ssr %p, ick %p\n",
ssi.sst_fck, ssi.ssr_fck, ssi.ick);
} else {
clk_prepare(ssi.sst_fck);
clk_prepare(ssi.ssr_fck);
clk_prepare(ssi.ick);
}
}
/**
* dsp_gpt_wait_overflow - set gpt overflow and wait for fixed timeout
* @clk_id: GP Timer clock id.
* @load: Overflow value.
*
* Sets an overflow interrupt for the desired GPT waiting for a timeout
* of 5 msecs for the interrupt to occur.
*/
void dsp_gpt_wait_overflow(short int clk_id, unsigned int load)
{
struct omap_dm_timer *gpt = timer[clk_id - 1];
unsigned long timeout;
if (!gpt)
return;
/* Enable overflow interrupt */
omap_dm_timer_set_int_enable(gpt, OMAP_TIMER_INT_OVERFLOW);
/*
* Set counter value to overflow counter after
* one tick and start timer.
*/
omap_dm_timer_set_load_start(gpt, 0, load);
/* Wait 80us for timer to overflow */
udelay(80);
timeout = msecs_to_jiffies(5);
/* Check interrupt status and wait for interrupt */
while (!(omap_dm_timer_read_status(gpt) & OMAP_TIMER_INT_OVERFLOW)) {
if (time_is_after_jiffies(timeout)) {
pr_err("%s: GPTimer interrupt failed\n", __func__);
break;
}
}
}
/*
* ======== dsp_clk_enable ========
* Purpose:
* Enable Clock .
*
*/
int dsp_clk_enable(enum dsp_clk_id clk_id)
{
int status = 0;
if (is_dsp_clk_active(dsp_clocks, clk_id)) {
dev_err(bridge, "WARN: clock id %d already enabled\n", clk_id);
goto out;
}
switch (get_clk_type(clk_id)) {
case IVA2_CLK:
clk_enable(iva2_clk);
break;
case GPT_CLK:
status = omap_dm_timer_start(timer[clk_id - 1]);
break;
#ifdef CONFIG_SND_OMAP_SOC_MCBSP
case MCBSP_CLK:
omap_mcbsp_request(MCBSP_ID(clk_id));
omap2_mcbsp_set_clks_src(MCBSP_ID(clk_id), MCBSP_CLKS_PAD_SRC);
break;
#endif
case WDT_CLK:
dev_err(bridge, "ERROR: DSP requested to enable WDT3 clk\n");
break;
case SSI_CLK:
clk_enable(ssi.sst_fck);
clk_enable(ssi.ssr_fck);
clk_enable(ssi.ick);
/*
* The SSI module need to configured not to have the Forced
* idle for master interface. If it is set to forced idle,
* the SSI module is transitioning to standby thereby causing
* the client in the DSP hang waiting for the SSI module to
* be active after enabling the clocks
*/
ssi_clk_prepare(true);
break;
default:
dev_err(bridge, "Invalid clock id for enable\n");
status = -EPERM;
}
if (!status)
set_dsp_clk_active(&dsp_clocks, clk_id);
out:
return status;
}
/**
* dsp_clock_enable_all - Enable clocks used by the DSP
* @dev_context Driver's device context strucure
*
* This function enables all the peripheral clocks that were requested by DSP.
*/
u32 dsp_clock_enable_all(u32 dsp_per_clocks)
{
u32 clk_id;
u32 status = -EPERM;
for (clk_id = 0; clk_id < DSP_CLK_NOT_DEFINED; clk_id++) {
if (is_dsp_clk_active(dsp_per_clocks, clk_id))
status = dsp_clk_enable(clk_id);
}
return status;
}
/*
* ======== dsp_clk_disable ========
* Purpose:
* Disable the clock.
*
*/
int dsp_clk_disable(enum dsp_clk_id clk_id)
{
int status = 0;
if (!is_dsp_clk_active(dsp_clocks, clk_id)) {
dev_err(bridge, "ERR: clock id %d already disabled\n", clk_id);
goto out;
}
switch (get_clk_type(clk_id)) {
case IVA2_CLK:
clk_disable(iva2_clk);
break;
case GPT_CLK:
status = omap_dm_timer_stop(timer[clk_id - 1]);
break;
#ifdef CONFIG_SND_OMAP_SOC_MCBSP
case MCBSP_CLK:
omap2_mcbsp_set_clks_src(MCBSP_ID(clk_id), MCBSP_CLKS_PRCM_SRC);
omap_mcbsp_free(MCBSP_ID(clk_id));
break;
#endif
case WDT_CLK:
dev_err(bridge, "ERROR: DSP requested to disable WDT3 clk\n");
break;
case SSI_CLK:
ssi_clk_prepare(false);
ssi_clk_prepare(false);
clk_disable(ssi.sst_fck);
clk_disable(ssi.ssr_fck);
clk_disable(ssi.ick);
break;
default:
dev_err(bridge, "Invalid clock id for disable\n");
status = -EPERM;
}
if (!status)
set_dsp_clk_inactive(&dsp_clocks, clk_id);
out:
return status;
}
/**
* dsp_clock_disable_all - Disable all active clocks
* @dev_context Driver's device context structure
*
* This function disables all the peripheral clocks that were enabled by DSP.
* It is meant to be called only when DSP is entering hibernation or when DSP
* is in error state.
*/
u32 dsp_clock_disable_all(u32 dsp_per_clocks)
{
u32 clk_id;
u32 status = -EPERM;
for (clk_id = 0; clk_id < DSP_CLK_NOT_DEFINED; clk_id++) {
if (is_dsp_clk_active(dsp_per_clocks, clk_id))
status = dsp_clk_disable(clk_id);
}
return status;
}
u32 dsp_clk_get_iva2_rate(void)
{
u32 clk_speed_khz;
clk_speed_khz = clk_get_rate(iva2_clk);
clk_speed_khz /= 1000;
dev_dbg(bridge, "%s: clk speed Khz = %d\n", __func__, clk_speed_khz);
return clk_speed_khz;
}
void ssi_clk_prepare(bool FLAG)
{
void __iomem *ssi_base;
unsigned int value;
ssi_base = ioremap(L4_34XX_BASE + OMAP_SSI_OFFSET, OMAP_SSI_SIZE);
if (!ssi_base) {
pr_err("%s: error, SSI not configured\n", __func__);
return;
}
if (FLAG) {
/* Set Autoidle, SIDLEMode to smart idle, and MIDLEmode to
* no idle
*/
value = SSI_AUTOIDLE | SSI_SIDLE_SMARTIDLE | SSI_MIDLE_NOIDLE;
} else {
/* Set Autoidle, SIDLEMode to forced idle, and MIDLEmode to
* forced idle
*/
value = SSI_AUTOIDLE;
}
__raw_writel(value, ssi_base + OMAP_SSI_SYSCONFIG_OFFSET);
iounmap(ssi_base);
}
| gpl-2.0 |
jehoffmann/l4linux | drivers/media/i2c/s5k4ecgx.c | 2856 | 26402 | /*
* Driver for Samsung S5K4ECGX 1/4" 5Mp CMOS Image Sensor SoC
* with an Embedded Image Signal Processor.
*
* Copyright (C) 2012, Linaro, Sangwook Lee <sangwook.lee@linaro.org>
* Copyright (C) 2012, Insignal Co,. Ltd, Homin Lee <suapapa@insignal.co.kr>
*
* Based on s5k6aa and noon010pc30 driver
* Copyright (C) 2011, Samsung Electronics Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/clk.h>
#include <linux/crc32.h>
#include <linux/ctype.h>
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <media/media-entity.h>
#include <media/s5k4ecgx.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-device.h>
#include <media/v4l2-mediabus.h>
#include <media/v4l2-subdev.h>
static int debug;
module_param(debug, int, 0644);
#define S5K4ECGX_DRIVER_NAME "s5k4ecgx"
#define S5K4ECGX_FIRMWARE "s5k4ecgx.bin"
/* Firmware revision information */
#define REG_FW_REVISION 0x700001a6
#define REG_FW_VERSION 0x700001a4
#define S5K4ECGX_REVISION_1_1 0x11
#define S5K4ECGX_FW_VERSION 0x4ec0
/* General purpose parameters */
#define REG_USER_BRIGHTNESS 0x7000022c
#define REG_USER_CONTRAST 0x7000022e
#define REG_USER_SATURATION 0x70000230
#define REG_G_ENABLE_PREV 0x7000023e
#define REG_G_ENABLE_PREV_CHG 0x70000240
#define REG_G_NEW_CFG_SYNC 0x7000024a
#define REG_G_PREV_IN_WIDTH 0x70000250
#define REG_G_PREV_IN_HEIGHT 0x70000252
#define REG_G_PREV_IN_XOFFS 0x70000254
#define REG_G_PREV_IN_YOFFS 0x70000256
#define REG_G_CAP_IN_WIDTH 0x70000258
#define REG_G_CAP_IN_HEIGHT 0x7000025a
#define REG_G_CAP_IN_XOFFS 0x7000025c
#define REG_G_CAP_IN_YOFFS 0x7000025e
#define REG_G_INPUTS_CHANGE_REQ 0x70000262
#define REG_G_ACTIVE_PREV_CFG 0x70000266
#define REG_G_PREV_CFG_CHG 0x70000268
#define REG_G_PREV_OPEN_AFTER_CH 0x7000026a
/* Preview context register sets. n = 0...4. */
#define PREG(n, x) ((n) * 0x30 + (x))
#define REG_P_OUT_WIDTH(n) PREG(n, 0x700002a6)
#define REG_P_OUT_HEIGHT(n) PREG(n, 0x700002a8)
#define REG_P_FMT(n) PREG(n, 0x700002aa)
#define REG_P_PVI_MASK(n) PREG(n, 0x700002b4)
#define REG_P_FR_TIME_TYPE(n) PREG(n, 0x700002be)
#define FR_TIME_DYNAMIC 0
#define FR_TIME_FIXED 1
#define FR_TIME_FIXED_ACCURATE 2
#define REG_P_FR_TIME_Q_TYPE(n) PREG(n, 0x700002c0)
#define FR_TIME_Q_DYNAMIC 0
#define FR_TIME_Q_BEST_FRRATE 1
#define FR_TIME_Q_BEST_QUALITY 2
/* Frame period in 0.1 ms units */
#define REG_P_MAX_FR_TIME(n) PREG(n, 0x700002c2)
#define REG_P_MIN_FR_TIME(n) PREG(n, 0x700002c4)
#define US_TO_FR_TIME(__t) ((__t) / 100)
#define REG_P_PREV_MIRROR(n) PREG(n, 0x700002d0)
#define REG_P_CAP_MIRROR(n) PREG(n, 0x700002d2)
#define REG_G_PREVZOOM_IN_WIDTH 0x70000494
#define REG_G_PREVZOOM_IN_HEIGHT 0x70000496
#define REG_G_PREVZOOM_IN_XOFFS 0x70000498
#define REG_G_PREVZOOM_IN_YOFFS 0x7000049a
#define REG_G_CAPZOOM_IN_WIDTH 0x7000049c
#define REG_G_CAPZOOM_IN_HEIGHT 0x7000049e
#define REG_G_CAPZOOM_IN_XOFFS 0x700004a0
#define REG_G_CAPZOOM_IN_YOFFS 0x700004a2
/* n = 0...4 */
#define REG_USER_SHARPNESS(n) (0x70000a28 + (n) * 0xb6)
/* Reduce sharpness range for user space API */
#define SHARPNESS_DIV 8208
#define TOK_TERM 0xffffffff
/*
* FIXME: This is copied from s5k6aa, because of no information
* in the S5K4ECGX datasheet.
* H/W register Interface (0xd0000000 - 0xd0000fff)
*/
#define AHB_MSB_ADDR_PTR 0xfcfc
#define GEN_REG_OFFSH 0xd000
#define REG_CMDWR_ADDRH 0x0028
#define REG_CMDWR_ADDRL 0x002a
#define REG_CMDRD_ADDRH 0x002c
#define REG_CMDRD_ADDRL 0x002e
#define REG_CMDBUF0_ADDR 0x0f12
struct s5k4ecgx_frmsize {
struct v4l2_frmsize_discrete size;
/* Fixed sensor matrix crop rectangle */
struct v4l2_rect input_window;
};
struct regval_list {
u32 addr;
u16 val;
};
/*
* TODO: currently only preview is supported and snapshot (capture)
* is not implemented yet
*/
static const struct s5k4ecgx_frmsize s5k4ecgx_prev_sizes[] = {
{
.size = { 176, 144 },
.input_window = { 0x00, 0x00, 0x928, 0x780 },
}, {
.size = { 352, 288 },
.input_window = { 0x00, 0x00, 0x928, 0x780 },
}, {
.size = { 640, 480 },
.input_window = { 0x00, 0x00, 0xa00, 0x780 },
}, {
.size = { 720, 480 },
.input_window = { 0x00, 0x00, 0xa00, 0x6a8 },
}
};
#define S5K4ECGX_NUM_PREV ARRAY_SIZE(s5k4ecgx_prev_sizes)
struct s5k4ecgx_pixfmt {
enum v4l2_mbus_pixelcode code;
u32 colorspace;
/* REG_TC_PCFG_Format register value */
u16 reg_p_format;
};
/* By default value, output from sensor will be YUV422 0-255 */
static const struct s5k4ecgx_pixfmt s5k4ecgx_formats[] = {
{ V4L2_MBUS_FMT_YUYV8_2X8, V4L2_COLORSPACE_JPEG, 5 },
};
static const char * const s5k4ecgx_supply_names[] = {
/*
* Usually 2.8V is used for analog power (vdda)
* and digital IO (vddio, vdddcore)
*/
"vdda",
"vddio",
"vddcore",
"vddreg", /* The internal s5k4ecgx regulator's supply (1.8V) */
};
#define S5K4ECGX_NUM_SUPPLIES ARRAY_SIZE(s5k4ecgx_supply_names)
enum s5k4ecgx_gpio_id {
STBY,
RST,
GPIO_NUM,
};
struct s5k4ecgx {
struct v4l2_subdev sd;
struct media_pad pad;
struct v4l2_ctrl_handler handler;
struct s5k4ecgx_platform_data *pdata;
const struct s5k4ecgx_pixfmt *curr_pixfmt;
const struct s5k4ecgx_frmsize *curr_frmsize;
struct mutex lock;
u8 streaming;
u8 set_params;
struct regulator_bulk_data supplies[S5K4ECGX_NUM_SUPPLIES];
struct s5k4ecgx_gpio gpio[GPIO_NUM];
};
static inline struct s5k4ecgx *to_s5k4ecgx(struct v4l2_subdev *sd)
{
return container_of(sd, struct s5k4ecgx, sd);
}
static int s5k4ecgx_i2c_read(struct i2c_client *client, u16 addr, u16 *val)
{
u8 wbuf[2] = { addr >> 8, addr & 0xff };
struct i2c_msg msg[2];
u8 rbuf[2];
int ret;
msg[0].addr = client->addr;
msg[0].flags = 0;
msg[0].len = 2;
msg[0].buf = wbuf;
msg[1].addr = client->addr;
msg[1].flags = I2C_M_RD;
msg[1].len = 2;
msg[1].buf = rbuf;
ret = i2c_transfer(client->adapter, msg, 2);
*val = be16_to_cpu(*((u16 *)rbuf));
v4l2_dbg(4, debug, client, "i2c_read: 0x%04X : 0x%04x\n", addr, *val);
return ret == 2 ? 0 : ret;
}
static int s5k4ecgx_i2c_write(struct i2c_client *client, u16 addr, u16 val)
{
u8 buf[4] = { addr >> 8, addr & 0xff, val >> 8, val & 0xff };
int ret = i2c_master_send(client, buf, 4);
v4l2_dbg(4, debug, client, "i2c_write: 0x%04x : 0x%04x\n", addr, val);
return ret == 4 ? 0 : ret;
}
static int s5k4ecgx_write(struct i2c_client *client, u32 addr, u16 val)
{
u16 high = addr >> 16, low = addr & 0xffff;
int ret;
v4l2_dbg(3, debug, client, "write: 0x%08x : 0x%04x\n", addr, val);
ret = s5k4ecgx_i2c_write(client, REG_CMDWR_ADDRH, high);
if (!ret)
ret = s5k4ecgx_i2c_write(client, REG_CMDWR_ADDRL, low);
if (!ret)
ret = s5k4ecgx_i2c_write(client, REG_CMDBUF0_ADDR, val);
return ret;
}
static int s5k4ecgx_read(struct i2c_client *client, u32 addr, u16 *val)
{
u16 high = addr >> 16, low = addr & 0xffff;
int ret;
ret = s5k4ecgx_i2c_write(client, REG_CMDRD_ADDRH, high);
if (!ret)
ret = s5k4ecgx_i2c_write(client, REG_CMDRD_ADDRL, low);
if (!ret)
ret = s5k4ecgx_i2c_read(client, REG_CMDBUF0_ADDR, val);
if (!ret)
dev_err(&client->dev, "Failed to execute read command\n");
return ret;
}
static int s5k4ecgx_read_fw_ver(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u16 hw_rev, fw_ver = 0;
int ret;
ret = s5k4ecgx_read(client, REG_FW_VERSION, &fw_ver);
if (ret < 0 || fw_ver != S5K4ECGX_FW_VERSION) {
v4l2_err(sd, "FW version check failed!\n");
return -ENODEV;
}
ret = s5k4ecgx_read(client, REG_FW_REVISION, &hw_rev);
if (ret < 0)
return ret;
v4l2_info(sd, "chip found FW ver: 0x%x, HW rev: 0x%x\n",
fw_ver, hw_rev);
return 0;
}
static int s5k4ecgx_set_ahb_address(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
/* Set APB peripherals start address */
ret = s5k4ecgx_i2c_write(client, AHB_MSB_ADDR_PTR, GEN_REG_OFFSH);
if (ret < 0)
return ret;
/*
* FIXME: This is copied from s5k6aa, because of no information
* in s5k4ecgx's datasheet.
* sw_reset is activated to put device into idle status
*/
ret = s5k4ecgx_i2c_write(client, 0x0010, 0x0001);
if (ret < 0)
return ret;
ret = s5k4ecgx_i2c_write(client, 0x1030, 0x0000);
if (ret < 0)
return ret;
/* Halt ARM CPU */
return s5k4ecgx_i2c_write(client, 0x0014, 0x0001);
}
#define FW_CRC_SIZE 4
/* Register address, value are 4, 2 bytes */
#define FW_RECORD_SIZE 6
/*
* The firmware has following format:
* < total number of records (4 bytes + 2 bytes padding) N >,
* < record 0 >, ..., < record N - 1 >, < CRC32-CCITT (4-bytes) >,
* where "record" is a 4-byte register address followed by 2-byte
* register value (little endian).
* The firmware generator can be found in following git repository:
* git://git.linaro.org/people/sangwook/fimc-v4l2-app.git
*/
static int s5k4ecgx_load_firmware(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
const struct firmware *fw;
const u8 *ptr;
int err, i, regs_num;
u32 addr, crc, crc_file, addr_inc = 0;
u16 val;
err = request_firmware(&fw, S5K4ECGX_FIRMWARE, sd->v4l2_dev->dev);
if (err) {
v4l2_err(sd, "Failed to read firmware %s\n", S5K4ECGX_FIRMWARE);
return err;
}
regs_num = le32_to_cpu(get_unaligned_le32(fw->data));
v4l2_dbg(3, debug, sd, "FW: %s size %zu register sets %d\n",
S5K4ECGX_FIRMWARE, fw->size, regs_num);
regs_num++; /* Add header */
if (fw->size != regs_num * FW_RECORD_SIZE + FW_CRC_SIZE) {
err = -EINVAL;
goto fw_out;
}
crc_file = le32_to_cpu(get_unaligned_le32(fw->data +
regs_num * FW_RECORD_SIZE));
crc = crc32_le(~0, fw->data, regs_num * FW_RECORD_SIZE);
if (crc != crc_file) {
v4l2_err(sd, "FW: invalid crc (%#x:%#x)\n", crc, crc_file);
err = -EINVAL;
goto fw_out;
}
ptr = fw->data + FW_RECORD_SIZE;
for (i = 1; i < regs_num; i++) {
addr = le32_to_cpu(get_unaligned_le32(ptr));
ptr += sizeof(u32);
val = le16_to_cpu(get_unaligned_le16(ptr));
ptr += sizeof(u16);
if (addr - addr_inc != 2)
err = s5k4ecgx_write(client, addr, val);
else
err = s5k4ecgx_i2c_write(client, REG_CMDBUF0_ADDR, val);
if (err)
break;
addr_inc = addr;
}
fw_out:
release_firmware(fw);
return err;
}
/* Set preview and capture input window */
static int s5k4ecgx_set_input_window(struct i2c_client *c,
const struct v4l2_rect *r)
{
int ret;
ret = s5k4ecgx_write(c, REG_G_PREV_IN_WIDTH, r->width);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_PREV_IN_HEIGHT, r->height);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_PREV_IN_XOFFS, r->left);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_PREV_IN_YOFFS, r->top);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAP_IN_WIDTH, r->width);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAP_IN_HEIGHT, r->height);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAP_IN_XOFFS, r->left);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAP_IN_YOFFS, r->top);
return ret;
}
/* Set preview and capture zoom input window */
static int s5k4ecgx_set_zoom_window(struct i2c_client *c,
const struct v4l2_rect *r)
{
int ret;
ret = s5k4ecgx_write(c, REG_G_PREVZOOM_IN_WIDTH, r->width);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_PREVZOOM_IN_HEIGHT, r->height);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_PREVZOOM_IN_XOFFS, r->left);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_PREVZOOM_IN_YOFFS, r->top);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAPZOOM_IN_WIDTH, r->width);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAPZOOM_IN_HEIGHT, r->height);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAPZOOM_IN_XOFFS, r->left);
if (!ret)
ret = s5k4ecgx_write(c, REG_G_CAPZOOM_IN_YOFFS, r->top);
return ret;
}
static int s5k4ecgx_set_output_framefmt(struct s5k4ecgx *priv)
{
struct i2c_client *client = v4l2_get_subdevdata(&priv->sd);
int ret;
ret = s5k4ecgx_write(client, REG_P_OUT_WIDTH(0),
priv->curr_frmsize->size.width);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_OUT_HEIGHT(0),
priv->curr_frmsize->size.height);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_FMT(0),
priv->curr_pixfmt->reg_p_format);
return ret;
}
static int s5k4ecgx_init_sensor(struct v4l2_subdev *sd)
{
int ret;
ret = s5k4ecgx_set_ahb_address(sd);
/* The delay is from manufacturer's settings */
msleep(100);
if (!ret)
ret = s5k4ecgx_load_firmware(sd);
if (ret)
v4l2_err(sd, "Failed to write initial settings\n");
return ret;
}
static int s5k4ecgx_gpio_set_value(struct s5k4ecgx *priv, int id, u32 val)
{
if (!gpio_is_valid(priv->gpio[id].gpio))
return 0;
gpio_set_value(priv->gpio[id].gpio, val);
return 1;
}
static int __s5k4ecgx_power_on(struct s5k4ecgx *priv)
{
int ret;
ret = regulator_bulk_enable(S5K4ECGX_NUM_SUPPLIES, priv->supplies);
if (ret)
return ret;
usleep_range(30, 50);
/* The polarity of STBY is controlled by TSP */
if (s5k4ecgx_gpio_set_value(priv, STBY, priv->gpio[STBY].level))
usleep_range(30, 50);
if (s5k4ecgx_gpio_set_value(priv, RST, priv->gpio[RST].level))
usleep_range(30, 50);
return 0;
}
static int __s5k4ecgx_power_off(struct s5k4ecgx *priv)
{
if (s5k4ecgx_gpio_set_value(priv, RST, !priv->gpio[RST].level))
usleep_range(30, 50);
if (s5k4ecgx_gpio_set_value(priv, STBY, !priv->gpio[STBY].level))
usleep_range(30, 50);
priv->streaming = 0;
return regulator_bulk_disable(S5K4ECGX_NUM_SUPPLIES, priv->supplies);
}
/* Find nearest matching image pixel size. */
static int s5k4ecgx_try_frame_size(struct v4l2_mbus_framefmt *mf,
const struct s5k4ecgx_frmsize **size)
{
unsigned int min_err = ~0;
int i = ARRAY_SIZE(s5k4ecgx_prev_sizes);
const struct s5k4ecgx_frmsize *fsize = &s5k4ecgx_prev_sizes[0],
*match = NULL;
while (i--) {
int err = abs(fsize->size.width - mf->width)
+ abs(fsize->size.height - mf->height);
if (err < min_err) {
min_err = err;
match = fsize;
}
fsize++;
}
if (match) {
mf->width = match->size.width;
mf->height = match->size.height;
if (size)
*size = match;
return 0;
}
return -EINVAL;
}
static int s5k4ecgx_enum_mbus_code(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_mbus_code_enum *code)
{
if (code->index >= ARRAY_SIZE(s5k4ecgx_formats))
return -EINVAL;
code->code = s5k4ecgx_formats[code->index].code;
return 0;
}
static int s5k4ecgx_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
struct v4l2_mbus_framefmt *mf;
if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
if (fh) {
mf = v4l2_subdev_get_try_format(fh, 0);
fmt->format = *mf;
}
return 0;
}
mf = &fmt->format;
mutex_lock(&priv->lock);
mf->width = priv->curr_frmsize->size.width;
mf->height = priv->curr_frmsize->size.height;
mf->code = priv->curr_pixfmt->code;
mf->colorspace = priv->curr_pixfmt->colorspace;
mf->field = V4L2_FIELD_NONE;
mutex_unlock(&priv->lock);
return 0;
}
static const struct s5k4ecgx_pixfmt *s5k4ecgx_try_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
int i = ARRAY_SIZE(s5k4ecgx_formats);
while (--i)
if (mf->code == s5k4ecgx_formats[i].code)
break;
mf->code = s5k4ecgx_formats[i].code;
return &s5k4ecgx_formats[i];
}
static int s5k4ecgx_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
const struct s5k4ecgx_frmsize *fsize = NULL;
const struct s5k4ecgx_pixfmt *pf;
struct v4l2_mbus_framefmt *mf;
int ret = 0;
pf = s5k4ecgx_try_fmt(sd, &fmt->format);
s5k4ecgx_try_frame_size(&fmt->format, &fsize);
fmt->format.colorspace = V4L2_COLORSPACE_JPEG;
if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
if (fh) {
mf = v4l2_subdev_get_try_format(fh, 0);
*mf = fmt->format;
}
return 0;
}
mutex_lock(&priv->lock);
if (!priv->streaming) {
priv->curr_frmsize = fsize;
priv->curr_pixfmt = pf;
priv->set_params = 1;
} else {
ret = -EBUSY;
}
mutex_unlock(&priv->lock);
return ret;
}
static const struct v4l2_subdev_pad_ops s5k4ecgx_pad_ops = {
.enum_mbus_code = s5k4ecgx_enum_mbus_code,
.get_fmt = s5k4ecgx_get_fmt,
.set_fmt = s5k4ecgx_set_fmt,
};
/*
* V4L2 subdev controls
*/
static int s5k4ecgx_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = &container_of(ctrl->handler, struct s5k4ecgx,
handler)->sd;
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
unsigned int i;
int err = 0;
v4l2_dbg(1, debug, sd, "ctrl: 0x%x, value: %d\n", ctrl->id, ctrl->val);
mutex_lock(&priv->lock);
switch (ctrl->id) {
case V4L2_CID_CONTRAST:
err = s5k4ecgx_write(client, REG_USER_CONTRAST, ctrl->val);
break;
case V4L2_CID_SATURATION:
err = s5k4ecgx_write(client, REG_USER_SATURATION, ctrl->val);
break;
case V4L2_CID_SHARPNESS:
/* TODO: Revisit, is this setting for all presets ? */
for (i = 0; i < 4 && !err; i++)
err = s5k4ecgx_write(client, REG_USER_SHARPNESS(i),
ctrl->val * SHARPNESS_DIV);
break;
case V4L2_CID_BRIGHTNESS:
err = s5k4ecgx_write(client, REG_USER_BRIGHTNESS, ctrl->val);
break;
}
mutex_unlock(&priv->lock);
if (err < 0)
v4l2_err(sd, "Failed to write s_ctrl err %d\n", err);
return err;
}
static const struct v4l2_ctrl_ops s5k4ecgx_ctrl_ops = {
.s_ctrl = s5k4ecgx_s_ctrl,
};
/*
* Reading s5k4ecgx version information
*/
static int s5k4ecgx_registered(struct v4l2_subdev *sd)
{
int ret;
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
mutex_lock(&priv->lock);
ret = __s5k4ecgx_power_on(priv);
if (!ret) {
ret = s5k4ecgx_read_fw_ver(sd);
__s5k4ecgx_power_off(priv);
}
mutex_unlock(&priv->lock);
return ret;
}
/*
* V4L2 subdev internal operations
*/
static int s5k4ecgx_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
struct v4l2_mbus_framefmt *mf = v4l2_subdev_get_try_format(fh, 0);
mf->width = s5k4ecgx_prev_sizes[0].size.width;
mf->height = s5k4ecgx_prev_sizes[0].size.height;
mf->code = s5k4ecgx_formats[0].code;
mf->colorspace = V4L2_COLORSPACE_JPEG;
mf->field = V4L2_FIELD_NONE;
return 0;
}
static const struct v4l2_subdev_internal_ops s5k4ecgx_subdev_internal_ops = {
.registered = s5k4ecgx_registered,
.open = s5k4ecgx_open,
};
static int s5k4ecgx_s_power(struct v4l2_subdev *sd, int on)
{
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
int ret;
v4l2_dbg(1, debug, sd, "Switching %s\n", on ? "on" : "off");
if (on) {
ret = __s5k4ecgx_power_on(priv);
if (ret < 0)
return ret;
/* Time to stabilize sensor */
msleep(100);
ret = s5k4ecgx_init_sensor(sd);
if (ret < 0)
__s5k4ecgx_power_off(priv);
else
priv->set_params = 1;
} else {
ret = __s5k4ecgx_power_off(priv);
}
return ret;
}
static int s5k4ecgx_log_status(struct v4l2_subdev *sd)
{
v4l2_ctrl_handler_log_status(sd->ctrl_handler, sd->name);
return 0;
}
static const struct v4l2_subdev_core_ops s5k4ecgx_core_ops = {
.s_power = s5k4ecgx_s_power,
.log_status = s5k4ecgx_log_status,
};
static int __s5k4ecgx_s_params(struct s5k4ecgx *priv)
{
struct i2c_client *client = v4l2_get_subdevdata(&priv->sd);
const struct v4l2_rect *crop_rect = &priv->curr_frmsize->input_window;
int ret;
ret = s5k4ecgx_set_input_window(client, crop_rect);
if (!ret)
ret = s5k4ecgx_set_zoom_window(client, crop_rect);
if (!ret)
ret = s5k4ecgx_write(client, REG_G_INPUTS_CHANGE_REQ, 1);
if (!ret)
ret = s5k4ecgx_write(client, 0x70000a1e, 0x28);
if (!ret)
ret = s5k4ecgx_write(client, 0x70000ad4, 0x3c);
if (!ret)
ret = s5k4ecgx_set_output_framefmt(priv);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_PVI_MASK(0), 0x52);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_FR_TIME_TYPE(0),
FR_TIME_DYNAMIC);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_FR_TIME_Q_TYPE(0),
FR_TIME_Q_BEST_FRRATE);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_MIN_FR_TIME(0),
US_TO_FR_TIME(33300));
if (!ret)
ret = s5k4ecgx_write(client, REG_P_MAX_FR_TIME(0),
US_TO_FR_TIME(66600));
if (!ret)
ret = s5k4ecgx_write(client, REG_P_PREV_MIRROR(0), 0);
if (!ret)
ret = s5k4ecgx_write(client, REG_P_CAP_MIRROR(0), 0);
if (!ret)
ret = s5k4ecgx_write(client, REG_G_ACTIVE_PREV_CFG, 0);
if (!ret)
ret = s5k4ecgx_write(client, REG_G_PREV_OPEN_AFTER_CH, 1);
if (!ret)
ret = s5k4ecgx_write(client, REG_G_NEW_CFG_SYNC, 1);
if (!ret)
ret = s5k4ecgx_write(client, REG_G_PREV_CFG_CHG, 1);
return ret;
}
static int __s5k4ecgx_s_stream(struct s5k4ecgx *priv, int on)
{
struct i2c_client *client = v4l2_get_subdevdata(&priv->sd);
int ret;
if (on && priv->set_params) {
ret = __s5k4ecgx_s_params(priv);
if (ret < 0)
return ret;
priv->set_params = 0;
}
/*
* This enables/disables preview stream only. Capture requests
* are not supported yet.
*/
ret = s5k4ecgx_write(client, REG_G_ENABLE_PREV, on);
if (ret < 0)
return ret;
return s5k4ecgx_write(client, REG_G_ENABLE_PREV_CHG, 1);
}
static int s5k4ecgx_s_stream(struct v4l2_subdev *sd, int on)
{
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
int ret = 0;
v4l2_dbg(1, debug, sd, "Turn streaming %s\n", on ? "on" : "off");
mutex_lock(&priv->lock);
if (priv->streaming == !on) {
ret = __s5k4ecgx_s_stream(priv, on);
if (!ret)
priv->streaming = on & 1;
}
mutex_unlock(&priv->lock);
return ret;
}
static const struct v4l2_subdev_video_ops s5k4ecgx_video_ops = {
.s_stream = s5k4ecgx_s_stream,
};
static const struct v4l2_subdev_ops s5k4ecgx_ops = {
.core = &s5k4ecgx_core_ops,
.pad = &s5k4ecgx_pad_ops,
.video = &s5k4ecgx_video_ops,
};
/*
* GPIO setup
*/
static int s5k4ecgx_config_gpio(int nr, int val, const char *name)
{
unsigned long flags = val ? GPIOF_OUT_INIT_HIGH : GPIOF_OUT_INIT_LOW;
int ret;
if (!gpio_is_valid(nr))
return 0;
ret = gpio_request_one(nr, flags, name);
if (!ret)
gpio_export(nr, 0);
return ret;
}
static void s5k4ecgx_free_gpios(struct s5k4ecgx *priv)
{
int i;
for (i = 0; i < ARRAY_SIZE(priv->gpio); i++) {
if (!gpio_is_valid(priv->gpio[i].gpio))
continue;
gpio_free(priv->gpio[i].gpio);
priv->gpio[i].gpio = -EINVAL;
}
}
static int s5k4ecgx_config_gpios(struct s5k4ecgx *priv,
const struct s5k4ecgx_platform_data *pdata)
{
const struct s5k4ecgx_gpio *gpio = &pdata->gpio_stby;
int ret;
priv->gpio[STBY].gpio = -EINVAL;
priv->gpio[RST].gpio = -EINVAL;
ret = s5k4ecgx_config_gpio(gpio->gpio, gpio->level, "S5K4ECGX_STBY");
if (ret) {
s5k4ecgx_free_gpios(priv);
return ret;
}
priv->gpio[STBY] = *gpio;
if (gpio_is_valid(gpio->gpio))
gpio_set_value(gpio->gpio, 0);
gpio = &pdata->gpio_reset;
ret = s5k4ecgx_config_gpio(gpio->gpio, gpio->level, "S5K4ECGX_RST");
if (ret) {
s5k4ecgx_free_gpios(priv);
return ret;
}
priv->gpio[RST] = *gpio;
if (gpio_is_valid(gpio->gpio))
gpio_set_value(gpio->gpio, 0);
return 0;
}
static int s5k4ecgx_init_v4l2_ctrls(struct s5k4ecgx *priv)
{
const struct v4l2_ctrl_ops *ops = &s5k4ecgx_ctrl_ops;
struct v4l2_ctrl_handler *hdl = &priv->handler;
int ret;
ret = v4l2_ctrl_handler_init(hdl, 4);
if (ret)
return ret;
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BRIGHTNESS, -208, 127, 1, 0);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_CONTRAST, -127, 127, 1, 0);
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SATURATION, -127, 127, 1, 0);
/* Sharpness default is 24612, and then (24612/SHARPNESS_DIV) = 2 */
v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SHARPNESS, -32704/SHARPNESS_DIV,
24612/SHARPNESS_DIV, 1, 2);
if (hdl->error) {
ret = hdl->error;
v4l2_ctrl_handler_free(hdl);
return ret;
}
priv->sd.ctrl_handler = hdl;
return 0;
};
static int s5k4ecgx_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct s5k4ecgx_platform_data *pdata = client->dev.platform_data;
struct v4l2_subdev *sd;
struct s5k4ecgx *priv;
int ret, i;
if (pdata == NULL) {
dev_err(&client->dev, "platform data is missing!\n");
return -EINVAL;
}
priv = devm_kzalloc(&client->dev, sizeof(struct s5k4ecgx), GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_init(&priv->lock);
priv->streaming = 0;
sd = &priv->sd;
/* Registering subdev */
v4l2_i2c_subdev_init(sd, client, &s5k4ecgx_ops);
strlcpy(sd->name, S5K4ECGX_DRIVER_NAME, sizeof(sd->name));
sd->internal_ops = &s5k4ecgx_subdev_internal_ops;
/* Support v4l2 sub-device user space API */
sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
priv->pad.flags = MEDIA_PAD_FL_SOURCE;
sd->entity.type = MEDIA_ENT_T_V4L2_SUBDEV_SENSOR;
ret = media_entity_init(&sd->entity, 1, &priv->pad, 0);
if (ret)
return ret;
ret = s5k4ecgx_config_gpios(priv, pdata);
if (ret) {
dev_err(&client->dev, "Failed to set gpios\n");
goto out_err1;
}
for (i = 0; i < S5K4ECGX_NUM_SUPPLIES; i++)
priv->supplies[i].supply = s5k4ecgx_supply_names[i];
ret = devm_regulator_bulk_get(&client->dev, S5K4ECGX_NUM_SUPPLIES,
priv->supplies);
if (ret) {
dev_err(&client->dev, "Failed to get regulators\n");
goto out_err2;
}
ret = s5k4ecgx_init_v4l2_ctrls(priv);
if (ret)
goto out_err2;
priv->curr_pixfmt = &s5k4ecgx_formats[0];
priv->curr_frmsize = &s5k4ecgx_prev_sizes[0];
return 0;
out_err2:
s5k4ecgx_free_gpios(priv);
out_err1:
media_entity_cleanup(&priv->sd.entity);
return ret;
}
static int s5k4ecgx_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct s5k4ecgx *priv = to_s5k4ecgx(sd);
mutex_destroy(&priv->lock);
s5k4ecgx_free_gpios(priv);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&priv->handler);
media_entity_cleanup(&sd->entity);
return 0;
}
static const struct i2c_device_id s5k4ecgx_id[] = {
{ S5K4ECGX_DRIVER_NAME, 0 },
{}
};
MODULE_DEVICE_TABLE(i2c, s5k4ecgx_id);
static struct i2c_driver v4l2_i2c_driver = {
.driver = {
.owner = THIS_MODULE,
.name = S5K4ECGX_DRIVER_NAME,
},
.probe = s5k4ecgx_probe,
.remove = s5k4ecgx_remove,
.id_table = s5k4ecgx_id,
};
module_i2c_driver(v4l2_i2c_driver);
MODULE_DESCRIPTION("Samsung S5K4ECGX 5MP SOC camera");
MODULE_AUTHOR("Sangwook Lee <sangwook.lee@linaro.org>");
MODULE_AUTHOR("Seok-Young Jang <quartz.jang@samsung.com>");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE(S5K4ECGX_FIRMWARE);
| gpl-2.0 |
Thrive-Hackers/tostab3-gnu-linux-kernel | drivers/net/cxgb4/l2t.c | 3112 | 15515 | /*
* This file is part of the Chelsio T4 Ethernet driver for Linux.
*
* Copyright (c) 2003-2010 Chelsio Communications, 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/if.h>
#include <linux/if_vlan.h>
#include <linux/jhash.h>
#include <net/neighbour.h>
#include "cxgb4.h"
#include "l2t.h"
#include "t4_msg.h"
#include "t4fw_api.h"
#define VLAN_NONE 0xfff
/* identifies sync vs async L2T_WRITE_REQs */
#define F_SYNC_WR (1 << 12)
enum {
L2T_STATE_VALID, /* entry is up to date */
L2T_STATE_STALE, /* entry may be used but needs revalidation */
L2T_STATE_RESOLVING, /* entry needs address resolution */
L2T_STATE_SYNC_WRITE, /* synchronous write of entry underway */
/* when state is one of the below the entry is not hashed */
L2T_STATE_SWITCHING, /* entry is being used by a switching filter */
L2T_STATE_UNUSED /* entry not in use */
};
struct l2t_data {
rwlock_t lock;
atomic_t nfree; /* number of free entries */
struct l2t_entry *rover; /* starting point for next allocation */
struct l2t_entry l2tab[L2T_SIZE];
};
static inline unsigned int vlan_prio(const struct l2t_entry *e)
{
return e->vlan >> 13;
}
static inline void l2t_hold(struct l2t_data *d, struct l2t_entry *e)
{
if (atomic_add_return(1, &e->refcnt) == 1) /* 0 -> 1 transition */
atomic_dec(&d->nfree);
}
/*
* To avoid having to check address families we do not allow v4 and v6
* neighbors to be on the same hash chain. We keep v4 entries in the first
* half of available hash buckets and v6 in the second.
*/
enum {
L2T_SZ_HALF = L2T_SIZE / 2,
L2T_HASH_MASK = L2T_SZ_HALF - 1
};
static inline unsigned int arp_hash(const u32 *key, int ifindex)
{
return jhash_2words(*key, ifindex, 0) & L2T_HASH_MASK;
}
static inline unsigned int ipv6_hash(const u32 *key, int ifindex)
{
u32 xor = key[0] ^ key[1] ^ key[2] ^ key[3];
return L2T_SZ_HALF + (jhash_2words(xor, ifindex, 0) & L2T_HASH_MASK);
}
static unsigned int addr_hash(const u32 *addr, int addr_len, int ifindex)
{
return addr_len == 4 ? arp_hash(addr, ifindex) :
ipv6_hash(addr, ifindex);
}
/*
* Checks if an L2T entry is for the given IP/IPv6 address. It does not check
* whether the L2T entry and the address are of the same address family.
* Callers ensure an address is only checked against L2T entries of the same
* family, something made trivial by the separation of IP and IPv6 hash chains
* mentioned above. Returns 0 if there's a match,
*/
static int addreq(const struct l2t_entry *e, const u32 *addr)
{
if (e->v6)
return (e->addr[0] ^ addr[0]) | (e->addr[1] ^ addr[1]) |
(e->addr[2] ^ addr[2]) | (e->addr[3] ^ addr[3]);
return e->addr[0] ^ addr[0];
}
static void neigh_replace(struct l2t_entry *e, struct neighbour *n)
{
neigh_hold(n);
if (e->neigh)
neigh_release(e->neigh);
e->neigh = n;
}
/*
* Write an L2T entry. Must be called with the entry locked.
* The write may be synchronous or asynchronous.
*/
static int write_l2e(struct adapter *adap, struct l2t_entry *e, int sync)
{
struct sk_buff *skb;
struct cpl_l2t_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_ATOMIC);
if (!skb)
return -ENOMEM;
req = (struct cpl_l2t_write_req *)__skb_put(skb, sizeof(*req));
INIT_TP_WR(req, 0);
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_L2T_WRITE_REQ,
e->idx | (sync ? F_SYNC_WR : 0) |
TID_QID(adap->sge.fw_evtq.abs_id)));
req->params = htons(L2T_W_PORT(e->lport) | L2T_W_NOREPLY(!sync));
req->l2t_idx = htons(e->idx);
req->vlan = htons(e->vlan);
if (e->neigh)
memcpy(e->dmac, e->neigh->ha, sizeof(e->dmac));
memcpy(req->dst_mac, e->dmac, sizeof(req->dst_mac));
set_wr_txq(skb, CPL_PRIORITY_CONTROL, 0);
t4_ofld_send(adap, skb);
if (sync && e->state != L2T_STATE_SWITCHING)
e->state = L2T_STATE_SYNC_WRITE;
return 0;
}
/*
* Send packets waiting in an L2T entry's ARP queue. Must be called with the
* entry locked.
*/
static void send_pending(struct adapter *adap, struct l2t_entry *e)
{
while (e->arpq_head) {
struct sk_buff *skb = e->arpq_head;
e->arpq_head = skb->next;
skb->next = NULL;
t4_ofld_send(adap, skb);
}
e->arpq_tail = NULL;
}
/*
* Process a CPL_L2T_WRITE_RPL. Wake up the ARP queue if it completes a
* synchronous L2T_WRITE. Note that the TID in the reply is really the L2T
* index it refers to.
*/
void do_l2t_write_rpl(struct adapter *adap, const struct cpl_l2t_write_rpl *rpl)
{
unsigned int tid = GET_TID(rpl);
unsigned int idx = tid & (L2T_SIZE - 1);
if (unlikely(rpl->status != CPL_ERR_NONE)) {
dev_err(adap->pdev_dev,
"Unexpected L2T_WRITE_RPL status %u for entry %u\n",
rpl->status, idx);
return;
}
if (tid & F_SYNC_WR) {
struct l2t_entry *e = &adap->l2t->l2tab[idx];
spin_lock(&e->lock);
if (e->state != L2T_STATE_SWITCHING) {
send_pending(adap, e);
e->state = (e->neigh->nud_state & NUD_STALE) ?
L2T_STATE_STALE : L2T_STATE_VALID;
}
spin_unlock(&e->lock);
}
}
/*
* Add a packet to an L2T entry's queue of packets awaiting resolution.
* Must be called with the entry's lock held.
*/
static inline void arpq_enqueue(struct l2t_entry *e, struct sk_buff *skb)
{
skb->next = NULL;
if (e->arpq_head)
e->arpq_tail->next = skb;
else
e->arpq_head = skb;
e->arpq_tail = skb;
}
int cxgb4_l2t_send(struct net_device *dev, struct sk_buff *skb,
struct l2t_entry *e)
{
struct adapter *adap = netdev2adap(dev);
again:
switch (e->state) {
case L2T_STATE_STALE: /* entry is stale, kick off revalidation */
neigh_event_send(e->neigh, NULL);
spin_lock_bh(&e->lock);
if (e->state == L2T_STATE_STALE)
e->state = L2T_STATE_VALID;
spin_unlock_bh(&e->lock);
case L2T_STATE_VALID: /* fast-path, send the packet on */
return t4_ofld_send(adap, skb);
case L2T_STATE_RESOLVING:
case L2T_STATE_SYNC_WRITE:
spin_lock_bh(&e->lock);
if (e->state != L2T_STATE_SYNC_WRITE &&
e->state != L2T_STATE_RESOLVING) {
spin_unlock_bh(&e->lock);
goto again;
}
arpq_enqueue(e, skb);
spin_unlock_bh(&e->lock);
if (e->state == L2T_STATE_RESOLVING &&
!neigh_event_send(e->neigh, NULL)) {
spin_lock_bh(&e->lock);
if (e->state == L2T_STATE_RESOLVING && e->arpq_head)
write_l2e(adap, e, 1);
spin_unlock_bh(&e->lock);
}
}
return 0;
}
EXPORT_SYMBOL(cxgb4_l2t_send);
/*
* Allocate a free L2T entry. Must be called with l2t_data.lock held.
*/
static struct l2t_entry *alloc_l2e(struct l2t_data *d)
{
struct l2t_entry *end, *e, **p;
if (!atomic_read(&d->nfree))
return NULL;
/* there's definitely a free entry */
for (e = d->rover, end = &d->l2tab[L2T_SIZE]; e != end; ++e)
if (atomic_read(&e->refcnt) == 0)
goto found;
for (e = d->l2tab; atomic_read(&e->refcnt); ++e)
;
found:
d->rover = e + 1;
atomic_dec(&d->nfree);
/*
* The entry we found may be an inactive entry that is
* presently in the hash table. We need to remove it.
*/
if (e->state < L2T_STATE_SWITCHING)
for (p = &d->l2tab[e->hash].first; *p; p = &(*p)->next)
if (*p == e) {
*p = e->next;
e->next = NULL;
break;
}
e->state = L2T_STATE_UNUSED;
return e;
}
/*
* Called when an L2T entry has no more users.
*/
static void t4_l2e_free(struct l2t_entry *e)
{
struct l2t_data *d;
spin_lock_bh(&e->lock);
if (atomic_read(&e->refcnt) == 0) { /* hasn't been recycled */
if (e->neigh) {
neigh_release(e->neigh);
e->neigh = NULL;
}
while (e->arpq_head) {
struct sk_buff *skb = e->arpq_head;
e->arpq_head = skb->next;
kfree_skb(skb);
}
e->arpq_tail = NULL;
}
spin_unlock_bh(&e->lock);
d = container_of(e, struct l2t_data, l2tab[e->idx]);
atomic_inc(&d->nfree);
}
void cxgb4_l2t_release(struct l2t_entry *e)
{
if (atomic_dec_and_test(&e->refcnt))
t4_l2e_free(e);
}
EXPORT_SYMBOL(cxgb4_l2t_release);
/*
* Update an L2T entry that was previously used for the same next hop as neigh.
* Must be called with softirqs disabled.
*/
static void reuse_entry(struct l2t_entry *e, struct neighbour *neigh)
{
unsigned int nud_state;
spin_lock(&e->lock); /* avoid race with t4_l2t_free */
if (neigh != e->neigh)
neigh_replace(e, neigh);
nud_state = neigh->nud_state;
if (memcmp(e->dmac, neigh->ha, sizeof(e->dmac)) ||
!(nud_state & NUD_VALID))
e->state = L2T_STATE_RESOLVING;
else if (nud_state & NUD_CONNECTED)
e->state = L2T_STATE_VALID;
else
e->state = L2T_STATE_STALE;
spin_unlock(&e->lock);
}
struct l2t_entry *cxgb4_l2t_get(struct l2t_data *d, struct neighbour *neigh,
const struct net_device *physdev,
unsigned int priority)
{
u8 lport;
u16 vlan;
struct l2t_entry *e;
int addr_len = neigh->tbl->key_len;
u32 *addr = (u32 *)neigh->primary_key;
int ifidx = neigh->dev->ifindex;
int hash = addr_hash(addr, addr_len, ifidx);
if (neigh->dev->flags & IFF_LOOPBACK)
lport = netdev2pinfo(physdev)->tx_chan + 4;
else
lport = netdev2pinfo(physdev)->lport;
if (neigh->dev->priv_flags & IFF_802_1Q_VLAN)
vlan = vlan_dev_vlan_id(neigh->dev);
else
vlan = VLAN_NONE;
write_lock_bh(&d->lock);
for (e = d->l2tab[hash].first; e; e = e->next)
if (!addreq(e, addr) && e->ifindex == ifidx &&
e->vlan == vlan && e->lport == lport) {
l2t_hold(d, e);
if (atomic_read(&e->refcnt) == 1)
reuse_entry(e, neigh);
goto done;
}
/* Need to allocate a new entry */
e = alloc_l2e(d);
if (e) {
spin_lock(&e->lock); /* avoid race with t4_l2t_free */
e->state = L2T_STATE_RESOLVING;
memcpy(e->addr, addr, addr_len);
e->ifindex = ifidx;
e->hash = hash;
e->lport = lport;
e->v6 = addr_len == 16;
atomic_set(&e->refcnt, 1);
neigh_replace(e, neigh);
e->vlan = vlan;
e->next = d->l2tab[hash].first;
d->l2tab[hash].first = e;
spin_unlock(&e->lock);
}
done:
write_unlock_bh(&d->lock);
return e;
}
EXPORT_SYMBOL(cxgb4_l2t_get);
/*
* Called when address resolution fails for an L2T entry to handle packets
* on the arpq head. If a packet specifies a failure handler it is invoked,
* otherwise the packet is sent to the device.
*/
static void handle_failed_resolution(struct adapter *adap, struct sk_buff *arpq)
{
while (arpq) {
struct sk_buff *skb = arpq;
const struct l2t_skb_cb *cb = L2T_SKB_CB(skb);
arpq = skb->next;
skb->next = NULL;
if (cb->arp_err_handler)
cb->arp_err_handler(cb->handle, skb);
else
t4_ofld_send(adap, skb);
}
}
/*
* Called when the host's neighbor layer makes a change to some entry that is
* loaded into the HW L2 table.
*/
void t4_l2t_update(struct adapter *adap, struct neighbour *neigh)
{
struct l2t_entry *e;
struct sk_buff *arpq = NULL;
struct l2t_data *d = adap->l2t;
int addr_len = neigh->tbl->key_len;
u32 *addr = (u32 *) neigh->primary_key;
int ifidx = neigh->dev->ifindex;
int hash = addr_hash(addr, addr_len, ifidx);
read_lock_bh(&d->lock);
for (e = d->l2tab[hash].first; e; e = e->next)
if (!addreq(e, addr) && e->ifindex == ifidx) {
spin_lock(&e->lock);
if (atomic_read(&e->refcnt))
goto found;
spin_unlock(&e->lock);
break;
}
read_unlock_bh(&d->lock);
return;
found:
read_unlock(&d->lock);
if (neigh != e->neigh)
neigh_replace(e, neigh);
if (e->state == L2T_STATE_RESOLVING) {
if (neigh->nud_state & NUD_FAILED) {
arpq = e->arpq_head;
e->arpq_head = e->arpq_tail = NULL;
} else if ((neigh->nud_state & (NUD_CONNECTED | NUD_STALE)) &&
e->arpq_head) {
write_l2e(adap, e, 1);
}
} else {
e->state = neigh->nud_state & NUD_CONNECTED ?
L2T_STATE_VALID : L2T_STATE_STALE;
if (memcmp(e->dmac, neigh->ha, sizeof(e->dmac)))
write_l2e(adap, e, 0);
}
spin_unlock_bh(&e->lock);
if (arpq)
handle_failed_resolution(adap, arpq);
}
struct l2t_data *t4_init_l2t(void)
{
int i;
struct l2t_data *d;
d = t4_alloc_mem(sizeof(*d));
if (!d)
return NULL;
d->rover = d->l2tab;
atomic_set(&d->nfree, L2T_SIZE);
rwlock_init(&d->lock);
for (i = 0; i < L2T_SIZE; ++i) {
d->l2tab[i].idx = i;
d->l2tab[i].state = L2T_STATE_UNUSED;
spin_lock_init(&d->l2tab[i].lock);
atomic_set(&d->l2tab[i].refcnt, 0);
}
return d;
}
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
static inline void *l2t_get_idx(struct seq_file *seq, loff_t pos)
{
struct l2t_entry *l2tab = seq->private;
return pos >= L2T_SIZE ? NULL : &l2tab[pos];
}
static void *l2t_seq_start(struct seq_file *seq, loff_t *pos)
{
return *pos ? l2t_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *l2t_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
v = l2t_get_idx(seq, *pos);
if (v)
++*pos;
return v;
}
static void l2t_seq_stop(struct seq_file *seq, void *v)
{
}
static char l2e_state(const struct l2t_entry *e)
{
switch (e->state) {
case L2T_STATE_VALID: return 'V';
case L2T_STATE_STALE: return 'S';
case L2T_STATE_SYNC_WRITE: return 'W';
case L2T_STATE_RESOLVING: return e->arpq_head ? 'A' : 'R';
case L2T_STATE_SWITCHING: return 'X';
default:
return 'U';
}
}
static int l2t_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, " Idx IP address "
"Ethernet address VLAN/P LP State Users Port\n");
else {
char ip[60];
struct l2t_entry *e = v;
spin_lock_bh(&e->lock);
if (e->state == L2T_STATE_SWITCHING)
ip[0] = '\0';
else
sprintf(ip, e->v6 ? "%pI6c" : "%pI4", e->addr);
seq_printf(seq, "%4u %-25s %17pM %4d %u %2u %c %5u %s\n",
e->idx, ip, e->dmac,
e->vlan & VLAN_VID_MASK, vlan_prio(e), e->lport,
l2e_state(e), atomic_read(&e->refcnt),
e->neigh ? e->neigh->dev->name : "");
spin_unlock_bh(&e->lock);
}
return 0;
}
static const struct seq_operations l2t_seq_ops = {
.start = l2t_seq_start,
.next = l2t_seq_next,
.stop = l2t_seq_stop,
.show = l2t_seq_show
};
static int l2t_seq_open(struct inode *inode, struct file *file)
{
int rc = seq_open(file, &l2t_seq_ops);
if (!rc) {
struct adapter *adap = inode->i_private;
struct seq_file *seq = file->private_data;
seq->private = adap->l2t->l2tab;
}
return rc;
}
const struct file_operations t4_l2t_fops = {
.owner = THIS_MODULE,
.open = l2t_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
| gpl-2.0 |
grzmot22/Alucard-Kernel-jfltexx | drivers/w1/slaves/w1_ds2781.c | 4904 | 4331 | /*
* 1-Wire implementation for the ds2781 chip
*
* Author: Renata Sayakhova <renata@oktetlabs.ru>
*
* Based on w1-ds2780 driver
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/idr.h>
#include "../w1.h"
#include "../w1_int.h"
#include "../w1_family.h"
#include "w1_ds2781.h"
static int w1_ds2781_do_io(struct device *dev, char *buf, int addr,
size_t count, int io)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
if (addr > DS2781_DATA_SIZE || addr < 0)
return 0;
count = min_t(int, count, DS2781_DATA_SIZE - addr);
if (w1_reset_select_slave(sl) == 0) {
if (io) {
w1_write_8(sl->master, W1_DS2781_WRITE_DATA);
w1_write_8(sl->master, addr);
w1_write_block(sl->master, buf, count);
} else {
w1_write_8(sl->master, W1_DS2781_READ_DATA);
w1_write_8(sl->master, addr);
count = w1_read_block(sl->master, buf, count);
}
}
return count;
}
int w1_ds2781_io(struct device *dev, char *buf, int addr, size_t count,
int io)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
int ret;
if (!dev)
return -ENODEV;
mutex_lock(&sl->master->mutex);
ret = w1_ds2781_do_io(dev, buf, addr, count, io);
mutex_unlock(&sl->master->mutex);
return ret;
}
EXPORT_SYMBOL(w1_ds2781_io);
int w1_ds2781_io_nolock(struct device *dev, char *buf, int addr, size_t count,
int io)
{
int ret;
if (!dev)
return -ENODEV;
ret = w1_ds2781_do_io(dev, buf, addr, count, io);
return ret;
}
EXPORT_SYMBOL(w1_ds2781_io_nolock);
int w1_ds2781_eeprom_cmd(struct device *dev, int addr, int cmd)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
if (!dev)
return -EINVAL;
mutex_lock(&sl->master->mutex);
if (w1_reset_select_slave(sl) == 0) {
w1_write_8(sl->master, cmd);
w1_write_8(sl->master, addr);
}
mutex_unlock(&sl->master->mutex);
return 0;
}
EXPORT_SYMBOL(w1_ds2781_eeprom_cmd);
static ssize_t w1_ds2781_read_bin(struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
return w1_ds2781_io(dev, buf, off, count, 0);
}
static struct bin_attribute w1_ds2781_bin_attr = {
.attr = {
.name = "w1_slave",
.mode = S_IRUGO,
},
.size = DS2781_DATA_SIZE,
.read = w1_ds2781_read_bin,
};
static DEFINE_IDA(bat_ida);
static int w1_ds2781_add_slave(struct w1_slave *sl)
{
int ret;
int id;
struct platform_device *pdev;
id = ida_simple_get(&bat_ida, 0, 0, GFP_KERNEL);
if (id < 0) {
ret = id;
goto noid;
}
pdev = platform_device_alloc("ds2781-battery", id);
if (!pdev) {
ret = -ENOMEM;
goto pdev_alloc_failed;
}
pdev->dev.parent = &sl->dev;
ret = platform_device_add(pdev);
if (ret)
goto pdev_add_failed;
ret = sysfs_create_bin_file(&sl->dev.kobj, &w1_ds2781_bin_attr);
if (ret)
goto bin_attr_failed;
dev_set_drvdata(&sl->dev, pdev);
return 0;
bin_attr_failed:
pdev_add_failed:
platform_device_unregister(pdev);
pdev_alloc_failed:
ida_simple_remove(&bat_ida, id);
noid:
return ret;
}
static void w1_ds2781_remove_slave(struct w1_slave *sl)
{
struct platform_device *pdev = dev_get_drvdata(&sl->dev);
int id = pdev->id;
platform_device_unregister(pdev);
ida_simple_remove(&bat_ida, id);
sysfs_remove_bin_file(&sl->dev.kobj, &w1_ds2781_bin_attr);
}
static struct w1_family_ops w1_ds2781_fops = {
.add_slave = w1_ds2781_add_slave,
.remove_slave = w1_ds2781_remove_slave,
};
static struct w1_family w1_ds2781_family = {
.fid = W1_FAMILY_DS2781,
.fops = &w1_ds2781_fops,
};
static int __init w1_ds2781_init(void)
{
ida_init(&bat_ida);
return w1_register_family(&w1_ds2781_family);
}
static void __exit w1_ds2781_exit(void)
{
w1_unregister_family(&w1_ds2781_family);
ida_destroy(&bat_ida);
}
module_init(w1_ds2781_init);
module_exit(w1_ds2781_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Renata Sayakhova <renata@oktetlabs.ru>");
MODULE_DESCRIPTION("1-wire Driver for Maxim/Dallas DS2781 Stand-Alone Fuel Gauge IC");
| gpl-2.0 |
hariimurti/kernel_armani | arch/powerpc/platforms/powermac/pfunc_core.c | 7720 | 25647 | /*
*
* FIXME: Properly make this race free with refcounting etc...
*
* FIXME: LOCKING !!!
*/
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <asm/prom.h>
#include <asm/pmac_pfunc.h>
/* Debug */
#define LOG_PARSE(fmt...)
#define LOG_ERROR(fmt...) printk(fmt)
#define LOG_BLOB(t,b,c)
#undef DEBUG
#ifdef DEBUG
#define DBG(fmt...) printk(fmt)
#else
#define DBG(fmt...)
#endif
/* Command numbers */
#define PMF_CMD_LIST 0
#define PMF_CMD_WRITE_GPIO 1
#define PMF_CMD_READ_GPIO 2
#define PMF_CMD_WRITE_REG32 3
#define PMF_CMD_READ_REG32 4
#define PMF_CMD_WRITE_REG16 5
#define PMF_CMD_READ_REG16 6
#define PMF_CMD_WRITE_REG8 7
#define PMF_CMD_READ_REG8 8
#define PMF_CMD_DELAY 9
#define PMF_CMD_WAIT_REG32 10
#define PMF_CMD_WAIT_REG16 11
#define PMF_CMD_WAIT_REG8 12
#define PMF_CMD_READ_I2C 13
#define PMF_CMD_WRITE_I2C 14
#define PMF_CMD_RMW_I2C 15
#define PMF_CMD_GEN_I2C 16
#define PMF_CMD_SHIFT_BYTES_RIGHT 17
#define PMF_CMD_SHIFT_BYTES_LEFT 18
#define PMF_CMD_READ_CFG 19
#define PMF_CMD_WRITE_CFG 20
#define PMF_CMD_RMW_CFG 21
#define PMF_CMD_READ_I2C_SUBADDR 22
#define PMF_CMD_WRITE_I2C_SUBADDR 23
#define PMF_CMD_SET_I2C_MODE 24
#define PMF_CMD_RMW_I2C_SUBADDR 25
#define PMF_CMD_READ_REG32_MASK_SHR_XOR 26
#define PMF_CMD_READ_REG16_MASK_SHR_XOR 27
#define PMF_CMD_READ_REG8_MASK_SHR_XOR 28
#define PMF_CMD_WRITE_REG32_SHL_MASK 29
#define PMF_CMD_WRITE_REG16_SHL_MASK 30
#define PMF_CMD_WRITE_REG8_SHL_MASK 31
#define PMF_CMD_MASK_AND_COMPARE 32
#define PMF_CMD_COUNT 33
/* This structure holds the state of the parser while walking through
* a function definition
*/
struct pmf_cmd {
const void *cmdptr;
const void *cmdend;
struct pmf_function *func;
void *instdata;
struct pmf_args *args;
int error;
};
#if 0
/* Debug output */
static void print_blob(const char *title, const void *blob, int bytes)
{
printk("%s", title);
while(bytes--) {
printk("%02x ", *((u8 *)blob));
blob += 1;
}
printk("\n");
}
#endif
/*
* Parser helpers
*/
static u32 pmf_next32(struct pmf_cmd *cmd)
{
u32 value;
if ((cmd->cmdend - cmd->cmdptr) < 4) {
cmd->error = 1;
return 0;
}
value = *((u32 *)cmd->cmdptr);
cmd->cmdptr += 4;
return value;
}
static const void* pmf_next_blob(struct pmf_cmd *cmd, int count)
{
const void *value;
if ((cmd->cmdend - cmd->cmdptr) < count) {
cmd->error = 1;
return NULL;
}
value = cmd->cmdptr;
cmd->cmdptr += count;
return value;
}
/*
* Individual command parsers
*/
#define PMF_PARSE_CALL(name, cmd, handlers, p...) \
do { \
if (cmd->error) \
return -ENXIO; \
if (handlers == NULL) \
return 0; \
if (handlers->name) \
return handlers->name(cmd->func, cmd->instdata, \
cmd->args, p); \
return -1; \
} while(0) \
static int pmf_parser_write_gpio(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u8 value = (u8)pmf_next32(cmd);
u8 mask = (u8)pmf_next32(cmd);
LOG_PARSE("pmf: write_gpio(value: %02x, mask: %02x)\n", value, mask);
PMF_PARSE_CALL(write_gpio, cmd, h, value, mask);
}
static int pmf_parser_read_gpio(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u8 mask = (u8)pmf_next32(cmd);
int rshift = (int)pmf_next32(cmd);
u8 xor = (u8)pmf_next32(cmd);
LOG_PARSE("pmf: read_gpio(mask: %02x, rshift: %d, xor: %02x)\n",
mask, rshift, xor);
PMF_PARSE_CALL(read_gpio, cmd, h, mask, rshift, xor);
}
static int pmf_parser_write_reg32(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 value = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
LOG_PARSE("pmf: write_reg32(offset: %08x, value: %08x, mask: %08x)\n",
offset, value, mask);
PMF_PARSE_CALL(write_reg32, cmd, h, offset, value, mask);
}
static int pmf_parser_read_reg32(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
LOG_PARSE("pmf: read_reg32(offset: %08x)\n", offset);
PMF_PARSE_CALL(read_reg32, cmd, h, offset);
}
static int pmf_parser_write_reg16(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u16 value = (u16)pmf_next32(cmd);
u16 mask = (u16)pmf_next32(cmd);
LOG_PARSE("pmf: write_reg16(offset: %08x, value: %04x, mask: %04x)\n",
offset, value, mask);
PMF_PARSE_CALL(write_reg16, cmd, h, offset, value, mask);
}
static int pmf_parser_read_reg16(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
LOG_PARSE("pmf: read_reg16(offset: %08x)\n", offset);
PMF_PARSE_CALL(read_reg16, cmd, h, offset);
}
static int pmf_parser_write_reg8(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u8 value = (u16)pmf_next32(cmd);
u8 mask = (u16)pmf_next32(cmd);
LOG_PARSE("pmf: write_reg8(offset: %08x, value: %02x, mask: %02x)\n",
offset, value, mask);
PMF_PARSE_CALL(write_reg8, cmd, h, offset, value, mask);
}
static int pmf_parser_read_reg8(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
LOG_PARSE("pmf: read_reg8(offset: %08x)\n", offset);
PMF_PARSE_CALL(read_reg8, cmd, h, offset);
}
static int pmf_parser_delay(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 duration = pmf_next32(cmd);
LOG_PARSE("pmf: delay(duration: %d us)\n", duration);
PMF_PARSE_CALL(delay, cmd, h, duration);
}
static int pmf_parser_wait_reg32(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 value = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
LOG_PARSE("pmf: wait_reg32(offset: %08x, comp_value: %08x,mask: %08x)\n",
offset, value, mask);
PMF_PARSE_CALL(wait_reg32, cmd, h, offset, value, mask);
}
static int pmf_parser_wait_reg16(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u16 value = (u16)pmf_next32(cmd);
u16 mask = (u16)pmf_next32(cmd);
LOG_PARSE("pmf: wait_reg16(offset: %08x, comp_value: %04x,mask: %04x)\n",
offset, value, mask);
PMF_PARSE_CALL(wait_reg16, cmd, h, offset, value, mask);
}
static int pmf_parser_wait_reg8(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u8 value = (u8)pmf_next32(cmd);
u8 mask = (u8)pmf_next32(cmd);
LOG_PARSE("pmf: wait_reg8(offset: %08x, comp_value: %02x,mask: %02x)\n",
offset, value, mask);
PMF_PARSE_CALL(wait_reg8, cmd, h, offset, value, mask);
}
static int pmf_parser_read_i2c(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 bytes = pmf_next32(cmd);
LOG_PARSE("pmf: read_i2c(bytes: %ud)\n", bytes);
PMF_PARSE_CALL(read_i2c, cmd, h, bytes);
}
static int pmf_parser_write_i2c(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 bytes = pmf_next32(cmd);
const void *blob = pmf_next_blob(cmd, bytes);
LOG_PARSE("pmf: write_i2c(bytes: %ud) ...\n", bytes);
LOG_BLOB("pmf: data: \n", blob, bytes);
PMF_PARSE_CALL(write_i2c, cmd, h, bytes, blob);
}
static int pmf_parser_rmw_i2c(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 maskbytes = pmf_next32(cmd);
u32 valuesbytes = pmf_next32(cmd);
u32 totalbytes = pmf_next32(cmd);
const void *maskblob = pmf_next_blob(cmd, maskbytes);
const void *valuesblob = pmf_next_blob(cmd, valuesbytes);
LOG_PARSE("pmf: rmw_i2c(maskbytes: %ud, valuebytes: %ud, "
"totalbytes: %d) ...\n",
maskbytes, valuesbytes, totalbytes);
LOG_BLOB("pmf: mask data: \n", maskblob, maskbytes);
LOG_BLOB("pmf: values data: \n", valuesblob, valuesbytes);
PMF_PARSE_CALL(rmw_i2c, cmd, h, maskbytes, valuesbytes, totalbytes,
maskblob, valuesblob);
}
static int pmf_parser_read_cfg(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 bytes = pmf_next32(cmd);
LOG_PARSE("pmf: read_cfg(offset: %x, bytes: %ud)\n", offset, bytes);
PMF_PARSE_CALL(read_cfg, cmd, h, offset, bytes);
}
static int pmf_parser_write_cfg(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 bytes = pmf_next32(cmd);
const void *blob = pmf_next_blob(cmd, bytes);
LOG_PARSE("pmf: write_cfg(offset: %x, bytes: %ud)\n", offset, bytes);
LOG_BLOB("pmf: data: \n", blob, bytes);
PMF_PARSE_CALL(write_cfg, cmd, h, offset, bytes, blob);
}
static int pmf_parser_rmw_cfg(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 maskbytes = pmf_next32(cmd);
u32 valuesbytes = pmf_next32(cmd);
u32 totalbytes = pmf_next32(cmd);
const void *maskblob = pmf_next_blob(cmd, maskbytes);
const void *valuesblob = pmf_next_blob(cmd, valuesbytes);
LOG_PARSE("pmf: rmw_cfg(maskbytes: %ud, valuebytes: %ud,"
" totalbytes: %d) ...\n",
maskbytes, valuesbytes, totalbytes);
LOG_BLOB("pmf: mask data: \n", maskblob, maskbytes);
LOG_BLOB("pmf: values data: \n", valuesblob, valuesbytes);
PMF_PARSE_CALL(rmw_cfg, cmd, h, offset, maskbytes, valuesbytes,
totalbytes, maskblob, valuesblob);
}
static int pmf_parser_read_i2c_sub(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u8 subaddr = (u8)pmf_next32(cmd);
u32 bytes = pmf_next32(cmd);
LOG_PARSE("pmf: read_i2c_sub(subaddr: %x, bytes: %ud)\n",
subaddr, bytes);
PMF_PARSE_CALL(read_i2c_sub, cmd, h, subaddr, bytes);
}
static int pmf_parser_write_i2c_sub(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u8 subaddr = (u8)pmf_next32(cmd);
u32 bytes = pmf_next32(cmd);
const void *blob = pmf_next_blob(cmd, bytes);
LOG_PARSE("pmf: write_i2c_sub(subaddr: %x, bytes: %ud) ...\n",
subaddr, bytes);
LOG_BLOB("pmf: data: \n", blob, bytes);
PMF_PARSE_CALL(write_i2c_sub, cmd, h, subaddr, bytes, blob);
}
static int pmf_parser_set_i2c_mode(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u32 mode = pmf_next32(cmd);
LOG_PARSE("pmf: set_i2c_mode(mode: %d)\n", mode);
PMF_PARSE_CALL(set_i2c_mode, cmd, h, mode);
}
static int pmf_parser_rmw_i2c_sub(struct pmf_cmd *cmd, struct pmf_handlers *h)
{
u8 subaddr = (u8)pmf_next32(cmd);
u32 maskbytes = pmf_next32(cmd);
u32 valuesbytes = pmf_next32(cmd);
u32 totalbytes = pmf_next32(cmd);
const void *maskblob = pmf_next_blob(cmd, maskbytes);
const void *valuesblob = pmf_next_blob(cmd, valuesbytes);
LOG_PARSE("pmf: rmw_i2c_sub(subaddr: %x, maskbytes: %ud, valuebytes: %ud"
", totalbytes: %d) ...\n",
subaddr, maskbytes, valuesbytes, totalbytes);
LOG_BLOB("pmf: mask data: \n", maskblob, maskbytes);
LOG_BLOB("pmf: values data: \n", valuesblob, valuesbytes);
PMF_PARSE_CALL(rmw_i2c_sub, cmd, h, subaddr, maskbytes, valuesbytes,
totalbytes, maskblob, valuesblob);
}
static int pmf_parser_read_reg32_msrx(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
u32 shift = pmf_next32(cmd);
u32 xor = pmf_next32(cmd);
LOG_PARSE("pmf: read_reg32_msrx(offset: %x, mask: %x, shift: %x,"
" xor: %x\n", offset, mask, shift, xor);
PMF_PARSE_CALL(read_reg32_msrx, cmd, h, offset, mask, shift, xor);
}
static int pmf_parser_read_reg16_msrx(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
u32 shift = pmf_next32(cmd);
u32 xor = pmf_next32(cmd);
LOG_PARSE("pmf: read_reg16_msrx(offset: %x, mask: %x, shift: %x,"
" xor: %x\n", offset, mask, shift, xor);
PMF_PARSE_CALL(read_reg16_msrx, cmd, h, offset, mask, shift, xor);
}
static int pmf_parser_read_reg8_msrx(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
u32 shift = pmf_next32(cmd);
u32 xor = pmf_next32(cmd);
LOG_PARSE("pmf: read_reg8_msrx(offset: %x, mask: %x, shift: %x,"
" xor: %x\n", offset, mask, shift, xor);
PMF_PARSE_CALL(read_reg8_msrx, cmd, h, offset, mask, shift, xor);
}
static int pmf_parser_write_reg32_slm(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 shift = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
LOG_PARSE("pmf: write_reg32_slm(offset: %x, shift: %x, mask: %x\n",
offset, shift, mask);
PMF_PARSE_CALL(write_reg32_slm, cmd, h, offset, shift, mask);
}
static int pmf_parser_write_reg16_slm(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 shift = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
LOG_PARSE("pmf: write_reg16_slm(offset: %x, shift: %x, mask: %x\n",
offset, shift, mask);
PMF_PARSE_CALL(write_reg16_slm, cmd, h, offset, shift, mask);
}
static int pmf_parser_write_reg8_slm(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 offset = pmf_next32(cmd);
u32 shift = pmf_next32(cmd);
u32 mask = pmf_next32(cmd);
LOG_PARSE("pmf: write_reg8_slm(offset: %x, shift: %x, mask: %x\n",
offset, shift, mask);
PMF_PARSE_CALL(write_reg8_slm, cmd, h, offset, shift, mask);
}
static int pmf_parser_mask_and_compare(struct pmf_cmd *cmd,
struct pmf_handlers *h)
{
u32 bytes = pmf_next32(cmd);
const void *maskblob = pmf_next_blob(cmd, bytes);
const void *valuesblob = pmf_next_blob(cmd, bytes);
LOG_PARSE("pmf: mask_and_compare(length: %ud ...\n", bytes);
LOG_BLOB("pmf: mask data: \n", maskblob, bytes);
LOG_BLOB("pmf: values data: \n", valuesblob, bytes);
PMF_PARSE_CALL(mask_and_compare, cmd, h,
bytes, maskblob, valuesblob);
}
typedef int (*pmf_cmd_parser_t)(struct pmf_cmd *cmd, struct pmf_handlers *h);
static pmf_cmd_parser_t pmf_parsers[PMF_CMD_COUNT] =
{
NULL,
pmf_parser_write_gpio,
pmf_parser_read_gpio,
pmf_parser_write_reg32,
pmf_parser_read_reg32,
pmf_parser_write_reg16,
pmf_parser_read_reg16,
pmf_parser_write_reg8,
pmf_parser_read_reg8,
pmf_parser_delay,
pmf_parser_wait_reg32,
pmf_parser_wait_reg16,
pmf_parser_wait_reg8,
pmf_parser_read_i2c,
pmf_parser_write_i2c,
pmf_parser_rmw_i2c,
NULL, /* Bogus command */
NULL, /* Shift bytes right: NYI */
NULL, /* Shift bytes left: NYI */
pmf_parser_read_cfg,
pmf_parser_write_cfg,
pmf_parser_rmw_cfg,
pmf_parser_read_i2c_sub,
pmf_parser_write_i2c_sub,
pmf_parser_set_i2c_mode,
pmf_parser_rmw_i2c_sub,
pmf_parser_read_reg32_msrx,
pmf_parser_read_reg16_msrx,
pmf_parser_read_reg8_msrx,
pmf_parser_write_reg32_slm,
pmf_parser_write_reg16_slm,
pmf_parser_write_reg8_slm,
pmf_parser_mask_and_compare,
};
struct pmf_device {
struct list_head link;
struct device_node *node;
struct pmf_handlers *handlers;
struct list_head functions;
struct kref ref;
};
static LIST_HEAD(pmf_devices);
static DEFINE_SPINLOCK(pmf_lock);
static DEFINE_MUTEX(pmf_irq_mutex);
static void pmf_release_device(struct kref *kref)
{
struct pmf_device *dev = container_of(kref, struct pmf_device, ref);
kfree(dev);
}
static inline void pmf_put_device(struct pmf_device *dev)
{
kref_put(&dev->ref, pmf_release_device);
}
static inline struct pmf_device *pmf_get_device(struct pmf_device *dev)
{
kref_get(&dev->ref);
return dev;
}
static inline struct pmf_device *pmf_find_device(struct device_node *np)
{
struct pmf_device *dev;
list_for_each_entry(dev, &pmf_devices, link) {
if (dev->node == np)
return pmf_get_device(dev);
}
return NULL;
}
static int pmf_parse_one(struct pmf_function *func,
struct pmf_handlers *handlers,
void *instdata, struct pmf_args *args)
{
struct pmf_cmd cmd;
u32 ccode;
int count, rc;
cmd.cmdptr = func->data;
cmd.cmdend = func->data + func->length;
cmd.func = func;
cmd.instdata = instdata;
cmd.args = args;
cmd.error = 0;
LOG_PARSE("pmf: func %s, %d bytes, %s...\n",
func->name, func->length,
handlers ? "executing" : "parsing");
/* One subcommand to parse for now */
count = 1;
while(count-- && cmd.cmdptr < cmd.cmdend) {
/* Get opcode */
ccode = pmf_next32(&cmd);
/* Check if we are hitting a command list, fetch new count */
if (ccode == 0) {
count = pmf_next32(&cmd) - 1;
ccode = pmf_next32(&cmd);
}
if (cmd.error) {
LOG_ERROR("pmf: parse error, not enough data\n");
return -ENXIO;
}
if (ccode >= PMF_CMD_COUNT) {
LOG_ERROR("pmf: command code %d unknown !\n", ccode);
return -ENXIO;
}
if (pmf_parsers[ccode] == NULL) {
LOG_ERROR("pmf: no parser for command %d !\n", ccode);
return -ENXIO;
}
rc = pmf_parsers[ccode](&cmd, handlers);
if (rc != 0) {
LOG_ERROR("pmf: parser for command %d returned"
" error %d\n", ccode, rc);
return rc;
}
}
/* We are doing an initial parse pass, we need to adjust the size */
if (handlers == NULL)
func->length = cmd.cmdptr - func->data;
return 0;
}
static int pmf_add_function_prop(struct pmf_device *dev, void *driverdata,
const char *name, u32 *data,
unsigned int length)
{
int count = 0;
struct pmf_function *func = NULL;
DBG("pmf: Adding functions for platform-do-%s\n", name);
while (length >= 12) {
/* Allocate a structure */
func = kzalloc(sizeof(struct pmf_function), GFP_KERNEL);
if (func == NULL)
goto bail;
kref_init(&func->ref);
INIT_LIST_HEAD(&func->irq_clients);
func->node = dev->node;
func->driver_data = driverdata;
func->name = name;
func->phandle = data[0];
func->flags = data[1];
data += 2;
length -= 8;
func->data = data;
func->length = length;
func->dev = dev;
DBG("pmf: idx %d: flags=%08x, phandle=%08x "
" %d bytes remaining, parsing...\n",
count+1, func->flags, func->phandle, length);
if (pmf_parse_one(func, NULL, NULL, NULL)) {
kfree(func);
goto bail;
}
length -= func->length;
data = (u32 *)(((u8 *)data) + func->length);
list_add(&func->link, &dev->functions);
pmf_get_device(dev);
count++;
}
bail:
DBG("pmf: Added %d functions\n", count);
return count;
}
static int pmf_add_functions(struct pmf_device *dev, void *driverdata)
{
struct property *pp;
#define PP_PREFIX "platform-do-"
const int plen = strlen(PP_PREFIX);
int count = 0;
for (pp = dev->node->properties; pp != 0; pp = pp->next) {
char *name;
if (strncmp(pp->name, PP_PREFIX, plen) != 0)
continue;
name = pp->name + plen;
if (strlen(name) && pp->length >= 12)
count += pmf_add_function_prop(dev, driverdata, name,
pp->value, pp->length);
}
return count;
}
int pmf_register_driver(struct device_node *np,
struct pmf_handlers *handlers,
void *driverdata)
{
struct pmf_device *dev;
unsigned long flags;
int rc = 0;
if (handlers == NULL)
return -EINVAL;
DBG("pmf: registering driver for node %s\n", np->full_name);
spin_lock_irqsave(&pmf_lock, flags);
dev = pmf_find_device(np);
spin_unlock_irqrestore(&pmf_lock, flags);
if (dev != NULL) {
DBG("pmf: already there !\n");
pmf_put_device(dev);
return -EBUSY;
}
dev = kzalloc(sizeof(struct pmf_device), GFP_KERNEL);
if (dev == NULL) {
DBG("pmf: no memory !\n");
return -ENOMEM;
}
kref_init(&dev->ref);
dev->node = of_node_get(np);
dev->handlers = handlers;
INIT_LIST_HEAD(&dev->functions);
rc = pmf_add_functions(dev, driverdata);
if (rc == 0) {
DBG("pmf: no functions, disposing.. \n");
of_node_put(np);
kfree(dev);
return -ENODEV;
}
spin_lock_irqsave(&pmf_lock, flags);
list_add(&dev->link, &pmf_devices);
spin_unlock_irqrestore(&pmf_lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(pmf_register_driver);
struct pmf_function *pmf_get_function(struct pmf_function *func)
{
if (!try_module_get(func->dev->handlers->owner))
return NULL;
kref_get(&func->ref);
return func;
}
EXPORT_SYMBOL_GPL(pmf_get_function);
static void pmf_release_function(struct kref *kref)
{
struct pmf_function *func =
container_of(kref, struct pmf_function, ref);
pmf_put_device(func->dev);
kfree(func);
}
static inline void __pmf_put_function(struct pmf_function *func)
{
kref_put(&func->ref, pmf_release_function);
}
void pmf_put_function(struct pmf_function *func)
{
if (func == NULL)
return;
module_put(func->dev->handlers->owner);
__pmf_put_function(func);
}
EXPORT_SYMBOL_GPL(pmf_put_function);
void pmf_unregister_driver(struct device_node *np)
{
struct pmf_device *dev;
unsigned long flags;
DBG("pmf: unregistering driver for node %s\n", np->full_name);
spin_lock_irqsave(&pmf_lock, flags);
dev = pmf_find_device(np);
if (dev == NULL) {
DBG("pmf: not such driver !\n");
spin_unlock_irqrestore(&pmf_lock, flags);
return;
}
list_del(&dev->link);
while(!list_empty(&dev->functions)) {
struct pmf_function *func =
list_entry(dev->functions.next, typeof(*func), link);
list_del(&func->link);
__pmf_put_function(func);
}
pmf_put_device(dev);
spin_unlock_irqrestore(&pmf_lock, flags);
}
EXPORT_SYMBOL_GPL(pmf_unregister_driver);
struct pmf_function *__pmf_find_function(struct device_node *target,
const char *name, u32 flags)
{
struct device_node *actor = of_node_get(target);
struct pmf_device *dev;
struct pmf_function *func, *result = NULL;
char fname[64];
const u32 *prop;
u32 ph;
/*
* Look for a "platform-*" function reference. If we can't find
* one, then we fallback to a direct call attempt
*/
snprintf(fname, 63, "platform-%s", name);
prop = of_get_property(target, fname, NULL);
if (prop == NULL)
goto find_it;
ph = *prop;
if (ph == 0)
goto find_it;
/*
* Ok, now try to find the actor. If we can't find it, we fail,
* there is no point in falling back there
*/
of_node_put(actor);
actor = of_find_node_by_phandle(ph);
if (actor == NULL)
return NULL;
find_it:
dev = pmf_find_device(actor);
if (dev == NULL) {
result = NULL;
goto out;
}
list_for_each_entry(func, &dev->functions, link) {
if (name && strcmp(name, func->name))
continue;
if (func->phandle && target->phandle != func->phandle)
continue;
if ((func->flags & flags) == 0)
continue;
result = func;
break;
}
pmf_put_device(dev);
out:
of_node_put(actor);
return result;
}
int pmf_register_irq_client(struct device_node *target,
const char *name,
struct pmf_irq_client *client)
{
struct pmf_function *func;
unsigned long flags;
spin_lock_irqsave(&pmf_lock, flags);
func = __pmf_find_function(target, name, PMF_FLAGS_INT_GEN);
if (func)
func = pmf_get_function(func);
spin_unlock_irqrestore(&pmf_lock, flags);
if (func == NULL)
return -ENODEV;
/* guard against manipulations of list */
mutex_lock(&pmf_irq_mutex);
if (list_empty(&func->irq_clients))
func->dev->handlers->irq_enable(func);
/* guard against pmf_do_irq while changing list */
spin_lock_irqsave(&pmf_lock, flags);
list_add(&client->link, &func->irq_clients);
spin_unlock_irqrestore(&pmf_lock, flags);
client->func = func;
mutex_unlock(&pmf_irq_mutex);
return 0;
}
EXPORT_SYMBOL_GPL(pmf_register_irq_client);
void pmf_unregister_irq_client(struct pmf_irq_client *client)
{
struct pmf_function *func = client->func;
unsigned long flags;
BUG_ON(func == NULL);
/* guard against manipulations of list */
mutex_lock(&pmf_irq_mutex);
client->func = NULL;
/* guard against pmf_do_irq while changing list */
spin_lock_irqsave(&pmf_lock, flags);
list_del(&client->link);
spin_unlock_irqrestore(&pmf_lock, flags);
if (list_empty(&func->irq_clients))
func->dev->handlers->irq_disable(func);
mutex_unlock(&pmf_irq_mutex);
pmf_put_function(func);
}
EXPORT_SYMBOL_GPL(pmf_unregister_irq_client);
void pmf_do_irq(struct pmf_function *func)
{
unsigned long flags;
struct pmf_irq_client *client;
/* For now, using a spinlock over the whole function. Can be made
* to drop the lock using 2 lists if necessary
*/
spin_lock_irqsave(&pmf_lock, flags);
list_for_each_entry(client, &func->irq_clients, link) {
if (!try_module_get(client->owner))
continue;
client->handler(client->data);
module_put(client->owner);
}
spin_unlock_irqrestore(&pmf_lock, flags);
}
EXPORT_SYMBOL_GPL(pmf_do_irq);
int pmf_call_one(struct pmf_function *func, struct pmf_args *args)
{
struct pmf_device *dev = func->dev;
void *instdata = NULL;
int rc = 0;
DBG(" ** pmf_call_one(%s/%s) **\n", dev->node->full_name, func->name);
if (dev->handlers->begin)
instdata = dev->handlers->begin(func, args);
rc = pmf_parse_one(func, dev->handlers, instdata, args);
if (dev->handlers->end)
dev->handlers->end(func, instdata);
return rc;
}
EXPORT_SYMBOL_GPL(pmf_call_one);
int pmf_do_functions(struct device_node *np, const char *name,
u32 phandle, u32 fflags, struct pmf_args *args)
{
struct pmf_device *dev;
struct pmf_function *func, *tmp;
unsigned long flags;
int rc = -ENODEV;
spin_lock_irqsave(&pmf_lock, flags);
dev = pmf_find_device(np);
if (dev == NULL) {
spin_unlock_irqrestore(&pmf_lock, flags);
return -ENODEV;
}
list_for_each_entry_safe(func, tmp, &dev->functions, link) {
if (name && strcmp(name, func->name))
continue;
if (phandle && func->phandle && phandle != func->phandle)
continue;
if ((func->flags & fflags) == 0)
continue;
if (pmf_get_function(func) == NULL)
continue;
spin_unlock_irqrestore(&pmf_lock, flags);
rc = pmf_call_one(func, args);
pmf_put_function(func);
spin_lock_irqsave(&pmf_lock, flags);
}
pmf_put_device(dev);
spin_unlock_irqrestore(&pmf_lock, flags);
return rc;
}
EXPORT_SYMBOL_GPL(pmf_do_functions);
struct pmf_function *pmf_find_function(struct device_node *target,
const char *name)
{
struct pmf_function *func;
unsigned long flags;
spin_lock_irqsave(&pmf_lock, flags);
func = __pmf_find_function(target, name, PMF_FLAGS_ON_DEMAND);
if (func)
func = pmf_get_function(func);
spin_unlock_irqrestore(&pmf_lock, flags);
return func;
}
EXPORT_SYMBOL_GPL(pmf_find_function);
int pmf_call_function(struct device_node *target, const char *name,
struct pmf_args *args)
{
struct pmf_function *func = pmf_find_function(target, name);
int rc;
if (func == NULL)
return -ENODEV;
rc = pmf_call_one(func, args);
pmf_put_function(func);
return rc;
}
EXPORT_SYMBOL_GPL(pmf_call_function);
| gpl-2.0 |
PyYoshi/android_kernel_kyocera_l03 | drivers/input/apm-power.c | 8232 | 2634 | /*
* Input Power Event -> APM Bridge
*
* Copyright (c) 2007 Richard Purdie
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/apm-emulation.h>
static void system_power_event(unsigned int keycode)
{
switch (keycode) {
case KEY_SUSPEND:
apm_queue_event(APM_USER_SUSPEND);
pr_info("Requesting system suspend...\n");
break;
default:
break;
}
}
static void apmpower_event(struct input_handle *handle, unsigned int type,
unsigned int code, int value)
{
/* only react on key down events */
if (value != 1)
return;
switch (type) {
case EV_PWR:
system_power_event(code);
break;
default:
break;
}
}
static int apmpower_connect(struct input_handler *handler,
struct input_dev *dev,
const struct input_device_id *id)
{
struct input_handle *handle;
int error;
handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
handle->dev = dev;
handle->handler = handler;
handle->name = "apm-power";
error = input_register_handle(handle);
if (error) {
pr_err("Failed to register input power handler, error %d\n",
error);
kfree(handle);
return error;
}
error = input_open_device(handle);
if (error) {
pr_err("Failed to open input power device, error %d\n", error);
input_unregister_handle(handle);
kfree(handle);
return error;
}
return 0;
}
static void apmpower_disconnect(struct input_handle *handle)
{
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
static const struct input_device_id apmpower_ids[] = {
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
.evbit = { BIT_MASK(EV_PWR) },
},
{ },
};
MODULE_DEVICE_TABLE(input, apmpower_ids);
static struct input_handler apmpower_handler = {
.event = apmpower_event,
.connect = apmpower_connect,
.disconnect = apmpower_disconnect,
.name = "apm-power",
.id_table = apmpower_ids,
};
static int __init apmpower_init(void)
{
return input_register_handler(&apmpower_handler);
}
static void __exit apmpower_exit(void)
{
input_unregister_handler(&apmpower_handler);
}
module_init(apmpower_init);
module_exit(apmpower_exit);
MODULE_AUTHOR("Richard Purdie <rpurdie@rpsys.net>");
MODULE_DESCRIPTION("Input Power Event -> APM Bridge");
MODULE_LICENSE("GPL");
| gpl-2.0 |
android-armv7a-belalang-tempur/android_kernel_samsung_royss | drivers/staging/vt6655/wpa2.c | 8232 | 12595 | /*
* 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: wpa2.c
*
* Purpose: Handles the Basic Service Set & Node Database functions
*
* Functions:
*
* Revision History:
*
* Author: Yiching Chen
*
* Date: Oct. 4, 2004
*
*/
#include "wpa2.h"
#include "device.h"
#include "wmgr.h"
/*--------------------- Static Definitions -------------------------*/
static int msglevel =MSG_LEVEL_INFO;
//static int msglevel =MSG_LEVEL_DEBUG;
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
const unsigned char abyOUIGK[4] = { 0x00, 0x0F, 0xAC, 0x00 };
const unsigned char abyOUIWEP40[4] = { 0x00, 0x0F, 0xAC, 0x01 };
const unsigned char abyOUIWEP104[4] = { 0x00, 0x0F, 0xAC, 0x05 };
const unsigned char abyOUITKIP[4] = { 0x00, 0x0F, 0xAC, 0x02 };
const unsigned char abyOUICCMP[4] = { 0x00, 0x0F, 0xAC, 0x04 };
const unsigned char abyOUI8021X[4] = { 0x00, 0x0F, 0xAC, 0x01 };
const unsigned char abyOUIPSK[4] = { 0x00, 0x0F, 0xAC, 0x02 };
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
/*--------------------- Export Functions --------------------------*/
/*+
*
* Description:
* Clear RSN information in BSSList.
*
* Parameters:
* In:
* pBSSNode - BSS list.
* Out:
* none
*
* Return Value: none.
*
-*/
void
WPA2_ClearRSN (
PKnownBSS pBSSNode
)
{
int ii;
pBSSNode->bWPA2Valid = false;
pBSSNode->byCSSGK = WLAN_11i_CSS_CCMP;
for (ii=0; ii < 4; ii ++)
pBSSNode->abyCSSPK[ii] = WLAN_11i_CSS_CCMP;
pBSSNode->wCSSPKCount = 1;
for (ii=0; ii < 4; ii ++)
pBSSNode->abyAKMSSAuthType[ii] = WLAN_11i_AKMSS_802_1X;
pBSSNode->wAKMSSAuthCount = 1;
pBSSNode->sRSNCapObj.bRSNCapExist = false;
pBSSNode->sRSNCapObj.wRSNCap = 0;
}
/*+
*
* Description:
* Parse RSN IE.
*
* Parameters:
* In:
* pBSSNode - BSS list.
* pRSN - Pointer to the RSN IE.
* Out:
* none
*
* Return Value: none.
*
-*/
void
WPA2vParseRSN (
PKnownBSS pBSSNode,
PWLAN_IE_RSN pRSN
)
{
int i, j;
unsigned short m = 0, n = 0;
unsigned char *pbyOUI;
bool bUseGK = false;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"WPA2_ParseRSN: [%d]\n", pRSN->len);
WPA2_ClearRSN(pBSSNode);
if (pRSN->len == 2) { // ver(2)
if ((pRSN->byElementID == WLAN_EID_RSN) && (pRSN->wVersion == 1)) {
pBSSNode->bWPA2Valid = true;
}
return;
}
if (pRSN->len < 6) { // ver(2) + GK(4)
// invalid CSS, P802.11i/D10.0, p31
return;
}
// information element header makes sense
if ((pRSN->byElementID == WLAN_EID_RSN) &&
(pRSN->wVersion == 1)) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Legal 802.11i RSN\n");
pbyOUI = &(pRSN->abyRSN[0]);
if ( !memcmp(pbyOUI, abyOUIWEP40, 4))
pBSSNode->byCSSGK = WLAN_11i_CSS_WEP40;
else if ( !memcmp(pbyOUI, abyOUITKIP, 4))
pBSSNode->byCSSGK = WLAN_11i_CSS_TKIP;
else if ( !memcmp(pbyOUI, abyOUICCMP, 4))
pBSSNode->byCSSGK = WLAN_11i_CSS_CCMP;
else if ( !memcmp(pbyOUI, abyOUIWEP104, 4))
pBSSNode->byCSSGK = WLAN_11i_CSS_WEP104;
else if ( !memcmp(pbyOUI, abyOUIGK, 4)) {
// invalid CSS, P802.11i/D10.0, p32
return;
} else
// any vendor checks here
pBSSNode->byCSSGK = WLAN_11i_CSS_UNKNOWN;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"802.11i CSS: %X\n", pBSSNode->byCSSGK);
if (pRSN->len == 6) {
pBSSNode->bWPA2Valid = true;
return;
}
if (pRSN->len >= 8) { // ver(2) + GK(4) + PK count(2)
pBSSNode->wCSSPKCount = *((unsigned short *) &(pRSN->abyRSN[4]));
j = 0;
pbyOUI = &(pRSN->abyRSN[6]);
for (i = 0; (i < pBSSNode->wCSSPKCount) && (j < sizeof(pBSSNode->abyCSSPK)/sizeof(unsigned char)); i++) {
if (pRSN->len >= 8+i*4+4) { // ver(2)+GK(4)+PKCnt(2)+PKS(4*i)
if ( !memcmp(pbyOUI, abyOUIGK, 4)) {
pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_USE_GROUP;
bUseGK = true;
} else if ( !memcmp(pbyOUI, abyOUIWEP40, 4)) {
// Invialid CSS, continue to parsing
} else if ( !memcmp(pbyOUI, abyOUITKIP, 4)) {
if (pBSSNode->byCSSGK != WLAN_11i_CSS_CCMP)
pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_TKIP;
else
; // Invialid CSS, continue to parsing
} else if ( !memcmp(pbyOUI, abyOUICCMP, 4)) {
pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_CCMP;
} else if ( !memcmp(pbyOUI, abyOUIWEP104, 4)) {
// Invialid CSS, continue to parsing
} else {
// any vendor checks here
pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_UNKNOWN;
}
pbyOUI += 4;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"abyCSSPK[%d]: %X\n", j-1, pBSSNode->abyCSSPK[j-1]);
} else
break;
} //for
if (bUseGK == true) {
if (j != 1) {
// invalid CSS, This should be only PK CSS.
return;
}
if (pBSSNode->byCSSGK == WLAN_11i_CSS_CCMP) {
// invalid CSS, If CCMP is enable , PK can't be CSSGK.
return;
}
}
if ((pBSSNode->wCSSPKCount != 0) && (j == 0)) {
// invalid CSS, No valid PK.
return;
}
pBSSNode->wCSSPKCount = (unsigned short)j;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wCSSPKCount: %d\n", pBSSNode->wCSSPKCount);
}
m = *((unsigned short *) &(pRSN->abyRSN[4]));
if (pRSN->len >= 10+m*4) { // ver(2) + GK(4) + PK count(2) + PKS(4*m) + AKMSS count(2)
pBSSNode->wAKMSSAuthCount = *((unsigned short *) &(pRSN->abyRSN[6+4*m]));
j = 0;
pbyOUI = &(pRSN->abyRSN[8+4*m]);
for (i = 0; (i < pBSSNode->wAKMSSAuthCount) && (j < sizeof(pBSSNode->abyAKMSSAuthType)/sizeof(unsigned char)); i++) {
if (pRSN->len >= 10+(m+i)*4+4) { // ver(2)+GK(4)+PKCnt(2)+PKS(4*m)+AKMSS(2)+AKS(4*i)
if ( !memcmp(pbyOUI, abyOUI8021X, 4))
pBSSNode->abyAKMSSAuthType[j++] = WLAN_11i_AKMSS_802_1X;
else if ( !memcmp(pbyOUI, abyOUIPSK, 4))
pBSSNode->abyAKMSSAuthType[j++] = WLAN_11i_AKMSS_PSK;
else
// any vendor checks here
pBSSNode->abyAKMSSAuthType[j++] = WLAN_11i_AKMSS_UNKNOWN;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"abyAKMSSAuthType[%d]: %X\n", j-1, pBSSNode->abyAKMSSAuthType[j-1]);
} else
break;
}
pBSSNode->wAKMSSAuthCount = (unsigned short)j;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wAKMSSAuthCount: %d\n", pBSSNode->wAKMSSAuthCount);
n = *((unsigned short *) &(pRSN->abyRSN[6+4*m]));
if (pRSN->len >= 12+4*m+4*n) { // ver(2)+GK(4)+PKCnt(2)+PKS(4*m)+AKMSSCnt(2)+AKMSS(4*n)+Cap(2)
pBSSNode->sRSNCapObj.bRSNCapExist = true;
pBSSNode->sRSNCapObj.wRSNCap = *((unsigned short *) &(pRSN->abyRSN[8+4*m+4*n]));
}
}
//ignore PMKID lists bcs only (Re)Assocrequest has this field
pBSSNode->bWPA2Valid = true;
}
}
/*+
*
* Description:
* Set WPA IEs
*
* Parameters:
* In:
* pMgmtHandle - Pointer to management object
* Out:
* pRSNIEs - Pointer to the RSN IE to set.
*
* Return Value: length of IEs.
*
-*/
unsigned int
WPA2uSetIEs(
void *pMgmtHandle,
PWLAN_IE_RSN pRSNIEs
)
{
PSMgmtObject pMgmt = (PSMgmtObject) pMgmtHandle;
unsigned char *pbyBuffer = NULL;
unsigned int ii = 0;
unsigned short *pwPMKID = NULL;
if (pRSNIEs == NULL) {
return(0);
}
if (((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) &&
(pMgmt->pCurrBSS != NULL)) {
/* WPA2 IE */
pbyBuffer = (unsigned char *) pRSNIEs;
pRSNIEs->byElementID = WLAN_EID_RSN;
pRSNIEs->len = 6; //Version(2)+GK(4)
pRSNIEs->wVersion = 1;
//Group Key Cipher Suite
pRSNIEs->abyRSN[0] = 0x00;
pRSNIEs->abyRSN[1] = 0x0F;
pRSNIEs->abyRSN[2] = 0xAC;
if (pMgmt->byCSSGK == KEY_CTL_WEP) {
pRSNIEs->abyRSN[3] = pMgmt->pCurrBSS->byCSSGK;
} else if (pMgmt->byCSSGK == KEY_CTL_TKIP) {
pRSNIEs->abyRSN[3] = WLAN_11i_CSS_TKIP;
} else if (pMgmt->byCSSGK == KEY_CTL_CCMP) {
pRSNIEs->abyRSN[3] = WLAN_11i_CSS_CCMP;
} else {
pRSNIEs->abyRSN[3] = WLAN_11i_CSS_UNKNOWN;
}
// Pairwise Key Cipher Suite
pRSNIEs->abyRSN[4] = 1;
pRSNIEs->abyRSN[5] = 0;
pRSNIEs->abyRSN[6] = 0x00;
pRSNIEs->abyRSN[7] = 0x0F;
pRSNIEs->abyRSN[8] = 0xAC;
if (pMgmt->byCSSPK == KEY_CTL_TKIP) {
pRSNIEs->abyRSN[9] = WLAN_11i_CSS_TKIP;
} else if (pMgmt->byCSSPK == KEY_CTL_CCMP) {
pRSNIEs->abyRSN[9] = WLAN_11i_CSS_CCMP;
} else if (pMgmt->byCSSPK == KEY_CTL_NONE) {
pRSNIEs->abyRSN[9] = WLAN_11i_CSS_USE_GROUP;
} else {
pRSNIEs->abyRSN[9] = WLAN_11i_CSS_UNKNOWN;
}
pRSNIEs->len += 6;
// Auth Key Management Suite
pRSNIEs->abyRSN[10] = 1;
pRSNIEs->abyRSN[11] = 0;
pRSNIEs->abyRSN[12] = 0x00;
pRSNIEs->abyRSN[13] = 0x0F;
pRSNIEs->abyRSN[14] = 0xAC;
if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK) {
pRSNIEs->abyRSN[15] = WLAN_11i_AKMSS_PSK;
} else if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) {
pRSNIEs->abyRSN[15] = WLAN_11i_AKMSS_802_1X;
} else {
pRSNIEs->abyRSN[15] = WLAN_11i_AKMSS_UNKNOWN;
}
pRSNIEs->len +=6;
// RSN Capabilites
if (pMgmt->pCurrBSS->sRSNCapObj.bRSNCapExist == true) {
memcpy(&pRSNIEs->abyRSN[16], &pMgmt->pCurrBSS->sRSNCapObj.wRSNCap, 2);
} else {
pRSNIEs->abyRSN[16] = 0;
pRSNIEs->abyRSN[17] = 0;
}
pRSNIEs->len +=2;
if ((pMgmt->gsPMKIDCache.BSSIDInfoCount > 0) &&
(pMgmt->bRoaming == true) &&
(pMgmt->eAuthenMode == WMAC_AUTH_WPA2)) {
// RSN PMKID
pwPMKID = (unsigned short *)(&pRSNIEs->abyRSN[18]); // Point to PMKID count
*pwPMKID = 0; // Initialize PMKID count
pbyBuffer = &pRSNIEs->abyRSN[20]; // Point to PMKID list
for (ii = 0; ii < pMgmt->gsPMKIDCache.BSSIDInfoCount; ii++) {
if ( !memcmp(&pMgmt->gsPMKIDCache.BSSIDInfo[ii].abyBSSID[0], pMgmt->abyCurrBSSID, ETH_ALEN)) {
(*pwPMKID) ++;
memcpy(pbyBuffer, pMgmt->gsPMKIDCache.BSSIDInfo[ii].abyPMKID, 16);
pbyBuffer += 16;
}
}
if (*pwPMKID != 0) {
pRSNIEs->len += (2 + (*pwPMKID)*16);
} else {
pbyBuffer = &pRSNIEs->abyRSN[18];
}
}
return(pRSNIEs->len + WLAN_IEHDR_LEN);
}
return(0);
}
| gpl-2.0 |
artemh/asuswrt-merlin | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/media/video/saa7134/saa7134-input.c | 41 | 30539 | /*
*
* handle saa7134 IR remotes via linux kernel input layer.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/slab.h>
#include "saa7134-reg.h"
#include "saa7134.h"
#define MODULE_NAME "saa7134"
static unsigned int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir,"disable infrared remote support");
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug,"enable debug messages [IR]");
static int pinnacle_remote;
module_param(pinnacle_remote, int, 0644); /* Choose Pinnacle PCTV remote */
MODULE_PARM_DESC(pinnacle_remote, "Specify Pinnacle PCTV remote: 0=coloured, 1=grey (defaults to 0)");
static int ir_rc5_remote_gap = 885;
module_param(ir_rc5_remote_gap, int, 0644);
static int ir_rc5_key_timeout = 115;
module_param(ir_rc5_key_timeout, int, 0644);
static int repeat_delay = 500;
module_param(repeat_delay, int, 0644);
MODULE_PARM_DESC(repeat_delay, "delay before key repeat started");
static int repeat_period = 33;
module_param(repeat_period, int, 0644);
MODULE_PARM_DESC(repeat_period, "repeat period between "
"keypresses when key is down");
static unsigned int disable_other_ir;
module_param(disable_other_ir, int, 0644);
MODULE_PARM_DESC(disable_other_ir, "disable full codes of "
"alternative remotes from other manufacturers");
#define dprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, dev->name , ## arg)
#define i2cdprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, ir->name , ## arg)
/* Helper functions for RC5 and NEC decoding at GPIO16 or GPIO18 */
static int saa7134_rc5_irq(struct saa7134_dev *dev);
static int saa7134_nec_irq(struct saa7134_dev *dev);
static int saa7134_raw_decode_irq(struct saa7134_dev *dev);
static void nec_task(unsigned long data);
static void saa7134_nec_timer(unsigned long data);
/* -------------------- GPIO generic keycode builder -------------------- */
static int build_key(struct saa7134_dev *dev)
{
struct card_ir *ir = dev->remote;
u32 gpio, data;
/* here comes the additional handshake steps for some cards */
switch (dev->board) {
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x80);
saa_clearb(SAA7134_GPIO_GPSTATUS1, 0x80);
break;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (ir->polling) {
if (ir->last_gpio == gpio)
return 0;
ir->last_gpio = gpio;
}
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("build_key gpio=0x%x mask=0x%x data=%d\n",
gpio, ir->mask_keycode, data);
switch (dev->board) {
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
if (data == ir->mask_keycode)
ir_input_nokey(ir->dev, &ir->ir);
else
ir_input_keydown(ir->dev, &ir->ir, data);
return 0;
}
if (ir->polling) {
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
ir_input_keydown(ir->dev, &ir->ir, data);
} else {
ir_input_nokey(ir->dev, &ir->ir);
}
}
else { /* IRQ driven mode - handle key press and release in one go */
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
ir_input_keydown(ir->dev, &ir->ir, data);
ir_input_nokey(ir->dev, &ir->ir);
}
}
return 0;
}
/* --------------------- Chip specific I2C key builders ----------------- */
static int get_key_flydvb_trio(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
int gpio;
int attempt = 0;
unsigned char b;
/* We need this to access GPI Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_flydvb_trio: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIGPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x40000 & ~gpio)
return 0; /* No button press */
/* No button press - only before first key pressed */
if (b == 0xFF)
return 0;
/* poll IR chip */
/* weak up the IR chip */
b = 0;
while (1 != i2c_master_send(ir->c, &b, 1)) {
if ((attempt++) < 10) {
/*
* wait a bit for next attempt -
* I don't know how make it better
*/
msleep(10);
continue;
}
i2cdprintk("send wake up byte to pic16C505 (IR chip)"
"failed %dx\n", attempt);
return -EIO;
}
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_msi_tvanywhere_plus(struct IR_i2c *ir, u32 *ir_key,
u32 *ir_raw)
{
unsigned char b;
int gpio;
/* <dev> is needed to access GPIO. Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_msi_tvanywhere_plus: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
/* GPIO&0x40 is pulsed low when a button is pressed. Don't do
I2C receive if gpio&0x40 is not low. */
if (gpio & 0x40)
return 0; /* No button press */
/* GPIO says there is a button press. Get it. */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* No button press */
if (b == 0xff)
return 0;
/* Button pressed */
dprintk("get_key_msi_tvanywhere_plus: Key = 0x%02X\n", b);
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_purpletv(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* no button press */
if (b==0)
return 0;
/* repeating */
if (b & 0x80)
return 1;
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_hvr1110(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char buf[5], cod4, code3, code4;
/* poll IR chip */
if (5 != i2c_master_recv(ir->c, buf, 5))
return -EIO;
cod4 = buf[4];
code4 = (cod4 >> 2);
code3 = buf[3];
if (code3 == 0)
/* no key pressed */
return 0;
/* return key */
*ir_key = code4;
*ir_raw = code4;
return 1;
}
static int get_key_beholdm6xx(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char data[12];
u32 gpio;
struct saa7134_dev *dev = ir->c->adapter->algo_data;
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x400000 & ~gpio)
return 0; /* No button press */
ir->c->addr = 0x5a >> 1;
if (12 != i2c_master_recv(ir->c, data, 12)) {
i2cdprintk("read error\n");
return -EIO;
}
/* IR of this card normally decode signals NEC-standard from
* - Sven IHOO MT 5.1R remote. xxyye718
* - Sven DVD HD-10xx remote. xxyyf708
* - BBK ...
* - mayby others
* So, skip not our, if disable full codes mode.
*/
if (data[10] != 0x6b && data[11] != 0x86 && disable_other_ir)
return 0;
/* Wrong data decode fix */
if (data[9] != (unsigned char)(~data[8]))
return 0;
*ir_key = data[9];
*ir_raw = data[9];
return 1;
}
/* Common (grey or coloured) pinnacle PCTV remote handling
*
*/
static int get_key_pinnacle(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw,
int parity_offset, int marker, int code_modulo)
{
unsigned char b[4];
unsigned int start = 0,parity = 0,code = 0;
/* poll IR chip */
if (4 != i2c_master_recv(ir->c, b, 4)) {
i2cdprintk("read error\n");
return -EIO;
}
for (start = 0; start < ARRAY_SIZE(b); start++) {
if (b[start] == marker) {
code=b[(start+parity_offset + 1) % 4];
parity=b[(start+parity_offset) % 4];
}
}
/* Empty Request */
if (parity == 0)
return 0;
/* Repeating... */
if (ir->old == parity)
return 0;
ir->old = parity;
/* drop special codes when a key is held down a long time for the grey controller
In this case, the second bit of the code is asserted */
if (marker == 0xfe && (code & 0x40))
return 0;
code %= code_modulo;
*ir_raw = code;
*ir_key = code;
i2cdprintk("Pinnacle PCTV key %02x\n", code);
return 1;
}
static int get_key_pinnacle_grey(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
return get_key_pinnacle(ir, ir_key, ir_raw, 1, 0xfe, 0xff);
}
/* The new pinnacle PCTV remote (with the colored buttons)
*
* Ricardo Cerqueira <v4l@cerqueira.org>
*/
static int get_key_pinnacle_color(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
/* code_modulo parameter (0x88) is used to reduce code value to fit inside IR_KEYTAB_SIZE
*
* this is the only value that results in 42 unique
* codes < 128
*/
return get_key_pinnacle(ir, ir_key, ir_raw, 2, 0x80, 0x88);
}
void saa7134_input_irq(struct saa7134_dev *dev)
{
struct card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (ir->nec_gpio) {
saa7134_nec_irq(dev);
} else if (!ir->polling && !ir->rc5_gpio && !ir->raw_decode) {
build_key(dev);
} else if (ir->rc5_gpio) {
saa7134_rc5_irq(dev);
} else if (ir->raw_decode) {
saa7134_raw_decode_irq(dev);
}
}
static void saa7134_input_timer(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct card_ir *ir = dev->remote;
build_key(dev);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
void ir_raw_decode_timer_end(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct card_ir *ir = dev->remote;
ir_raw_event_handle(dev->remote->dev);
ir->active = 0;
}
static int __saa7134_ir_start(void *priv)
{
struct saa7134_dev *dev = priv;
struct card_ir *ir;
if (!dev)
return -EINVAL;
ir = dev->remote;
if (!ir)
return -EINVAL;
if (ir->running)
return 0;
ir->running = 1;
if (ir->polling) {
setup_timer(&ir->timer, saa7134_input_timer,
(unsigned long)dev);
ir->timer.expires = jiffies + HZ;
add_timer(&ir->timer);
} else if (ir->rc5_gpio) {
/* set timer_end for code completion */
init_timer(&ir->timer_end);
ir->timer_end.function = ir_rc5_timer_end;
ir->timer_end.data = (unsigned long)ir;
init_timer(&ir->timer_keyup);
ir->timer_keyup.function = ir_rc5_timer_keyup;
ir->timer_keyup.data = (unsigned long)ir;
ir->shift_by = 2;
ir->start = 0x2;
ir->addr = 0x17;
ir->rc5_key_timeout = ir_rc5_key_timeout;
ir->rc5_remote_gap = ir_rc5_remote_gap;
} else if (ir->nec_gpio) {
setup_timer(&ir->timer_keyup, saa7134_nec_timer,
(unsigned long)dev);
tasklet_init(&ir->tlet, nec_task, (unsigned long)dev);
} else if (ir->raw_decode) {
/* set timer_end for code completion */
init_timer(&ir->timer_end);
ir->timer_end.function = ir_raw_decode_timer_end;
ir->timer_end.data = (unsigned long)dev;
ir->active = 0;
}
return 0;
}
static void __saa7134_ir_stop(void *priv)
{
struct saa7134_dev *dev = priv;
struct card_ir *ir;
if (!dev)
return;
ir = dev->remote;
if (!ir)
return;
if (!ir->running)
return;
if (dev->remote->polling)
del_timer_sync(&dev->remote->timer);
else if (ir->rc5_gpio)
del_timer_sync(&ir->timer_end);
else if (ir->nec_gpio)
tasklet_kill(&ir->tlet);
else if (ir->raw_decode) {
del_timer_sync(&ir->timer_end);
ir->active = 0;
}
ir->running = 0;
return;
}
int saa7134_ir_start(struct saa7134_dev *dev)
{
if (dev->remote->users)
return __saa7134_ir_start(dev);
return 0;
}
void saa7134_ir_stop(struct saa7134_dev *dev)
{
if (dev->remote->users)
__saa7134_ir_stop(dev);
}
static int saa7134_ir_open(void *priv)
{
struct saa7134_dev *dev = priv;
dev->remote->users++;
return __saa7134_ir_start(dev);
}
static void saa7134_ir_close(void *priv)
{
struct saa7134_dev *dev = priv;
dev->remote->users--;
if (!dev->remote->users)
__saa7134_ir_stop(dev);
}
int saa7134_ir_change_protocol(void *priv, u64 ir_type)
{
struct saa7134_dev *dev = priv;
struct card_ir *ir = dev->remote;
u32 nec_gpio, rc5_gpio;
if (ir_type == IR_TYPE_RC5) {
dprintk("Changing protocol to RC5\n");
nec_gpio = 0;
rc5_gpio = 1;
} else if (ir_type == IR_TYPE_NEC) {
dprintk("Changing protocol to NEC\n");
nec_gpio = 1;
rc5_gpio = 0;
} else {
dprintk("IR protocol type %ud is not supported\n",
(unsigned)ir_type);
return -EINVAL;
}
if (ir->running) {
saa7134_ir_stop(dev);
ir->nec_gpio = nec_gpio;
ir->rc5_gpio = rc5_gpio;
saa7134_ir_start(dev);
} else {
ir->nec_gpio = nec_gpio;
ir->rc5_gpio = rc5_gpio;
}
return 0;
}
int saa7134_input_init1(struct saa7134_dev *dev)
{
struct card_ir *ir;
struct input_dev *input_dev;
char *ir_codes = NULL;
u32 mask_keycode = 0;
u32 mask_keydown = 0;
u32 mask_keyup = 0;
int polling = 0;
int rc5_gpio = 0;
int nec_gpio = 0;
int raw_decode = 0;
int allow_protocol_change = 0;
u64 ir_type = IR_TYPE_OTHER;
int err;
if (dev->has_remote != SAA7134_REMOTE_GPIO)
return -ENODEV;
if (disable_ir)
return -ENODEV;
/* detect & configure */
switch (dev->board) {
case SAA7134_BOARD_FLYVIDEO2000:
case SAA7134_BOARD_FLYVIDEO3000:
case SAA7134_BOARD_FLYTVPLATINUM_FM:
case SAA7134_BOARD_FLYTVPLATINUM_MINI2:
case SAA7134_BOARD_ROVERMEDIA_LINK_PRO_FM:
ir_codes = RC_MAP_FLYVIDEO;
mask_keycode = 0xEC00000;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_CINERGY400:
case SAA7134_BOARD_CINERGY600:
case SAA7134_BOARD_CINERGY600_MK3:
ir_codes = RC_MAP_CINERGY;
mask_keycode = 0x00003f;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_ECS_TVP3XP:
case SAA7134_BOARD_ECS_TVP3XP_4CB5:
ir_codes = RC_MAP_EZTV;
mask_keycode = 0x00017c;
mask_keyup = 0x000002;
polling = 50; // ms
break;
case SAA7134_BOARD_KWORLD_XPERT:
case SAA7134_BOARD_AVACSSMARTTV:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001F;
mask_keyup = 0x000020;
polling = 50; // ms
break;
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x0007C8;
mask_keydown = 0x000010;
polling = 50; // ms
/* Set GPIO pin2 to high to enable the IR controller */
saa_setb(SAA7134_GPIO_GPMODE0, 0x4);
saa_setb(SAA7134_GPIO_GPSTATUS0, 0x4);
break;
case SAA7134_BOARD_AVERMEDIA_M135A:
ir_codes = RC_MAP_AVERMEDIA_M135A;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = 1;
break;
case SAA7134_BOARD_AVERMEDIA_M733A:
ir_codes = RC_MAP_AVERMEDIA_M733A_RM_K6;
mask_keydown = 0x0040000;
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = 1;
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; // ms
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
ir_codes = RC_MAP_AVERMEDIA_A16D;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; /* ms */
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_KWORLD_TERMINATOR:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001f;
mask_keyup = 0x000060;
polling = 50; // ms
break;
case SAA7134_BOARD_MANLI_MTV001:
case SAA7134_BOARD_MANLI_MTV002:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_409FM:
case SAA7134_BOARD_BEHOLD_401:
case SAA7134_BOARD_BEHOLD_403:
case SAA7134_BOARD_BEHOLD_403FM:
case SAA7134_BOARD_BEHOLD_405:
case SAA7134_BOARD_BEHOLD_405FM:
case SAA7134_BOARD_BEHOLD_407:
case SAA7134_BOARD_BEHOLD_407FM:
case SAA7134_BOARD_BEHOLD_409:
case SAA7134_BOARD_BEHOLD_505FM:
case SAA7134_BOARD_BEHOLD_505RDS_MK5:
case SAA7134_BOARD_BEHOLD_505RDS_MK3:
case SAA7134_BOARD_BEHOLD_507_9FM:
case SAA7134_BOARD_BEHOLD_507RDS_MK3:
case SAA7134_BOARD_BEHOLD_507RDS_MK5:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_COLUMBUS_TVFM:
ir_codes = RC_MAP_BEHOLD_COLUMBUS;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_SEDNA_PC_TV_CARDBUS:
ir_codes = RC_MAP_PCTV_SEDNA;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_GOTVIEW_7135:
ir_codes = RC_MAP_GOTVIEW7135;
mask_keycode = 0x0003CC;
mask_keydown = 0x000010;
polling = 5; /* ms */
saa_setb(SAA7134_GPIO_GPMODE1, 0x80);
break;
case SAA7134_BOARD_VIDEOMATE_TV_PVR:
case SAA7134_BOARD_VIDEOMATE_GOLD_PLUS:
case SAA7134_BOARD_VIDEOMATE_TV_GOLD_PLUSII:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x00003F;
mask_keyup = 0x400000;
polling = 50; // ms
break;
case SAA7134_BOARD_PROTEUS_2309:
ir_codes = RC_MAP_PROTEUS_2309;
mask_keycode = 0x00007F;
mask_keyup = 0x000080;
polling = 50; // ms
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_300:
case SAA7134_BOARD_VIDEOMATE_DVBT_200:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x003F00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_FLYDVBS_LR300:
case SAA7134_BOARD_FLYDVBT_LR301:
case SAA7134_BOARD_FLYDVBTDUO:
ir_codes = RC_MAP_FLYDVB;
mask_keycode = 0x0001F00;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_ASUSTeK_P7131_DUAL:
case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA:
case SAA7134_BOARD_ASUSTeK_P7131_ANALOG:
ir_codes = RC_MAP_ASUS_PC39;
mask_keydown = 0x0040000;
rc5_gpio = 1;
break;
case SAA7134_BOARD_ENCORE_ENLTV:
case SAA7134_BOARD_ENCORE_ENLTV_FM:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x00007f;
mask_keyup = 0x040000;
polling = 50; // ms
break;
case SAA7134_BOARD_ENCORE_ENLTV_FM53:
ir_codes = RC_MAP_ENCORE_ENLTV_FM53;
mask_keydown = 0x0040000;
mask_keycode = 0x00007f;
nec_gpio = 1;
break;
case SAA7134_BOARD_10MOONSTVMASTER3:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x5f80000;
mask_keyup = 0x8000000;
polling = 50; //ms
break;
case SAA7134_BOARD_GENIUS_TVGO_A11MCE:
ir_codes = RC_MAP_GENIUS_TVGO_A11MCE;
mask_keycode = 0xff;
mask_keydown = 0xf00000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_REAL_ANGEL_220:
ir_codes = RC_MAP_REAL_AUDIO_220_32_KEYS;
mask_keycode = 0x3f00;
mask_keyup = 0x4000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
ir_codes = RC_MAP_KWORLD_PLUS_TV_ANALOG;
mask_keycode = 0x7f;
polling = 40; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_S350:
ir_codes = RC_MAP_VIDEOMATE_S350;
mask_keycode = 0x003f00;
mask_keydown = 0x040000;
break;
case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S:
ir_codes = RC_MAP_WINFAST;
mask_keycode = 0x5f00;
mask_keyup = 0x020000;
polling = 50; /* ms */
break;
}
if (NULL == ir_codes) {
printk("%s: Oops: IR config error [card=%d]\n",
dev->name, dev->board);
return -ENODEV;
}
ir = kzalloc(sizeof(*ir), GFP_KERNEL);
input_dev = input_allocate_device();
if (!ir || !input_dev) {
err = -ENOMEM;
goto err_out_free;
}
ir->dev = input_dev;
dev->remote = ir;
ir->running = 0;
/* init hardware-specific stuff */
ir->mask_keycode = mask_keycode;
ir->mask_keydown = mask_keydown;
ir->mask_keyup = mask_keyup;
ir->polling = polling;
ir->rc5_gpio = rc5_gpio;
ir->nec_gpio = nec_gpio;
ir->raw_decode = raw_decode;
/* init input device */
snprintf(ir->name, sizeof(ir->name), "saa7134 IR (%s)",
saa7134_boards[dev->board].name);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(dev->pci));
ir->props.priv = dev;
ir->props.open = saa7134_ir_open;
ir->props.close = saa7134_ir_close;
if (raw_decode)
ir->props.driver_type = RC_DRIVER_IR_RAW;
if (!raw_decode && allow_protocol_change) {
ir->props.allowed_protos = IR_TYPE_RC5 | IR_TYPE_NEC;
ir->props.change_protocol = saa7134_ir_change_protocol;
}
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 (dev->pci->subsystem_vendor) {
input_dev->id.vendor = dev->pci->subsystem_vendor;
input_dev->id.product = dev->pci->subsystem_device;
} else {
input_dev->id.vendor = dev->pci->vendor;
input_dev->id.product = dev->pci->device;
}
input_dev->dev.parent = &dev->pci->dev;
err = ir_input_register(ir->dev, ir_codes, &ir->props, MODULE_NAME);
if (err)
goto err_out_free;
/* the remote isn't as bouncy as a keyboard */
ir->dev->rep[REP_DELAY] = repeat_delay;
ir->dev->rep[REP_PERIOD] = repeat_period;
return 0;
err_out_free:
dev->remote = NULL;
kfree(ir);
return err;
}
void saa7134_input_fini(struct saa7134_dev *dev)
{
if (NULL == dev->remote)
return;
saa7134_ir_stop(dev);
ir_input_unregister(dev->remote->dev);
kfree(dev->remote);
dev->remote = NULL;
}
void saa7134_probe_i2c_ir(struct saa7134_dev *dev)
{
struct i2c_board_info info;
struct i2c_msg msg_msi = {
.addr = 0x50,
.flags = I2C_M_RD,
.len = 0,
.buf = NULL,
};
int rc;
if (disable_ir) {
dprintk("IR has been disabled, not probing for i2c remote\n");
return;
}
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&dev->init_data, 0, sizeof(dev->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (dev->board) {
case SAA7134_BOARD_PINNACLE_PCTV_110i:
case SAA7134_BOARD_PINNACLE_PCTV_310i:
dev->init_data.name = "Pinnacle PCTV";
if (pinnacle_remote == 0) {
dev->init_data.get_key = get_key_pinnacle_color;
dev->init_data.ir_codes = RC_MAP_PINNACLE_COLOR;
info.addr = 0x47;
} else {
dev->init_data.get_key = get_key_pinnacle_grey;
dev->init_data.ir_codes = RC_MAP_PINNACLE_GREY;
info.addr = 0x47;
}
break;
case SAA7134_BOARD_UPMOST_PURPLE_TV:
dev->init_data.name = "Purple TV";
dev->init_data.get_key = get_key_purpletv;
dev->init_data.ir_codes = RC_MAP_PURPLETV;
info.addr = 0x7a;
break;
case SAA7134_BOARD_MSI_TVATANYWHERE_PLUS:
dev->init_data.name = "MSI TV@nywhere Plus";
dev->init_data.get_key = get_key_msi_tvanywhere_plus;
dev->init_data.ir_codes = RC_MAP_MSI_TVANYWHERE_PLUS;
info.addr = 0x30;
/* MSI TV@nywhere Plus controller doesn't seem to
respond to probes unless we read something from
an existing device. Weird...
REVISIT: might no longer be needed */
rc = i2c_transfer(&dev->i2c_adap, &msg_msi, 1);
dprintk(KERN_DEBUG "probe 0x%02x @ %s: %s\n",
msg_msi.addr, dev->i2c_adap.name,
(1 == rc) ? "yes" : "no");
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1110:
dev->init_data.name = "HVR 1110";
dev->init_data.get_key = get_key_hvr1110;
dev->init_data.ir_codes = RC_MAP_HAUPPAUGE_NEW;
info.addr = 0x71;
break;
case SAA7134_BOARD_BEHOLD_607FM_MK3:
case SAA7134_BOARD_BEHOLD_607FM_MK5:
case SAA7134_BOARD_BEHOLD_609FM_MK3:
case SAA7134_BOARD_BEHOLD_609FM_MK5:
case SAA7134_BOARD_BEHOLD_607RDS_MK3:
case SAA7134_BOARD_BEHOLD_607RDS_MK5:
case SAA7134_BOARD_BEHOLD_609RDS_MK3:
case SAA7134_BOARD_BEHOLD_609RDS_MK5:
case SAA7134_BOARD_BEHOLD_M6:
case SAA7134_BOARD_BEHOLD_M63:
case SAA7134_BOARD_BEHOLD_M6_EXTRA:
case SAA7134_BOARD_BEHOLD_H6:
case SAA7134_BOARD_BEHOLD_X7:
case SAA7134_BOARD_BEHOLD_H7:
case SAA7134_BOARD_BEHOLD_A7:
dev->init_data.name = "BeholdTV";
dev->init_data.get_key = get_key_beholdm6xx;
dev->init_data.ir_codes = RC_MAP_BEHOLD;
dev->init_data.type = IR_TYPE_NEC;
info.addr = 0x2d;
break;
case SAA7134_BOARD_AVERMEDIA_CARDBUS_501:
case SAA7134_BOARD_AVERMEDIA_CARDBUS_506:
info.addr = 0x40;
break;
case SAA7134_BOARD_FLYDVB_TRIO:
dev->init_data.name = "FlyDVB Trio";
dev->init_data.get_key = get_key_flydvb_trio;
dev->init_data.ir_codes = RC_MAP_FLYDVB;
info.addr = 0x0b;
break;
default:
dprintk("No I2C IR support for board %x\n", dev->board);
return;
}
if (dev->init_data.name)
info.platform_data = &dev->init_data;
i2c_new_device(&dev->i2c_adap, &info);
}
static int saa7134_raw_decode_irq(struct saa7134_dev *dev)
{
struct card_ir *ir = dev->remote;
unsigned long timeout;
int space;
/* Generate initial event */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
space = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2) & ir->mask_keydown;
ir_raw_event_store_edge(dev->remote->dev, space ? IR_SPACE : IR_PULSE);
/*
* Wait 15 ms from the start of the first IR event before processing
* the event. This time is enough for NEC protocol. May need adjustments
* to work with other protocols.
*/
if (!ir->active) {
timeout = jiffies + jiffies_to_msecs(15);
mod_timer(&ir->timer_end, timeout);
ir->active = 1;
}
return 1;
}
static int saa7134_rc5_irq(struct saa7134_dev *dev)
{
struct card_ir *ir = dev->remote;
struct timeval tv;
u32 gap;
unsigned long current_jiffies, timeout;
/* get time of bit */
current_jiffies = jiffies;
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
/* active code => add bit */
if (ir->active) {
/* only if in the code (otherwise spurious IRQ or timer
late) */
if (ir->last_bit < 28) {
ir->last_bit = (gap - ir_rc5_remote_gap / 2) /
ir_rc5_remote_gap;
ir->code |= 1 << ir->last_bit;
}
/* starting new code */
} else {
ir->active = 1;
ir->code = 0;
ir->base_time = tv;
ir->last_bit = 0;
timeout = current_jiffies + (500 + 30 * HZ) / 1000;
mod_timer(&ir->timer_end, timeout);
}
return 1;
}
/* On NEC protocol, One has 2.25 ms, and zero has 1.125 ms
The first pulse (start) has 9 + 4.5 ms
*/
static void saa7134_nec_timer(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *) data;
struct card_ir *ir = dev->remote;
dprintk("Cancel key repeat\n");
ir_input_nokey(ir->dev, &ir->ir);
}
static void nec_task(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *) data;
struct card_ir *ir;
struct timeval tv;
int count, pulse, oldpulse, gap;
u32 ircode = 0, not_code = 0;
int ngap = 0;
if (!data) {
printk(KERN_ERR "saa713x/ir: Can't recover dev struct\n");
/* GPIO will be kept disabled */
return;
}
ir = dev->remote;
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
oldpulse = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2) & ir->mask_keydown;
pulse = oldpulse;
do_gettimeofday(&tv);
ir->base_time = tv;
/* Decode NEC pulsecode. This code can take up to 76.5 ms to run.
Unfortunately, using IRQ to decode pulse didn't work, since it uses
a pulse train of 38KHz. This means one pulse on each 52 us
*/
do {
/* Wait until the end of pulse/space or 5 ms */
for (count = 0; count < 500; count++) {
udelay(10);
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
pulse = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2)
& ir->mask_keydown;
if (pulse != oldpulse)
break;
}
do_gettimeofday(&tv);
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
if (!pulse) {
/* Bit 0 has 560 us, while bit 1 has 1120 us.
Do something only if bit == 1
*/
if (ngap && (gap > 560 + 280)) {
unsigned int shift = ngap - 1;
/* Address first, then command */
if (shift < 8) {
shift += 8;
ircode |= 1 << shift;
} else if (shift < 16) {
not_code |= 1 << shift;
} else if (shift < 24) {
shift -= 16;
ircode |= 1 << shift;
} else {
shift -= 24;
not_code |= 1 << shift;
}
}
ngap++;
}
ir->base_time = tv;
/* TIMEOUT - Long pulse */
if (gap >= 5000)
break;
oldpulse = pulse;
} while (ngap < 32);
if (ngap == 32) {
ir->code = ir_extract_bits(ircode, ir->mask_keycode);
dprintk("scancode = 0x%02x (code = 0x%02x, notcode= 0x%02x)\n",
ir->code, ircode, not_code);
ir_input_keydown(ir->dev, &ir->ir, ir->code);
} else
dprintk("Repeat last key\n");
/* Keep repeating the last key */
mod_timer(&ir->timer_keyup, jiffies + msecs_to_jiffies(150));
saa_setl(SAA7134_IRQ2, SAA7134_IRQ2_INTE_GPIO18_P);
}
static int saa7134_nec_irq(struct saa7134_dev *dev)
{
struct card_ir *ir = dev->remote;
saa_clearl(SAA7134_IRQ2, SAA7134_IRQ2_INTE_GPIO18_P);
tasklet_schedule(&ir->tlet);
return 1;
}
| gpl-2.0 |
hwdro/obs-studio | libobs/util/file-serializer.c | 41 | 4098 | /*
* Copyright (c) 2015 Hugh Bailey <obs.jim@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.
*/
#include "dstr.h"
#include "file-serializer.h"
#include "platform.h"
static size_t file_input_read(void *file, void *data, size_t size)
{
return fread(data, 1, size, file);
}
static int64_t file_input_seek(void *file, int64_t offset,
enum serialize_seek_type seek_type)
{
int origin = SEEK_SET;
switch (seek_type) {
case SERIALIZE_SEEK_START: origin = SEEK_SET; break;
case SERIALIZE_SEEK_CURRENT: origin = SEEK_CUR; break;
case SERIALIZE_SEEK_END: origin = SEEK_END; break;
}
if (os_fseeki64(file, offset, origin) == -1)
return -1;
return os_ftelli64(file);
}
static int64_t file_input_get_pos(void *file)
{
return os_ftelli64(file);
}
bool file_input_serializer_init(struct serializer *s, const char *path)
{
s->data = os_fopen(path, "rb");
if (!s->data)
return false;
s->read = file_input_read;
s->write = NULL;
s->seek = file_input_seek;
s->get_pos = file_input_get_pos;
return true;
}
void file_input_serializer_free(struct serializer *s)
{
if (s->data)
fclose(s->data);
}
/* ------------------------------------------------------------------------- */
struct file_output_data {
FILE *file;
char *temp_name;
char *file_name;
};
static size_t file_output_write(void *sdata, const void *data, size_t size)
{
struct file_output_data *out = sdata;
return fwrite(data, 1, size, out->file);
}
static int64_t file_output_seek(void *sdata, int64_t offset,
enum serialize_seek_type seek_type)
{
struct file_output_data *out = sdata;
int origin = SEEK_SET;
switch (seek_type) {
case SERIALIZE_SEEK_START: origin = SEEK_SET; break;
case SERIALIZE_SEEK_CURRENT: origin = SEEK_CUR; break;
case SERIALIZE_SEEK_END: origin = SEEK_END; break;
}
if (os_fseeki64(out->file, offset, origin) == -1)
return -1;
return os_ftelli64(out->file);
}
static int64_t file_output_get_pos(void *sdata)
{
struct file_output_data *out = sdata;
return os_ftelli64(out->file);
}
bool file_output_serializer_init(struct serializer *s, const char *path)
{
FILE *file = os_fopen(path, "wb");
struct file_output_data *out;
if (!file)
return false;
out = bzalloc(sizeof(*out));
out->file = file;
s->data = out;
s->read = NULL;
s->write = file_output_write;
s->seek = file_output_seek;
s->get_pos = file_output_get_pos;
return true;
}
bool file_output_serializer_init_safe(struct serializer *s,
const char *path, const char *temp_ext)
{
struct dstr temp_name = {0};
struct file_output_data *out;
FILE *file;
if (!temp_ext || !*temp_ext)
return false;
dstr_copy(&temp_name, path);
if (*temp_ext != '.')
dstr_cat_ch(&temp_name, '.');
dstr_cat(&temp_name, temp_ext);
file = os_fopen(temp_name.array, "wb");
if (!file) {
dstr_free(&temp_name);
return false;
}
out = bzalloc(sizeof(*out));
out->file_name = bstrdup(path);
out->temp_name = temp_name.array;
out->file = file;
s->data = out;
s->read = NULL;
s->write = file_output_write;
s->seek = file_output_seek;
s->get_pos = file_output_get_pos;
return true;
}
void file_output_serializer_free(struct serializer *s)
{
struct file_output_data *out = s->data;
if (out) {
fclose(out->file);
if (out->temp_name) {
os_unlink(out->file_name);
os_rename(out->temp_name, out->file_name);
}
bfree(out->file_name);
bfree(out->temp_name);
bfree(out);
}
}
| gpl-2.0 |
alcobar/asuswrt-merlin | release/src-rt-7.14.114.x/src/linux/linux-2.6.36/drivers/net/sunlance.c | 41 | 41644 | /* $Id: sunlance.c,v 1.112 2002/01/15 06:48:55 Exp $
* lance.c: Linux/Sparc/Lance driver
*
* Written 1995, 1996 by Miguel de Icaza
* Sources:
* The Linux depca driver
* The Linux lance driver.
* The Linux skeleton driver.
* The NetBSD Sparc/Lance driver.
* Theo de Raadt (deraadt@openbsd.org)
* NCR92C990 Lan Controller manual
*
* 1.4:
* Added support to run with a ledma on the Sun4m
*
* 1.5:
* Added multiple card detection.
*
* 4/17/96: Burst sizes and tpe selection on sun4m by Eddie C. Dost
* (ecd@skynet.be)
*
* 5/15/96: auto carrier detection on sun4m by Eddie C. Dost
* (ecd@skynet.be)
*
* 5/17/96: lebuffer on scsi/ether cards now work David S. Miller
* (davem@caip.rutgers.edu)
*
* 5/29/96: override option 'tpe-link-test?', if it is 'false', as
* this disables auto carrier detection on sun4m. Eddie C. Dost
* (ecd@skynet.be)
*
* 1.7:
* 6/26/96: Bug fix for multiple ledmas, miguel.
*
* 1.8:
* Stole multicast code from depca.c, fixed lance_tx.
*
* 1.9:
* 8/21/96: Fixed the multicast code (Pedro Roque)
*
* 8/28/96: Send fake packet in lance_open() if auto_select is true,
* so we can detect the carrier loss condition in time.
* Eddie C. Dost (ecd@skynet.be)
*
* 9/15/96: Align rx_buf so that eth_copy_and_sum() won't cause an
* MNA trap during chksum_partial_copy(). (ecd@skynet.be)
*
* 11/17/96: Handle LE_C0_MERR in lance_interrupt(). (ecd@skynet.be)
*
* 12/22/96: Don't loop forever in lance_rx() on incomplete packets.
* This was the sun4c killer. Shit, stupid bug.
* (ecd@skynet.be)
*
* 1.10:
* 1/26/97: Modularize driver. (ecd@skynet.be)
*
* 1.11:
* 12/27/97: Added sun4d support. (jj@sunsite.mff.cuni.cz)
*
* 1.12:
* 11/3/99: Fixed SMP race in lance_start_xmit found by davem.
* Anton Blanchard (anton@progsoc.uts.edu.au)
* 2.00: 11/9/99: Massive overhaul and port to new SBUS driver interfaces.
* David S. Miller (davem@redhat.com)
* 2.01:
* 11/08/01: Use library crc32 functions (Matt_Domsch@dell.com)
*
*/
#undef DEBUG_DRIVER
static char lancestr[] = "LANCE";
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/crc32.h>
#include <linux/errno.h>
#include <linux/socket.h> /* Used for the temporal inet entries and routing */
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/bitops.h>
#include <linux/dma-mapping.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/gfp.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/pgtable.h>
#include <asm/byteorder.h> /* Used by the checksum routines */
#include <asm/idprom.h>
#include <asm/prom.h>
#include <asm/auxio.h> /* For tpe-link-test? setting */
#include <asm/irq.h>
#define DRV_NAME "sunlance"
#define DRV_VERSION "2.02"
#define DRV_RELDATE "8/24/03"
#define DRV_AUTHOR "Miguel de Icaza (miguel@nuclecu.unam.mx)"
static char version[] =
DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " " DRV_AUTHOR "\n";
MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR(DRV_AUTHOR);
MODULE_DESCRIPTION("Sun Lance ethernet driver");
MODULE_LICENSE("GPL");
/* Define: 2^4 Tx buffers and 2^4 Rx buffers */
#ifndef LANCE_LOG_TX_BUFFERS
#define LANCE_LOG_TX_BUFFERS 4
#define LANCE_LOG_RX_BUFFERS 4
#endif
#define LE_CSR0 0
#define LE_CSR1 1
#define LE_CSR2 2
#define LE_CSR3 3
#define LE_MO_PROM 0x8000 /* Enable promiscuous mode */
#define LE_C0_ERR 0x8000 /* Error: set if BAB, SQE, MISS or ME is set */
#define LE_C0_BABL 0x4000 /* BAB: Babble: tx timeout. */
#define LE_C0_CERR 0x2000 /* SQE: Signal quality error */
#define LE_C0_MISS 0x1000 /* MISS: Missed a packet */
#define LE_C0_MERR 0x0800 /* ME: Memory error */
#define LE_C0_RINT 0x0400 /* Received interrupt */
#define LE_C0_TINT 0x0200 /* Transmitter Interrupt */
#define LE_C0_IDON 0x0100 /* IFIN: Init finished. */
#define LE_C0_INTR 0x0080 /* Interrupt or error */
#define LE_C0_INEA 0x0040 /* Interrupt enable */
#define LE_C0_RXON 0x0020 /* Receiver on */
#define LE_C0_TXON 0x0010 /* Transmitter on */
#define LE_C0_TDMD 0x0008 /* Transmitter demand */
#define LE_C0_STOP 0x0004 /* Stop the card */
#define LE_C0_STRT 0x0002 /* Start the card */
#define LE_C0_INIT 0x0001 /* Init the card */
#define LE_C3_BSWP 0x4 /* SWAP */
#define LE_C3_ACON 0x2 /* ALE Control */
#define LE_C3_BCON 0x1 /* Byte control */
/* Receive message descriptor 1 */
#define LE_R1_OWN 0x80 /* Who owns the entry */
#define LE_R1_ERR 0x40 /* Error: if FRA, OFL, CRC or BUF is set */
#define LE_R1_FRA 0x20 /* FRA: Frame error */
#define LE_R1_OFL 0x10 /* OFL: Frame overflow */
#define LE_R1_CRC 0x08 /* CRC error */
#define LE_R1_BUF 0x04 /* BUF: Buffer error */
#define LE_R1_SOP 0x02 /* Start of packet */
#define LE_R1_EOP 0x01 /* End of packet */
#define LE_R1_POK 0x03 /* Packet is complete: SOP + EOP */
#define LE_T1_OWN 0x80 /* Lance owns the packet */
#define LE_T1_ERR 0x40 /* Error summary */
#define LE_T1_EMORE 0x10 /* Error: more than one retry needed */
#define LE_T1_EONE 0x08 /* Error: one retry needed */
#define LE_T1_EDEF 0x04 /* Error: deferred */
#define LE_T1_SOP 0x02 /* Start of packet */
#define LE_T1_EOP 0x01 /* End of packet */
#define LE_T1_POK 0x03 /* Packet is complete: SOP + EOP */
#define LE_T3_BUF 0x8000 /* Buffer error */
#define LE_T3_UFL 0x4000 /* Error underflow */
#define LE_T3_LCOL 0x1000 /* Error late collision */
#define LE_T3_CLOS 0x0800 /* Error carrier loss */
#define LE_T3_RTY 0x0400 /* Error retry */
#define LE_T3_TDR 0x03ff /* Time Domain Reflectometry counter */
#define TX_RING_SIZE (1 << (LANCE_LOG_TX_BUFFERS))
#define TX_RING_MOD_MASK (TX_RING_SIZE - 1)
#define TX_RING_LEN_BITS ((LANCE_LOG_TX_BUFFERS) << 29)
#define TX_NEXT(__x) (((__x)+1) & TX_RING_MOD_MASK)
#define RX_RING_SIZE (1 << (LANCE_LOG_RX_BUFFERS))
#define RX_RING_MOD_MASK (RX_RING_SIZE - 1)
#define RX_RING_LEN_BITS ((LANCE_LOG_RX_BUFFERS) << 29)
#define RX_NEXT(__x) (((__x)+1) & RX_RING_MOD_MASK)
#define PKT_BUF_SZ 1544
#define RX_BUFF_SIZE PKT_BUF_SZ
#define TX_BUFF_SIZE PKT_BUF_SZ
struct lance_rx_desc {
u16 rmd0; /* low address of packet */
u8 rmd1_bits; /* descriptor bits */
u8 rmd1_hadr; /* high address of packet */
s16 length; /* This length is 2s complement (negative)!
* Buffer length
*/
u16 mblength; /* This is the actual number of bytes received */
};
struct lance_tx_desc {
u16 tmd0; /* low address of packet */
u8 tmd1_bits; /* descriptor bits */
u8 tmd1_hadr; /* high address of packet */
s16 length; /* Length is 2s complement (negative)! */
u16 misc;
};
/* The LANCE initialization block, described in databook. */
/* On the Sparc, this block should be on a DMA region */
struct lance_init_block {
u16 mode; /* Pre-set mode (reg. 15) */
u8 phys_addr[6]; /* Physical ethernet address */
u32 filter[2]; /* Multicast filter. */
/* Receive and transmit ring base, along with extra bits. */
u16 rx_ptr; /* receive descriptor addr */
u16 rx_len; /* receive len and high addr */
u16 tx_ptr; /* transmit descriptor addr */
u16 tx_len; /* transmit len and high addr */
/* The Tx and Rx ring entries must aligned on 8-byte boundaries. */
struct lance_rx_desc brx_ring[RX_RING_SIZE];
struct lance_tx_desc btx_ring[TX_RING_SIZE];
u8 tx_buf [TX_RING_SIZE][TX_BUFF_SIZE];
u8 pad[2]; /* align rx_buf for copy_and_sum(). */
u8 rx_buf [RX_RING_SIZE][RX_BUFF_SIZE];
};
#define libdesc_offset(rt, elem) \
((__u32)(((unsigned long)(&(((struct lance_init_block *)0)->rt[elem])))))
#define libbuff_offset(rt, elem) \
((__u32)(((unsigned long)(&(((struct lance_init_block *)0)->rt[elem][0])))))
struct lance_private {
void __iomem *lregs; /* Lance RAP/RDP regs. */
void __iomem *dregs; /* DMA controller regs. */
struct lance_init_block __iomem *init_block_iomem;
struct lance_init_block *init_block_mem;
spinlock_t lock;
int rx_new, tx_new;
int rx_old, tx_old;
struct platform_device *ledma; /* If set this points to ledma */
char tpe; /* cable-selection is TPE */
char auto_select; /* cable-selection by carrier */
char burst_sizes; /* ledma SBus burst sizes */
char pio_buffer; /* init block in PIO space? */
unsigned short busmaster_regval;
void (*init_ring)(struct net_device *);
void (*rx)(struct net_device *);
void (*tx)(struct net_device *);
char *name;
dma_addr_t init_block_dvma;
struct net_device *dev; /* Backpointer */
struct platform_device *op;
struct platform_device *lebuffer;
struct timer_list multicast_timer;
};
#define TX_BUFFS_AVAIL ((lp->tx_old<=lp->tx_new)?\
lp->tx_old+TX_RING_MOD_MASK-lp->tx_new:\
lp->tx_old - lp->tx_new-1)
/* Lance registers. */
#define RDP 0x00UL /* register data port */
#define RAP 0x02UL /* register address port */
#define LANCE_REG_SIZE 0x04UL
#define STOP_LANCE(__lp) \
do { void __iomem *__base = (__lp)->lregs; \
sbus_writew(LE_CSR0, __base + RAP); \
sbus_writew(LE_C0_STOP, __base + RDP); \
} while (0)
int sparc_lance_debug = 2;
/* The Lance uses 24 bit addresses */
/* On the Sun4c the DVMA will provide the remaining bytes for us */
/* On the Sun4m we have to instruct the ledma to provide them */
/* Even worse, on scsi/ether SBUS cards, the init block and the
* transmit/receive buffers are addresses as offsets from absolute
* zero on the lebuffer PIO area. -DaveM
*/
#define LANCE_ADDR(x) ((long)(x) & ~0xff000000)
/* Load the CSR registers */
static void load_csrs(struct lance_private *lp)
{
u32 leptr;
if (lp->pio_buffer)
leptr = 0;
else
leptr = LANCE_ADDR(lp->init_block_dvma);
sbus_writew(LE_CSR1, lp->lregs + RAP);
sbus_writew(leptr & 0xffff, lp->lregs + RDP);
sbus_writew(LE_CSR2, lp->lregs + RAP);
sbus_writew(leptr >> 16, lp->lregs + RDP);
sbus_writew(LE_CSR3, lp->lregs + RAP);
sbus_writew(lp->busmaster_regval, lp->lregs + RDP);
/* Point back to csr0 */
sbus_writew(LE_CSR0, lp->lregs + RAP);
}
/* Setup the Lance Rx and Tx rings */
static void lance_init_ring_dvma(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block *ib = lp->init_block_mem;
dma_addr_t aib = lp->init_block_dvma;
__u32 leptr;
int i;
/* Lock out other processes while setting up hardware */
netif_stop_queue(dev);
lp->rx_new = lp->tx_new = 0;
lp->rx_old = lp->tx_old = 0;
/* Copy the ethernet address to the lance init block
* Note that on the sparc you need to swap the ethernet address.
*/
ib->phys_addr [0] = dev->dev_addr [1];
ib->phys_addr [1] = dev->dev_addr [0];
ib->phys_addr [2] = dev->dev_addr [3];
ib->phys_addr [3] = dev->dev_addr [2];
ib->phys_addr [4] = dev->dev_addr [5];
ib->phys_addr [5] = dev->dev_addr [4];
/* Setup the Tx ring entries */
for (i = 0; i < TX_RING_SIZE; i++) {
leptr = LANCE_ADDR(aib + libbuff_offset(tx_buf, i));
ib->btx_ring [i].tmd0 = leptr;
ib->btx_ring [i].tmd1_hadr = leptr >> 16;
ib->btx_ring [i].tmd1_bits = 0;
ib->btx_ring [i].length = 0xf000; /* The ones required by tmd2 */
ib->btx_ring [i].misc = 0;
}
/* Setup the Rx ring entries */
for (i = 0; i < RX_RING_SIZE; i++) {
leptr = LANCE_ADDR(aib + libbuff_offset(rx_buf, i));
ib->brx_ring [i].rmd0 = leptr;
ib->brx_ring [i].rmd1_hadr = leptr >> 16;
ib->brx_ring [i].rmd1_bits = LE_R1_OWN;
ib->brx_ring [i].length = -RX_BUFF_SIZE | 0xf000;
ib->brx_ring [i].mblength = 0;
}
/* Setup the initialization block */
/* Setup rx descriptor pointer */
leptr = LANCE_ADDR(aib + libdesc_offset(brx_ring, 0));
ib->rx_len = (LANCE_LOG_RX_BUFFERS << 13) | (leptr >> 16);
ib->rx_ptr = leptr;
/* Setup tx descriptor pointer */
leptr = LANCE_ADDR(aib + libdesc_offset(btx_ring, 0));
ib->tx_len = (LANCE_LOG_TX_BUFFERS << 13) | (leptr >> 16);
ib->tx_ptr = leptr;
}
static void lance_init_ring_pio(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block __iomem *ib = lp->init_block_iomem;
u32 leptr;
int i;
/* Lock out other processes while setting up hardware */
netif_stop_queue(dev);
lp->rx_new = lp->tx_new = 0;
lp->rx_old = lp->tx_old = 0;
/* Copy the ethernet address to the lance init block
* Note that on the sparc you need to swap the ethernet address.
*/
sbus_writeb(dev->dev_addr[1], &ib->phys_addr[0]);
sbus_writeb(dev->dev_addr[0], &ib->phys_addr[1]);
sbus_writeb(dev->dev_addr[3], &ib->phys_addr[2]);
sbus_writeb(dev->dev_addr[2], &ib->phys_addr[3]);
sbus_writeb(dev->dev_addr[5], &ib->phys_addr[4]);
sbus_writeb(dev->dev_addr[4], &ib->phys_addr[5]);
/* Setup the Tx ring entries */
for (i = 0; i < TX_RING_SIZE; i++) {
leptr = libbuff_offset(tx_buf, i);
sbus_writew(leptr, &ib->btx_ring [i].tmd0);
sbus_writeb(leptr >> 16,&ib->btx_ring [i].tmd1_hadr);
sbus_writeb(0, &ib->btx_ring [i].tmd1_bits);
/* The ones required by tmd2 */
sbus_writew(0xf000, &ib->btx_ring [i].length);
sbus_writew(0, &ib->btx_ring [i].misc);
}
/* Setup the Rx ring entries */
for (i = 0; i < RX_RING_SIZE; i++) {
leptr = libbuff_offset(rx_buf, i);
sbus_writew(leptr, &ib->brx_ring [i].rmd0);
sbus_writeb(leptr >> 16,&ib->brx_ring [i].rmd1_hadr);
sbus_writeb(LE_R1_OWN, &ib->brx_ring [i].rmd1_bits);
sbus_writew(-RX_BUFF_SIZE|0xf000,
&ib->brx_ring [i].length);
sbus_writew(0, &ib->brx_ring [i].mblength);
}
/* Setup the initialization block */
/* Setup rx descriptor pointer */
leptr = libdesc_offset(brx_ring, 0);
sbus_writew((LANCE_LOG_RX_BUFFERS << 13) | (leptr >> 16),
&ib->rx_len);
sbus_writew(leptr, &ib->rx_ptr);
/* Setup tx descriptor pointer */
leptr = libdesc_offset(btx_ring, 0);
sbus_writew((LANCE_LOG_TX_BUFFERS << 13) | (leptr >> 16),
&ib->tx_len);
sbus_writew(leptr, &ib->tx_ptr);
}
static void init_restart_ledma(struct lance_private *lp)
{
u32 csr = sbus_readl(lp->dregs + DMA_CSR);
if (!(csr & DMA_HNDL_ERROR)) {
/* E-Cache draining */
while (sbus_readl(lp->dregs + DMA_CSR) & DMA_FIFO_ISDRAIN)
barrier();
}
csr = sbus_readl(lp->dregs + DMA_CSR);
csr &= ~DMA_E_BURSTS;
if (lp->burst_sizes & DMA_BURST32)
csr |= DMA_E_BURST32;
else
csr |= DMA_E_BURST16;
csr |= (DMA_DSBL_RD_DRN | DMA_DSBL_WR_INV | DMA_FIFO_INV);
if (lp->tpe)
csr |= DMA_EN_ENETAUI;
else
csr &= ~DMA_EN_ENETAUI;
udelay(20);
sbus_writel(csr, lp->dregs + DMA_CSR);
udelay(200);
}
static int init_restart_lance(struct lance_private *lp)
{
u16 regval = 0;
int i;
if (lp->dregs)
init_restart_ledma(lp);
sbus_writew(LE_CSR0, lp->lregs + RAP);
sbus_writew(LE_C0_INIT, lp->lregs + RDP);
/* Wait for the lance to complete initialization */
for (i = 0; i < 100; i++) {
regval = sbus_readw(lp->lregs + RDP);
if (regval & (LE_C0_ERR | LE_C0_IDON))
break;
barrier();
}
if (i == 100 || (regval & LE_C0_ERR)) {
printk(KERN_ERR "LANCE unopened after %d ticks, csr0=%4.4x.\n",
i, regval);
if (lp->dregs)
printk("dcsr=%8.8x\n", sbus_readl(lp->dregs + DMA_CSR));
return -1;
}
/* Clear IDON by writing a "1", enable interrupts and start lance */
sbus_writew(LE_C0_IDON, lp->lregs + RDP);
sbus_writew(LE_C0_INEA | LE_C0_STRT, lp->lregs + RDP);
if (lp->dregs) {
u32 csr = sbus_readl(lp->dregs + DMA_CSR);
csr |= DMA_INT_ENAB;
sbus_writel(csr, lp->dregs + DMA_CSR);
}
return 0;
}
static void lance_rx_dvma(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block *ib = lp->init_block_mem;
struct lance_rx_desc *rd;
u8 bits;
int len, entry = lp->rx_new;
struct sk_buff *skb;
for (rd = &ib->brx_ring [entry];
!((bits = rd->rmd1_bits) & LE_R1_OWN);
rd = &ib->brx_ring [entry]) {
/* We got an incomplete frame? */
if ((bits & LE_R1_POK) != LE_R1_POK) {
dev->stats.rx_over_errors++;
dev->stats.rx_errors++;
} else if (bits & LE_R1_ERR) {
/* Count only the end frame as a rx error,
* not the beginning
*/
if (bits & LE_R1_BUF) dev->stats.rx_fifo_errors++;
if (bits & LE_R1_CRC) dev->stats.rx_crc_errors++;
if (bits & LE_R1_OFL) dev->stats.rx_over_errors++;
if (bits & LE_R1_FRA) dev->stats.rx_frame_errors++;
if (bits & LE_R1_EOP) dev->stats.rx_errors++;
} else {
len = (rd->mblength & 0xfff) - 4;
skb = dev_alloc_skb(len + 2);
if (skb == NULL) {
printk(KERN_INFO "%s: Memory squeeze, deferring packet.\n",
dev->name);
dev->stats.rx_dropped++;
rd->mblength = 0;
rd->rmd1_bits = LE_R1_OWN;
lp->rx_new = RX_NEXT(entry);
return;
}
dev->stats.rx_bytes += len;
skb_reserve(skb, 2); /* 16 byte align */
skb_put(skb, len); /* make room */
skb_copy_to_linear_data(skb,
(unsigned char *)&(ib->rx_buf [entry][0]),
len);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->stats.rx_packets++;
}
/* Return the packet to the pool */
rd->mblength = 0;
rd->rmd1_bits = LE_R1_OWN;
entry = RX_NEXT(entry);
}
lp->rx_new = entry;
}
static void lance_tx_dvma(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block *ib = lp->init_block_mem;
int i, j;
spin_lock(&lp->lock);
j = lp->tx_old;
for (i = j; i != lp->tx_new; i = j) {
struct lance_tx_desc *td = &ib->btx_ring [i];
u8 bits = td->tmd1_bits;
/* If we hit a packet not owned by us, stop */
if (bits & LE_T1_OWN)
break;
if (bits & LE_T1_ERR) {
u16 status = td->misc;
dev->stats.tx_errors++;
if (status & LE_T3_RTY) dev->stats.tx_aborted_errors++;
if (status & LE_T3_LCOL) dev->stats.tx_window_errors++;
if (status & LE_T3_CLOS) {
dev->stats.tx_carrier_errors++;
if (lp->auto_select) {
lp->tpe = 1 - lp->tpe;
printk(KERN_NOTICE "%s: Carrier Lost, trying %s\n",
dev->name, lp->tpe?"TPE":"AUI");
STOP_LANCE(lp);
lp->init_ring(dev);
load_csrs(lp);
init_restart_lance(lp);
goto out;
}
}
/* Buffer errors and underflows turn off the
* transmitter, restart the adapter.
*/
if (status & (LE_T3_BUF|LE_T3_UFL)) {
dev->stats.tx_fifo_errors++;
printk(KERN_ERR "%s: Tx: ERR_BUF|ERR_UFL, restarting\n",
dev->name);
STOP_LANCE(lp);
lp->init_ring(dev);
load_csrs(lp);
init_restart_lance(lp);
goto out;
}
} else if ((bits & LE_T1_POK) == LE_T1_POK) {
/*
* So we don't count the packet more than once.
*/
td->tmd1_bits = bits & ~(LE_T1_POK);
/* One collision before packet was sent. */
if (bits & LE_T1_EONE)
dev->stats.collisions++;
/* More than one collision, be optimistic. */
if (bits & LE_T1_EMORE)
dev->stats.collisions += 2;
dev->stats.tx_packets++;
}
j = TX_NEXT(j);
}
lp->tx_old = j;
out:
if (netif_queue_stopped(dev) &&
TX_BUFFS_AVAIL > 0)
netif_wake_queue(dev);
spin_unlock(&lp->lock);
}
static void lance_piocopy_to_skb(struct sk_buff *skb, void __iomem *piobuf, int len)
{
u16 *p16 = (u16 *) skb->data;
u32 *p32;
u8 *p8;
void __iomem *pbuf = piobuf;
/* We know here that both src and dest are on a 16bit boundary. */
*p16++ = sbus_readw(pbuf);
p32 = (u32 *) p16;
pbuf += 2;
len -= 2;
while (len >= 4) {
*p32++ = sbus_readl(pbuf);
pbuf += 4;
len -= 4;
}
p8 = (u8 *) p32;
if (len >= 2) {
p16 = (u16 *) p32;
*p16++ = sbus_readw(pbuf);
pbuf += 2;
len -= 2;
p8 = (u8 *) p16;
}
if (len >= 1)
*p8 = sbus_readb(pbuf);
}
static void lance_rx_pio(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block __iomem *ib = lp->init_block_iomem;
struct lance_rx_desc __iomem *rd;
unsigned char bits;
int len, entry;
struct sk_buff *skb;
entry = lp->rx_new;
for (rd = &ib->brx_ring [entry];
!((bits = sbus_readb(&rd->rmd1_bits)) & LE_R1_OWN);
rd = &ib->brx_ring [entry]) {
/* We got an incomplete frame? */
if ((bits & LE_R1_POK) != LE_R1_POK) {
dev->stats.rx_over_errors++;
dev->stats.rx_errors++;
} else if (bits & LE_R1_ERR) {
/* Count only the end frame as a rx error,
* not the beginning
*/
if (bits & LE_R1_BUF) dev->stats.rx_fifo_errors++;
if (bits & LE_R1_CRC) dev->stats.rx_crc_errors++;
if (bits & LE_R1_OFL) dev->stats.rx_over_errors++;
if (bits & LE_R1_FRA) dev->stats.rx_frame_errors++;
if (bits & LE_R1_EOP) dev->stats.rx_errors++;
} else {
len = (sbus_readw(&rd->mblength) & 0xfff) - 4;
skb = dev_alloc_skb(len + 2);
if (skb == NULL) {
printk(KERN_INFO "%s: Memory squeeze, deferring packet.\n",
dev->name);
dev->stats.rx_dropped++;
sbus_writew(0, &rd->mblength);
sbus_writeb(LE_R1_OWN, &rd->rmd1_bits);
lp->rx_new = RX_NEXT(entry);
return;
}
dev->stats.rx_bytes += len;
skb_reserve (skb, 2); /* 16 byte align */
skb_put(skb, len); /* make room */
lance_piocopy_to_skb(skb, &(ib->rx_buf[entry][0]), len);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->stats.rx_packets++;
}
/* Return the packet to the pool */
sbus_writew(0, &rd->mblength);
sbus_writeb(LE_R1_OWN, &rd->rmd1_bits);
entry = RX_NEXT(entry);
}
lp->rx_new = entry;
}
static void lance_tx_pio(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block __iomem *ib = lp->init_block_iomem;
int i, j;
spin_lock(&lp->lock);
j = lp->tx_old;
for (i = j; i != lp->tx_new; i = j) {
struct lance_tx_desc __iomem *td = &ib->btx_ring [i];
u8 bits = sbus_readb(&td->tmd1_bits);
/* If we hit a packet not owned by us, stop */
if (bits & LE_T1_OWN)
break;
if (bits & LE_T1_ERR) {
u16 status = sbus_readw(&td->misc);
dev->stats.tx_errors++;
if (status & LE_T3_RTY) dev->stats.tx_aborted_errors++;
if (status & LE_T3_LCOL) dev->stats.tx_window_errors++;
if (status & LE_T3_CLOS) {
dev->stats.tx_carrier_errors++;
if (lp->auto_select) {
lp->tpe = 1 - lp->tpe;
printk(KERN_NOTICE "%s: Carrier Lost, trying %s\n",
dev->name, lp->tpe?"TPE":"AUI");
STOP_LANCE(lp);
lp->init_ring(dev);
load_csrs(lp);
init_restart_lance(lp);
goto out;
}
}
/* Buffer errors and underflows turn off the
* transmitter, restart the adapter.
*/
if (status & (LE_T3_BUF|LE_T3_UFL)) {
dev->stats.tx_fifo_errors++;
printk(KERN_ERR "%s: Tx: ERR_BUF|ERR_UFL, restarting\n",
dev->name);
STOP_LANCE(lp);
lp->init_ring(dev);
load_csrs(lp);
init_restart_lance(lp);
goto out;
}
} else if ((bits & LE_T1_POK) == LE_T1_POK) {
/*
* So we don't count the packet more than once.
*/
sbus_writeb(bits & ~(LE_T1_POK), &td->tmd1_bits);
/* One collision before packet was sent. */
if (bits & LE_T1_EONE)
dev->stats.collisions++;
/* More than one collision, be optimistic. */
if (bits & LE_T1_EMORE)
dev->stats.collisions += 2;
dev->stats.tx_packets++;
}
j = TX_NEXT(j);
}
lp->tx_old = j;
if (netif_queue_stopped(dev) &&
TX_BUFFS_AVAIL > 0)
netif_wake_queue(dev);
out:
spin_unlock(&lp->lock);
}
static irqreturn_t lance_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct lance_private *lp = netdev_priv(dev);
int csr0;
sbus_writew(LE_CSR0, lp->lregs + RAP);
csr0 = sbus_readw(lp->lregs + RDP);
/* Acknowledge all the interrupt sources ASAP */
sbus_writew(csr0 & (LE_C0_INTR | LE_C0_TINT | LE_C0_RINT),
lp->lregs + RDP);
if ((csr0 & LE_C0_ERR) != 0) {
/* Clear the error condition */
sbus_writew((LE_C0_BABL | LE_C0_ERR | LE_C0_MISS |
LE_C0_CERR | LE_C0_MERR),
lp->lregs + RDP);
}
if (csr0 & LE_C0_RINT)
lp->rx(dev);
if (csr0 & LE_C0_TINT)
lp->tx(dev);
if (csr0 & LE_C0_BABL)
dev->stats.tx_errors++;
if (csr0 & LE_C0_MISS)
dev->stats.rx_errors++;
if (csr0 & LE_C0_MERR) {
if (lp->dregs) {
u32 addr = sbus_readl(lp->dregs + DMA_ADDR);
printk(KERN_ERR "%s: Memory error, status %04x, addr %06x\n",
dev->name, csr0, addr & 0xffffff);
} else {
printk(KERN_ERR "%s: Memory error, status %04x\n",
dev->name, csr0);
}
sbus_writew(LE_C0_STOP, lp->lregs + RDP);
if (lp->dregs) {
u32 dma_csr = sbus_readl(lp->dregs + DMA_CSR);
dma_csr |= DMA_FIFO_INV;
sbus_writel(dma_csr, lp->dregs + DMA_CSR);
}
lp->init_ring(dev);
load_csrs(lp);
init_restart_lance(lp);
netif_wake_queue(dev);
}
sbus_writew(LE_C0_INEA, lp->lregs + RDP);
return IRQ_HANDLED;
}
/* Build a fake network packet and send it to ourselves. */
static void build_fake_packet(struct lance_private *lp)
{
struct net_device *dev = lp->dev;
int i, entry;
entry = lp->tx_new & TX_RING_MOD_MASK;
if (lp->pio_buffer) {
struct lance_init_block __iomem *ib = lp->init_block_iomem;
u16 __iomem *packet = (u16 __iomem *) &(ib->tx_buf[entry][0]);
struct ethhdr __iomem *eth = (struct ethhdr __iomem *) packet;
for (i = 0; i < (ETH_ZLEN / sizeof(u16)); i++)
sbus_writew(0, &packet[i]);
for (i = 0; i < 6; i++) {
sbus_writeb(dev->dev_addr[i], ð->h_dest[i]);
sbus_writeb(dev->dev_addr[i], ð->h_source[i]);
}
sbus_writew((-ETH_ZLEN) | 0xf000, &ib->btx_ring[entry].length);
sbus_writew(0, &ib->btx_ring[entry].misc);
sbus_writeb(LE_T1_POK|LE_T1_OWN, &ib->btx_ring[entry].tmd1_bits);
} else {
struct lance_init_block *ib = lp->init_block_mem;
u16 *packet = (u16 *) &(ib->tx_buf[entry][0]);
struct ethhdr *eth = (struct ethhdr *) packet;
memset(packet, 0, ETH_ZLEN);
for (i = 0; i < 6; i++) {
eth->h_dest[i] = dev->dev_addr[i];
eth->h_source[i] = dev->dev_addr[i];
}
ib->btx_ring[entry].length = (-ETH_ZLEN) | 0xf000;
ib->btx_ring[entry].misc = 0;
ib->btx_ring[entry].tmd1_bits = (LE_T1_POK|LE_T1_OWN);
}
lp->tx_new = TX_NEXT(entry);
}
static int lance_open(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
int status = 0;
STOP_LANCE(lp);
if (request_irq(dev->irq, lance_interrupt, IRQF_SHARED,
lancestr, (void *) dev)) {
printk(KERN_ERR "Lance: Can't get irq %d\n", dev->irq);
return -EAGAIN;
}
/* On the 4m, setup the ledma to provide the upper bits for buffers */
if (lp->dregs) {
u32 regval = lp->init_block_dvma & 0xff000000;
sbus_writel(regval, lp->dregs + DMA_TEST);
}
/* Set mode and clear multicast filter only at device open,
* so that lance_init_ring() called at any error will not
* forget multicast filters.
*
* BTW it is common bug in all lance drivers! --ANK
*/
if (lp->pio_buffer) {
struct lance_init_block __iomem *ib = lp->init_block_iomem;
sbus_writew(0, &ib->mode);
sbus_writel(0, &ib->filter[0]);
sbus_writel(0, &ib->filter[1]);
} else {
struct lance_init_block *ib = lp->init_block_mem;
ib->mode = 0;
ib->filter [0] = 0;
ib->filter [1] = 0;
}
lp->init_ring(dev);
load_csrs(lp);
netif_start_queue(dev);
status = init_restart_lance(lp);
if (!status && lp->auto_select) {
build_fake_packet(lp);
sbus_writew(LE_C0_INEA | LE_C0_TDMD, lp->lregs + RDP);
}
return status;
}
static int lance_close(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
netif_stop_queue(dev);
del_timer_sync(&lp->multicast_timer);
STOP_LANCE(lp);
free_irq(dev->irq, (void *) dev);
return 0;
}
static int lance_reset(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
int status;
STOP_LANCE(lp);
/* On the 4m, reset the dma too */
if (lp->dregs) {
u32 csr, addr;
printk(KERN_ERR "resetting ledma\n");
csr = sbus_readl(lp->dregs + DMA_CSR);
sbus_writel(csr | DMA_RST_ENET, lp->dregs + DMA_CSR);
udelay(200);
sbus_writel(csr & ~DMA_RST_ENET, lp->dregs + DMA_CSR);
addr = lp->init_block_dvma & 0xff000000;
sbus_writel(addr, lp->dregs + DMA_TEST);
}
lp->init_ring(dev);
load_csrs(lp);
dev->trans_start = jiffies; /* prevent tx timeout */
status = init_restart_lance(lp);
return status;
}
static void lance_piocopy_from_skb(void __iomem *dest, unsigned char *src, int len)
{
void __iomem *piobuf = dest;
u32 *p32;
u16 *p16;
u8 *p8;
switch ((unsigned long)src & 0x3) {
case 0:
p32 = (u32 *) src;
while (len >= 4) {
sbus_writel(*p32, piobuf);
p32++;
piobuf += 4;
len -= 4;
}
src = (char *) p32;
break;
case 1:
case 3:
p8 = (u8 *) src;
while (len >= 4) {
u32 val;
val = p8[0] << 24;
val |= p8[1] << 16;
val |= p8[2] << 8;
val |= p8[3];
sbus_writel(val, piobuf);
p8 += 4;
piobuf += 4;
len -= 4;
}
src = (char *) p8;
break;
case 2:
p16 = (u16 *) src;
while (len >= 4) {
u32 val = p16[0]<<16 | p16[1];
sbus_writel(val, piobuf);
p16 += 2;
piobuf += 4;
len -= 4;
}
src = (char *) p16;
break;
}
if (len >= 2) {
u16 val = src[0] << 8 | src[1];
sbus_writew(val, piobuf);
src += 2;
piobuf += 2;
len -= 2;
}
if (len >= 1)
sbus_writeb(src[0], piobuf);
}
static void lance_piozero(void __iomem *dest, int len)
{
void __iomem *piobuf = dest;
if ((unsigned long)piobuf & 1) {
sbus_writeb(0, piobuf);
piobuf += 1;
len -= 1;
if (len == 0)
return;
}
if (len == 1) {
sbus_writeb(0, piobuf);
return;
}
if ((unsigned long)piobuf & 2) {
sbus_writew(0, piobuf);
piobuf += 2;
len -= 2;
if (len == 0)
return;
}
while (len >= 4) {
sbus_writel(0, piobuf);
piobuf += 4;
len -= 4;
}
if (len >= 2) {
sbus_writew(0, piobuf);
piobuf += 2;
len -= 2;
}
if (len >= 1)
sbus_writeb(0, piobuf);
}
static void lance_tx_timeout(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
printk(KERN_ERR "%s: transmit timed out, status %04x, reset\n",
dev->name, sbus_readw(lp->lregs + RDP));
lance_reset(dev);
netif_wake_queue(dev);
}
static int lance_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
int entry, skblen, len;
skblen = skb->len;
len = (skblen <= ETH_ZLEN) ? ETH_ZLEN : skblen;
spin_lock_irq(&lp->lock);
dev->stats.tx_bytes += len;
entry = lp->tx_new & TX_RING_MOD_MASK;
if (lp->pio_buffer) {
struct lance_init_block __iomem *ib = lp->init_block_iomem;
sbus_writew((-len) | 0xf000, &ib->btx_ring[entry].length);
sbus_writew(0, &ib->btx_ring[entry].misc);
lance_piocopy_from_skb(&ib->tx_buf[entry][0], skb->data, skblen);
if (len != skblen)
lance_piozero(&ib->tx_buf[entry][skblen], len - skblen);
sbus_writeb(LE_T1_POK | LE_T1_OWN, &ib->btx_ring[entry].tmd1_bits);
} else {
struct lance_init_block *ib = lp->init_block_mem;
ib->btx_ring [entry].length = (-len) | 0xf000;
ib->btx_ring [entry].misc = 0;
skb_copy_from_linear_data(skb, &ib->tx_buf [entry][0], skblen);
if (len != skblen)
memset((char *) &ib->tx_buf [entry][skblen], 0, len - skblen);
ib->btx_ring [entry].tmd1_bits = (LE_T1_POK | LE_T1_OWN);
}
lp->tx_new = TX_NEXT(entry);
if (TX_BUFFS_AVAIL <= 0)
netif_stop_queue(dev);
/* Kick the lance: transmit now */
sbus_writew(LE_C0_INEA | LE_C0_TDMD, lp->lregs + RDP);
/* Read back CSR to invalidate the E-Cache.
* This is needed, because DMA_DSBL_WR_INV is set.
*/
if (lp->dregs)
sbus_readw(lp->lregs + RDP);
spin_unlock_irq(&lp->lock);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* taken from the depca driver */
static void lance_load_multicast(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct netdev_hw_addr *ha;
char *addrs;
u32 crc;
u32 val;
/* set all multicast bits */
if (dev->flags & IFF_ALLMULTI)
val = ~0;
else
val = 0;
if (lp->pio_buffer) {
struct lance_init_block __iomem *ib = lp->init_block_iomem;
sbus_writel(val, &ib->filter[0]);
sbus_writel(val, &ib->filter[1]);
} else {
struct lance_init_block *ib = lp->init_block_mem;
ib->filter [0] = val;
ib->filter [1] = val;
}
if (dev->flags & IFF_ALLMULTI)
return;
/* Add addresses */
netdev_for_each_mc_addr(ha, dev) {
addrs = ha->addr;
/* multicast address? */
if (!(*addrs & 1))
continue;
crc = ether_crc_le(6, addrs);
crc = crc >> 26;
if (lp->pio_buffer) {
struct lance_init_block __iomem *ib = lp->init_block_iomem;
u16 __iomem *mcast_table = (u16 __iomem *) &ib->filter;
u16 tmp = sbus_readw(&mcast_table[crc>>4]);
tmp |= 1 << (crc & 0xf);
sbus_writew(tmp, &mcast_table[crc>>4]);
} else {
struct lance_init_block *ib = lp->init_block_mem;
u16 *mcast_table = (u16 *) &ib->filter;
mcast_table [crc >> 4] |= 1 << (crc & 0xf);
}
}
}
static void lance_set_multicast(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
struct lance_init_block *ib_mem = lp->init_block_mem;
struct lance_init_block __iomem *ib_iomem = lp->init_block_iomem;
u16 mode;
if (!netif_running(dev))
return;
if (lp->tx_old != lp->tx_new) {
mod_timer(&lp->multicast_timer, jiffies + 4);
netif_wake_queue(dev);
return;
}
netif_stop_queue(dev);
STOP_LANCE(lp);
lp->init_ring(dev);
if (lp->pio_buffer)
mode = sbus_readw(&ib_iomem->mode);
else
mode = ib_mem->mode;
if (dev->flags & IFF_PROMISC) {
mode |= LE_MO_PROM;
if (lp->pio_buffer)
sbus_writew(mode, &ib_iomem->mode);
else
ib_mem->mode = mode;
} else {
mode &= ~LE_MO_PROM;
if (lp->pio_buffer)
sbus_writew(mode, &ib_iomem->mode);
else
ib_mem->mode = mode;
lance_load_multicast(dev);
}
load_csrs(lp);
init_restart_lance(lp);
netif_wake_queue(dev);
}
static void lance_set_multicast_retry(unsigned long _opaque)
{
struct net_device *dev = (struct net_device *) _opaque;
lance_set_multicast(dev);
}
static void lance_free_hwresources(struct lance_private *lp)
{
if (lp->lregs)
of_iounmap(&lp->op->resource[0], lp->lregs, LANCE_REG_SIZE);
if (lp->dregs) {
struct platform_device *ledma = lp->ledma;
of_iounmap(&ledma->resource[0], lp->dregs,
resource_size(&ledma->resource[0]));
}
if (lp->init_block_iomem) {
of_iounmap(&lp->lebuffer->resource[0], lp->init_block_iomem,
sizeof(struct lance_init_block));
} else if (lp->init_block_mem) {
dma_free_coherent(&lp->op->dev,
sizeof(struct lance_init_block),
lp->init_block_mem,
lp->init_block_dvma);
}
}
/* Ethtool support... */
static void sparc_lance_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
strcpy(info->driver, "sunlance");
strcpy(info->version, "2.02");
}
static u32 sparc_lance_get_link(struct net_device *dev)
{
/* We really do not keep track of this, but this
* is better than not reporting anything at all.
*/
return 1;
}
static const struct ethtool_ops sparc_lance_ethtool_ops = {
.get_drvinfo = sparc_lance_get_drvinfo,
.get_link = sparc_lance_get_link,
};
static const struct net_device_ops sparc_lance_ops = {
.ndo_open = lance_open,
.ndo_stop = lance_close,
.ndo_start_xmit = lance_start_xmit,
.ndo_set_multicast_list = lance_set_multicast,
.ndo_tx_timeout = lance_tx_timeout,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static int __devinit sparc_lance_probe_one(struct platform_device *op,
struct platform_device *ledma,
struct platform_device *lebuffer)
{
struct device_node *dp = op->dev.of_node;
static unsigned version_printed;
struct lance_private *lp;
struct net_device *dev;
int i;
dev = alloc_etherdev(sizeof(struct lance_private) + 8);
if (!dev)
return -ENOMEM;
lp = netdev_priv(dev);
if (sparc_lance_debug && version_printed++ == 0)
printk (KERN_INFO "%s", version);
spin_lock_init(&lp->lock);
/* Copy the IDPROM ethernet address to the device structure, later we
* will copy the address in the device structure to the lance
* initialization block.
*/
for (i = 0; i < 6; i++)
dev->dev_addr[i] = idprom->id_ethaddr[i];
/* Get the IO region */
lp->lregs = of_ioremap(&op->resource[0], 0,
LANCE_REG_SIZE, lancestr);
if (!lp->lregs) {
printk(KERN_ERR "SunLance: Cannot map registers.\n");
goto fail;
}
lp->ledma = ledma;
if (lp->ledma) {
lp->dregs = of_ioremap(&ledma->resource[0], 0,
resource_size(&ledma->resource[0]),
"ledma");
if (!lp->dregs) {
printk(KERN_ERR "SunLance: Cannot map "
"ledma registers.\n");
goto fail;
}
}
lp->op = op;
lp->lebuffer = lebuffer;
if (lebuffer) {
/* sanity check */
if (lebuffer->resource[0].start & 7) {
printk(KERN_ERR "SunLance: ERROR: Rx and Tx rings not on even boundary.\n");
goto fail;
}
lp->init_block_iomem =
of_ioremap(&lebuffer->resource[0], 0,
sizeof(struct lance_init_block), "lebuffer");
if (!lp->init_block_iomem) {
printk(KERN_ERR "SunLance: Cannot map PIO buffer.\n");
goto fail;
}
lp->init_block_dvma = 0;
lp->pio_buffer = 1;
lp->init_ring = lance_init_ring_pio;
lp->rx = lance_rx_pio;
lp->tx = lance_tx_pio;
} else {
lp->init_block_mem =
dma_alloc_coherent(&op->dev,
sizeof(struct lance_init_block),
&lp->init_block_dvma, GFP_ATOMIC);
if (!lp->init_block_mem) {
printk(KERN_ERR "SunLance: Cannot allocate consistent DMA memory.\n");
goto fail;
}
lp->pio_buffer = 0;
lp->init_ring = lance_init_ring_dvma;
lp->rx = lance_rx_dvma;
lp->tx = lance_tx_dvma;
}
lp->busmaster_regval = of_getintprop_default(dp, "busmaster-regval",
(LE_C3_BSWP |
LE_C3_ACON |
LE_C3_BCON));
lp->name = lancestr;
lp->burst_sizes = 0;
if (lp->ledma) {
struct device_node *ledma_dp = ledma->dev.of_node;
struct device_node *sbus_dp;
unsigned int sbmask;
const char *prop;
u32 csr;
/* Find burst-size property for ledma */
lp->burst_sizes = of_getintprop_default(ledma_dp,
"burst-sizes", 0);
/* ledma may be capable of fast bursts, but sbus may not. */
sbus_dp = ledma_dp->parent;
sbmask = of_getintprop_default(sbus_dp, "burst-sizes",
DMA_BURSTBITS);
lp->burst_sizes &= sbmask;
/* Get the cable-selection property */
prop = of_get_property(ledma_dp, "cable-selection", NULL);
if (!prop || prop[0] == '\0') {
struct device_node *nd;
printk(KERN_INFO "SunLance: using "
"auto-carrier-detection.\n");
nd = of_find_node_by_path("/options");
if (!nd)
goto no_link_test;
prop = of_get_property(nd, "tpe-link-test?", NULL);
if (!prop)
goto no_link_test;
if (strcmp(prop, "true")) {
printk(KERN_NOTICE "SunLance: warning: overriding option "
"'tpe-link-test?'\n");
printk(KERN_NOTICE "SunLance: warning: mail any problems "
"to ecd@skynet.be\n");
auxio_set_lte(AUXIO_LTE_ON);
}
no_link_test:
lp->auto_select = 1;
lp->tpe = 0;
} else if (!strcmp(prop, "aui")) {
lp->auto_select = 0;
lp->tpe = 0;
} else {
lp->auto_select = 0;
lp->tpe = 1;
}
/* Reset ledma */
csr = sbus_readl(lp->dregs + DMA_CSR);
sbus_writel(csr | DMA_RST_ENET, lp->dregs + DMA_CSR);
udelay(200);
sbus_writel(csr & ~DMA_RST_ENET, lp->dregs + DMA_CSR);
} else
lp->dregs = NULL;
lp->dev = dev;
SET_NETDEV_DEV(dev, &op->dev);
dev->watchdog_timeo = 5*HZ;
dev->ethtool_ops = &sparc_lance_ethtool_ops;
dev->netdev_ops = &sparc_lance_ops;
dev->irq = op->archdata.irqs[0];
/* We cannot sleep if the chip is busy during a
* multicast list update event, because such events
* can occur from interrupts (ex. IPv6). So we
* use a timer to try again later when necessary. -DaveM
*/
init_timer(&lp->multicast_timer);
lp->multicast_timer.data = (unsigned long) dev;
lp->multicast_timer.function = &lance_set_multicast_retry;
if (register_netdev(dev)) {
printk(KERN_ERR "SunLance: Cannot register device.\n");
goto fail;
}
dev_set_drvdata(&op->dev, lp);
printk(KERN_INFO "%s: LANCE %pM\n",
dev->name, dev->dev_addr);
return 0;
fail:
lance_free_hwresources(lp);
free_netdev(dev);
return -ENODEV;
}
static int __devinit sunlance_sbus_probe(struct platform_device *op, const struct of_device_id *match)
{
struct platform_device *parent = to_platform_device(op->dev.parent);
struct device_node *parent_dp = parent->dev.of_node;
int err;
if (!strcmp(parent_dp->name, "ledma")) {
err = sparc_lance_probe_one(op, parent, NULL);
} else if (!strcmp(parent_dp->name, "lebuffer")) {
err = sparc_lance_probe_one(op, NULL, parent);
} else
err = sparc_lance_probe_one(op, NULL, NULL);
return err;
}
static int __devexit sunlance_sbus_remove(struct platform_device *op)
{
struct lance_private *lp = dev_get_drvdata(&op->dev);
struct net_device *net_dev = lp->dev;
unregister_netdev(net_dev);
lance_free_hwresources(lp);
free_netdev(net_dev);
dev_set_drvdata(&op->dev, NULL);
return 0;
}
static const struct of_device_id sunlance_sbus_match[] = {
{
.name = "le",
},
{},
};
MODULE_DEVICE_TABLE(of, sunlance_sbus_match);
static struct of_platform_driver sunlance_sbus_driver = {
.driver = {
.name = "sunlance",
.owner = THIS_MODULE,
.of_match_table = sunlance_sbus_match,
},
.probe = sunlance_sbus_probe,
.remove = __devexit_p(sunlance_sbus_remove),
};
/* Find all the lance cards on the system and initialize them */
static int __init sparc_lance_init(void)
{
return of_register_platform_driver(&sunlance_sbus_driver);
}
static void __exit sparc_lance_exit(void)
{
of_unregister_platform_driver(&sunlance_sbus_driver);
}
module_init(sparc_lance_init);
module_exit(sparc_lance_exit);
| gpl-2.0 |
megraf/asuswrt-merlin | release/src-rt-6.x.4708/linux/linux-2.6.36/fs/ext4/block_validity.c | 41 | 6345 | /*
* linux/fs/ext4/block_validity.c
*
* Copyright (C) 2009
* Theodore Ts'o (tytso@mit.edu)
*
* Track which blocks in the filesystem are metadata blocks that
* should never be used as data blocks by files or directories.
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/module.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include "ext4.h"
struct ext4_system_zone {
struct rb_node node;
ext4_fsblk_t start_blk;
unsigned int count;
};
static struct kmem_cache *ext4_system_zone_cachep;
int __init init_ext4_system_zone(void)
{
ext4_system_zone_cachep = KMEM_CACHE(ext4_system_zone,
SLAB_RECLAIM_ACCOUNT);
if (ext4_system_zone_cachep == NULL)
return -ENOMEM;
return 0;
}
void exit_ext4_system_zone(void)
{
kmem_cache_destroy(ext4_system_zone_cachep);
}
static inline int can_merge(struct ext4_system_zone *entry1,
struct ext4_system_zone *entry2)
{
if ((entry1->start_blk + entry1->count) == entry2->start_blk)
return 1;
return 0;
}
/*
* Mark a range of blocks as belonging to the "system zone" --- that
* is, filesystem metadata blocks which should never be used by
* inodes.
*/
static int add_system_zone(struct ext4_sb_info *sbi,
ext4_fsblk_t start_blk,
unsigned int count)
{
struct ext4_system_zone *new_entry = NULL, *entry;
struct rb_node **n = &sbi->system_blks.rb_node, *node;
struct rb_node *parent = NULL, *new_node = NULL;
while (*n) {
parent = *n;
entry = rb_entry(parent, struct ext4_system_zone, node);
if (start_blk < entry->start_blk)
n = &(*n)->rb_left;
else if (start_blk >= (entry->start_blk + entry->count))
n = &(*n)->rb_right;
else {
if (start_blk + count > (entry->start_blk +
entry->count))
entry->count = (start_blk + count -
entry->start_blk);
new_node = *n;
new_entry = rb_entry(new_node, struct ext4_system_zone,
node);
break;
}
}
if (!new_entry) {
new_entry = kmem_cache_alloc(ext4_system_zone_cachep,
GFP_KERNEL);
if (!new_entry)
return -ENOMEM;
new_entry->start_blk = start_blk;
new_entry->count = count;
new_node = &new_entry->node;
rb_link_node(new_node, parent, n);
rb_insert_color(new_node, &sbi->system_blks);
}
/* Can we merge to the left? */
node = rb_prev(new_node);
if (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
if (can_merge(entry, new_entry)) {
new_entry->start_blk = entry->start_blk;
new_entry->count += entry->count;
rb_erase(node, &sbi->system_blks);
kmem_cache_free(ext4_system_zone_cachep, entry);
}
}
/* Can we merge to the right? */
node = rb_next(new_node);
if (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
if (can_merge(new_entry, entry)) {
new_entry->count += entry->count;
rb_erase(node, &sbi->system_blks);
kmem_cache_free(ext4_system_zone_cachep, entry);
}
}
return 0;
}
static void debug_print_tree(struct ext4_sb_info *sbi)
{
struct rb_node *node;
struct ext4_system_zone *entry;
int first = 1;
printk(KERN_INFO "System zones: ");
node = rb_first(&sbi->system_blks);
while (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
printk("%s%llu-%llu", first ? "" : ", ",
entry->start_blk, entry->start_blk + entry->count - 1);
first = 0;
node = rb_next(node);
}
printk("\n");
}
int ext4_setup_system_zone(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_group_t i;
int flex_size = ext4_flex_bg_size(sbi);
int ret;
if (!test_opt(sb, BLOCK_VALIDITY)) {
if (EXT4_SB(sb)->system_blks.rb_node)
ext4_release_system_zone(sb);
return 0;
}
if (EXT4_SB(sb)->system_blks.rb_node)
return 0;
for (i=0; i < ngroups; i++) {
if (ext4_bg_has_super(sb, i) &&
((i < 5) || ((i % flex_size) == 0)))
add_system_zone(sbi, ext4_group_first_block_no(sb, i),
ext4_bg_num_gdb(sb, i) + 1);
gdp = ext4_get_group_desc(sb, i, NULL);
ret = add_system_zone(sbi, ext4_block_bitmap(sb, gdp), 1);
if (ret)
return ret;
ret = add_system_zone(sbi, ext4_inode_bitmap(sb, gdp), 1);
if (ret)
return ret;
ret = add_system_zone(sbi, ext4_inode_table(sb, gdp),
sbi->s_itb_per_group);
if (ret)
return ret;
}
if (test_opt(sb, DEBUG))
debug_print_tree(EXT4_SB(sb));
return 0;
}
/* Called when the filesystem is unmounted */
void ext4_release_system_zone(struct super_block *sb)
{
struct rb_node *n = EXT4_SB(sb)->system_blks.rb_node;
struct rb_node *parent;
struct ext4_system_zone *entry;
while (n) {
/* Do the node's children first */
if (n->rb_left) {
n = n->rb_left;
continue;
}
if (n->rb_right) {
n = n->rb_right;
continue;
}
/*
* The node has no children; free it, and then zero
* out parent's link to it. Finally go to the
* beginning of the loop and try to free the parent
* node.
*/
parent = rb_parent(n);
entry = rb_entry(n, struct ext4_system_zone, node);
kmem_cache_free(ext4_system_zone_cachep, entry);
if (!parent)
EXT4_SB(sb)->system_blks = RB_ROOT;
else if (parent->rb_left == n)
parent->rb_left = NULL;
else if (parent->rb_right == n)
parent->rb_right = NULL;
n = parent;
}
EXT4_SB(sb)->system_blks = RB_ROOT;
}
/*
* Returns 1 if the passed-in block region (start_blk,
* start_blk+count) is valid; 0 if some part of the block region
* overlaps with filesystem metadata blocks.
*/
int ext4_data_block_valid(struct ext4_sb_info *sbi, ext4_fsblk_t start_blk,
unsigned int count)
{
struct ext4_system_zone *entry;
struct rb_node *n = sbi->system_blks.rb_node;
if ((start_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
(start_blk + count < start_blk) ||
(start_blk + count > ext4_blocks_count(sbi->s_es))) {
sbi->s_es->s_last_error_block = cpu_to_le64(start_blk);
return 0;
}
while (n) {
entry = rb_entry(n, struct ext4_system_zone, node);
if (start_blk + count - 1 < entry->start_blk)
n = n->rb_left;
else if (start_blk >= (entry->start_blk + entry->count))
n = n->rb_right;
else {
sbi->s_es->s_last_error_block = cpu_to_le64(start_blk);
return 0;
}
}
return 1;
}
| gpl-2.0 |
stepsongit/linux | fs/xfs/libxfs/xfs_dquot_buf.c | 297 | 7706 | /*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* Copyright (c) 2013 Red Hat, 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_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_mount.h"
#include "xfs_inode.h"
#include "xfs_quota.h"
#include "xfs_trans.h"
#include "xfs_qm.h"
#include "xfs_error.h"
#include "xfs_cksum.h"
#include "xfs_trace.h"
int
xfs_calc_dquots_per_chunk(
unsigned int nbblks) /* basic block units */
{
unsigned int ndquots;
ASSERT(nbblks > 0);
ndquots = BBTOB(nbblks);
do_div(ndquots, sizeof(xfs_dqblk_t));
return ndquots;
}
/*
* Do some primitive error checking on ondisk dquot data structures.
*/
int
xfs_dqcheck(
struct xfs_mount *mp,
xfs_disk_dquot_t *ddq,
xfs_dqid_t id,
uint type, /* used only when IO_dorepair is true */
uint flags,
char *str)
{
xfs_dqblk_t *d = (xfs_dqblk_t *)ddq;
int errs = 0;
/*
* We can encounter an uninitialized dquot buffer for 2 reasons:
* 1. If we crash while deleting the quotainode(s), and those blks got
* used for user data. This is because we take the path of regular
* file deletion; however, the size field of quotainodes is never
* updated, so all the tricks that we play in itruncate_finish
* don't quite matter.
*
* 2. We don't play the quota buffers when there's a quotaoff logitem.
* But the allocation will be replayed so we'll end up with an
* uninitialized quota block.
*
* This is all fine; things are still consistent, and we haven't lost
* any quota information. Just don't complain about bad dquot blks.
*/
if (ddq->d_magic != cpu_to_be16(XFS_DQUOT_MAGIC)) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : XFS dquot ID 0x%x, magic 0x%x != 0x%x",
str, id, be16_to_cpu(ddq->d_magic), XFS_DQUOT_MAGIC);
errs++;
}
if (ddq->d_version != XFS_DQUOT_VERSION) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : XFS dquot ID 0x%x, version 0x%x != 0x%x",
str, id, ddq->d_version, XFS_DQUOT_VERSION);
errs++;
}
if (ddq->d_flags != XFS_DQ_USER &&
ddq->d_flags != XFS_DQ_PROJ &&
ddq->d_flags != XFS_DQ_GROUP) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : XFS dquot ID 0x%x, unknown flags 0x%x",
str, id, ddq->d_flags);
errs++;
}
if (id != -1 && id != be32_to_cpu(ddq->d_id)) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : ondisk-dquot 0x%p, ID mismatch: "
"0x%x expected, found id 0x%x",
str, ddq, id, be32_to_cpu(ddq->d_id));
errs++;
}
if (!errs && ddq->d_id) {
if (ddq->d_blk_softlimit &&
be64_to_cpu(ddq->d_bcount) >
be64_to_cpu(ddq->d_blk_softlimit)) {
if (!ddq->d_btimer) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : Dquot ID 0x%x (0x%p) BLK TIMER NOT STARTED",
str, (int)be32_to_cpu(ddq->d_id), ddq);
errs++;
}
}
if (ddq->d_ino_softlimit &&
be64_to_cpu(ddq->d_icount) >
be64_to_cpu(ddq->d_ino_softlimit)) {
if (!ddq->d_itimer) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : Dquot ID 0x%x (0x%p) INODE TIMER NOT STARTED",
str, (int)be32_to_cpu(ddq->d_id), ddq);
errs++;
}
}
if (ddq->d_rtb_softlimit &&
be64_to_cpu(ddq->d_rtbcount) >
be64_to_cpu(ddq->d_rtb_softlimit)) {
if (!ddq->d_rtbtimer) {
if (flags & XFS_QMOPT_DOWARN)
xfs_alert(mp,
"%s : Dquot ID 0x%x (0x%p) RTBLK TIMER NOT STARTED",
str, (int)be32_to_cpu(ddq->d_id), ddq);
errs++;
}
}
}
if (!errs || !(flags & XFS_QMOPT_DQREPAIR))
return errs;
if (flags & XFS_QMOPT_DOWARN)
xfs_notice(mp, "Re-initializing dquot ID 0x%x", id);
/*
* Typically, a repair is only requested by quotacheck.
*/
ASSERT(id != -1);
ASSERT(flags & XFS_QMOPT_DQREPAIR);
memset(d, 0, sizeof(xfs_dqblk_t));
d->dd_diskdq.d_magic = cpu_to_be16(XFS_DQUOT_MAGIC);
d->dd_diskdq.d_version = XFS_DQUOT_VERSION;
d->dd_diskdq.d_flags = type;
d->dd_diskdq.d_id = cpu_to_be32(id);
if (xfs_sb_version_hascrc(&mp->m_sb)) {
uuid_copy(&d->dd_uuid, &mp->m_sb.sb_meta_uuid);
xfs_update_cksum((char *)d, sizeof(struct xfs_dqblk),
XFS_DQUOT_CRC_OFF);
}
return errs;
}
STATIC bool
xfs_dquot_buf_verify_crc(
struct xfs_mount *mp,
struct xfs_buf *bp)
{
struct xfs_dqblk *d = (struct xfs_dqblk *)bp->b_addr;
int ndquots;
int i;
if (!xfs_sb_version_hascrc(&mp->m_sb))
return true;
/*
* if we are in log recovery, the quota subsystem has not been
* initialised so we have no quotainfo structure. In that case, we need
* to manually calculate the number of dquots in the buffer.
*/
if (mp->m_quotainfo)
ndquots = mp->m_quotainfo->qi_dqperchunk;
else
ndquots = xfs_calc_dquots_per_chunk(
XFS_BB_TO_FSB(mp, bp->b_length));
for (i = 0; i < ndquots; i++, d++) {
if (!xfs_verify_cksum((char *)d, sizeof(struct xfs_dqblk),
XFS_DQUOT_CRC_OFF))
return false;
if (!uuid_equal(&d->dd_uuid, &mp->m_sb.sb_meta_uuid))
return false;
}
return true;
}
STATIC bool
xfs_dquot_buf_verify(
struct xfs_mount *mp,
struct xfs_buf *bp)
{
struct xfs_dqblk *d = (struct xfs_dqblk *)bp->b_addr;
xfs_dqid_t id = 0;
int ndquots;
int i;
/*
* if we are in log recovery, the quota subsystem has not been
* initialised so we have no quotainfo structure. In that case, we need
* to manually calculate the number of dquots in the buffer.
*/
if (mp->m_quotainfo)
ndquots = mp->m_quotainfo->qi_dqperchunk;
else
ndquots = xfs_calc_dquots_per_chunk(bp->b_length);
/*
* On the first read of the buffer, verify that each dquot is valid.
* We don't know what the id of the dquot is supposed to be, just that
* they should be increasing monotonically within the buffer. If the
* first id is corrupt, then it will fail on the second dquot in the
* buffer so corruptions could point to the wrong dquot in this case.
*/
for (i = 0; i < ndquots; i++) {
struct xfs_disk_dquot *ddq;
int error;
ddq = &d[i].dd_diskdq;
if (i == 0)
id = be32_to_cpu(ddq->d_id);
error = xfs_dqcheck(mp, ddq, id + i, 0, XFS_QMOPT_DOWARN,
"xfs_dquot_buf_verify");
if (error)
return false;
}
return true;
}
static void
xfs_dquot_buf_read_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
if (!xfs_dquot_buf_verify_crc(mp, bp))
xfs_buf_ioerror(bp, -EFSBADCRC);
else if (!xfs_dquot_buf_verify(mp, bp))
xfs_buf_ioerror(bp, -EFSCORRUPTED);
if (bp->b_error)
xfs_verifier_error(bp);
}
/*
* we don't calculate the CRC here as that is done when the dquot is flushed to
* the buffer after the update is done. This ensures that the dquot in the
* buffer always has an up-to-date CRC value.
*/
static void
xfs_dquot_buf_write_verify(
struct xfs_buf *bp)
{
struct xfs_mount *mp = bp->b_target->bt_mount;
if (!xfs_dquot_buf_verify(mp, bp)) {
xfs_buf_ioerror(bp, -EFSCORRUPTED);
xfs_verifier_error(bp);
return;
}
}
const struct xfs_buf_ops xfs_dquot_buf_ops = {
.verify_read = xfs_dquot_buf_read_verify,
.verify_write = xfs_dquot_buf_write_verify,
};
| gpl-2.0 |
elelinux/hero_kernel | drivers/media/video/gspca/pac7302.c | 809 | 32784 | /*
* Pixart PAC7302 library
* Copyright (C) 2005 Thomas Kaiser thomas@kaiser-linux.li
*
* V4L2 by Jean-Francois Moine <http://moinejf.free.fr>
*
* Separated from Pixart PAC7311 library by Márton Németh
* Camera button input handling by Márton Németh <nm127@freemail.hu>
* Copyright (C) 2009-2010 Márton Németh <nm127@freemail.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Some documentation about various registers as determined by trial and error.
Register page 1:
Address Description
0x78 Global control, bit 6 controls the LED (inverted)
Register page 3:
Address Description
0x02 Clock divider 3-63, fps = 90 / val. Must be a multiple of 3 on
the 7302, so one of 3, 6, 9, ..., except when between 6 and 12?
0x03 Variable framerate ctrl reg2==3: 0 -> ~30 fps, 255 -> ~22fps
0x04 Another var framerate ctrl reg2==3, reg3==0: 0 -> ~30 fps,
63 -> ~27 fps, the 2 msb's must always be 1 !!
0x05 Another var framerate ctrl reg2==3, reg3==0, reg4==0xc0:
1 -> ~30 fps, 2 -> ~20 fps
0x0e Exposure bits 0-7, 0-448, 0 = use full frame time
0x0f Exposure bit 8, 0-448, 448 = no exposure at all
0x10 Master gain 0-31
0x21 Bitfield: 0-1 unused, 2-3 vflip/hflip, 4-5 unknown, 6-7 unused
The registers are accessed in the following functions:
Page | Register | Function
-----+------------+---------------------------------------------------
0 | 0x0f..0x20 | setcolors()
0 | 0xa2..0xab | setbrightcont()
0 | 0xc5 | setredbalance()
0 | 0xc6 | setwhitebalance()
0 | 0xc7 | setbluebalance()
0 | 0xdc | setbrightcont(), setcolors()
3 | 0x02 | setexposure()
3 | 0x10 | setgain()
3 | 0x11 | setcolors(), setgain(), setexposure(), sethvflip()
3 | 0x21 | sethvflip()
*/
#define MODULE_NAME "pac7302"
#include <linux/input.h>
#include <media/v4l2-chip-ident.h>
#include "gspca.h"
MODULE_AUTHOR("Thomas Kaiser thomas@kaiser-linux.li");
MODULE_DESCRIPTION("Pixart PAC7302");
MODULE_LICENSE("GPL");
/* specific webcam descriptor for pac7302 */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
unsigned char brightness;
unsigned char contrast;
unsigned char colors;
unsigned char white_balance;
unsigned char red_balance;
unsigned char blue_balance;
unsigned char gain;
unsigned char autogain;
unsigned short exposure;
__u8 hflip;
__u8 vflip;
u8 flags;
#define FL_HFLIP 0x01 /* mirrored by default */
#define FL_VFLIP 0x02 /* vertical flipped by default */
u8 sof_read;
u8 autogain_ignore_frames;
atomic_t avg_lum;
};
/* V4L2 controls supported by the driver */
static int sd_setbrightness(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getbrightness(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setcontrast(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getcontrast(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setcolors(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getcolors(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setwhitebalance(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getwhitebalance(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setredbalance(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getredbalance(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setbluebalance(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getbluebalance(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getautogain(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_sethflip(struct gspca_dev *gspca_dev, __s32 val);
static int sd_gethflip(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setvflip(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getvflip(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setgain(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getgain(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setexposure(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getexposure(struct gspca_dev *gspca_dev, __s32 *val);
static const struct ctrl sd_ctrls[] = {
{
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
#define BRIGHTNESS_MAX 0x20
.maximum = BRIGHTNESS_MAX,
.step = 1,
#define BRIGHTNESS_DEF 0x10
.default_value = BRIGHTNESS_DEF,
},
.set = sd_setbrightness,
.get = sd_getbrightness,
},
{
{
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
#define CONTRAST_MAX 255
.maximum = CONTRAST_MAX,
.step = 1,
#define CONTRAST_DEF 127
.default_value = CONTRAST_DEF,
},
.set = sd_setcontrast,
.get = sd_getcontrast,
},
{
{
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Saturation",
.minimum = 0,
#define COLOR_MAX 255
.maximum = COLOR_MAX,
.step = 1,
#define COLOR_DEF 127
.default_value = COLOR_DEF,
},
.set = sd_setcolors,
.get = sd_getcolors,
},
{
{
.id = V4L2_CID_WHITE_BALANCE_TEMPERATURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "White Balance",
.minimum = 0,
.maximum = 255,
.step = 1,
#define WHITEBALANCE_DEF 4
.default_value = WHITEBALANCE_DEF,
},
.set = sd_setwhitebalance,
.get = sd_getwhitebalance,
},
{
{
.id = V4L2_CID_RED_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Red",
.minimum = 0,
.maximum = 3,
.step = 1,
#define REDBALANCE_DEF 1
.default_value = REDBALANCE_DEF,
},
.set = sd_setredbalance,
.get = sd_getredbalance,
},
{
{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Blue",
.minimum = 0,
.maximum = 3,
.step = 1,
#define BLUEBALANCE_DEF 1
.default_value = BLUEBALANCE_DEF,
},
.set = sd_setbluebalance,
.get = sd_getbluebalance,
},
{
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain",
.minimum = 0,
#define GAIN_MAX 255
.maximum = GAIN_MAX,
.step = 1,
#define GAIN_DEF 127
#define GAIN_KNEE 255 /* Gain seems to cause little noise on the pac73xx */
.default_value = GAIN_DEF,
},
.set = sd_setgain,
.get = sd_getgain,
},
{
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Exposure",
.minimum = 0,
.maximum = 1023,
.step = 1,
#define EXPOSURE_DEF 66 /* 33 ms / 30 fps */
#define EXPOSURE_KNEE 133 /* 66 ms / 15 fps */
.default_value = EXPOSURE_DEF,
},
.set = sd_setexposure,
.get = sd_getexposure,
},
{
{
.id = V4L2_CID_AUTOGAIN,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Auto Gain",
.minimum = 0,
.maximum = 1,
.step = 1,
#define AUTOGAIN_DEF 1
.default_value = AUTOGAIN_DEF,
},
.set = sd_setautogain,
.get = sd_getautogain,
},
{
{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Mirror",
.minimum = 0,
.maximum = 1,
.step = 1,
#define HFLIP_DEF 0
.default_value = HFLIP_DEF,
},
.set = sd_sethflip,
.get = sd_gethflip,
},
{
{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Vflip",
.minimum = 0,
.maximum = 1,
.step = 1,
#define VFLIP_DEF 0
.default_value = VFLIP_DEF,
},
.set = sd_setvflip,
.get = sd_getvflip,
},
};
static const struct v4l2_pix_format vga_mode[] = {
{640, 480, V4L2_PIX_FMT_PJPG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
#define LOAD_PAGE3 255
#define END_OF_SEQUENCE 0
/* pac 7302 */
static const __u8 init_7302[] = {
/* index,value */
0xff, 0x01, /* page 1 */
0x78, 0x00, /* deactivate */
0xff, 0x01,
0x78, 0x40, /* led off */
};
static const __u8 start_7302[] = {
/* index, len, [value]* */
0xff, 1, 0x00, /* page 0 */
0x00, 12, 0x01, 0x40, 0x40, 0x40, 0x01, 0xe0, 0x02, 0x80,
0x00, 0x00, 0x00, 0x00,
0x0d, 24, 0x03, 0x01, 0x00, 0xb5, 0x07, 0xcb, 0x00, 0x00,
0x07, 0xc8, 0x00, 0xea, 0x07, 0xcf, 0x07, 0xf7,
0x07, 0x7e, 0x01, 0x0b, 0x00, 0x00, 0x00, 0x11,
0x26, 2, 0xaa, 0xaa,
0x2e, 1, 0x31,
0x38, 1, 0x01,
0x3a, 3, 0x14, 0xff, 0x5a,
0x43, 11, 0x00, 0x0a, 0x18, 0x11, 0x01, 0x2c, 0x88, 0x11,
0x00, 0x54, 0x11,
0x55, 1, 0x00,
0x62, 4, 0x10, 0x1e, 0x1e, 0x18,
0x6b, 1, 0x00,
0x6e, 3, 0x08, 0x06, 0x00,
0x72, 3, 0x00, 0xff, 0x00,
0x7d, 23, 0x01, 0x01, 0x58, 0x46, 0x50, 0x3c, 0x50, 0x3c,
0x54, 0x46, 0x54, 0x56, 0x52, 0x50, 0x52, 0x50,
0x56, 0x64, 0xa4, 0x00, 0xda, 0x00, 0x00,
0xa2, 10, 0x22, 0x2c, 0x3c, 0x54, 0x69, 0x7c, 0x9c, 0xb9,
0xd2, 0xeb,
0xaf, 1, 0x02,
0xb5, 2, 0x08, 0x08,
0xb8, 2, 0x08, 0x88,
0xc4, 4, 0xae, 0x01, 0x04, 0x01,
0xcc, 1, 0x00,
0xd1, 11, 0x01, 0x30, 0x49, 0x5e, 0x6f, 0x7f, 0x8e, 0xa9,
0xc1, 0xd7, 0xec,
0xdc, 1, 0x01,
0xff, 1, 0x01, /* page 1 */
0x12, 3, 0x02, 0x00, 0x01,
0x3e, 2, 0x00, 0x00,
0x76, 5, 0x01, 0x20, 0x40, 0x00, 0xf2,
0x7c, 1, 0x00,
0x7f, 10, 0x4b, 0x0f, 0x01, 0x2c, 0x02, 0x58, 0x03, 0x20,
0x02, 0x00,
0x96, 5, 0x01, 0x10, 0x04, 0x01, 0x04,
0xc8, 14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00,
0x07, 0x00, 0x01, 0x07, 0x04, 0x01,
0xd8, 1, 0x01,
0xdb, 2, 0x00, 0x01,
0xde, 7, 0x00, 0x01, 0x04, 0x04, 0x00, 0x00, 0x00,
0xe6, 4, 0x00, 0x00, 0x00, 0x01,
0xeb, 1, 0x00,
0xff, 1, 0x02, /* page 2 */
0x22, 1, 0x00,
0xff, 1, 0x03, /* page 3 */
0, LOAD_PAGE3, /* load the page 3 */
0x11, 1, 0x01,
0xff, 1, 0x02, /* page 2 */
0x13, 1, 0x00,
0x22, 4, 0x1f, 0xa4, 0xf0, 0x96,
0x27, 2, 0x14, 0x0c,
0x2a, 5, 0xc8, 0x00, 0x18, 0x12, 0x22,
0x64, 8, 0x00, 0x00, 0xf0, 0x01, 0x14, 0x44, 0x44, 0x44,
0x6e, 1, 0x08,
0xff, 1, 0x01, /* page 1 */
0x78, 1, 0x00,
0, END_OF_SEQUENCE /* end of sequence */
};
#define SKIP 0xaa
/* page 3 - the value SKIP says skip the index - see reg_w_page() */
static const __u8 page3_7302[] = {
0x90, 0x40, 0x03, 0x00, 0xc0, 0x01, 0x14, 0x16,
0x14, 0x12, 0x00, 0x00, 0x00, 0x02, 0x33, 0x00,
0x0f, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x47, 0x01, 0xb3, 0x01, 0x00,
0x00, 0x08, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x21,
0x00, 0x00, 0x00, 0x54, 0xf4, 0x02, 0x52, 0x54,
0xa4, 0xb8, 0xe0, 0x2a, 0xf6, 0x00, 0x00, 0x00,
0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xfc, 0x00, 0xf2, 0x1f, 0x04, 0x00, 0x00,
SKIP, 0x00, 0x00, 0xc0, 0xc0, 0x10, 0x00, 0x00,
0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x40, 0xff, 0x03, 0x19, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0xc8, 0xc8,
0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50,
0x08, 0x10, 0x24, 0x40, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x02, 0x47, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0xfa, 0x00, 0x64, 0x5a, 0x28, 0x00,
0x00
};
static void reg_w_buf(struct gspca_dev *gspca_dev,
__u8 index,
const char *buffer, int len)
{
int ret;
if (gspca_dev->usb_err < 0)
return;
memcpy(gspca_dev->usb_buf, buffer, len);
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
1, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, /* value */
index, gspca_dev->usb_buf, len,
500);
if (ret < 0) {
PDEBUG(D_ERR, "reg_w_buf(): "
"Failed to write registers to index 0x%x, error %i",
index, ret);
gspca_dev->usb_err = ret;
}
}
static void reg_w(struct gspca_dev *gspca_dev,
__u8 index,
__u8 value)
{
int ret;
if (gspca_dev->usb_err < 0)
return;
gspca_dev->usb_buf[0] = value;
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
0, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, gspca_dev->usb_buf, 1,
500);
if (ret < 0) {
PDEBUG(D_ERR, "reg_w(): "
"Failed to write register to index 0x%x, value 0x%x, error %i",
index, value, ret);
gspca_dev->usb_err = ret;
}
}
static void reg_w_seq(struct gspca_dev *gspca_dev,
const __u8 *seq, int len)
{
while (--len >= 0) {
reg_w(gspca_dev, seq[0], seq[1]);
seq += 2;
}
}
/* load the beginning of a page */
static void reg_w_page(struct gspca_dev *gspca_dev,
const __u8 *page, int len)
{
int index;
int ret = 0;
if (gspca_dev->usb_err < 0)
return;
for (index = 0; index < len; index++) {
if (page[index] == SKIP) /* skip this index */
continue;
gspca_dev->usb_buf[0] = page[index];
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
0, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, gspca_dev->usb_buf, 1,
500);
if (ret < 0) {
PDEBUG(D_ERR, "reg_w_page(): "
"Failed to write register to index 0x%x, "
"value 0x%x, error %i",
index, page[index], ret);
gspca_dev->usb_err = ret;
break;
}
}
}
/* output a variable sequence */
static void reg_w_var(struct gspca_dev *gspca_dev,
const __u8 *seq,
const __u8 *page3, unsigned int page3_len)
{
int index, len;
for (;;) {
index = *seq++;
len = *seq++;
switch (len) {
case END_OF_SEQUENCE:
return;
case LOAD_PAGE3:
reg_w_page(gspca_dev, page3, page3_len);
break;
default:
if (len > USB_BUF_SZ) {
PDEBUG(D_ERR|D_STREAM,
"Incorrect variable sequence");
return;
}
while (len > 0) {
if (len < 8) {
reg_w_buf(gspca_dev,
index, seq, len);
seq += len;
break;
}
reg_w_buf(gspca_dev, index, seq, 8);
seq += 8;
index += 8;
len -= 8;
}
}
}
/* not reached */
}
/* this function is called at probe time for pac7302 */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam;
cam = &gspca_dev->cam;
PDEBUG(D_CONF, "Find Sensor PAC7302");
cam->cam_mode = vga_mode; /* only 640x480 */
cam->nmodes = ARRAY_SIZE(vga_mode);
sd->brightness = BRIGHTNESS_DEF;
sd->contrast = CONTRAST_DEF;
sd->colors = COLOR_DEF;
sd->white_balance = WHITEBALANCE_DEF;
sd->red_balance = REDBALANCE_DEF;
sd->blue_balance = BLUEBALANCE_DEF;
sd->gain = GAIN_DEF;
sd->exposure = EXPOSURE_DEF;
sd->autogain = AUTOGAIN_DEF;
sd->hflip = HFLIP_DEF;
sd->vflip = VFLIP_DEF;
sd->flags = id->driver_info;
return 0;
}
/* This function is used by pac7302 only */
static void setbrightcont(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i, v;
static const __u8 max[10] =
{0x29, 0x33, 0x42, 0x5a, 0x6e, 0x80, 0x9f, 0xbb,
0xd4, 0xec};
static const __u8 delta[10] =
{0x35, 0x33, 0x33, 0x2f, 0x2a, 0x25, 0x1e, 0x17,
0x11, 0x0b};
reg_w(gspca_dev, 0xff, 0x00); /* page 0 */
for (i = 0; i < 10; i++) {
v = max[i];
v += (sd->brightness - BRIGHTNESS_MAX)
* 150 / BRIGHTNESS_MAX; /* 200 ? */
v -= delta[i] * sd->contrast / CONTRAST_MAX;
if (v < 0)
v = 0;
else if (v > 0xff)
v = 0xff;
reg_w(gspca_dev, 0xa2 + i, v);
}
reg_w(gspca_dev, 0xdc, 0x01);
}
/* This function is used by pac7302 only */
static void setcolors(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i, v;
static const int a[9] =
{217, -212, 0, -101, 170, -67, -38, -315, 355};
static const int b[9] =
{19, 106, 0, 19, 106, 1, 19, 106, 1};
reg_w(gspca_dev, 0xff, 0x03); /* page 3 */
reg_w(gspca_dev, 0x11, 0x01);
reg_w(gspca_dev, 0xff, 0x00); /* page 0 */
for (i = 0; i < 9; i++) {
v = a[i] * sd->colors / COLOR_MAX + b[i];
reg_w(gspca_dev, 0x0f + 2 * i, (v >> 8) & 0x07);
reg_w(gspca_dev, 0x0f + 2 * i + 1, v);
}
reg_w(gspca_dev, 0xdc, 0x01);
PDEBUG(D_CONF|D_STREAM, "color: %i", sd->colors);
}
static void setwhitebalance(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w(gspca_dev, 0xff, 0x00); /* page 0 */
reg_w(gspca_dev, 0xc6, sd->white_balance);
reg_w(gspca_dev, 0xdc, 0x01);
PDEBUG(D_CONF|D_STREAM, "white_balance: %i", sd->white_balance);
}
static void setredbalance(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w(gspca_dev, 0xff, 0x00); /* page 0 */
reg_w(gspca_dev, 0xc5, sd->red_balance);
reg_w(gspca_dev, 0xdc, 0x01);
PDEBUG(D_CONF|D_STREAM, "red_balance: %i", sd->red_balance);
}
static void setbluebalance(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w(gspca_dev, 0xff, 0x00); /* page 0 */
reg_w(gspca_dev, 0xc7, sd->blue_balance);
reg_w(gspca_dev, 0xdc, 0x01);
PDEBUG(D_CONF|D_STREAM, "blue_balance: %i", sd->blue_balance);
}
static void setgain(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w(gspca_dev, 0xff, 0x03); /* page 3 */
reg_w(gspca_dev, 0x10, sd->gain >> 3);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
static void setexposure(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
__u8 clockdiv;
__u16 exposure;
/* register 2 of frame 3 contains the clock divider configuring the
no fps according to the formula: 90 / reg. sd->exposure is the
desired exposure time in 0.5 ms. */
clockdiv = (90 * sd->exposure + 1999) / 2000;
/* Note clockdiv = 3 also works, but when running at 30 fps, depending
on the scene being recorded, the camera switches to another
quantization table for certain JPEG blocks, and we don't know how
to decompress these blocks. So we cap the framerate at 15 fps */
if (clockdiv < 6)
clockdiv = 6;
else if (clockdiv > 63)
clockdiv = 63;
/* reg2 MUST be a multiple of 3, except when between 6 and 12?
Always round up, otherwise we cannot get the desired frametime
using the partial frame time exposure control */
if (clockdiv < 6 || clockdiv > 12)
clockdiv = ((clockdiv + 2) / 3) * 3;
/* frame exposure time in ms = 1000 * clockdiv / 90 ->
exposure = (sd->exposure / 2) * 448 / (1000 * clockdiv / 90) */
exposure = (sd->exposure * 45 * 448) / (1000 * clockdiv);
/* 0 = use full frametime, 448 = no exposure, reverse it */
exposure = 448 - exposure;
reg_w(gspca_dev, 0xff, 0x03); /* page 3 */
reg_w(gspca_dev, 0x02, clockdiv);
reg_w(gspca_dev, 0x0e, exposure & 0xff);
reg_w(gspca_dev, 0x0f, exposure >> 8);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
static void sethvflip(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 data, hflip, vflip;
hflip = sd->hflip;
if (sd->flags & FL_HFLIP)
hflip = !hflip;
vflip = sd->vflip;
if (sd->flags & FL_VFLIP)
vflip = !vflip;
reg_w(gspca_dev, 0xff, 0x03); /* page 3 */
data = (hflip ? 0x08 : 0x00) | (vflip ? 0x04 : 0x00);
reg_w(gspca_dev, 0x21, data);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
/* this function is called at probe and resume time for pac7302 */
static int sd_init(struct gspca_dev *gspca_dev)
{
reg_w_seq(gspca_dev, init_7302, sizeof(init_7302)/2);
return gspca_dev->usb_err;
}
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->sof_read = 0;
reg_w_var(gspca_dev, start_7302,
page3_7302, sizeof(page3_7302));
setbrightcont(gspca_dev);
setcolors(gspca_dev);
setwhitebalance(gspca_dev);
setredbalance(gspca_dev);
setbluebalance(gspca_dev);
setgain(gspca_dev);
setexposure(gspca_dev);
sethvflip(gspca_dev);
/* only resolution 640x480 is supported for pac7302 */
sd->sof_read = 0;
sd->autogain_ignore_frames = 0;
atomic_set(&sd->avg_lum, -1);
/* start stream */
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x78, 0x01);
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
/* stop stream */
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x78, 0x00);
}
/* called on streamoff with alt 0 and on disconnect for pac7302 */
static void sd_stop0(struct gspca_dev *gspca_dev)
{
if (!gspca_dev->present)
return;
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x78, 0x40);
}
/* Include pac common sof detection functions */
#include "pac_common.h"
static void do_autogain(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int avg_lum = atomic_read(&sd->avg_lum);
int desired_lum;
const int deadzone = 30;
if (avg_lum == -1)
return;
desired_lum = 270 + sd->brightness;
if (sd->autogain_ignore_frames > 0)
sd->autogain_ignore_frames--;
else if (gspca_auto_gain_n_exposure(gspca_dev, avg_lum, desired_lum,
deadzone, GAIN_KNEE, EXPOSURE_KNEE))
sd->autogain_ignore_frames = PAC_AUTOGAIN_IGNORE_FRAMES;
}
/* JPEG header, part 1 */
static const unsigned char pac_jpeg_header1[] = {
0xff, 0xd8, /* SOI: Start of Image */
0xff, 0xc0, /* SOF0: Start of Frame (Baseline DCT) */
0x00, 0x11, /* length = 17 bytes (including this length field) */
0x08 /* Precision: 8 */
/* 2 bytes is placed here: number of image lines */
/* 2 bytes is placed here: samples per line */
};
/* JPEG header, continued */
static const unsigned char pac_jpeg_header2[] = {
0x03, /* Number of image components: 3 */
0x01, 0x21, 0x00, /* ID=1, Subsampling 1x1, Quantization table: 0 */
0x02, 0x11, 0x01, /* ID=2, Subsampling 2x1, Quantization table: 1 */
0x03, 0x11, 0x01, /* ID=3, Subsampling 2x1, Quantization table: 1 */
0xff, 0xda, /* SOS: Start Of Scan */
0x00, 0x0c, /* length = 12 bytes (including this length field) */
0x03, /* number of components: 3 */
0x01, 0x00, /* selector 1, table 0x00 */
0x02, 0x11, /* selector 2, table 0x11 */
0x03, 0x11, /* selector 3, table 0x11 */
0x00, 0x3f, /* Spectral selection: 0 .. 63 */
0x00 /* Successive approximation: 0 */
};
static void pac_start_frame(struct gspca_dev *gspca_dev,
struct gspca_frame *frame,
__u16 lines, __u16 samples_per_line)
{
unsigned char tmpbuf[4];
gspca_frame_add(gspca_dev, FIRST_PACKET,
pac_jpeg_header1, sizeof(pac_jpeg_header1));
tmpbuf[0] = lines >> 8;
tmpbuf[1] = lines & 0xff;
tmpbuf[2] = samples_per_line >> 8;
tmpbuf[3] = samples_per_line & 0xff;
gspca_frame_add(gspca_dev, INTER_PACKET,
tmpbuf, sizeof(tmpbuf));
gspca_frame_add(gspca_dev, INTER_PACKET,
pac_jpeg_header2, sizeof(pac_jpeg_header2));
}
/* this function is run at interrupt level */
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
struct gspca_frame *frame;
unsigned char *sof;
sof = pac_find_sof(&sd->sof_read, data, len);
if (sof) {
int n, lum_offset, footer_length;
frame = gspca_get_i_frame(gspca_dev);
if (frame == NULL) {
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
/* 6 bytes after the FF D9 EOF marker a number of lumination
bytes are send corresponding to different parts of the
image, the 14th and 15th byte after the EOF seem to
correspond to the center of the image */
lum_offset = 61 + sizeof pac_sof_marker;
footer_length = 74;
/* Finish decoding current frame */
n = (sof - data) - (footer_length + sizeof pac_sof_marker);
if (n < 0) {
frame->data_end += n;
n = 0;
}
gspca_frame_add(gspca_dev, INTER_PACKET,
data, n);
if (gspca_dev->last_packet_type != DISCARD_PACKET &&
frame->data_end[-2] == 0xff &&
frame->data_end[-1] == 0xd9)
gspca_frame_add(gspca_dev, LAST_PACKET,
NULL, 0);
n = sof - data;
len -= n;
data = sof;
/* Get average lumination */
if (gspca_dev->last_packet_type == LAST_PACKET &&
n >= lum_offset)
atomic_set(&sd->avg_lum, data[-lum_offset] +
data[-lum_offset + 1]);
else
atomic_set(&sd->avg_lum, -1);
/* Start the new frame with the jpeg header */
/* The PAC7302 has the image rotated 90 degrees */
pac_start_frame(gspca_dev, frame,
gspca_dev->width, gspca_dev->height);
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
static int sd_setbrightness(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->brightness = val;
if (gspca_dev->streaming)
setbrightcont(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getbrightness(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->brightness;
return 0;
}
static int sd_setcontrast(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->contrast = val;
if (gspca_dev->streaming) {
setbrightcont(gspca_dev);
}
return gspca_dev->usb_err;
}
static int sd_getcontrast(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->contrast;
return 0;
}
static int sd_setcolors(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->colors = val;
if (gspca_dev->streaming)
setcolors(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getcolors(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->colors;
return 0;
}
static int sd_setwhitebalance(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->white_balance = val;
if (gspca_dev->streaming)
setwhitebalance(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getwhitebalance(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->white_balance;
return 0;
}
static int sd_setredbalance(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->red_balance = val;
if (gspca_dev->streaming)
setredbalance(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getredbalance(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->red_balance;
return 0;
}
static int sd_setbluebalance(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->blue_balance = val;
if (gspca_dev->streaming)
setbluebalance(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getbluebalance(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->blue_balance;
return 0;
}
static int sd_setgain(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->gain = val;
if (gspca_dev->streaming)
setgain(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getgain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->gain;
return 0;
}
static int sd_setexposure(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->exposure = val;
if (gspca_dev->streaming)
setexposure(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getexposure(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->exposure;
return 0;
}
static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->autogain = val;
/* when switching to autogain set defaults to make sure
we are on a valid point of the autogain gain /
exposure knee graph, and give this change time to
take effect before doing autogain. */
if (sd->autogain) {
sd->exposure = EXPOSURE_DEF;
sd->gain = GAIN_DEF;
if (gspca_dev->streaming) {
sd->autogain_ignore_frames =
PAC_AUTOGAIN_IGNORE_FRAMES;
setexposure(gspca_dev);
setgain(gspca_dev);
}
}
return gspca_dev->usb_err;
}
static int sd_getautogain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->autogain;
return 0;
}
static int sd_sethflip(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->hflip = val;
if (gspca_dev->streaming)
sethvflip(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_gethflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->hflip;
return 0;
}
static int sd_setvflip(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->vflip = val;
if (gspca_dev->streaming)
sethvflip(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_getvflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->vflip;
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int sd_dbg_s_register(struct gspca_dev *gspca_dev,
struct v4l2_dbg_register *reg)
{
__u8 index;
__u8 value;
/* reg->reg: bit0..15: reserved for register index (wIndex is 16bit
long on the USB bus)
*/
if (reg->match.type == V4L2_CHIP_MATCH_HOST &&
reg->match.addr == 0 &&
(reg->reg < 0x000000ff) &&
(reg->val <= 0x000000ff)
) {
/* Currently writing to page 0 is only supported. */
/* reg_w() only supports 8bit index */
index = reg->reg & 0x000000ff;
value = reg->val & 0x000000ff;
/* Note that there shall be no access to other page
by any other function between the page swith and
the actual register write */
reg_w(gspca_dev, 0xff, 0x00); /* page 0 */
reg_w(gspca_dev, index, value);
reg_w(gspca_dev, 0xdc, 0x01);
}
return gspca_dev->usb_err;
}
static int sd_chip_ident(struct gspca_dev *gspca_dev,
struct v4l2_dbg_chip_ident *chip)
{
int ret = -EINVAL;
if (chip->match.type == V4L2_CHIP_MATCH_HOST &&
chip->match.addr == 0) {
chip->revision = 0;
chip->ident = V4L2_IDENT_UNKNOWN;
ret = 0;
}
return ret;
}
#endif
#ifdef CONFIG_INPUT
static int sd_int_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* interrupt packet data */
int len) /* interrput packet length */
{
int ret = -EINVAL;
u8 data0, data1;
if (len == 2) {
data0 = data[0];
data1 = data[1];
if ((data0 == 0x00 && data1 == 0x11) ||
(data0 == 0x22 && data1 == 0x33) ||
(data0 == 0x44 && data1 == 0x55) ||
(data0 == 0x66 && data1 == 0x77) ||
(data0 == 0x88 && data1 == 0x99) ||
(data0 == 0xaa && data1 == 0xbb) ||
(data0 == 0xcc && data1 == 0xdd) ||
(data0 == 0xee && data1 == 0xff)) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1);
input_sync(gspca_dev->input_dev);
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
ret = 0;
}
}
return ret;
}
#endif
/* sub-driver description for pac7302 */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.ctrls = sd_ctrls,
.nctrls = ARRAY_SIZE(sd_ctrls),
.config = sd_config,
.init = sd_init,
.start = sd_start,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
.dq_callback = do_autogain,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.set_register = sd_dbg_s_register,
.get_chip_ident = sd_chip_ident,
#endif
#ifdef CONFIG_INPUT
.int_pkt_scan = sd_int_pkt_scan,
#endif
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] __devinitconst = {
{USB_DEVICE(0x06f8, 0x3009)},
{USB_DEVICE(0x093a, 0x2620)},
{USB_DEVICE(0x093a, 0x2621)},
{USB_DEVICE(0x093a, 0x2622), .driver_info = FL_VFLIP},
{USB_DEVICE(0x093a, 0x2624), .driver_info = FL_VFLIP},
{USB_DEVICE(0x093a, 0x2626)},
{USB_DEVICE(0x093a, 0x2628)},
{USB_DEVICE(0x093a, 0x2629), .driver_info = FL_VFLIP},
{USB_DEVICE(0x093a, 0x262a)},
{USB_DEVICE(0x093a, 0x262c)},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int __devinit sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
#endif
};
/* -- module insert / remove -- */
static int __init sd_mod_init(void)
{
int ret;
ret = usb_register(&sd_driver);
if (ret < 0)
return ret;
PDEBUG(D_PROBE, "registered");
return 0;
}
static void __exit sd_mod_exit(void)
{
usb_deregister(&sd_driver);
PDEBUG(D_PROBE, "deregistered");
}
module_init(sd_mod_init);
module_exit(sd_mod_exit);
| gpl-2.0 |
mrabe89sigma/linux-curie | drivers/net/usb/dm9601.c | 1577 | 15630 | /*
* Davicom DM96xx USB 10/100Mbps ethernet devices
*
* Peter Korsgaard <jacmet@sunsite.dk>
*
* 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.
*/
//#define DEBUG
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/stddef.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/crc32.h>
#include <linux/usb/usbnet.h>
#include <linux/slab.h>
/* datasheet:
http://ptm2.cc.utu.fi/ftp/network/cards/DM9601/From_NET/DM9601-DS-P01-930914.pdf
*/
/* control requests */
#define DM_READ_REGS 0x00
#define DM_WRITE_REGS 0x01
#define DM_READ_MEMS 0x02
#define DM_WRITE_REG 0x03
#define DM_WRITE_MEMS 0x05
#define DM_WRITE_MEM 0x07
/* registers */
#define DM_NET_CTRL 0x00
#define DM_RX_CTRL 0x05
#define DM_SHARED_CTRL 0x0b
#define DM_SHARED_ADDR 0x0c
#define DM_SHARED_DATA 0x0d /* low + high */
#define DM_PHY_ADDR 0x10 /* 6 bytes */
#define DM_MCAST_ADDR 0x16 /* 8 bytes */
#define DM_GPR_CTRL 0x1e
#define DM_GPR_DATA 0x1f
#define DM_CHIP_ID 0x2c
#define DM_MODE_CTRL 0x91 /* only on dm9620 */
/* chip id values */
#define ID_DM9601 0
#define ID_DM9620 1
#define DM_MAX_MCAST 64
#define DM_MCAST_SIZE 8
#define DM_EEPROM_LEN 256
#define DM_TX_OVERHEAD 2 /* 2 byte header */
#define DM_RX_OVERHEAD 7 /* 3 byte header + 4 byte crc tail */
#define DM_TIMEOUT 1000
static int dm_read(struct usbnet *dev, u8 reg, u16 length, void *data)
{
int err;
err = usbnet_read_cmd(dev, DM_READ_REGS,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, reg, data, length);
if(err != length && err >= 0)
err = -EINVAL;
return err;
}
static int dm_read_reg(struct usbnet *dev, u8 reg, u8 *value)
{
return dm_read(dev, reg, 1, value);
}
static int dm_write(struct usbnet *dev, u8 reg, u16 length, void *data)
{
int err;
err = usbnet_write_cmd(dev, DM_WRITE_REGS,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, reg, data, length);
if (err >= 0 && err < length)
err = -EINVAL;
return err;
}
static int dm_write_reg(struct usbnet *dev, u8 reg, u8 value)
{
return usbnet_write_cmd(dev, DM_WRITE_REG,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, reg, NULL, 0);
}
static void dm_write_async(struct usbnet *dev, u8 reg, u16 length, void *data)
{
usbnet_write_cmd_async(dev, DM_WRITE_REGS,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, reg, data, length);
}
static void dm_write_reg_async(struct usbnet *dev, u8 reg, u8 value)
{
usbnet_write_cmd_async(dev, DM_WRITE_REG,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, reg, NULL, 0);
}
static int dm_read_shared_word(struct usbnet *dev, int phy, u8 reg, __le16 *value)
{
int ret, i;
mutex_lock(&dev->phy_mutex);
dm_write_reg(dev, DM_SHARED_ADDR, phy ? (reg | 0x40) : reg);
dm_write_reg(dev, DM_SHARED_CTRL, phy ? 0xc : 0x4);
for (i = 0; i < DM_TIMEOUT; i++) {
u8 tmp = 0;
udelay(1);
ret = dm_read_reg(dev, DM_SHARED_CTRL, &tmp);
if (ret < 0)
goto out;
/* ready */
if ((tmp & 1) == 0)
break;
}
if (i == DM_TIMEOUT) {
netdev_err(dev->net, "%s read timed out!\n", phy ? "phy" : "eeprom");
ret = -EIO;
goto out;
}
dm_write_reg(dev, DM_SHARED_CTRL, 0x0);
ret = dm_read(dev, DM_SHARED_DATA, 2, value);
netdev_dbg(dev->net, "read shared %d 0x%02x returned 0x%04x, %d\n",
phy, reg, *value, ret);
out:
mutex_unlock(&dev->phy_mutex);
return ret;
}
static int dm_write_shared_word(struct usbnet *dev, int phy, u8 reg, __le16 value)
{
int ret, i;
mutex_lock(&dev->phy_mutex);
ret = dm_write(dev, DM_SHARED_DATA, 2, &value);
if (ret < 0)
goto out;
dm_write_reg(dev, DM_SHARED_ADDR, phy ? (reg | 0x40) : reg);
dm_write_reg(dev, DM_SHARED_CTRL, phy ? 0x1a : 0x12);
for (i = 0; i < DM_TIMEOUT; i++) {
u8 tmp = 0;
udelay(1);
ret = dm_read_reg(dev, DM_SHARED_CTRL, &tmp);
if (ret < 0)
goto out;
/* ready */
if ((tmp & 1) == 0)
break;
}
if (i == DM_TIMEOUT) {
netdev_err(dev->net, "%s write timed out!\n", phy ? "phy" : "eeprom");
ret = -EIO;
goto out;
}
dm_write_reg(dev, DM_SHARED_CTRL, 0x0);
out:
mutex_unlock(&dev->phy_mutex);
return ret;
}
static int dm_read_eeprom_word(struct usbnet *dev, u8 offset, void *value)
{
return dm_read_shared_word(dev, 0, offset, value);
}
static int dm9601_get_eeprom_len(struct net_device *dev)
{
return DM_EEPROM_LEN;
}
static int dm9601_get_eeprom(struct net_device *net,
struct ethtool_eeprom *eeprom, u8 * data)
{
struct usbnet *dev = netdev_priv(net);
__le16 *ebuf = (__le16 *) data;
int i;
/* access is 16bit */
if ((eeprom->offset % 2) || (eeprom->len % 2))
return -EINVAL;
for (i = 0; i < eeprom->len / 2; i++) {
if (dm_read_eeprom_word(dev, eeprom->offset / 2 + i,
&ebuf[i]) < 0)
return -EINVAL;
}
return 0;
}
static int dm9601_mdio_read(struct net_device *netdev, int phy_id, int loc)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 res;
if (phy_id) {
netdev_dbg(dev->net, "Only internal phy supported\n");
return 0;
}
dm_read_shared_word(dev, 1, loc, &res);
netdev_dbg(dev->net,
"dm9601_mdio_read() phy_id=0x%02x, loc=0x%02x, returns=0x%04x\n",
phy_id, loc, le16_to_cpu(res));
return le16_to_cpu(res);
}
static void dm9601_mdio_write(struct net_device *netdev, int phy_id, int loc,
int val)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 res = cpu_to_le16(val);
if (phy_id) {
netdev_dbg(dev->net, "Only internal phy supported\n");
return;
}
netdev_dbg(dev->net, "dm9601_mdio_write() phy_id=0x%02x, loc=0x%02x, val=0x%04x\n",
phy_id, loc, val);
dm_write_shared_word(dev, 1, loc, res);
}
static void dm9601_get_drvinfo(struct net_device *net,
struct ethtool_drvinfo *info)
{
/* Inherit standard device info */
usbnet_get_drvinfo(net, info);
info->eedump_len = DM_EEPROM_LEN;
}
static u32 dm9601_get_link(struct net_device *net)
{
struct usbnet *dev = netdev_priv(net);
return mii_link_ok(&dev->mii);
}
static int dm9601_ioctl(struct net_device *net, struct ifreq *rq, int cmd)
{
struct usbnet *dev = netdev_priv(net);
return generic_mii_ioctl(&dev->mii, if_mii(rq), cmd, NULL);
}
static const struct ethtool_ops dm9601_ethtool_ops = {
.get_drvinfo = dm9601_get_drvinfo,
.get_link = dm9601_get_link,
.get_msglevel = usbnet_get_msglevel,
.set_msglevel = usbnet_set_msglevel,
.get_eeprom_len = dm9601_get_eeprom_len,
.get_eeprom = dm9601_get_eeprom,
.get_settings = usbnet_get_settings,
.set_settings = usbnet_set_settings,
.nway_reset = usbnet_nway_reset,
};
static void dm9601_set_multicast(struct net_device *net)
{
struct usbnet *dev = netdev_priv(net);
/* We use the 20 byte dev->data for our 8 byte filter buffer
* to avoid allocating memory that is tricky to free later */
u8 *hashes = (u8 *) & dev->data;
u8 rx_ctl = 0x31;
memset(hashes, 0x00, DM_MCAST_SIZE);
hashes[DM_MCAST_SIZE - 1] |= 0x80; /* broadcast address */
if (net->flags & IFF_PROMISC) {
rx_ctl |= 0x02;
} else if (net->flags & IFF_ALLMULTI ||
netdev_mc_count(net) > DM_MAX_MCAST) {
rx_ctl |= 0x08;
} else if (!netdev_mc_empty(net)) {
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, net) {
u32 crc = ether_crc(ETH_ALEN, ha->addr) >> 26;
hashes[crc >> 3] |= 1 << (crc & 0x7);
}
}
dm_write_async(dev, DM_MCAST_ADDR, DM_MCAST_SIZE, hashes);
dm_write_reg_async(dev, DM_RX_CTRL, rx_ctl);
}
static void __dm9601_set_mac_address(struct usbnet *dev)
{
dm_write_async(dev, DM_PHY_ADDR, ETH_ALEN, dev->net->dev_addr);
}
static int dm9601_set_mac_address(struct net_device *net, void *p)
{
struct sockaddr *addr = p;
struct usbnet *dev = netdev_priv(net);
if (!is_valid_ether_addr(addr->sa_data)) {
dev_err(&net->dev, "not setting invalid mac address %pM\n",
addr->sa_data);
return -EINVAL;
}
memcpy(net->dev_addr, addr->sa_data, net->addr_len);
__dm9601_set_mac_address(dev);
return 0;
}
static const struct net_device_ops dm9601_netdev_ops = {
.ndo_open = usbnet_open,
.ndo_stop = usbnet_stop,
.ndo_start_xmit = usbnet_start_xmit,
.ndo_tx_timeout = usbnet_tx_timeout,
.ndo_change_mtu = usbnet_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = dm9601_ioctl,
.ndo_set_rx_mode = dm9601_set_multicast,
.ndo_set_mac_address = dm9601_set_mac_address,
};
static int dm9601_bind(struct usbnet *dev, struct usb_interface *intf)
{
int ret;
u8 mac[ETH_ALEN], id;
ret = usbnet_get_endpoints(dev, intf);
if (ret)
goto out;
dev->net->netdev_ops = &dm9601_netdev_ops;
dev->net->ethtool_ops = &dm9601_ethtool_ops;
dev->net->hard_header_len += DM_TX_OVERHEAD;
dev->hard_mtu = dev->net->mtu + dev->net->hard_header_len;
/* dm9620/21a require room for 4 byte padding, even in dm9601
* mode, so we need +1 to be able to receive full size
* ethernet frames.
*/
dev->rx_urb_size = dev->net->mtu + ETH_HLEN + DM_RX_OVERHEAD + 1;
dev->mii.dev = dev->net;
dev->mii.mdio_read = dm9601_mdio_read;
dev->mii.mdio_write = dm9601_mdio_write;
dev->mii.phy_id_mask = 0x1f;
dev->mii.reg_num_mask = 0x1f;
/* reset */
dm_write_reg(dev, DM_NET_CTRL, 1);
udelay(20);
/* read MAC */
if (dm_read(dev, DM_PHY_ADDR, ETH_ALEN, mac) < 0) {
printk(KERN_ERR "Error reading MAC address\n");
ret = -ENODEV;
goto out;
}
/*
* Overwrite the auto-generated address only with good ones.
*/
if (is_valid_ether_addr(mac))
memcpy(dev->net->dev_addr, mac, ETH_ALEN);
else {
printk(KERN_WARNING
"dm9601: No valid MAC address in EEPROM, using %pM\n",
dev->net->dev_addr);
__dm9601_set_mac_address(dev);
}
if (dm_read_reg(dev, DM_CHIP_ID, &id) < 0) {
netdev_err(dev->net, "Error reading chip ID\n");
ret = -ENODEV;
goto out;
}
/* put dm9620 devices in dm9601 mode */
if (id == ID_DM9620) {
u8 mode;
if (dm_read_reg(dev, DM_MODE_CTRL, &mode) < 0) {
netdev_err(dev->net, "Error reading MODE_CTRL\n");
ret = -ENODEV;
goto out;
}
dm_write_reg(dev, DM_MODE_CTRL, mode & 0x7f);
}
/* power up phy */
dm_write_reg(dev, DM_GPR_CTRL, 1);
dm_write_reg(dev, DM_GPR_DATA, 0);
/* receive broadcast packets */
dm9601_set_multicast(dev->net);
dm9601_mdio_write(dev->net, dev->mii.phy_id, MII_BMCR, BMCR_RESET);
dm9601_mdio_write(dev->net, dev->mii.phy_id, MII_ADVERTISE,
ADVERTISE_ALL | ADVERTISE_CSMA | ADVERTISE_PAUSE_CAP);
mii_nway_restart(&dev->mii);
out:
return ret;
}
static int dm9601_rx_fixup(struct usbnet *dev, struct sk_buff *skb)
{
u8 status;
int len;
/* format:
b1: rx status
b2: packet length (incl crc) low
b3: packet length (incl crc) high
b4..n-4: packet data
bn-3..bn: ethernet crc
*/
if (unlikely(skb->len < DM_RX_OVERHEAD)) {
dev_err(&dev->udev->dev, "unexpected tiny rx frame\n");
return 0;
}
status = skb->data[0];
len = (skb->data[1] | (skb->data[2] << 8)) - 4;
if (unlikely(status & 0xbf)) {
if (status & 0x01) dev->net->stats.rx_fifo_errors++;
if (status & 0x02) dev->net->stats.rx_crc_errors++;
if (status & 0x04) dev->net->stats.rx_frame_errors++;
if (status & 0x20) dev->net->stats.rx_missed_errors++;
if (status & 0x90) dev->net->stats.rx_length_errors++;
return 0;
}
skb_pull(skb, 3);
skb_trim(skb, len);
return 1;
}
static struct sk_buff *dm9601_tx_fixup(struct usbnet *dev, struct sk_buff *skb,
gfp_t flags)
{
int len, pad;
/* format:
b1: packet length low
b2: packet length high
b3..n: packet data
*/
len = skb->len + DM_TX_OVERHEAD;
/* workaround for dm962x errata with tx fifo getting out of
* sync if a USB bulk transfer retry happens right after a
* packet with odd / maxpacket length by adding up to 3 bytes
* padding.
*/
while ((len & 1) || !(len % dev->maxpacket))
len++;
len -= DM_TX_OVERHEAD; /* hw header doesn't count as part of length */
pad = len - skb->len;
if (skb_headroom(skb) < DM_TX_OVERHEAD || skb_tailroom(skb) < pad) {
struct sk_buff *skb2;
skb2 = skb_copy_expand(skb, DM_TX_OVERHEAD, pad, flags);
dev_kfree_skb_any(skb);
skb = skb2;
if (!skb)
return NULL;
}
__skb_push(skb, DM_TX_OVERHEAD);
if (pad) {
memset(skb->data + skb->len, 0, pad);
__skb_put(skb, pad);
}
skb->data[0] = len;
skb->data[1] = len >> 8;
return skb;
}
static void dm9601_status(struct usbnet *dev, struct urb *urb)
{
int link;
u8 *buf;
/* format:
b0: net status
b1: tx status 1
b2: tx status 2
b3: rx status
b4: rx overflow
b5: rx count
b6: tx count
b7: gpr
*/
if (urb->actual_length < 8)
return;
buf = urb->transfer_buffer;
link = !!(buf[0] & 0x40);
if (netif_carrier_ok(dev->net) != link) {
usbnet_link_change(dev, link, 1);
netdev_dbg(dev->net, "Link Status is: %d\n", link);
}
}
static int dm9601_link_reset(struct usbnet *dev)
{
struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
mii_check_media(&dev->mii, 1, 1);
mii_ethtool_gset(&dev->mii, &ecmd);
netdev_dbg(dev->net, "link_reset() speed: %u duplex: %d\n",
ethtool_cmd_speed(&ecmd), ecmd.duplex);
return 0;
}
static const struct driver_info dm9601_info = {
.description = "Davicom DM96xx USB 10/100 Ethernet",
.flags = FLAG_ETHER | FLAG_LINK_INTR,
.bind = dm9601_bind,
.rx_fixup = dm9601_rx_fixup,
.tx_fixup = dm9601_tx_fixup,
.status = dm9601_status,
.link_reset = dm9601_link_reset,
.reset = dm9601_link_reset,
};
static const struct usb_device_id products[] = {
{
USB_DEVICE(0x07aa, 0x9601), /* Corega FEther USB-TXC */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x9601), /* Davicom USB-100 */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x6688), /* ZT6688 USB NIC */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x0268), /* ShanTou ST268 USB NIC */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x8515), /* ADMtek ADM8515 USB NIC */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a47, 0x9601), /* Hirose USB-100 */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0fe6, 0x8101), /* DM9601 USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0fe6, 0x9700), /* DM9601 USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x9000), /* DM9000E */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x9620), /* DM9620 USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x9621), /* DM9621A USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x9622), /* DM9622 USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x0269), /* DM962OA USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{
USB_DEVICE(0x0a46, 0x1269), /* DM9621A USB to Fast Ethernet Adapter */
.driver_info = (unsigned long)&dm9601_info,
},
{}, // END
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver dm9601_driver = {
.name = "dm9601",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(dm9601_driver);
MODULE_AUTHOR("Peter Korsgaard <jacmet@sunsite.dk>");
MODULE_DESCRIPTION("Davicom DM96xx USB 10/100 ethernet devices");
MODULE_LICENSE("GPL");
| gpl-2.0 |
AD5GB/android_kernel_googlesource-common | drivers/of/of_i2c.c | 2089 | 2934 | /*
* OF helpers for the I2C API
*
* Copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
*
* Based on a previous patch from Jon Smirl <jonsmirl@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/of.h>
#include <linux/of_i2c.h>
#include <linux/of_irq.h>
#include <linux/module.h>
void of_i2c_register_devices(struct i2c_adapter *adap)
{
void *result;
struct device_node *node;
/* Only register child devices if the adapter has a node pointer set */
if (!adap->dev.of_node)
return;
dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
for_each_available_child_of_node(adap->dev.of_node, node) {
struct i2c_board_info info = {};
struct dev_archdata dev_ad = {};
const __be32 *addr;
int len;
dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
node->full_name);
continue;
}
addr = of_get_property(node, "reg", &len);
if (!addr || (len < sizeof(int))) {
dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
node->full_name);
continue;
}
info.addr = be32_to_cpup(addr);
if (info.addr > (1 << 10) - 1) {
dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
info.addr, node->full_name);
continue;
}
info.irq = irq_of_parse_and_map(node, 0);
info.of_node = of_node_get(node);
info.archdata = &dev_ad;
if (of_get_property(node, "wakeup-source", NULL))
info.flags |= I2C_CLIENT_WAKE;
request_module("%s%s", I2C_MODULE_PREFIX, info.type);
result = i2c_new_device(adap, &info);
if (result == NULL) {
dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
node->full_name);
of_node_put(node);
irq_dispose_mapping(info.irq);
continue;
}
}
}
EXPORT_SYMBOL(of_i2c_register_devices);
static int of_dev_node_match(struct device *dev, void *data)
{
return dev->of_node == data;
}
/* must call put_device() when done with returned i2c_client device */
struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
{
struct device *dev;
dev = bus_find_device(&i2c_bus_type, NULL, node,
of_dev_node_match);
if (!dev)
return NULL;
return i2c_verify_client(dev);
}
EXPORT_SYMBOL(of_find_i2c_device_by_node);
/* must call put_device() when done with returned i2c_adapter device */
struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
{
struct device *dev;
dev = bus_find_device(&i2c_bus_type, NULL, node,
of_dev_node_match);
if (!dev)
return NULL;
return i2c_verify_adapter(dev);
}
EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Galaxy-Tab-S2/android_kernel_samsung_gts28wifi | net/netfilter/ipvs/ip_vs_lc.c | 2089 | 2466 | /*
* IPVS: Least-Connection Scheduling module
*
* Authors: Wensong Zhang <wensong@linuxvirtualserver.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.
*
* Changes:
* Wensong Zhang : added the ip_vs_lc_update_svc
* Wensong Zhang : added any dest with weight=0 is quiesced
*
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <net/ip_vs.h>
/*
* Least Connection scheduling
*/
static struct ip_vs_dest *
ip_vs_lc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb)
{
struct ip_vs_dest *dest, *least = NULL;
unsigned int loh = 0, doh;
IP_VS_DBG(6, "%s(): Scheduling...\n", __func__);
/*
* Simply select the server with the least number of
* (activeconns<<5) + inactconns
* Except whose weight is equal to zero.
* If the weight is equal to zero, it means that the server is
* quiesced, the existing connections to the server still get
* served, but no new connection is assigned to the server.
*/
list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
if ((dest->flags & IP_VS_DEST_F_OVERLOAD) ||
atomic_read(&dest->weight) == 0)
continue;
doh = ip_vs_dest_conn_overhead(dest);
if (!least || doh < loh) {
least = dest;
loh = doh;
}
}
if (!least)
ip_vs_scheduler_err(svc, "no destination available");
else
IP_VS_DBG_BUF(6, "LC: server %s:%u activeconns %d "
"inactconns %d\n",
IP_VS_DBG_ADDR(svc->af, &least->addr),
ntohs(least->port),
atomic_read(&least->activeconns),
atomic_read(&least->inactconns));
return least;
}
static struct ip_vs_scheduler ip_vs_lc_scheduler = {
.name = "lc",
.refcnt = ATOMIC_INIT(0),
.module = THIS_MODULE,
.n_list = LIST_HEAD_INIT(ip_vs_lc_scheduler.n_list),
.schedule = ip_vs_lc_schedule,
};
static int __init ip_vs_lc_init(void)
{
return register_ip_vs_scheduler(&ip_vs_lc_scheduler) ;
}
static void __exit ip_vs_lc_cleanup(void)
{
unregister_ip_vs_scheduler(&ip_vs_lc_scheduler);
synchronize_rcu();
}
module_init(ip_vs_lc_init);
module_exit(ip_vs_lc_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
uzairabdulmajeed/uam-kernel | drivers/zorro/proc.c | 2089 | 3772 | /*
* Procfs interface for the Zorro bus.
*
* Copyright (C) 1998-2003 Geert Uytterhoeven
*
* Heavily based on the procfs interface for the PCI bus, which is
*
* Copyright (C) 1997, 1998 Martin Mares <mj@atrey.karlin.mff.cuni.cz>
*/
#include <linux/types.h>
#include <linux/zorro.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/export.h>
#include <asm/uaccess.h>
#include <asm/amigahw.h>
#include <asm/setup.h>
static loff_t
proc_bus_zorro_lseek(struct file *file, loff_t off, int whence)
{
loff_t new = -1;
struct inode *inode = file_inode(file);
mutex_lock(&inode->i_mutex);
switch (whence) {
case 0:
new = off;
break;
case 1:
new = file->f_pos + off;
break;
case 2:
new = sizeof(struct ConfigDev) + off;
break;
}
if (new < 0 || new > sizeof(struct ConfigDev))
new = -EINVAL;
else
file->f_pos = new;
mutex_unlock(&inode->i_mutex);
return new;
}
static ssize_t
proc_bus_zorro_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
struct zorro_dev *z = PDE_DATA(file_inode(file));
struct ConfigDev cd;
loff_t pos = *ppos;
if (pos >= sizeof(struct ConfigDev))
return 0;
if (nbytes >= sizeof(struct ConfigDev))
nbytes = sizeof(struct ConfigDev);
if (pos + nbytes > sizeof(struct ConfigDev))
nbytes = sizeof(struct ConfigDev) - pos;
/* Construct a ConfigDev */
memset(&cd, 0, sizeof(cd));
cd.cd_Rom = z->rom;
cd.cd_SlotAddr = z->slotaddr;
cd.cd_SlotSize = z->slotsize;
cd.cd_BoardAddr = (void *)zorro_resource_start(z);
cd.cd_BoardSize = zorro_resource_len(z);
if (copy_to_user(buf, (void *)&cd + pos, nbytes))
return -EFAULT;
*ppos += nbytes;
return nbytes;
}
static const struct file_operations proc_bus_zorro_operations = {
.owner = THIS_MODULE,
.llseek = proc_bus_zorro_lseek,
.read = proc_bus_zorro_read,
};
static void * zorro_seq_start(struct seq_file *m, loff_t *pos)
{
return (*pos < zorro_num_autocon) ? pos : NULL;
}
static void * zorro_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return (*pos < zorro_num_autocon) ? pos : NULL;
}
static void zorro_seq_stop(struct seq_file *m, void *v)
{
}
static int zorro_seq_show(struct seq_file *m, void *v)
{
unsigned int slot = *(loff_t *)v;
struct zorro_dev *z = &zorro_autocon[slot];
seq_printf(m, "%02x\t%08x\t%08lx\t%08lx\t%02x\n", slot, z->id,
(unsigned long)zorro_resource_start(z),
(unsigned long)zorro_resource_len(z),
z->rom.er_Type);
return 0;
}
static const struct seq_operations zorro_devices_seq_ops = {
.start = zorro_seq_start,
.next = zorro_seq_next,
.stop = zorro_seq_stop,
.show = zorro_seq_show,
};
static int zorro_devices_proc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &zorro_devices_seq_ops);
}
static const struct file_operations zorro_devices_proc_fops = {
.owner = THIS_MODULE,
.open = zorro_devices_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static struct proc_dir_entry *proc_bus_zorro_dir;
static int __init zorro_proc_attach_device(unsigned int slot)
{
struct proc_dir_entry *entry;
char name[4];
sprintf(name, "%02x", slot);
entry = proc_create_data(name, 0, proc_bus_zorro_dir,
&proc_bus_zorro_operations,
&zorro_autocon[slot]);
if (!entry)
return -ENOMEM;
proc_set_size(entry, sizeof(struct zorro_dev));
return 0;
}
static int __init zorro_proc_init(void)
{
unsigned int slot;
if (MACH_IS_AMIGA && AMIGAHW_PRESENT(ZORRO)) {
proc_bus_zorro_dir = proc_mkdir("bus/zorro", NULL);
proc_create("devices", 0, proc_bus_zorro_dir,
&zorro_devices_proc_fops);
for (slot = 0; slot < zorro_num_autocon; slot++)
zorro_proc_attach_device(slot);
}
return 0;
}
device_initcall(zorro_proc_init);
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE551KL | kernel/drivers/zorro/proc.c | 2089 | 3772 | /*
* Procfs interface for the Zorro bus.
*
* Copyright (C) 1998-2003 Geert Uytterhoeven
*
* Heavily based on the procfs interface for the PCI bus, which is
*
* Copyright (C) 1997, 1998 Martin Mares <mj@atrey.karlin.mff.cuni.cz>
*/
#include <linux/types.h>
#include <linux/zorro.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/export.h>
#include <asm/uaccess.h>
#include <asm/amigahw.h>
#include <asm/setup.h>
static loff_t
proc_bus_zorro_lseek(struct file *file, loff_t off, int whence)
{
loff_t new = -1;
struct inode *inode = file_inode(file);
mutex_lock(&inode->i_mutex);
switch (whence) {
case 0:
new = off;
break;
case 1:
new = file->f_pos + off;
break;
case 2:
new = sizeof(struct ConfigDev) + off;
break;
}
if (new < 0 || new > sizeof(struct ConfigDev))
new = -EINVAL;
else
file->f_pos = new;
mutex_unlock(&inode->i_mutex);
return new;
}
static ssize_t
proc_bus_zorro_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
struct zorro_dev *z = PDE_DATA(file_inode(file));
struct ConfigDev cd;
loff_t pos = *ppos;
if (pos >= sizeof(struct ConfigDev))
return 0;
if (nbytes >= sizeof(struct ConfigDev))
nbytes = sizeof(struct ConfigDev);
if (pos + nbytes > sizeof(struct ConfigDev))
nbytes = sizeof(struct ConfigDev) - pos;
/* Construct a ConfigDev */
memset(&cd, 0, sizeof(cd));
cd.cd_Rom = z->rom;
cd.cd_SlotAddr = z->slotaddr;
cd.cd_SlotSize = z->slotsize;
cd.cd_BoardAddr = (void *)zorro_resource_start(z);
cd.cd_BoardSize = zorro_resource_len(z);
if (copy_to_user(buf, (void *)&cd + pos, nbytes))
return -EFAULT;
*ppos += nbytes;
return nbytes;
}
static const struct file_operations proc_bus_zorro_operations = {
.owner = THIS_MODULE,
.llseek = proc_bus_zorro_lseek,
.read = proc_bus_zorro_read,
};
static void * zorro_seq_start(struct seq_file *m, loff_t *pos)
{
return (*pos < zorro_num_autocon) ? pos : NULL;
}
static void * zorro_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return (*pos < zorro_num_autocon) ? pos : NULL;
}
static void zorro_seq_stop(struct seq_file *m, void *v)
{
}
static int zorro_seq_show(struct seq_file *m, void *v)
{
unsigned int slot = *(loff_t *)v;
struct zorro_dev *z = &zorro_autocon[slot];
seq_printf(m, "%02x\t%08x\t%08lx\t%08lx\t%02x\n", slot, z->id,
(unsigned long)zorro_resource_start(z),
(unsigned long)zorro_resource_len(z),
z->rom.er_Type);
return 0;
}
static const struct seq_operations zorro_devices_seq_ops = {
.start = zorro_seq_start,
.next = zorro_seq_next,
.stop = zorro_seq_stop,
.show = zorro_seq_show,
};
static int zorro_devices_proc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &zorro_devices_seq_ops);
}
static const struct file_operations zorro_devices_proc_fops = {
.owner = THIS_MODULE,
.open = zorro_devices_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static struct proc_dir_entry *proc_bus_zorro_dir;
static int __init zorro_proc_attach_device(unsigned int slot)
{
struct proc_dir_entry *entry;
char name[4];
sprintf(name, "%02x", slot);
entry = proc_create_data(name, 0, proc_bus_zorro_dir,
&proc_bus_zorro_operations,
&zorro_autocon[slot]);
if (!entry)
return -ENOMEM;
proc_set_size(entry, sizeof(struct zorro_dev));
return 0;
}
static int __init zorro_proc_init(void)
{
unsigned int slot;
if (MACH_IS_AMIGA && AMIGAHW_PRESENT(ZORRO)) {
proc_bus_zorro_dir = proc_mkdir("bus/zorro", NULL);
proc_create("devices", 0, proc_bus_zorro_dir,
&zorro_devices_proc_fops);
for (slot = 0; slot < zorro_num_autocon; slot++)
zorro_proc_attach_device(slot);
}
return 0;
}
device_initcall(zorro_proc_init);
| gpl-2.0 |
Electrex/Electroactive-N5 | arch/arm/mach-msm/avs.c | 3113 | 2027 | /*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <asm/mach-types.h>
#include <asm/cputype.h>
#include "avs.h"
#include "spm.h"
u32 avs_get_avscsr(void)
{
u32 val = 0;
asm volatile ("mrc p15, 7, %[avscsr], c15, c1, 7\n\t"
: [avscsr]"=r" (val)
);
return val;
}
EXPORT_SYMBOL(avs_get_avscsr);
void avs_set_avscsr(u32 avscsr)
{
asm volatile ("mcr p15, 7, %[avscsr], c15, c1, 7\n\t"
"isb\n\t"
:
: [avscsr]"r" (avscsr)
);
}
EXPORT_SYMBOL(avs_set_avscsr);
u32 avs_get_avsdscr(void)
{
u32 val = 0;
asm volatile ("mrc p15, 7, %[avsdscr], c15, c0, 6\n\t"
: [avsdscr]"=r" (val)
);
return val;
}
EXPORT_SYMBOL(avs_get_avsdscr);
void avs_set_avsdscr(u32 avsdscr)
{
asm volatile("mcr p15, 7, %[avsdscr], c15, c0, 6\n\t"
"isb\n\t"
:
: [avsdscr]"r" (avsdscr)
);
}
EXPORT_SYMBOL(avs_set_avsdscr);
static void avs_enable_local(void *data)
{
u32 avsdscr = (u32) data;
u32 avscsr_enable = 0x61;
avs_set_avsdscr(avsdscr);
avs_set_avscsr(avscsr_enable);
}
static void avs_disable_local(void *data)
{
int cpu = smp_processor_id();
avs_set_avscsr(0);
msm_spm_set_vdd(cpu, msm_spm_get_vdd(cpu));
}
void avs_enable(int cpu, u32 avsdscr)
{
int ret;
ret = smp_call_function_single(cpu, avs_enable_local,
(void *)avsdscr, true);
WARN_ON(ret);
}
EXPORT_SYMBOL(avs_enable);
void avs_disable(int cpu)
{
int ret;
ret = smp_call_function_single(cpu, avs_disable_local,
(void *) 0, true);
WARN_ON(ret);
}
EXPORT_SYMBOL(avs_disable);
| gpl-2.0 |
javilonas/Lonas_KL-GT-I9300-Sammy | arch/powerpc/platforms/iseries/hvlpconfig.c | 4649 | 1239 | /*
* Copyright (C) 2001 Kyle A. Lucke, IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <asm/iseries/hv_lp_config.h>
#include "it_lp_naca.h"
HvLpIndex HvLpConfig_getLpIndex_outline(void)
{
return HvLpConfig_getLpIndex();
}
EXPORT_SYMBOL(HvLpConfig_getLpIndex_outline);
HvLpIndex HvLpConfig_getLpIndex(void)
{
return itLpNaca.xLpIndex;
}
EXPORT_SYMBOL(HvLpConfig_getLpIndex);
HvLpIndex HvLpConfig_getPrimaryLpIndex(void)
{
return itLpNaca.xPrimaryLpIndex;
}
EXPORT_SYMBOL_GPL(HvLpConfig_getPrimaryLpIndex);
| gpl-2.0 |
kbc-developers/android_kernel_samsung_klte | drivers/media/radio/dsbr100.c | 4905 | 16552 | /* A driver for the D-Link DSB-R100 USB radio and Gemtek USB Radio 21.
The device plugs into both the USB and an analog audio input, so this thing
only deals with initialisation and frequency setting, the
audio data has to be handled by a sound driver.
Major issue: I can't find out where the device reports the signal
strength, and indeed the windows software appearantly just looks
at the stereo indicator as well. So, scanning will only find
stereo stations. Sad, but I can't help it.
Also, the windows program sends oodles of messages over to the
device, and I couldn't figure out their meaning. My suspicion
is that they don't have any:-)
You might find some interesting stuff about this module at
http://unimut.fsk.uni-heidelberg.de/unimut/demi/dsbr
Copyright (c) 2000 Markus Demleitner <msdemlei@cl.uni-heidelberg.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
History:
Version 0.46:
Removed usb_dsbr100_open/close calls and radio->users counter. Also,
radio->muted changed to radio->status and suspend/resume calls updated.
Version 0.45:
Converted to v4l2_device.
Version 0.44:
Add suspend/resume functions, fix unplug of device,
a lot of cleanups and fixes by Alexey Klimov <klimov.linux@gmail.com>
Version 0.43:
Oliver Neukum: avoided DMA coherency issue
Version 0.42:
Converted dsbr100 to use video_ioctl2
by Douglas Landgraf <dougsland@gmail.com>
Version 0.41-ac1:
Alan Cox: Some cleanups and fixes
Version 0.41:
Converted to V4L2 API by Mauro Carvalho Chehab <mchehab@infradead.org>
Version 0.40:
Markus: Updates for 2.6.x kernels, code layout changes, name sanitizing
Version 0.30:
Markus: Updates for 2.5.x kernel and more ISO compliant source
Version 0.25:
PSL and Markus: Cleanup, radio now doesn't stop on device close
Version 0.24:
Markus: Hope I got these silly VIDEO_TUNER_LOW issues finally
right. Some minor cleanup, improved standalone compilation
Version 0.23:
Markus: Sign extension bug fixed by declaring transfer_buffer unsigned
Version 0.22:
Markus: Some (brown bag) cleanup in what VIDIOCSTUNER returns,
thanks to Mike Cox for pointing the problem out.
Version 0.21:
Markus: Minor cleanup, warnings if something goes wrong, lame attempt
to adhere to Documentation/CodingStyle
Version 0.2:
Brad Hards <bradh@dynamite.com.au>: Fixes to make it work as non-module
Markus: Copyright clarification
Version 0.01: Markus: initial release
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <linux/usb.h>
/*
* Version Information
*/
#define DRIVER_VERSION "0.4.7"
#define DRIVER_AUTHOR "Markus Demleitner <msdemlei@tucana.harvard.edu>"
#define DRIVER_DESC "D-Link DSB-R100 USB FM radio driver"
#define DSB100_VENDOR 0x04b4
#define DSB100_PRODUCT 0x1002
/* Commands the device appears to understand */
#define DSB100_TUNE 1
#define DSB100_ONOFF 2
#define TB_LEN 16
/* Frequency limits in MHz -- these are European values. For Japanese
devices, that would be 76 and 91. */
#define FREQ_MIN 87.5
#define FREQ_MAX 108.0
#define FREQ_MUL 16000
/* defines for radio->status */
#define STARTED 0
#define STOPPED 1
#define v4l2_dev_to_radio(d) container_of(d, struct dsbr100_device, v4l2_dev)
static int usb_dsbr100_probe(struct usb_interface *intf,
const struct usb_device_id *id);
static void usb_dsbr100_disconnect(struct usb_interface *intf);
static int usb_dsbr100_suspend(struct usb_interface *intf,
pm_message_t message);
static int usb_dsbr100_resume(struct usb_interface *intf);
static int radio_nr = -1;
module_param(radio_nr, int, 0);
/* Data for one (physical) device */
struct dsbr100_device {
struct usb_device *usbdev;
struct video_device videodev;
struct v4l2_device v4l2_dev;
u8 *transfer_buffer;
struct mutex v4l2_lock;
int curfreq;
int stereo;
int status;
};
static struct usb_device_id usb_dsbr100_device_table [] = {
{ USB_DEVICE(DSB100_VENDOR, DSB100_PRODUCT) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, usb_dsbr100_device_table);
/* USB subsystem interface */
static struct usb_driver usb_dsbr100_driver = {
.name = "dsbr100",
.probe = usb_dsbr100_probe,
.disconnect = usb_dsbr100_disconnect,
.id_table = usb_dsbr100_device_table,
.suspend = usb_dsbr100_suspend,
.resume = usb_dsbr100_resume,
.reset_resume = usb_dsbr100_resume,
.supports_autosuspend = 0,
};
/* Low-level device interface begins here */
/* switch on radio */
static int dsbr100_start(struct dsbr100_device *radio)
{
int retval;
int request;
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
USB_REQ_GET_STATUS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x00, 0xC7, radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = USB_REQ_GET_STATUS;
goto usb_control_msg_failed;
}
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
DSB100_ONOFF,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x01, 0x00, radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = DSB100_ONOFF;
goto usb_control_msg_failed;
}
radio->status = STARTED;
return (radio->transfer_buffer)[0];
usb_control_msg_failed:
dev_err(&radio->usbdev->dev,
"%s - usb_control_msg returned %i, request %i\n",
__func__, retval, request);
return retval;
}
/* switch off radio */
static int dsbr100_stop(struct dsbr100_device *radio)
{
int retval;
int request;
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
USB_REQ_GET_STATUS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x16, 0x1C, radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = USB_REQ_GET_STATUS;
goto usb_control_msg_failed;
}
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
DSB100_ONOFF,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x00, 0x00, radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = DSB100_ONOFF;
goto usb_control_msg_failed;
}
radio->status = STOPPED;
return (radio->transfer_buffer)[0];
usb_control_msg_failed:
dev_err(&radio->usbdev->dev,
"%s - usb_control_msg returned %i, request %i\n",
__func__, retval, request);
return retval;
}
/* set a frequency, freq is defined by v4l's TUNER_LOW, i.e. 1/16th kHz */
static int dsbr100_setfreq(struct dsbr100_device *radio)
{
int retval;
int request;
int freq = (radio->curfreq / 16 * 80) / 1000 + 856;
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
DSB100_TUNE,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
(freq >> 8) & 0x00ff, freq & 0xff,
radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = DSB100_TUNE;
goto usb_control_msg_failed;
}
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
USB_REQ_GET_STATUS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x96, 0xB7, radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = USB_REQ_GET_STATUS;
goto usb_control_msg_failed;
}
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
USB_REQ_GET_STATUS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x00, 0x24, radio->transfer_buffer, 8, 300);
if (retval < 0) {
request = USB_REQ_GET_STATUS;
goto usb_control_msg_failed;
}
radio->stereo = !((radio->transfer_buffer)[0] & 0x01);
return (radio->transfer_buffer)[0];
usb_control_msg_failed:
radio->stereo = -1;
dev_err(&radio->usbdev->dev,
"%s - usb_control_msg returned %i, request %i\n",
__func__, retval, request);
return retval;
}
/* return the device status. This is, in effect, just whether it
sees a stereo signal or not. Pity. */
static void dsbr100_getstat(struct dsbr100_device *radio)
{
int retval;
retval = usb_control_msg(radio->usbdev,
usb_rcvctrlpipe(radio->usbdev, 0),
USB_REQ_GET_STATUS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x00 , 0x24, radio->transfer_buffer, 8, 300);
if (retval < 0) {
radio->stereo = -1;
dev_err(&radio->usbdev->dev,
"%s - usb_control_msg returned %i, request %i\n",
__func__, retval, USB_REQ_GET_STATUS);
} else {
radio->stereo = !(radio->transfer_buffer[0] & 0x01);
}
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
struct dsbr100_device *radio = video_drvdata(file);
strlcpy(v->driver, "dsbr100", sizeof(v->driver));
strlcpy(v->card, "D-Link R-100 USB FM Radio", sizeof(v->card));
usb_make_path(radio->usbdev, v->bus_info, sizeof(v->bus_info));
v->capabilities = V4L2_CAP_TUNER;
return 0;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct dsbr100_device *radio = video_drvdata(file);
if (v->index > 0)
return -EINVAL;
dsbr100_getstat(radio);
strcpy(v->name, "FM");
v->type = V4L2_TUNER_RADIO;
v->rangelow = FREQ_MIN * FREQ_MUL;
v->rangehigh = FREQ_MAX * FREQ_MUL;
v->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_STEREO;
v->capability = V4L2_TUNER_CAP_LOW;
if(radio->stereo)
v->audmode = V4L2_TUNER_MODE_STEREO;
else
v->audmode = V4L2_TUNER_MODE_MONO;
v->signal = 0xffff; /* We can't get the signal strength */
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct dsbr100_device *radio = video_drvdata(file);
int retval;
radio->curfreq = f->frequency;
retval = dsbr100_setfreq(radio);
if (retval < 0)
dev_warn(&radio->usbdev->dev, "Set frequency failed\n");
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct dsbr100_device *radio = video_drvdata(file);
f->type = V4L2_TUNER_RADIO;
f->frequency = radio->curfreq;
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_AUDIO_MUTE:
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 1);
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct dsbr100_device *radio = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
ctrl->value = radio->status;
return 0;
}
return -EINVAL;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct dsbr100_device *radio = video_drvdata(file);
int retval;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (ctrl->value) {
retval = dsbr100_stop(radio);
if (retval < 0) {
dev_warn(&radio->usbdev->dev,
"Radio did not respond properly\n");
return -EBUSY;
}
} else {
retval = dsbr100_start(radio);
if (retval < 0) {
dev_warn(&radio->usbdev->dev,
"Radio did not respond properly\n");
return -EBUSY;
}
}
return 0;
}
return -EINVAL;
}
static int vidioc_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
if (a->index > 1)
return -EINVAL;
strcpy(a->name, "Radio");
a->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static int vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *filp, void *priv, unsigned int i)
{
return i ? -EINVAL : 0;
}
static int vidioc_s_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
return a->index ? -EINVAL : 0;
}
/* USB subsystem interface begins here */
/*
* Handle unplugging of the device.
* We call video_unregister_device in any case.
* The last function called in this procedure is
* usb_dsbr100_video_device_release
*/
static void usb_dsbr100_disconnect(struct usb_interface *intf)
{
struct dsbr100_device *radio = usb_get_intfdata(intf);
v4l2_device_get(&radio->v4l2_dev);
mutex_lock(&radio->v4l2_lock);
usb_set_intfdata(intf, NULL);
video_unregister_device(&radio->videodev);
v4l2_device_disconnect(&radio->v4l2_dev);
mutex_unlock(&radio->v4l2_lock);
v4l2_device_put(&radio->v4l2_dev);
}
/* Suspend device - stop device. */
static int usb_dsbr100_suspend(struct usb_interface *intf, pm_message_t message)
{
struct dsbr100_device *radio = usb_get_intfdata(intf);
int retval;
mutex_lock(&radio->v4l2_lock);
if (radio->status == STARTED) {
retval = dsbr100_stop(radio);
if (retval < 0)
dev_warn(&intf->dev, "dsbr100_stop failed\n");
/* After dsbr100_stop() status set to STOPPED.
* If we want driver to start radio on resume
* we set status equal to STARTED.
* On resume we will check status and run radio if needed.
*/
radio->status = STARTED;
}
mutex_unlock(&radio->v4l2_lock);
dev_info(&intf->dev, "going into suspend..\n");
return 0;
}
/* Resume device - start device. */
static int usb_dsbr100_resume(struct usb_interface *intf)
{
struct dsbr100_device *radio = usb_get_intfdata(intf);
int retval;
mutex_lock(&radio->v4l2_lock);
if (radio->status == STARTED) {
retval = dsbr100_start(radio);
if (retval < 0)
dev_warn(&intf->dev, "dsbr100_start failed\n");
}
mutex_unlock(&radio->v4l2_lock);
dev_info(&intf->dev, "coming out of suspend..\n");
return 0;
}
/* free data structures */
static void usb_dsbr100_release(struct v4l2_device *v4l2_dev)
{
struct dsbr100_device *radio = v4l2_dev_to_radio(v4l2_dev);
v4l2_device_unregister(&radio->v4l2_dev);
kfree(radio->transfer_buffer);
kfree(radio);
}
/* File system interface */
static const struct v4l2_file_operations usb_dsbr100_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops usb_dsbr100_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
};
/* check if the device is present and register with v4l and usb if it is */
static int usb_dsbr100_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct dsbr100_device *radio;
struct v4l2_device *v4l2_dev;
int retval;
radio = kzalloc(sizeof(struct dsbr100_device), GFP_KERNEL);
if (!radio)
return -ENOMEM;
radio->transfer_buffer = kmalloc(TB_LEN, GFP_KERNEL);
if (!(radio->transfer_buffer)) {
kfree(radio);
return -ENOMEM;
}
v4l2_dev = &radio->v4l2_dev;
v4l2_dev->release = usb_dsbr100_release;
retval = v4l2_device_register(&intf->dev, v4l2_dev);
if (retval < 0) {
v4l2_err(v4l2_dev, "couldn't register v4l2_device\n");
kfree(radio->transfer_buffer);
kfree(radio);
return retval;
}
mutex_init(&radio->v4l2_lock);
strlcpy(radio->videodev.name, v4l2_dev->name, sizeof(radio->videodev.name));
radio->videodev.v4l2_dev = v4l2_dev;
radio->videodev.fops = &usb_dsbr100_fops;
radio->videodev.ioctl_ops = &usb_dsbr100_ioctl_ops;
radio->videodev.release = video_device_release_empty;
radio->videodev.lock = &radio->v4l2_lock;
radio->usbdev = interface_to_usbdev(intf);
radio->curfreq = FREQ_MIN * FREQ_MUL;
radio->status = STOPPED;
video_set_drvdata(&radio->videodev, radio);
retval = video_register_device(&radio->videodev, VFL_TYPE_RADIO, radio_nr);
if (retval < 0) {
v4l2_err(v4l2_dev, "couldn't register video device\n");
v4l2_device_unregister(v4l2_dev);
kfree(radio->transfer_buffer);
kfree(radio);
return -EIO;
}
usb_set_intfdata(intf, radio);
return 0;
}
module_usb_driver(usb_dsbr100_driver);
MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
| gpl-2.0 |
manishj-patel/netbook_kernel_3.4.5_plus | sound/core/isadma.c | 5417 | 3098 | /*
* ISA DMA support functions
* 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
*
*/
/*
* Defining following add some delay. Maybe this helps for some broken
* ISA DMA controllers.
*/
#undef HAVE_REALLY_SLOW_DMA_CONTROLLER
#include <linux/export.h>
#include <sound/core.h>
#include <asm/dma.h>
/**
* snd_dma_program - program an ISA DMA transfer
* @dma: the dma number
* @addr: the physical address of the buffer
* @size: the DMA transfer size
* @mode: the DMA transfer mode, DMA_MODE_XXX
*
* Programs an ISA DMA transfer for the given buffer.
*/
void snd_dma_program(unsigned long dma,
unsigned long addr, unsigned int size,
unsigned short mode)
{
unsigned long flags;
flags = claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma, mode);
set_dma_addr(dma, addr);
set_dma_count(dma, size);
if (!(mode & DMA_MODE_NO_ENABLE))
enable_dma(dma);
release_dma_lock(flags);
}
EXPORT_SYMBOL(snd_dma_program);
/**
* snd_dma_disable - stop the ISA DMA transfer
* @dma: the dma number
*
* Stops the ISA DMA transfer.
*/
void snd_dma_disable(unsigned long dma)
{
unsigned long flags;
flags = claim_dma_lock();
clear_dma_ff(dma);
disable_dma(dma);
release_dma_lock(flags);
}
EXPORT_SYMBOL(snd_dma_disable);
/**
* snd_dma_pointer - return the current pointer to DMA transfer buffer in bytes
* @dma: the dma number
* @size: the dma transfer size
*
* Returns the current pointer in DMA tranfer buffer in bytes
*/
unsigned int snd_dma_pointer(unsigned long dma, unsigned int size)
{
unsigned long flags;
unsigned int result, result1;
flags = claim_dma_lock();
clear_dma_ff(dma);
if (!isa_dma_bridge_buggy)
disable_dma(dma);
result = get_dma_residue(dma);
/*
* HACK - read the counter again and choose higher value in order to
* avoid reading during counter lower byte roll over if the
* isa_dma_bridge_buggy is set.
*/
result1 = get_dma_residue(dma);
if (!isa_dma_bridge_buggy)
enable_dma(dma);
release_dma_lock(flags);
if (unlikely(result < result1))
result = result1;
#ifdef CONFIG_SND_DEBUG
if (result > size)
snd_printk(KERN_ERR "pointer (0x%x) for DMA #%ld is greater than transfer size (0x%x)\n", result, dma, size);
#endif
if (result >= size || result == 0)
return 0;
else
return size - result;
}
EXPORT_SYMBOL(snd_dma_pointer);
| gpl-2.0 |
Think-Silicon/linux-thinksilicon | arch/x86/platform/efi/efi_32.c | 7209 | 1754 | /*
* Extensible Firmware Interface
*
* Based on Extensible Firmware Interface Specification version 1.0
*
* Copyright (C) 1999 VA Linux Systems
* Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
* Copyright (C) 1999-2002 Hewlett-Packard Co.
* David Mosberger-Tang <davidm@hpl.hp.com>
* Stephane Eranian <eranian@hpl.hp.com>
*
* All EFI Runtime Services are not implemented yet as EFI only
* supports physical mode addressing on SoftSDV. This is to be fixed
* in a future version. --drummond 1999-07-20
*
* Implemented EFI runtime services and virtual mode calls. --davidm
*
* Goutham Rao: <goutham.rao@intel.com>
* Skip non-WB memory and ignore empty memory ranges.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/efi.h>
#include <asm/io.h>
#include <asm/desc.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include <asm/efi.h>
/*
* To make EFI call EFI runtime service in physical addressing mode we need
* prelog/epilog before/after the invocation to disable interrupt, to
* claim EFI runtime service handler exclusively and to duplicate a memory in
* low memory space say 0 - 3G.
*/
static unsigned long efi_rt_eflags;
void efi_call_phys_prelog(void)
{
struct desc_ptr gdt_descr;
local_irq_save(efi_rt_eflags);
load_cr3(initial_page_table);
__flush_tlb_all();
gdt_descr.address = __pa(get_cpu_gdt_table(0));
gdt_descr.size = GDT_SIZE - 1;
load_gdt(&gdt_descr);
}
void efi_call_phys_epilog(void)
{
struct desc_ptr gdt_descr;
gdt_descr.address = (unsigned long)get_cpu_gdt_table(0);
gdt_descr.size = GDT_SIZE - 1;
load_gdt(&gdt_descr);
load_cr3(swapper_pg_dir);
__flush_tlb_all();
local_irq_restore(efi_rt_eflags);
}
| gpl-2.0 |
zetalabs/linux-3.4-clover | drivers/isdn/hardware/eicon/debug.c | 9257 | 63069 | #include "platform.h"
#include "pc.h"
#include "di_defs.h"
#include "debug_if.h"
#include "divasync.h"
#include "kst_ifc.h"
#include "maintidi.h"
#include "man_defs.h"
/*
LOCALS
*/
#define DBG_MAGIC (0x47114711L)
static void DI_register(void *arg);
static void DI_deregister(pDbgHandle hDbg);
static void DI_format(int do_lock, word id, int type, char *format, va_list argument_list);
static void DI_format_locked(word id, int type, char *format, va_list argument_list);
static void DI_format_old(word id, char *format, va_list ap) { }
static void DiProcessEventLog(unsigned short id, unsigned long msgID, va_list ap) { }
static void single_p(byte *P, word *PLength, byte Id);
static void diva_maint_xdi_cb(ENTITY *e);
static word SuperTraceCreateReadReq(byte *P, const char *path);
static int diva_mnt_cmp_nmbr(const char *nmbr);
static void diva_free_dma_descriptor(IDI_CALL request, int nr);
static int diva_get_dma_descriptor(IDI_CALL request, dword *dma_magic);
void diva_mnt_internal_dprintf(dword drv_id, dword type, char *p, ...);
static dword MaxDumpSize = 256;
static dword MaxXlogSize = 2 + 128;
static char TraceFilter[DIVA_MAX_SELECTIVE_FILTER_LENGTH + 1];
static int TraceFilterIdent = -1;
static int TraceFilterChannel = -1;
typedef struct _diva_maint_client {
dword sec;
dword usec;
pDbgHandle hDbg;
char drvName[128];
dword dbgMask;
dword last_dbgMask;
IDI_CALL request;
_DbgHandle_ Dbg;
int logical;
int channels;
diva_strace_library_interface_t *pIdiLib;
BUFFERS XData;
char xbuffer[2048 + 512];
byte *pmem;
int request_pending;
int dma_handle;
} diva_maint_client_t;
static diva_maint_client_t clients[MAX_DESCRIPTORS];
static void diva_change_management_debug_mask(diva_maint_client_t *pC, dword old_mask);
static void diva_maint_error(void *user_context,
diva_strace_library_interface_t *hLib,
int Adapter,
int error,
const char *file,
int line);
static void diva_maint_state_change_notify(void *user_context,
diva_strace_library_interface_t *hLib,
int Adapter,
diva_trace_line_state_t *channel,
int notify_subject);
static void diva_maint_trace_notify(void *user_context,
diva_strace_library_interface_t *hLib,
int Adapter,
void *xlog_buffer,
int length);
typedef struct MSG_QUEUE {
dword Size; /* total size of queue (constant) */
byte *Base; /* lowest address (constant) */
byte *High; /* Base + Size (constant) */
byte *Head; /* first message in queue (if any) */
byte *Tail; /* first free position */
byte *Wrap; /* current wraparound position */
dword Count; /* current no of bytes in queue */
} MSG_QUEUE;
typedef struct MSG_HEAD {
volatile dword Size; /* size of data following MSG_HEAD */
#define MSG_INCOMPLETE 0x8000 /* ored to Size until queueCompleteMsg */
} MSG_HEAD;
#define queueCompleteMsg(p) do { ((MSG_HEAD *)p - 1)->Size &= ~MSG_INCOMPLETE; } while (0)
#define queueCount(q) ((q)->Count)
#define MSG_NEED(size) \
((sizeof(MSG_HEAD) + size + sizeof(dword) - 1) & ~(sizeof(dword) - 1))
static void queueInit(MSG_QUEUE *Q, byte *Buffer, dword sizeBuffer) {
Q->Size = sizeBuffer;
Q->Base = Q->Head = Q->Tail = Buffer;
Q->High = Buffer + sizeBuffer;
Q->Wrap = NULL;
Q->Count = 0;
}
static byte *queueAllocMsg(MSG_QUEUE *Q, word size) {
/* Allocate 'size' bytes at tail of queue which will be filled later
* directly with callers own message header info and/or message.
* An 'alloced' message is marked incomplete by oring the 'Size' field
* with MSG_INCOMPLETE.
* This must be reset via queueCompleteMsg() after the message is filled.
* As long as a message is marked incomplete queuePeekMsg() will return
* a 'queue empty' condition when it reaches such a message. */
MSG_HEAD *Msg;
word need = MSG_NEED(size);
if (Q->Tail == Q->Head) {
if (Q->Wrap || need > Q->Size) {
return NULL; /* full */
}
goto alloc; /* empty */
}
if (Q->Tail > Q->Head) {
if (Q->Tail + need <= Q->High) goto alloc; /* append */
if (Q->Base + need > Q->Head) {
return NULL; /* too much */
}
/* wraparound the queue (but not the message) */
Q->Wrap = Q->Tail;
Q->Tail = Q->Base;
goto alloc;
}
if (Q->Tail + need > Q->Head) {
return NULL; /* too much */
}
alloc:
Msg = (MSG_HEAD *)Q->Tail;
Msg->Size = size | MSG_INCOMPLETE;
Q->Tail += need;
Q->Count += size;
return ((byte *)(Msg + 1));
}
static void queueFreeMsg(MSG_QUEUE *Q) {
/* Free the message at head of queue */
word size = ((MSG_HEAD *)Q->Head)->Size & ~MSG_INCOMPLETE;
Q->Head += MSG_NEED(size);
Q->Count -= size;
if (Q->Wrap) {
if (Q->Head >= Q->Wrap) {
Q->Head = Q->Base;
Q->Wrap = NULL;
}
} else if (Q->Head >= Q->Tail) {
Q->Head = Q->Tail = Q->Base;
}
}
static byte *queuePeekMsg(MSG_QUEUE *Q, word *size) {
/* Show the first valid message in queue BUT DON'T free the message.
* After looking on the message contents it can be freed queueFreeMsg()
* or simply remain in message queue. */
MSG_HEAD *Msg = (MSG_HEAD *)Q->Head;
if (((byte *)Msg == Q->Tail && !Q->Wrap) ||
(Msg->Size & MSG_INCOMPLETE)) {
return NULL;
} else {
*size = Msg->Size;
return ((byte *)(Msg + 1));
}
}
/*
Message queue header
*/
static MSG_QUEUE *dbg_queue;
static byte *dbg_base;
static int external_dbg_queue;
static diva_os_spin_lock_t dbg_q_lock;
static diva_os_spin_lock_t dbg_adapter_lock;
static int dbg_q_busy;
static volatile dword dbg_sequence;
static dword start_sec;
static dword start_usec;
/*
INTERFACE:
Initialize run time queue structures.
base: base of the message queue
length: length of the message queue
do_init: perfor queue reset
return: zero on success, -1 on error
*/
int diva_maint_init(byte *base, unsigned long length, int do_init) {
if (dbg_queue || (!base) || (length < (4096 * 4))) {
return (-1);
}
TraceFilter[0] = 0;
TraceFilterIdent = -1;
TraceFilterChannel = -1;
dbg_base = base;
diva_os_get_time(&start_sec, &start_usec);
*(dword *)base = (dword)DBG_MAGIC; /* Store Magic */
base += sizeof(dword);
length -= sizeof(dword);
*(dword *)base = 2048; /* Extension Field Length */
base += sizeof(dword);
length -= sizeof(dword);
strcpy(base, "KERNEL MODE BUFFER\n");
base += 2048;
length -= 2048;
*(dword *)base = 0; /* Terminate extension */
base += sizeof(dword);
length -= sizeof(dword);
*(void **)base = (void *)(base + sizeof(void *)); /* Store Base */
base += sizeof(void *);
length -= sizeof(void *);
dbg_queue = (MSG_QUEUE *)base;
queueInit(dbg_queue, base + sizeof(MSG_QUEUE), length - sizeof(MSG_QUEUE) - 512);
external_dbg_queue = 0;
if (!do_init) {
external_dbg_queue = 1; /* memory was located on the external device */
}
if (diva_os_initialize_spin_lock(&dbg_q_lock, "dbg_init")) {
dbg_queue = NULL;
dbg_base = NULL;
external_dbg_queue = 0;
return (-1);
}
if (diva_os_initialize_spin_lock(&dbg_adapter_lock, "dbg_init")) {
diva_os_destroy_spin_lock(&dbg_q_lock, "dbg_init");
dbg_queue = NULL;
dbg_base = NULL;
external_dbg_queue = 0;
return (-1);
}
return (0);
}
/*
INTERFACE:
Finit at unload time
return address of internal queue or zero if queue
was external
*/
void *diva_maint_finit(void) {
void *ret = (void *)dbg_base;
int i;
dbg_queue = NULL;
dbg_base = NULL;
if (ret) {
diva_os_destroy_spin_lock(&dbg_q_lock, "dbg_finit");
diva_os_destroy_spin_lock(&dbg_adapter_lock, "dbg_finit");
}
if (external_dbg_queue) {
ret = NULL;
}
external_dbg_queue = 0;
for (i = 1; i < ARRAY_SIZE(clients); i++) {
if (clients[i].pmem) {
diva_os_free(0, clients[i].pmem);
}
}
return (ret);
}
/*
INTERFACE:
Return amount of messages in debug queue
*/
dword diva_dbg_q_length(void) {
return (dbg_queue ? queueCount(dbg_queue) : 0);
}
/*
INTERFACE:
Lock message queue and return the pointer to the first
entry.
*/
diva_dbg_entry_head_t *diva_maint_get_message(word *size,
diva_os_spin_lock_magic_t *old_irql) {
diva_dbg_entry_head_t *pmsg = NULL;
diva_os_enter_spin_lock(&dbg_q_lock, old_irql, "read");
if (dbg_q_busy) {
diva_os_leave_spin_lock(&dbg_q_lock, old_irql, "read_busy");
return NULL;
}
dbg_q_busy = 1;
if (!(pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, size))) {
dbg_q_busy = 0;
diva_os_leave_spin_lock(&dbg_q_lock, old_irql, "read_empty");
}
return (pmsg);
}
/*
INTERFACE:
acknowledge last message and unlock queue
*/
void diva_maint_ack_message(int do_release,
diva_os_spin_lock_magic_t *old_irql) {
if (!dbg_q_busy) {
return;
}
if (do_release) {
queueFreeMsg(dbg_queue);
}
dbg_q_busy = 0;
diva_os_leave_spin_lock(&dbg_q_lock, old_irql, "read_ack");
}
/*
INTERFACE:
PRT COMP function used to register
with MAINT adapter or log in compatibility
mode in case older driver version is connected too
*/
void diva_maint_prtComp(char *format, ...) {
void *hDbg;
va_list ap;
if (!format)
return;
va_start(ap, format);
/*
register to new log driver functions
*/
if ((format[0] == 0) && ((unsigned char)format[1] == 255)) {
hDbg = va_arg(ap, void *); /* ptr to DbgHandle */
DI_register(hDbg);
}
va_end(ap);
}
static void DI_register(void *arg) {
diva_os_spin_lock_magic_t old_irql;
dword sec, usec;
pDbgHandle hDbg;
int id, free_id = -1, best_id = 0;
diva_os_get_time(&sec, &usec);
hDbg = (pDbgHandle)arg;
/*
Check for bad args, specially for the old obsolete debug handle
*/
if ((hDbg == NULL) ||
((hDbg->id == 0) && (((_OldDbgHandle_ *)hDbg)->id == -1)) ||
(hDbg->Registered != 0)) {
return;
}
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "register");
for (id = 1; id < ARRAY_SIZE(clients); id++) {
if (clients[id].hDbg == hDbg) {
/*
driver already registered
*/
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "register");
return;
}
if (clients[id].hDbg) { /* slot is busy */
continue;
}
free_id = id;
if (!strcmp(clients[id].drvName, hDbg->drvName)) {
/*
This driver was already registered with this name
and slot is still free - reuse it
*/
best_id = 1;
break;
}
if (!clients[id].hDbg) { /* slot is busy */
break;
}
}
if (free_id != -1) {
diva_dbg_entry_head_t *pmsg = NULL;
int len;
char tmp[256];
word size;
/*
Register new driver with id == free_id
*/
clients[free_id].hDbg = hDbg;
clients[free_id].sec = sec;
clients[free_id].usec = usec;
strcpy(clients[free_id].drvName, hDbg->drvName);
clients[free_id].dbgMask = hDbg->dbgMask;
if (best_id) {
hDbg->dbgMask |= clients[free_id].last_dbgMask;
} else {
clients[free_id].last_dbgMask = 0;
}
hDbg->Registered = DBG_HANDLE_REG_NEW;
hDbg->id = (byte)free_id;
hDbg->dbg_end = DI_deregister;
hDbg->dbg_prt = DI_format_locked;
hDbg->dbg_ev = DiProcessEventLog;
hDbg->dbg_irq = DI_format_locked;
if (hDbg->Version > 0) {
hDbg->dbg_old = DI_format_old;
}
hDbg->next = (pDbgHandle)DBG_MAGIC;
/*
Log driver register, MAINT driver ID is '0'
*/
len = sprintf(tmp, "DIMAINT - drv # %d = '%s' registered",
free_id, hDbg->drvName);
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)(len + 1 + sizeof(*pmsg))))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_STRING;
pmsg->dli = DLI_REG;
pmsg->drv_id = 0; /* id 0 - DIMAINT */
pmsg->di_cpu = 0;
pmsg->data_length = len + 1;
memcpy(&pmsg[1], tmp, len + 1);
queueCompleteMsg(pmsg);
diva_maint_wakeup_read();
}
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "register");
}
static void DI_deregister(pDbgHandle hDbg) {
diva_os_spin_lock_magic_t old_irql, old_irql1;
dword sec, usec;
int i;
word size;
byte *pmem = NULL;
diva_os_get_time(&sec, &usec);
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "read");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "read");
for (i = 1; i < ARRAY_SIZE(clients); i++) {
if (clients[i].hDbg == hDbg) {
diva_dbg_entry_head_t *pmsg;
char tmp[256];
int len;
clients[i].hDbg = NULL;
hDbg->id = -1;
hDbg->dbgMask = 0;
hDbg->dbg_end = NULL;
hDbg->dbg_prt = NULL;
hDbg->dbg_irq = NULL;
if (hDbg->Version > 0)
hDbg->dbg_old = NULL;
hDbg->Registered = 0;
hDbg->next = NULL;
if (clients[i].pIdiLib) {
(*(clients[i].pIdiLib->DivaSTraceLibraryFinit))(clients[i].pIdiLib->hLib);
clients[i].pIdiLib = NULL;
pmem = clients[i].pmem;
clients[i].pmem = NULL;
}
/*
Log driver register, MAINT driver ID is '0'
*/
len = sprintf(tmp, "DIMAINT - drv # %d = '%s' de-registered",
i, hDbg->drvName);
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)(len + 1 + sizeof(*pmsg))))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_STRING;
pmsg->dli = DLI_REG;
pmsg->drv_id = 0; /* id 0 - DIMAINT */
pmsg->di_cpu = 0;
pmsg->data_length = len + 1;
memcpy(&pmsg[1], tmp, len + 1);
queueCompleteMsg(pmsg);
diva_maint_wakeup_read();
}
break;
}
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "read_ack");
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "read_ack");
if (pmem) {
diva_os_free(0, pmem);
}
}
static void DI_format_locked(unsigned short id,
int type,
char *format,
va_list argument_list) {
DI_format(1, id, type, format, argument_list);
}
static void DI_format(int do_lock,
unsigned short id,
int type,
char *format,
va_list ap) {
diva_os_spin_lock_magic_t old_irql;
dword sec, usec;
diva_dbg_entry_head_t *pmsg = NULL;
dword length;
word size;
static char fmtBuf[MSG_FRAME_MAX_SIZE + sizeof(*pmsg) + 1];
char *data;
unsigned short code;
if (diva_os_in_irq()) {
dbg_sequence++;
return;
}
if ((!format) ||
((TraceFilter[0] != 0) && ((TraceFilterIdent < 0) || (TraceFilterChannel < 0)))) {
return;
}
diva_os_get_time(&sec, &usec);
if (do_lock) {
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "format");
}
switch (type) {
case DLI_MXLOG:
case DLI_BLK:
case DLI_SEND:
case DLI_RECV:
if (!(length = va_arg(ap, unsigned long))) {
break;
}
if (length > MaxDumpSize) {
length = MaxDumpSize;
}
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)length + sizeof(*pmsg)))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
memcpy(&pmsg[1], format, length);
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_BINARY;
pmsg->dli = type; /* DLI_XXX */
pmsg->drv_id = id; /* driver MAINT id */
pmsg->di_cpu = 0;
pmsg->data_length = length;
queueCompleteMsg(pmsg);
}
break;
case DLI_XLOG: {
byte *p;
data = va_arg(ap, char *);
code = (unsigned short)va_arg(ap, unsigned int);
length = (unsigned long)va_arg(ap, unsigned int);
if (length > MaxXlogSize)
length = MaxXlogSize;
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)length + sizeof(*pmsg) + 2))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
p = (byte *)&pmsg[1];
p[0] = (char)(code);
p[1] = (char)(code >> 8);
if (data && length) {
memcpy(&p[2], &data[0], length);
}
length += 2;
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_BINARY;
pmsg->dli = type; /* DLI_XXX */
pmsg->drv_id = id; /* driver MAINT id */
pmsg->di_cpu = 0;
pmsg->data_length = length;
queueCompleteMsg(pmsg);
}
} break;
case DLI_LOG:
case DLI_FTL:
case DLI_ERR:
case DLI_TRC:
case DLI_REG:
case DLI_MEM:
case DLI_SPL:
case DLI_IRP:
case DLI_TIM:
case DLI_TAPI:
case DLI_NDIS:
case DLI_CONN:
case DLI_STAT:
case DLI_PRV0:
case DLI_PRV1:
case DLI_PRV2:
case DLI_PRV3:
if ((length = (unsigned long)vsprintf(&fmtBuf[0], format, ap)) > 0) {
length += (sizeof(*pmsg) + 1);
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)length))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_STRING;
pmsg->dli = type; /* DLI_XXX */
pmsg->drv_id = id; /* driver MAINT id */
pmsg->di_cpu = 0;
pmsg->data_length = length - sizeof(*pmsg);
memcpy(&pmsg[1], fmtBuf, pmsg->data_length);
queueCompleteMsg(pmsg);
}
break;
} /* switch type */
if (queueCount(dbg_queue)) {
diva_maint_wakeup_read();
}
if (do_lock) {
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "format");
}
}
/*
Write driver ID and driver revision to callers buffer
*/
int diva_get_driver_info(dword id, byte *data, int data_length) {
diva_os_spin_lock_magic_t old_irql;
byte *p = data;
int to_copy;
if (!data || !id || (data_length < 17) ||
(id >= ARRAY_SIZE(clients))) {
return (-1);
}
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "driver info");
if (clients[id].hDbg) {
*p++ = 1;
*p++ = (byte)clients[id].sec; /* save seconds */
*p++ = (byte)(clients[id].sec >> 8);
*p++ = (byte)(clients[id].sec >> 16);
*p++ = (byte)(clients[id].sec >> 24);
*p++ = (byte)(clients[id].usec / 1000); /* save mseconds */
*p++ = (byte)((clients[id].usec / 1000) >> 8);
*p++ = (byte)((clients[id].usec / 1000) >> 16);
*p++ = (byte)((clients[id].usec / 1000) >> 24);
data_length -= 9;
if ((to_copy = min(strlen(clients[id].drvName), (size_t)(data_length - 1)))) {
memcpy(p, clients[id].drvName, to_copy);
p += to_copy;
data_length -= to_copy;
if ((data_length >= 4) && clients[id].hDbg->drvTag[0]) {
*p++ = '(';
data_length -= 1;
if ((to_copy = min(strlen(clients[id].hDbg->drvTag), (size_t)(data_length - 2)))) {
memcpy(p, clients[id].hDbg->drvTag, to_copy);
p += to_copy;
data_length -= to_copy;
if (data_length >= 2) {
*p++ = ')';
data_length--;
}
}
}
}
}
*p++ = 0;
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "driver info");
return (p - data);
}
int diva_get_driver_dbg_mask(dword id, byte *data) {
diva_os_spin_lock_magic_t old_irql;
int ret = -1;
if (!data || !id || (id >= ARRAY_SIZE(clients))) {
return (-1);
}
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "driver info");
if (clients[id].hDbg) {
ret = 4;
*data++ = (byte)(clients[id].hDbg->dbgMask);
*data++ = (byte)(clients[id].hDbg->dbgMask >> 8);
*data++ = (byte)(clients[id].hDbg->dbgMask >> 16);
*data++ = (byte)(clients[id].hDbg->dbgMask >> 24);
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "driver info");
return (ret);
}
int diva_set_driver_dbg_mask(dword id, dword mask) {
diva_os_spin_lock_magic_t old_irql, old_irql1;
int ret = -1;
if (!id || (id >= ARRAY_SIZE(clients))) {
return (-1);
}
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "dbg mask");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "dbg mask");
if (clients[id].hDbg) {
dword old_mask = clients[id].hDbg->dbgMask;
mask &= 0x7fffffff;
clients[id].hDbg->dbgMask = mask;
clients[id].last_dbgMask = (clients[id].hDbg->dbgMask | clients[id].dbgMask);
ret = 4;
diva_change_management_debug_mask(&clients[id], old_mask);
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "dbg mask");
if (clients[id].request_pending) {
clients[id].request_pending = 0;
(*(clients[id].request))((ENTITY *)(*(clients[id].pIdiLib->DivaSTraceGetHandle))(clients[id].pIdiLib->hLib));
}
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "dbg mask");
return (ret);
}
static int diva_get_idi_adapter_info(IDI_CALL request, dword *serial, dword *logical) {
IDI_SYNC_REQ sync_req;
sync_req.xdi_logical_adapter_number.Req = 0;
sync_req.xdi_logical_adapter_number.Rc = IDI_SYNC_REQ_XDI_GET_LOGICAL_ADAPTER_NUMBER;
(*request)((ENTITY *)&sync_req);
*logical = sync_req.xdi_logical_adapter_number.info.logical_adapter_number;
sync_req.GetSerial.Req = 0;
sync_req.GetSerial.Rc = IDI_SYNC_REQ_GET_SERIAL;
sync_req.GetSerial.serial = 0;
(*request)((ENTITY *)&sync_req);
*serial = sync_req.GetSerial.serial;
return (0);
}
/*
Register XDI adapter as MAINT compatible driver
*/
void diva_mnt_add_xdi_adapter(const DESCRIPTOR *d) {
diva_os_spin_lock_magic_t old_irql, old_irql1;
dword sec, usec, logical, serial, org_mask;
int id, free_id = -1;
char tmp[128];
diva_dbg_entry_head_t *pmsg = NULL;
int len;
word size;
byte *pmem;
diva_os_get_time(&sec, &usec);
diva_get_idi_adapter_info(d->request, &serial, &logical);
if (serial & 0xff000000) {
sprintf(tmp, "ADAPTER:%d SN:%u-%d",
(int)logical,
serial & 0x00ffffff,
(byte)(((serial & 0xff000000) >> 24) + 1));
} else {
sprintf(tmp, "ADAPTER:%d SN:%u", (int)logical, serial);
}
if (!(pmem = diva_os_malloc(0, DivaSTraceGetMemotyRequirement(d->channels)))) {
return;
}
memset(pmem, 0x00, DivaSTraceGetMemotyRequirement(d->channels));
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "register");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "register");
for (id = 1; id < ARRAY_SIZE(clients); id++) {
if (clients[id].hDbg && (clients[id].request == d->request)) {
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "register");
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "register");
diva_os_free(0, pmem);
return;
}
if (clients[id].hDbg) { /* slot is busy */
continue;
}
if (free_id < 0) {
free_id = id;
}
if (!strcmp(clients[id].drvName, tmp)) {
/*
This driver was already registered with this name
and slot is still free - reuse it
*/
free_id = id;
break;
}
}
if (free_id < 0) {
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "register");
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "register");
diva_os_free(0, pmem);
return;
}
id = free_id;
clients[id].request = d->request;
clients[id].request_pending = 0;
clients[id].hDbg = &clients[id].Dbg;
clients[id].sec = sec;
clients[id].usec = usec;
strcpy(clients[id].drvName, tmp);
strcpy(clients[id].Dbg.drvName, tmp);
clients[id].Dbg.drvTag[0] = 0;
clients[id].logical = (int)logical;
clients[id].channels = (int)d->channels;
clients[id].dma_handle = -1;
clients[id].Dbg.dbgMask = 0;
clients[id].dbgMask = clients[id].Dbg.dbgMask;
if (id) {
clients[id].Dbg.dbgMask |= clients[free_id].last_dbgMask;
} else {
clients[id].last_dbgMask = 0;
}
clients[id].Dbg.Registered = DBG_HANDLE_REG_NEW;
clients[id].Dbg.id = (byte)id;
clients[id].Dbg.dbg_end = DI_deregister;
clients[id].Dbg.dbg_prt = DI_format_locked;
clients[id].Dbg.dbg_ev = DiProcessEventLog;
clients[id].Dbg.dbg_irq = DI_format_locked;
clients[id].Dbg.next = (pDbgHandle)DBG_MAGIC;
{
diva_trace_library_user_interface_t diva_maint_user_ifc = { &clients[id],
diva_maint_state_change_notify,
diva_maint_trace_notify,
diva_maint_error };
/*
Attach to adapter management interface
*/
if ((clients[id].pIdiLib =
DivaSTraceLibraryCreateInstance((int)logical, &diva_maint_user_ifc, pmem))) {
if (((*(clients[id].pIdiLib->DivaSTraceLibraryStart))(clients[id].pIdiLib->hLib))) {
diva_mnt_internal_dprintf(0, DLI_ERR, "Adapter(%d) Start failed", (int)logical);
(*(clients[id].pIdiLib->DivaSTraceLibraryFinit))(clients[id].pIdiLib->hLib);
clients[id].pIdiLib = NULL;
}
} else {
diva_mnt_internal_dprintf(0, DLI_ERR, "A(%d) management init failed", (int)logical);
}
}
if (!clients[id].pIdiLib) {
clients[id].request = NULL;
clients[id].request_pending = 0;
clients[id].hDbg = NULL;
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "register");
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "register");
diva_os_free(0, pmem);
return;
}
/*
Log driver register, MAINT driver ID is '0'
*/
len = sprintf(tmp, "DIMAINT - drv # %d = '%s' registered",
id, clients[id].Dbg.drvName);
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)(len + 1 + sizeof(*pmsg))))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_STRING;
pmsg->dli = DLI_REG;
pmsg->drv_id = 0; /* id 0 - DIMAINT */
pmsg->di_cpu = 0;
pmsg->data_length = len + 1;
memcpy(&pmsg[1], tmp, len + 1);
queueCompleteMsg(pmsg);
diva_maint_wakeup_read();
}
org_mask = clients[id].Dbg.dbgMask;
clients[id].Dbg.dbgMask = 0;
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "register");
if (clients[id].request_pending) {
clients[id].request_pending = 0;
(*(clients[id].request))((ENTITY *)(*(clients[id].pIdiLib->DivaSTraceGetHandle))(clients[id].pIdiLib->hLib));
}
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "register");
diva_set_driver_dbg_mask(id, org_mask);
}
/*
De-Register XDI adapter
*/
void diva_mnt_remove_xdi_adapter(const DESCRIPTOR *d) {
diva_os_spin_lock_magic_t old_irql, old_irql1;
dword sec, usec;
int i;
word size;
byte *pmem = NULL;
diva_os_get_time(&sec, &usec);
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "read");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "read");
for (i = 1; i < ARRAY_SIZE(clients); i++) {
if (clients[i].hDbg && (clients[i].request == d->request)) {
diva_dbg_entry_head_t *pmsg;
char tmp[256];
int len;
if (clients[i].pIdiLib) {
(*(clients[i].pIdiLib->DivaSTraceLibraryFinit))(clients[i].pIdiLib->hLib);
clients[i].pIdiLib = NULL;
pmem = clients[i].pmem;
clients[i].pmem = NULL;
}
clients[i].hDbg = NULL;
clients[i].request_pending = 0;
if (clients[i].dma_handle >= 0) {
/*
Free DMA handle
*/
diva_free_dma_descriptor(clients[i].request, clients[i].dma_handle);
clients[i].dma_handle = -1;
}
clients[i].request = NULL;
/*
Log driver register, MAINT driver ID is '0'
*/
len = sprintf(tmp, "DIMAINT - drv # %d = '%s' de-registered",
i, clients[i].Dbg.drvName);
memset(&clients[i].Dbg, 0x00, sizeof(clients[i].Dbg));
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)(len + 1 + sizeof(*pmsg))))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_STRING;
pmsg->dli = DLI_REG;
pmsg->drv_id = 0; /* id 0 - DIMAINT */
pmsg->di_cpu = 0;
pmsg->data_length = len + 1;
memcpy(&pmsg[1], tmp, len + 1);
queueCompleteMsg(pmsg);
diva_maint_wakeup_read();
}
break;
}
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "read_ack");
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "read_ack");
if (pmem) {
diva_os_free(0, pmem);
}
}
/* ----------------------------------------------------------------
Low level interface for management interface client
---------------------------------------------------------------- */
/*
Return handle to client structure
*/
void *SuperTraceOpenAdapter(int AdapterNumber) {
int i;
for (i = 1; i < ARRAY_SIZE(clients); i++) {
if (clients[i].hDbg && clients[i].request && (clients[i].logical == AdapterNumber)) {
return (&clients[i]);
}
}
return NULL;
}
int SuperTraceCloseAdapter(void *AdapterHandle) {
return (0);
}
int SuperTraceReadRequest(void *AdapterHandle, const char *name, byte *data) {
diva_maint_client_t *pC = (diva_maint_client_t *)AdapterHandle;
if (pC && pC->pIdiLib && pC->request) {
ENTITY *e = (ENTITY *)(*(pC->pIdiLib->DivaSTraceGetHandle))(pC->pIdiLib->hLib);
byte *xdata = (byte *)&pC->xbuffer[0];
char tmp = 0;
word length;
if (!strcmp(name, "\\")) { /* Read ROOT */
name = &tmp;
}
length = SuperTraceCreateReadReq(xdata, name);
single_p(xdata, &length, 0); /* End Of Message */
e->Req = MAN_READ;
e->ReqCh = 0;
e->X->PLength = length;
e->X->P = (byte *)xdata;
pC->request_pending = 1;
return (0);
}
return (-1);
}
int SuperTraceGetNumberOfChannels(void *AdapterHandle) {
if (AdapterHandle) {
diva_maint_client_t *pC = (diva_maint_client_t *)AdapterHandle;
return (pC->channels);
}
return (0);
}
int SuperTraceASSIGN(void *AdapterHandle, byte *data) {
diva_maint_client_t *pC = (diva_maint_client_t *)AdapterHandle;
if (pC && pC->pIdiLib && pC->request) {
ENTITY *e = (ENTITY *)(*(pC->pIdiLib->DivaSTraceGetHandle))(pC->pIdiLib->hLib);
IDI_SYNC_REQ *preq;
char buffer[((sizeof(preq->xdi_extended_features) + 4) > sizeof(ENTITY)) ? (sizeof(preq->xdi_extended_features) + 4) : sizeof(ENTITY)];
char features[4];
word assign_data_length = 1;
features[0] = 0;
pC->xbuffer[0] = 0;
preq = (IDI_SYNC_REQ *)&buffer[0];
preq->xdi_extended_features.Req = 0;
preq->xdi_extended_features.Rc = IDI_SYNC_REQ_XDI_GET_EXTENDED_FEATURES;
preq->xdi_extended_features.info.buffer_length_in_bytes = sizeof(features);
preq->xdi_extended_features.info.features = &features[0];
(*(pC->request))((ENTITY *)preq);
if ((features[0] & DIVA_XDI_EXTENDED_FEATURES_VALID) &&
(features[0] & DIVA_XDI_EXTENDED_FEATURE_MANAGEMENT_DMA)) {
dword uninitialized_var(rx_dma_magic);
if ((pC->dma_handle = diva_get_dma_descriptor(pC->request, &rx_dma_magic)) >= 0) {
pC->xbuffer[0] = LLI;
pC->xbuffer[1] = 8;
pC->xbuffer[2] = 0x40;
pC->xbuffer[3] = (byte)pC->dma_handle;
pC->xbuffer[4] = (byte)rx_dma_magic;
pC->xbuffer[5] = (byte)(rx_dma_magic >> 8);
pC->xbuffer[6] = (byte)(rx_dma_magic >> 16);
pC->xbuffer[7] = (byte)(rx_dma_magic >> 24);
pC->xbuffer[8] = (byte)(DIVA_MAX_MANAGEMENT_TRANSFER_SIZE & 0xFF);
pC->xbuffer[9] = (byte)(DIVA_MAX_MANAGEMENT_TRANSFER_SIZE >> 8);
pC->xbuffer[10] = 0;
assign_data_length = 11;
}
} else {
pC->dma_handle = -1;
}
e->Id = MAN_ID;
e->callback = diva_maint_xdi_cb;
e->XNum = 1;
e->X = &pC->XData;
e->Req = ASSIGN;
e->ReqCh = 0;
e->X->PLength = assign_data_length;
e->X->P = (byte *)&pC->xbuffer[0];
pC->request_pending = 1;
return (0);
}
return (-1);
}
int SuperTraceREMOVE(void *AdapterHandle) {
diva_maint_client_t *pC = (diva_maint_client_t *)AdapterHandle;
if (pC && pC->pIdiLib && pC->request) {
ENTITY *e = (ENTITY *)(*(pC->pIdiLib->DivaSTraceGetHandle))(pC->pIdiLib->hLib);
e->XNum = 1;
e->X = &pC->XData;
e->Req = REMOVE;
e->ReqCh = 0;
e->X->PLength = 1;
e->X->P = (byte *)&pC->xbuffer[0];
pC->xbuffer[0] = 0;
pC->request_pending = 1;
return (0);
}
return (-1);
}
int SuperTraceTraceOnRequest(void *hAdapter, const char *name, byte *data) {
diva_maint_client_t *pC = (diva_maint_client_t *)hAdapter;
if (pC && pC->pIdiLib && pC->request) {
ENTITY *e = (ENTITY *)(*(pC->pIdiLib->DivaSTraceGetHandle))(pC->pIdiLib->hLib);
byte *xdata = (byte *)&pC->xbuffer[0];
char tmp = 0;
word length;
if (!strcmp(name, "\\")) { /* Read ROOT */
name = &tmp;
}
length = SuperTraceCreateReadReq(xdata, name);
single_p(xdata, &length, 0); /* End Of Message */
e->Req = MAN_EVENT_ON;
e->ReqCh = 0;
e->X->PLength = length;
e->X->P = (byte *)xdata;
pC->request_pending = 1;
return (0);
}
return (-1);
}
int SuperTraceWriteVar(void *AdapterHandle,
byte *data,
const char *name,
void *var,
byte type,
byte var_length) {
diva_maint_client_t *pC = (diva_maint_client_t *)AdapterHandle;
if (pC && pC->pIdiLib && pC->request) {
ENTITY *e = (ENTITY *)(*(pC->pIdiLib->DivaSTraceGetHandle))(pC->pIdiLib->hLib);
diva_man_var_header_t *pVar = (diva_man_var_header_t *)&pC->xbuffer[0];
word length = SuperTraceCreateReadReq((byte *)pVar, name);
memcpy(&pC->xbuffer[length], var, var_length);
length += var_length;
pVar->length += var_length;
pVar->value_length = var_length;
pVar->type = type;
single_p((byte *)pVar, &length, 0); /* End Of Message */
e->Req = MAN_WRITE;
e->ReqCh = 0;
e->X->PLength = length;
e->X->P = (byte *)pVar;
pC->request_pending = 1;
return (0);
}
return (-1);
}
int SuperTraceExecuteRequest(void *AdapterHandle,
const char *name,
byte *data) {
diva_maint_client_t *pC = (diva_maint_client_t *)AdapterHandle;
if (pC && pC->pIdiLib && pC->request) {
ENTITY *e = (ENTITY *)(*(pC->pIdiLib->DivaSTraceGetHandle))(pC->pIdiLib->hLib);
byte *xdata = (byte *)&pC->xbuffer[0];
word length;
length = SuperTraceCreateReadReq(xdata, name);
single_p(xdata, &length, 0); /* End Of Message */
e->Req = MAN_EXECUTE;
e->ReqCh = 0;
e->X->PLength = length;
e->X->P = (byte *)xdata;
pC->request_pending = 1;
return (0);
}
return (-1);
}
static word SuperTraceCreateReadReq(byte *P, const char *path) {
byte var_length;
byte *plen;
var_length = (byte)strlen(path);
*P++ = ESC;
plen = P++;
*P++ = 0x80; /* MAN_IE */
*P++ = 0x00; /* Type */
*P++ = 0x00; /* Attribute */
*P++ = 0x00; /* Status */
*P++ = 0x00; /* Variable Length */
*P++ = var_length;
memcpy(P, path, var_length);
P += var_length;
*plen = var_length + 0x06;
return ((word)(var_length + 0x08));
}
static void single_p(byte *P, word *PLength, byte Id) {
P[(*PLength)++] = Id;
}
static void diva_maint_xdi_cb(ENTITY *e) {
diva_strace_context_t *pLib = DIVAS_CONTAINING_RECORD(e, diva_strace_context_t, e);
diva_maint_client_t *pC;
diva_os_spin_lock_magic_t old_irql, old_irql1;
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "xdi_cb");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "xdi_cb");
pC = (diva_maint_client_t *)pLib->hAdapter;
if ((e->complete == 255) || (pC->dma_handle < 0)) {
if ((*(pLib->instance.DivaSTraceMessageInput))(&pLib->instance)) {
diva_mnt_internal_dprintf(0, DLI_ERR, "Trace internal library error");
}
} else {
/*
Process combined management interface indication
*/
if ((*(pLib->instance.DivaSTraceMessageInput))(&pLib->instance)) {
diva_mnt_internal_dprintf(0, DLI_ERR, "Trace internal library error (DMA mode)");
}
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "xdi_cb");
if (pC->request_pending) {
pC->request_pending = 0;
(*(pC->request))(e);
}
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "xdi_cb");
}
static void diva_maint_error(void *user_context,
diva_strace_library_interface_t *hLib,
int Adapter,
int error,
const char *file,
int line) {
diva_mnt_internal_dprintf(0, DLI_ERR,
"Trace library error(%d) A(%d) %s %d", error, Adapter, file, line);
}
static void print_ie(diva_trace_ie_t *ie, char *buffer, int length) {
int i;
buffer[0] = 0;
if (length > 32) {
for (i = 0; ((i < ie->length) && (length > 3)); i++) {
sprintf(buffer, "%02x", ie->data[i]);
buffer += 2;
length -= 2;
if (i < (ie->length - 1)) {
strcpy(buffer, " ");
buffer++;
length--;
}
}
}
}
static void diva_maint_state_change_notify(void *user_context,
diva_strace_library_interface_t *hLib,
int Adapter,
diva_trace_line_state_t *channel,
int notify_subject) {
diva_maint_client_t *pC = (diva_maint_client_t *)user_context;
diva_trace_fax_state_t *fax = &channel->fax;
diva_trace_modem_state_t *modem = &channel->modem;
char tmp[256];
if (!pC->hDbg) {
return;
}
switch (notify_subject) {
case DIVA_SUPER_TRACE_NOTIFY_LINE_CHANGE: {
int view = (TraceFilter[0] == 0);
/*
Process selective Trace
*/
if (channel->Line[0] == 'I' && channel->Line[1] == 'd' &&
channel->Line[2] == 'l' && channel->Line[3] == 'e') {
if ((TraceFilterIdent == pC->hDbg->id) && (TraceFilterChannel == (int)channel->ChannelNumber)) {
(*(hLib->DivaSTraceSetBChannel))(hLib, (int)channel->ChannelNumber, 0);
(*(hLib->DivaSTraceSetAudioTap))(hLib, (int)channel->ChannelNumber, 0);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG, "Selective Trace OFF for Ch=%d",
(int)channel->ChannelNumber);
TraceFilterIdent = -1;
TraceFilterChannel = -1;
view = 1;
}
} else if (TraceFilter[0] && (TraceFilterIdent < 0) && !(diva_mnt_cmp_nmbr(&channel->RemoteAddress[0]) &&
diva_mnt_cmp_nmbr(&channel->LocalAddress[0]))) {
if ((pC->hDbg->dbgMask & DIVA_MGT_DBG_IFC_BCHANNEL) != 0) { /* Activate B-channel trace */
(*(hLib->DivaSTraceSetBChannel))(hLib, (int)channel->ChannelNumber, 1);
}
if ((pC->hDbg->dbgMask & DIVA_MGT_DBG_IFC_AUDIO) != 0) { /* Activate AudioTap Trace */
(*(hLib->DivaSTraceSetAudioTap))(hLib, (int)channel->ChannelNumber, 1);
}
TraceFilterIdent = pC->hDbg->id;
TraceFilterChannel = (int)channel->ChannelNumber;
if (TraceFilterIdent >= 0) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG, "Selective Trace ON for Ch=%d",
(int)channel->ChannelNumber);
view = 1;
}
}
if (view && (pC->hDbg->dbgMask & DIVA_MGT_DBG_LINE_EVENTS)) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Ch = %d",
(int)channel->ChannelNumber);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Status = <%s>", &channel->Line[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Layer1 = <%s>", &channel->Framing[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Layer2 = <%s>", &channel->Layer2[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Layer3 = <%s>", &channel->Layer3[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L RAddr = <%s>",
&channel->RemoteAddress[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L RSAddr = <%s>",
&channel->RemoteSubAddress[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L LAddr = <%s>",
&channel->LocalAddress[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L LSAddr = <%s>",
&channel->LocalSubAddress[0]);
print_ie(&channel->call_BC, tmp, sizeof(tmp));
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L BC = <%s>", tmp);
print_ie(&channel->call_HLC, tmp, sizeof(tmp));
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L HLC = <%s>", tmp);
print_ie(&channel->call_LLC, tmp, sizeof(tmp));
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L LLC = <%s>", tmp);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L CR = 0x%x", channel->CallReference);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Disc = 0x%x",
channel->LastDisconnecCause);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "L Owner = <%s>", &channel->UserID[0]);
}
} break;
case DIVA_SUPER_TRACE_NOTIFY_MODEM_CHANGE:
if (pC->hDbg->dbgMask & DIVA_MGT_DBG_MDM_PROGRESS) {
{
int ch = TraceFilterChannel;
int id = TraceFilterIdent;
if ((id >= 0) && (ch >= 0) && (id < ARRAY_SIZE(clients)) &&
(clients[id].Dbg.id == (byte)id) && (clients[id].pIdiLib == hLib)) {
if (ch != (int)modem->ChannelNumber) {
break;
}
} else if (TraceFilter[0] != 0) {
break;
}
}
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Ch = %lu",
(int)modem->ChannelNumber);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Event = %lu", modem->Event);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Norm = %lu", modem->Norm);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Opts. = 0x%08x", modem->Options);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Tx = %lu Bps", modem->TxSpeed);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Rx = %lu Bps", modem->RxSpeed);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM RT = %lu mSec",
modem->RoundtripMsec);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Sr = %lu", modem->SymbolRate);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Rxl = %d dBm", modem->RxLeveldBm);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM El = %d dBm", modem->EchoLeveldBm);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM SNR = %lu dB", modem->SNRdb);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM MAE = %lu", modem->MAE);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM LRet = %lu",
modem->LocalRetrains);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM RRet = %lu",
modem->RemoteRetrains);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM LRes = %lu", modem->LocalResyncs);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM RRes = %lu",
modem->RemoteResyncs);
if (modem->Event == 3) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "MDM Disc = %lu", modem->DiscReason);
}
}
if ((modem->Event == 3) && (pC->hDbg->dbgMask & DIVA_MGT_DBG_MDM_STATISTICS)) {
(*(pC->pIdiLib->DivaSTraceGetModemStatistics))(pC->pIdiLib);
}
break;
case DIVA_SUPER_TRACE_NOTIFY_FAX_CHANGE:
if (pC->hDbg->dbgMask & DIVA_MGT_DBG_FAX_PROGRESS) {
{
int ch = TraceFilterChannel;
int id = TraceFilterIdent;
if ((id >= 0) && (ch >= 0) && (id < ARRAY_SIZE(clients)) &&
(clients[id].Dbg.id == (byte)id) && (clients[id].pIdiLib == hLib)) {
if (ch != (int)fax->ChannelNumber) {
break;
}
} else if (TraceFilter[0] != 0) {
break;
}
}
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Ch = %lu", (int)fax->ChannelNumber);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Event = %lu", fax->Event);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Pages = %lu", fax->Page_Counter);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Feat. = 0x%08x", fax->Features);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX ID = <%s>", &fax->Station_ID[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Saddr = <%s>", &fax->Subaddress[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Pwd = <%s>", &fax->Password[0]);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Speed = %lu", fax->Speed);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Res. = 0x%08x", fax->Resolution);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Width = %lu", fax->Paper_Width);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Length= %lu", fax->Paper_Length);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX SLT = %lu", fax->Scanline_Time);
if (fax->Event == 3) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT, "FAX Disc = %lu", fax->Disc_Reason);
}
}
if ((fax->Event == 3) && (pC->hDbg->dbgMask & DIVA_MGT_DBG_FAX_STATISTICS)) {
(*(pC->pIdiLib->DivaSTraceGetFaxStatistics))(pC->pIdiLib);
}
break;
case DIVA_SUPER_TRACE_INTERFACE_CHANGE:
if (pC->hDbg->dbgMask & DIVA_MGT_DBG_IFC_EVENTS) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT,
"Layer 1 -> [%s]", channel->pInterface->Layer1);
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_STAT,
"Layer 2 -> [%s]", channel->pInterface->Layer2);
}
break;
case DIVA_SUPER_TRACE_NOTIFY_STAT_CHANGE:
if (pC->hDbg->dbgMask & DIVA_MGT_DBG_IFC_STATISTICS) {
/*
Incoming Statistics
*/
if (channel->pInterfaceStat->inc.Calls) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Calls =%lu", channel->pInterfaceStat->inc.Calls);
}
if (channel->pInterfaceStat->inc.Connected) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Connected =%lu", channel->pInterfaceStat->inc.Connected);
}
if (channel->pInterfaceStat->inc.User_Busy) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Busy =%lu", channel->pInterfaceStat->inc.User_Busy);
}
if (channel->pInterfaceStat->inc.Call_Rejected) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Rejected =%lu", channel->pInterfaceStat->inc.Call_Rejected);
}
if (channel->pInterfaceStat->inc.Wrong_Number) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Wrong Nr =%lu", channel->pInterfaceStat->inc.Wrong_Number);
}
if (channel->pInterfaceStat->inc.Incompatible_Dst) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Incomp. Dest =%lu", channel->pInterfaceStat->inc.Incompatible_Dst);
}
if (channel->pInterfaceStat->inc.Out_of_Order) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Out of Order =%lu", channel->pInterfaceStat->inc.Out_of_Order);
}
if (channel->pInterfaceStat->inc.Ignored) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Inc Ignored =%lu", channel->pInterfaceStat->inc.Ignored);
}
/*
Outgoing Statistics
*/
if (channel->pInterfaceStat->outg.Calls) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg Calls =%lu", channel->pInterfaceStat->outg.Calls);
}
if (channel->pInterfaceStat->outg.Connected) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg Connected =%lu", channel->pInterfaceStat->outg.Connected);
}
if (channel->pInterfaceStat->outg.User_Busy) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg Busy =%lu", channel->pInterfaceStat->outg.User_Busy);
}
if (channel->pInterfaceStat->outg.No_Answer) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg No Answer =%lu", channel->pInterfaceStat->outg.No_Answer);
}
if (channel->pInterfaceStat->outg.Wrong_Number) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg Wrong Nr =%lu", channel->pInterfaceStat->outg.Wrong_Number);
}
if (channel->pInterfaceStat->outg.Call_Rejected) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg Rejected =%lu", channel->pInterfaceStat->outg.Call_Rejected);
}
if (channel->pInterfaceStat->outg.Other_Failures) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"Outg Other Failures =%lu", channel->pInterfaceStat->outg.Other_Failures);
}
}
break;
case DIVA_SUPER_TRACE_NOTIFY_MDM_STAT_CHANGE:
if (channel->pInterfaceStat->mdm.Disc_Normal) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Normal = %lu", channel->pInterfaceStat->mdm.Disc_Normal);
}
if (channel->pInterfaceStat->mdm.Disc_Unspecified) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Unsp. = %lu", channel->pInterfaceStat->mdm.Disc_Unspecified);
}
if (channel->pInterfaceStat->mdm.Disc_Busy_Tone) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Busy Tone = %lu", channel->pInterfaceStat->mdm.Disc_Busy_Tone);
}
if (channel->pInterfaceStat->mdm.Disc_Congestion) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Congestion = %lu", channel->pInterfaceStat->mdm.Disc_Congestion);
}
if (channel->pInterfaceStat->mdm.Disc_Carr_Wait) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Carrier Wait = %lu", channel->pInterfaceStat->mdm.Disc_Carr_Wait);
}
if (channel->pInterfaceStat->mdm.Disc_Trn_Timeout) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Trn. T.o. = %lu", channel->pInterfaceStat->mdm.Disc_Trn_Timeout);
}
if (channel->pInterfaceStat->mdm.Disc_Incompat) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Incompatible = %lu", channel->pInterfaceStat->mdm.Disc_Incompat);
}
if (channel->pInterfaceStat->mdm.Disc_Frame_Rej) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc Frame Reject = %lu", channel->pInterfaceStat->mdm.Disc_Frame_Rej);
}
if (channel->pInterfaceStat->mdm.Disc_V42bis) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"MDM Disc V.42bis = %lu", channel->pInterfaceStat->mdm.Disc_V42bis);
}
break;
case DIVA_SUPER_TRACE_NOTIFY_FAX_STAT_CHANGE:
if (channel->pInterfaceStat->fax.Disc_Normal) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Normal = %lu", channel->pInterfaceStat->fax.Disc_Normal);
}
if (channel->pInterfaceStat->fax.Disc_Not_Ident) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Not Ident. = %lu", channel->pInterfaceStat->fax.Disc_Not_Ident);
}
if (channel->pInterfaceStat->fax.Disc_No_Response) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc No Response = %lu", channel->pInterfaceStat->fax.Disc_No_Response);
}
if (channel->pInterfaceStat->fax.Disc_Retries) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Max Retries = %lu", channel->pInterfaceStat->fax.Disc_Retries);
}
if (channel->pInterfaceStat->fax.Disc_Unexp_Msg) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Unexp. Msg. = %lu", channel->pInterfaceStat->fax.Disc_Unexp_Msg);
}
if (channel->pInterfaceStat->fax.Disc_No_Polling) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc No Polling = %lu", channel->pInterfaceStat->fax.Disc_No_Polling);
}
if (channel->pInterfaceStat->fax.Disc_Training) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Training = %lu", channel->pInterfaceStat->fax.Disc_Training);
}
if (channel->pInterfaceStat->fax.Disc_Unexpected) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Unexpected = %lu", channel->pInterfaceStat->fax.Disc_Unexpected);
}
if (channel->pInterfaceStat->fax.Disc_Application) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Application = %lu", channel->pInterfaceStat->fax.Disc_Application);
}
if (channel->pInterfaceStat->fax.Disc_Incompat) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Incompatible = %lu", channel->pInterfaceStat->fax.Disc_Incompat);
}
if (channel->pInterfaceStat->fax.Disc_No_Command) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc No Command = %lu", channel->pInterfaceStat->fax.Disc_No_Command);
}
if (channel->pInterfaceStat->fax.Disc_Long_Msg) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Long Msg. = %lu", channel->pInterfaceStat->fax.Disc_Long_Msg);
}
if (channel->pInterfaceStat->fax.Disc_Supervisor) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Supervisor = %lu", channel->pInterfaceStat->fax.Disc_Supervisor);
}
if (channel->pInterfaceStat->fax.Disc_SUB_SEP_PWD) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc SUP SEP PWD = %lu", channel->pInterfaceStat->fax.Disc_SUB_SEP_PWD);
}
if (channel->pInterfaceStat->fax.Disc_Invalid_Msg) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Invalid Msg. = %lu", channel->pInterfaceStat->fax.Disc_Invalid_Msg);
}
if (channel->pInterfaceStat->fax.Disc_Page_Coding) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Page Coding = %lu", channel->pInterfaceStat->fax.Disc_Page_Coding);
}
if (channel->pInterfaceStat->fax.Disc_App_Timeout) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Appl. T.o. = %lu", channel->pInterfaceStat->fax.Disc_App_Timeout);
}
if (channel->pInterfaceStat->fax.Disc_Unspecified) {
diva_mnt_internal_dprintf(pC->hDbg->id, DLI_LOG,
"FAX Disc Unspec. = %lu", channel->pInterfaceStat->fax.Disc_Unspecified);
}
break;
}
}
/*
Receive trace information from the Management Interface and store it in the
internal trace buffer with MSG_TYPE_MLOG as is, without any filtering.
Event Filtering and formatting is done in Management Interface self.
*/
static void diva_maint_trace_notify(void *user_context,
diva_strace_library_interface_t *hLib,
int Adapter,
void *xlog_buffer,
int length) {
diva_maint_client_t *pC = (diva_maint_client_t *)user_context;
diva_dbg_entry_head_t *pmsg;
word size;
dword sec, usec;
int ch = TraceFilterChannel;
int id = TraceFilterIdent;
/*
Selective trace
*/
if ((id >= 0) && (ch >= 0) && (id < ARRAY_SIZE(clients)) &&
(clients[id].Dbg.id == (byte)id) && (clients[id].pIdiLib == hLib)) {
const char *p = NULL;
int ch_value = -1;
MI_XLOG_HDR *TrcData = (MI_XLOG_HDR *)xlog_buffer;
if (Adapter != clients[id].logical) {
return; /* Ignore all trace messages from other adapters */
}
if (TrcData->code == 24) {
p = (char *)&TrcData->code;
p += 2;
}
/*
All L1 messages start as [dsp,ch], so we can filter this information
and filter out all messages that use different channel
*/
if (p && p[0] == '[') {
if (p[2] == ',') {
p += 3;
ch_value = *p - '0';
} else if (p[3] == ',') {
p += 4;
ch_value = *p - '0';
}
if (ch_value >= 0) {
if (p[2] == ']') {
ch_value = ch_value * 10 + p[1] - '0';
}
if (ch_value != ch) {
return; /* Ignore other channels */
}
}
}
} else if (TraceFilter[0] != 0) {
return; /* Ignore trace if trace filter is activated, but idle */
}
diva_os_get_time(&sec, &usec);
while (!(pmsg = (diva_dbg_entry_head_t *)queueAllocMsg(dbg_queue,
(word)length + sizeof(*pmsg)))) {
if ((pmsg = (diva_dbg_entry_head_t *)queuePeekMsg(dbg_queue, &size))) {
queueFreeMsg(dbg_queue);
} else {
break;
}
}
if (pmsg) {
memcpy(&pmsg[1], xlog_buffer, length);
pmsg->sequence = dbg_sequence++;
pmsg->time_sec = sec;
pmsg->time_usec = usec;
pmsg->facility = MSG_TYPE_MLOG;
pmsg->dli = pC->logical;
pmsg->drv_id = pC->hDbg->id;
pmsg->di_cpu = 0;
pmsg->data_length = length;
queueCompleteMsg(pmsg);
if (queueCount(dbg_queue)) {
diva_maint_wakeup_read();
}
}
}
/*
Convert MAINT trace mask to management interface trace mask/work/facility and
issue command to management interface
*/
static void diva_change_management_debug_mask(diva_maint_client_t *pC, dword old_mask) {
if (pC->request && pC->hDbg && pC->pIdiLib) {
dword changed = pC->hDbg->dbgMask ^ old_mask;
if (changed & DIVA_MGT_DBG_TRACE) {
(*(pC->pIdiLib->DivaSTraceSetInfo))(pC->pIdiLib,
(pC->hDbg->dbgMask & DIVA_MGT_DBG_TRACE) != 0);
}
if (changed & DIVA_MGT_DBG_DCHAN) {
(*(pC->pIdiLib->DivaSTraceSetDChannel))(pC->pIdiLib,
(pC->hDbg->dbgMask & DIVA_MGT_DBG_DCHAN) != 0);
}
if (!TraceFilter[0]) {
if (changed & DIVA_MGT_DBG_IFC_BCHANNEL) {
int i, state = ((pC->hDbg->dbgMask & DIVA_MGT_DBG_IFC_BCHANNEL) != 0);
for (i = 0; i < pC->channels; i++) {
(*(pC->pIdiLib->DivaSTraceSetBChannel))(pC->pIdiLib, i + 1, state);
}
}
if (changed & DIVA_MGT_DBG_IFC_AUDIO) {
int i, state = ((pC->hDbg->dbgMask & DIVA_MGT_DBG_IFC_AUDIO) != 0);
for (i = 0; i < pC->channels; i++) {
(*(pC->pIdiLib->DivaSTraceSetAudioTap))(pC->pIdiLib, i + 1, state);
}
}
}
}
}
void diva_mnt_internal_dprintf(dword drv_id, dword type, char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
DI_format(0, (word)drv_id, (int)type, fmt, ap);
va_end(ap);
}
/*
Shutdown all adapters before driver removal
*/
int diva_mnt_shutdown_xdi_adapters(void) {
diva_os_spin_lock_magic_t old_irql, old_irql1;
int i, fret = 0;
byte *pmem;
for (i = 1; i < ARRAY_SIZE(clients); i++) {
pmem = NULL;
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "unload");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "unload");
if (clients[i].hDbg && clients[i].pIdiLib && clients[i].request) {
if ((*(clients[i].pIdiLib->DivaSTraceLibraryStop))(clients[i].pIdiLib) == 1) {
/*
Adapter removal complete
*/
if (clients[i].pIdiLib) {
(*(clients[i].pIdiLib->DivaSTraceLibraryFinit))(clients[i].pIdiLib->hLib);
clients[i].pIdiLib = NULL;
pmem = clients[i].pmem;
clients[i].pmem = NULL;
}
clients[i].hDbg = NULL;
clients[i].request_pending = 0;
if (clients[i].dma_handle >= 0) {
/*
Free DMA handle
*/
diva_free_dma_descriptor(clients[i].request, clients[i].dma_handle);
clients[i].dma_handle = -1;
}
clients[i].request = NULL;
} else {
fret = -1;
}
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "unload");
if (clients[i].hDbg && clients[i].pIdiLib && clients[i].request && clients[i].request_pending) {
clients[i].request_pending = 0;
(*(clients[i].request))((ENTITY *)(*(clients[i].pIdiLib->DivaSTraceGetHandle))(clients[i].pIdiLib->hLib));
if (clients[i].dma_handle >= 0) {
diva_free_dma_descriptor(clients[i].request, clients[i].dma_handle);
clients[i].dma_handle = -1;
}
}
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "unload");
if (pmem) {
diva_os_free(0, pmem);
}
}
return (fret);
}
/*
Set/Read the trace filter used for selective tracing.
Affects B- and Audio Tap trace mask at run time
*/
int diva_set_trace_filter(int filter_length, const char *filter) {
diva_os_spin_lock_magic_t old_irql, old_irql1;
int i, ch, on, client_b_on, client_atap_on;
diva_os_enter_spin_lock(&dbg_adapter_lock, &old_irql1, "dbg mask");
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "write_filter");
if (filter_length <= DIVA_MAX_SELECTIVE_FILTER_LENGTH) {
memcpy(&TraceFilter[0], filter, filter_length);
if (TraceFilter[filter_length]) {
TraceFilter[filter_length] = 0;
}
if (TraceFilter[0] == '*') {
TraceFilter[0] = 0;
}
} else {
filter_length = -1;
}
TraceFilterIdent = -1;
TraceFilterChannel = -1;
on = (TraceFilter[0] == 0);
for (i = 1; i < ARRAY_SIZE(clients); i++) {
if (clients[i].hDbg && clients[i].pIdiLib && clients[i].request) {
client_b_on = on && ((clients[i].hDbg->dbgMask & DIVA_MGT_DBG_IFC_BCHANNEL) != 0);
client_atap_on = on && ((clients[i].hDbg->dbgMask & DIVA_MGT_DBG_IFC_AUDIO) != 0);
for (ch = 0; ch < clients[i].channels; ch++) {
(*(clients[i].pIdiLib->DivaSTraceSetBChannel))(clients[i].pIdiLib->hLib, ch + 1, client_b_on);
(*(clients[i].pIdiLib->DivaSTraceSetAudioTap))(clients[i].pIdiLib->hLib, ch + 1, client_atap_on);
}
}
}
for (i = 1; i < ARRAY_SIZE(clients); i++) {
if (clients[i].hDbg && clients[i].pIdiLib && clients[i].request && clients[i].request_pending) {
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "write_filter");
clients[i].request_pending = 0;
(*(clients[i].request))((ENTITY *)(*(clients[i].pIdiLib->DivaSTraceGetHandle))(clients[i].pIdiLib->hLib));
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "write_filter");
}
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "write_filter");
diva_os_leave_spin_lock(&dbg_adapter_lock, &old_irql1, "dbg mask");
return (filter_length);
}
int diva_get_trace_filter(int max_length, char *filter) {
diva_os_spin_lock_magic_t old_irql;
int len;
diva_os_enter_spin_lock(&dbg_q_lock, &old_irql, "read_filter");
len = strlen(&TraceFilter[0]) + 1;
if (max_length >= len) {
memcpy(filter, &TraceFilter[0], len);
}
diva_os_leave_spin_lock(&dbg_q_lock, &old_irql, "read_filter");
return (len);
}
static int diva_dbg_cmp_key(const char *ref, const char *key) {
while (*key && (*ref++ == *key++));
return (!*key && !*ref);
}
/*
In case trace filter starts with "C" character then
all following characters are interpreted as command.
Followings commands are available:
- single, trace single call at time, independent from CPN/CiPN
*/
static int diva_mnt_cmp_nmbr(const char *nmbr) {
const char *ref = &TraceFilter[0];
int ref_len = strlen(&TraceFilter[0]), nmbr_len = strlen(nmbr);
if (ref[0] == 'C') {
if (diva_dbg_cmp_key(&ref[1], "single")) {
return (0);
}
return (-1);
}
if (!ref_len || (ref_len > nmbr_len)) {
return (-1);
}
nmbr = nmbr + nmbr_len - 1;
ref = ref + ref_len - 1;
while (ref_len--) {
if (*nmbr-- != *ref--) {
return (-1);
}
}
return (0);
}
static int diva_get_dma_descriptor(IDI_CALL request, dword *dma_magic) {
ENTITY e;
IDI_SYNC_REQ *pReq = (IDI_SYNC_REQ *)&e;
if (!request) {
return (-1);
}
pReq->xdi_dma_descriptor_operation.Req = 0;
pReq->xdi_dma_descriptor_operation.Rc = IDI_SYNC_REQ_DMA_DESCRIPTOR_OPERATION;
pReq->xdi_dma_descriptor_operation.info.operation = IDI_SYNC_REQ_DMA_DESCRIPTOR_ALLOC;
pReq->xdi_dma_descriptor_operation.info.descriptor_number = -1;
pReq->xdi_dma_descriptor_operation.info.descriptor_address = NULL;
pReq->xdi_dma_descriptor_operation.info.descriptor_magic = 0;
(*request)((ENTITY *)pReq);
if (!pReq->xdi_dma_descriptor_operation.info.operation &&
(pReq->xdi_dma_descriptor_operation.info.descriptor_number >= 0) &&
pReq->xdi_dma_descriptor_operation.info.descriptor_magic) {
*dma_magic = pReq->xdi_dma_descriptor_operation.info.descriptor_magic;
return (pReq->xdi_dma_descriptor_operation.info.descriptor_number);
} else {
return (-1);
}
}
static void diva_free_dma_descriptor(IDI_CALL request, int nr) {
ENTITY e;
IDI_SYNC_REQ *pReq = (IDI_SYNC_REQ *)&e;
if (!request || (nr < 0)) {
return;
}
pReq->xdi_dma_descriptor_operation.Req = 0;
pReq->xdi_dma_descriptor_operation.Rc = IDI_SYNC_REQ_DMA_DESCRIPTOR_OPERATION;
pReq->xdi_dma_descriptor_operation.info.operation = IDI_SYNC_REQ_DMA_DESCRIPTOR_FREE;
pReq->xdi_dma_descriptor_operation.info.descriptor_number = nr;
pReq->xdi_dma_descriptor_operation.info.descriptor_address = NULL;
pReq->xdi_dma_descriptor_operation.info.descriptor_magic = 0;
(*request)((ENTITY *)pReq);
}
| gpl-2.0 |
baselsayeh/Kyleopen-4.4 | drivers/macintosh/ans-lcd.c | 12073 | 4048 | /*
* /dev/lcd driver for Apple Network Servers.
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <asm/sections.h>
#include <asm/prom.h>
#include <asm/io.h>
#include "ans-lcd.h"
#define ANSLCD_ADDR 0xf301c000
#define ANSLCD_CTRL_IX 0x00
#define ANSLCD_DATA_IX 0x10
static unsigned long anslcd_short_delay = 80;
static unsigned long anslcd_long_delay = 3280;
static volatile unsigned char __iomem *anslcd_ptr;
static DEFINE_MUTEX(anslcd_mutex);
#undef DEBUG
static void
anslcd_write_byte_ctrl ( unsigned char c )
{
#ifdef DEBUG
printk(KERN_DEBUG "LCD: CTRL byte: %02x\n",c);
#endif
out_8(anslcd_ptr + ANSLCD_CTRL_IX, c);
switch(c) {
case 1:
case 2:
case 3:
udelay(anslcd_long_delay); break;
default: udelay(anslcd_short_delay);
}
}
static void
anslcd_write_byte_data ( unsigned char c )
{
out_8(anslcd_ptr + ANSLCD_DATA_IX, c);
udelay(anslcd_short_delay);
}
static ssize_t
anslcd_write( struct file * file, const char __user * buf,
size_t count, loff_t *ppos )
{
const char __user *p = buf;
int i;
#ifdef DEBUG
printk(KERN_DEBUG "LCD: write\n");
#endif
if (!access_ok(VERIFY_READ, buf, count))
return -EFAULT;
mutex_lock(&anslcd_mutex);
for ( i = *ppos; count > 0; ++i, ++p, --count )
{
char c;
__get_user(c, p);
anslcd_write_byte_data( c );
}
mutex_unlock(&anslcd_mutex);
*ppos = i;
return p - buf;
}
static long
anslcd_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
char ch, __user *temp;
long ret = 0;
#ifdef DEBUG
printk(KERN_DEBUG "LCD: ioctl(%d,%d)\n",cmd,arg);
#endif
mutex_lock(&anslcd_mutex);
switch ( cmd )
{
case ANSLCD_CLEAR:
anslcd_write_byte_ctrl ( 0x38 );
anslcd_write_byte_ctrl ( 0x0f );
anslcd_write_byte_ctrl ( 0x06 );
anslcd_write_byte_ctrl ( 0x01 );
anslcd_write_byte_ctrl ( 0x02 );
break;
case ANSLCD_SENDCTRL:
temp = (char __user *) arg;
__get_user(ch, temp);
for (; ch; temp++) { /* FIXME: This is ugly, but should work, as a \0 byte is not a valid command code */
anslcd_write_byte_ctrl ( ch );
__get_user(ch, temp);
}
break;
case ANSLCD_SETSHORTDELAY:
if (!capable(CAP_SYS_ADMIN))
ret =-EACCES;
else
anslcd_short_delay=arg;
break;
case ANSLCD_SETLONGDELAY:
if (!capable(CAP_SYS_ADMIN))
ret = -EACCES;
else
anslcd_long_delay=arg;
break;
default:
ret = -EINVAL;
}
mutex_unlock(&anslcd_mutex);
return ret;
}
static int
anslcd_open( struct inode * inode, struct file * file )
{
return 0;
}
const struct file_operations anslcd_fops = {
.write = anslcd_write,
.unlocked_ioctl = anslcd_ioctl,
.open = anslcd_open,
.llseek = default_llseek,
};
static struct miscdevice anslcd_dev = {
ANSLCD_MINOR,
"anslcd",
&anslcd_fops
};
const char anslcd_logo[] = "********************" /* Line #1 */
"* LINUX! *" /* Line #3 */
"* Welcome to *" /* Line #2 */
"********************"; /* Line #4 */
static int __init
anslcd_init(void)
{
int a;
int retval;
struct device_node* node;
node = of_find_node_by_name(NULL, "lcd");
if (!node || !node->parent || strcmp(node->parent->name, "gc")) {
of_node_put(node);
return -ENODEV;
}
of_node_put(node);
anslcd_ptr = ioremap(ANSLCD_ADDR, 0x20);
retval = misc_register(&anslcd_dev);
if(retval < 0){
printk(KERN_INFO "LCD: misc_register failed\n");
iounmap(anslcd_ptr);
return retval;
}
#ifdef DEBUG
printk(KERN_DEBUG "LCD: init\n");
#endif
mutex_lock(&anslcd_mutex);
anslcd_write_byte_ctrl ( 0x38 );
anslcd_write_byte_ctrl ( 0x0c );
anslcd_write_byte_ctrl ( 0x06 );
anslcd_write_byte_ctrl ( 0x01 );
anslcd_write_byte_ctrl ( 0x02 );
for(a=0;a<80;a++) {
anslcd_write_byte_data(anslcd_logo[a]);
}
mutex_unlock(&anslcd_mutex);
return 0;
}
static void __exit
anslcd_exit(void)
{
misc_deregister(&anslcd_dev);
iounmap(anslcd_ptr);
}
module_init(anslcd_init);
module_exit(anslcd_exit);
| gpl-2.0 |
CitrusB/android_kernel_samsung_s6810 | drivers/misc/bcm59055-selftest.c | 42 | 70624 | /************************************************************************************************/
/* */
/* Copyright 2011 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. */
/* */
/************************************************************************************************/
/* Tests supported in this file */
#define GPS_TEST_SUPPORTED /* GPS GPIO control */ /* Implemented in LMP */
/* #define USB_ST_SUPPORTED */
/* #define ADC_ST_SUPPORTED */
#define SLEEPCLOCK_SUPPORTED /* Implemented in LMP */ /* Test OK */
#define DIGIMIC_SUPPORTED /* Implemented in LMP */ /* Test OK */
#define HEADSET_ST_SUPPORTED /* Implemented in LMP */ /* Test Fails */
#define IHF_ST_SUPPORTED /* Implemented in LMP */ /* Test OK */
#define PMU_ST_SUPPORTED /* Implemented in LMP */ /* Test OK */
/* Use RDB calls used as CHAL calls are not available */
#define USE_AUDIOH_RDB_DMIC
#define USE_AUDIOH_RDB_IHF
#define USE_AUDIOH_RDB_HS
/* Generel includes */
#include <linux/string.h>
#include <stdbool.h>
#include "linux/kernel.h"
#include "linux/delay.h"
#include "linux/init.h"
#include "linux/device.h"
#include "linux/err.h"
#include "linux/fs.h"
#include "linux/proc_fs.h"
#include "linux/types.h"
#include <asm/uaccess.h>
#include <asm/errno.h>
#include <asm/io.h>
#include <mach/hardware.h>
/* Generel Broadcom includes */
/* PMU */
#include "linux/mfd/bcm590xx/core.h"
#include "linux/broadcom/bcm59055-adc.h"
#include "linux/broadcom/bcm59055-audio.h"
#include "linux/broadcom/bcm59055-selftest.h"
/*#include "chipset_iomap.h"*/
/*#define ST_DBG(text,...) pr_debug (text"\n", ## __VA_ARGS__)*/
/*#define ST_MDBG(text,...) pr_debug (text"\n", ## __VA_ARGS__)*/
#define ST_DBG(text, ...) printk(KERN_INFO text"\n", ## __VA_ARGS__)
#define ST_MDBG(text, ...) printk(KERN_INFO text"\n", ## __VA_ARGS__)
#include <mach/io_map.h>
/* RDB access */
#include <mach/rdb/brcm_rdb_sysmap.h>
#include <mach/rdb/brcm_rdb_audioh.h>
#include <mach/rdb/brcm_rdb_khub_clk_mgr_reg.h> /* For DigiMic test */
#include <mach/rdb/brcm_rdb_sclkcal.h> /* For Sleep clock test */
#include <mach/rdb/brcm_rdb_bmdm_clk_mgr_reg.h> /* For Sleep clock test */
#include <mach/rdb/brcm_rdb_simi.h> /* For BARTM test */
#include <mach/rdb/brcm_rdb_slptimer.h> /* For PMU_CLK32 test test */
#define UNDER_LINUX
#include <mach/rdb/brcm_rdb_util.h>
/* Pinmux */
#include "mach/chip_pinmux.h"
#include "mach/pinmux.h"
/* GPIO */
#include "linux/gpio.h"
#include "linux/interrupt.h"
#ifdef GPS_TEST_SUPPORTED
/* GPS IO test variables */
static bool GPS_PABLANK_Setup_as_GPIO = false;
static struct pin_config StoredValue_GPS_PABLANK;
static bool GPS_TMARK_Setup_as_GPIO = false;
static struct pin_config StoredValue_GPS_TMARK;
#endif
/* PMU Selftest Driver */
static struct bcm590xx *bcm590xx_dev;
/* DIGIMIC*/
#define ST_GPIO_DMIC0DQ GPIO_DMIC0DQ
#define ST_GPIO_DMIC1DQ GPIO34
#define ST_GPIO_DMIC0CLK GPIO_DMIC0CLK
#define ST_GPIO_DMIC1CLK GPIO33
#define ST_PN_DMIC1DQ PN_GPIO34
#define ST_PN_DMIC1CLK PN_GPIO33
#define AUDIO_SETTLING_TIME 15
#define DMIC_SETTLING_TIME 30
/* Audio BB Test enable defines */
#define BB_TEST_DISABLE 0x00
#define BB_TEST_10_KOHM 0x01
#define BB_TEST_500_OHM 0x02
#define BB_TEST_500_OHM_10_KOHM 0x03
/* Sleep Clock Defines */
#define SLEEP_CLOCK_FREQUENCY_SPECIFIED 32768 /*32KHz*/
#define SLEEP_CLOCK_FREQUENCY_MAXIMUM (SLEEP_CLOCK_FREQUENCY_SPECIFIED + 2)
#define SLEEP_CLOCK_FREQUENCY_MINIMUM (SLEEP_CLOCK_FREQUENCY_SPECIFIED - 11)
#ifdef DIGIMIC_SUPPORTED
/* Variable for DigiMic test */
static bool DigiMicInterruptReceived;
#endif
/* Helper Macroes */
#define IHF_NUMBER_OF_SUBTESTS1 2
#define IHF_NUMBER_OF_SUBTESTS2 2
#define HA_NUMBER_OF_SUBTESTS 4
#define CHECKBIT_AND_ASSIGN_ERROR(xAssertLevel, xChecks, \
xReadValue, xResultArray, xErrorCode) \
{ \
int i; \
u8 TestValue; \
TestValue = xReadValue; \
for (i = 0 ; i < (xChecks) ; i++) { \
ST_MDBG("GLUE_SELFTEST::CHECKBIT_AND_ASSIGN_ERROR(%u):" \
" AL:%u, TV=0x%X, BTV=0x%X",\
i, xAssertLevel, TestValue,\
((TestValue) & (1 << i))); \
if (xResultArray[i] == ST_SELFTEST_OK) {\
if ((xAssertLevel == 1)) { \
ST_MDBG("GLUE_SELFTEST::CHECKBIT_AND_ASSIGN_ERROR:" \
" High Check (%u)", i); \
if (((TestValue) & (1 << i)) != 0) { \
xResultArray[i] = xErrorCode; \
ST_MDBG("GLUE_SELFTEST::CHECKBIT_AND_ASSIGN_ERROR:" \
" High Assign err = %u", \
xErrorCode); \
} \
} \
else { \
ST_MDBG("GLUE_SELFTEST::CHECKBIT_AND_ASSIGN_ERROR:" \
" Low Check (%u)", i); \
if (((TestValue) & (1 << i)) == 0) { \
xResultArray[i] = xErrorCode; \
ST_MDBG("GLUE_SELFTEST::CHECKBIT_AND_ASSIGN_ERROR:" \
" Low Assign err = %u", \
xErrorCode); \
} \
} \
} \
} \
}
/**********************************************************/
/** Stuff that should be defined in header files - Begin **/
/**********************************************************/
/* GPIO defines */
#define GPIO_DMIC0DQ 124
#define GPIO33 33
#define GPIO_DMIC0CLK 123
#define GPIO34 34
#define GPIO_GPS_TMARK 97
#define GPIO_GPS_PABLANK 98
/**********************************************************/
/** Stuff that should be defined in header files - End **/
/**********************************************************/
/* Missing Functions - where to find ?*/
#define assert(x)
/****************************/
/* ST_SLEEP_CLOCK_FREQ_TEST */
/****************************/
#ifdef SLEEPCLOCK_SUPPORTED
static void std_selftest_sleepclk(struct SelftestDevData_t *dev,
struct SelftestUserCmdData_t *cmddata)
{
bool isCalibrationStarted = false;
bool isCalibrationFinished = false;
bool CalibrateAgain = true;
int CalibrateTries = 0;
int i = 0;
u32 calibratedClockFrequency = 0;
u32 calibrationCounterFastRegister = 0;
u32 calibrationCounterSlowRegister = 0;
u32 originalCompareRegisterData = 0;
u32 original32kClockRegisterData = 0;
u32 originalSCLKCALClockRegisterData = 0;
u8 result = ST_SELFTEST_FAILED;
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk");
/*Save the original CMP value and set it to 50,*/
originalCompareRegisterData = BRCM_READ_REG(KONA_SCLKCAL_VA,
SCLKCAL_CACMP);
original32kClockRegisterData = BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_WCDMA_32K_CLKGATE);
originalSCLKCALClockRegisterData = BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_SCLKCAL_CLKGATE);
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() SCLKCAL_CACMP = 0x%08X",
(unsigned int)originalCompareRegisterData);
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() SCLKCAL_CACTRL = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_SCLKCAL_VA, SCLKCAL_CACTRL));
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() WCDMA_32K_CLKGATE = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_WCDMA_32K_CLKGATE));
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() SCLKCAL_CLKGATE = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_SCLKCAL_CLKGATE));
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() ACTIVITY_MON1 = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_ACTIVITY_MON1));
/* Enable Clocks */
BRCM_WRITE_REG_FIELD(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_SCLKCAL_CLKGATE,
SCLKCAL_CLK_EN, 1);
BRCM_WRITE_REG_FIELD(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_WCDMA_32K_CLKGATE,
WCDMA_32K_CLK_EN, 1);
while (CalibrateAgain) {
CalibrateAgain = false;
CalibrateTries++;
BRCM_WRITE_REG_FIELD(KONA_SCLKCAL_VA,
SCLKCAL_CACMP, CACMP, 50);
BRCM_WRITE_REG_FIELD(KONA_SCLKCAL_VA,
SCLKCAL_CACMP, MODE13MHZ, 0);
/*Start the calibration*/
BRCM_WRITE_REG_FIELD(KONA_SCLKCAL_VA, SCLKCAL_CACTRL, CAINIT, 1);
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() WCDMA_32K_CLKGATE = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_WCDMA_32K_CLKGATE));
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() SCLKCAL_CLKGATE = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_SCLKCAL_CLKGATE));
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() ACTIVITY_MON1 = 0x%08X",
(unsigned int)BRCM_READ_REG(KONA_BMDM_CCU_VA,
BMDM_CLK_MGR_REG_ACTIVITY_MON1));
/*make sure the 9th bit is set to 1, which is the CASTAT field of Calibration Control/Status Register*/
do {
if (0 != (BRCM_READ_REG_FIELD(KONA_SCLKCAL_VA, SCLKCAL_CACTRL, CASTAT))) {
isCalibrationStarted = true;
} else {
mdelay(2);
i++;
}
} while (!isCalibrationStarted && (i < 10));
if (isCalibrationStarted) {
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() isCalibrationStarted");
mdelay(45);
i = 0;
/*verify if calibration has finished, by checking if the CASTAT field is reset to 0*/
do {
if (0 == (BRCM_READ_REG_FIELD(KONA_SCLKCAL_VA, SCLKCAL_CACTRL, CASTAT))) {
isCalibrationFinished = true;
} else {
ST_DBG("GLUE_SELFTEST:: Waiting for Calibration#%02u", i);
mdelay(5);
i++;
}
} while (!isCalibrationFinished && (i < 10));
}
if (isCalibrationFinished) {
/*Read CAFR and CASR*/
calibrationCounterFastRegister = BRCM_READ_REG(KONA_SCLKCAL_VA, SCLKCAL_CAFR);
calibrationCounterSlowRegister = BRCM_READ_REG(KONA_SCLKCAL_VA, SCLKCAL_CASR);
ST_DBG("GLUE_SELFTEST::calibrationCounterFastRegister = %u, calibrationCounterSlowRegister = %u.", calibrationCounterFastRegister, calibrationCounterSlowRegister);
if ((calibrationCounterFastRegister == 1) && (calibrationCounterSlowRegister == 1) && (CalibrateTries < 10)) {
ST_DBG("GLUE_SELFTEST:: Calibrate again...");
CalibrateAgain = true;
continue;
}
/*Calculate the frequency and check if it is in the range.*/
calibratedClockFrequency = 13000000.0 / 12 * calibrationCounterSlowRegister / calibrationCounterFastRegister;
ST_DBG("GLUE_SELFTEST::calibratedClockFrequency = %u", calibratedClockFrequency);
if ((calibratedClockFrequency >= SLEEP_CLOCK_FREQUENCY_MINIMUM) && (calibratedClockFrequency <= SLEEP_CLOCK_FREQUENCY_MAXIMUM)) {
result = ST_SELFTEST_OK;
}
} else {
calibrationCounterFastRegister = BRCM_READ_REG(KONA_SCLKCAL_VA, SCLKCAL_CAFR);
calibrationCounterSlowRegister = BRCM_READ_REG(KONA_SCLKCAL_VA, SCLKCAL_CASR);
ST_DBG("GLUE_SELFTEST:: Calibration failed: calibrationCounterFastRegister = %u, calibrationCounterSlowRegister = %u.", calibrationCounterFastRegister, calibrationCounterSlowRegister);
if (CalibrateTries < 10) {
ST_DBG("GLUE_SELFTEST:: Calibrate again...");
CalibrateAgain = true;
continue;
}
}
}
/*restore the original data of the register*/
BRCM_WRITE_REG(KONA_SCLKCAL_VA, SCLKCAL_CACMP, originalCompareRegisterData);
BRCM_WRITE_REG(KONA_BMDM_CCU_VA, BMDM_CLK_MGR_REG_WCDMA_32K_CLKGATE, original32kClockRegisterData);
BRCM_WRITE_REG(KONA_BMDM_CCU_VA, BMDM_CLK_MGR_REG_SCLKCAL_CLKGATE, originalSCLKCALClockRegisterData);
/* Create failure structure */
if (ST_SELFTEST_OK == result) {
cmddata->subtestCount = 0;
} else {
cmddata->subtestCount = 1;
cmddata->subtestStatus[0] = ST_SELFTEST_FAILED;
}
if (ST_SELFTEST_OK == result) {
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() returned -----> ST_SELFTEST_OK");
} else {
ST_DBG("GLUE_SELFTEST::std_selftest_sleepclk() returned -----> ST_SELFTEST_FAILED");
}
cmddata->testStatus = result;
}
#endif
/*******************/
/* ST_DIGIMIC_TEST */
/*******************/
#ifdef DIGIMIC_SUPPORTED
#define WRITE_REG32(reg, value) (*((volatile u32 *) (reg)) = (u32) (value))
/****************************************************************************
*
* NAME: AUDIOH_hw_clkInit
*
*
* Description: Initializes the clock manager settings for APB13
*
*
* Parameters: None
*
* Returns: None
*
* Notes: This function is should be part of CLKMGR block. Will be replaced with CLKMGR_hw_XXX
* function once available
*
****************************************************************************/
void AUDIOH_hw_clkInit(void)
{
u32 regVal;
/* Enable write access */
regVal = (0x00A5A5 << KHUB_CLK_MGR_REG_WR_ACCESS_PASSWORD_SHIFT);
regVal |= KHUB_CLK_MGR_REG_WR_ACCESS_CLKMGR_ACC_MASK;
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_WR_ACCESS, regVal);
/* Set the frequency policy */
regVal = (0x06 << KHUB_CLK_MGR_REG_POLICY_FREQ_POLICY0_FREQ_SHIFT);
regVal |= (0x06 << KHUB_CLK_MGR_REG_POLICY_FREQ_POLICY1_FREQ_SHIFT);
regVal |= (0x06 << KHUB_CLK_MGR_REG_POLICY_FREQ_POLICY2_FREQ_SHIFT);
regVal |= (0x06 << KHUB_CLK_MGR_REG_POLICY_FREQ_POLICY3_FREQ_SHIFT);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY_FREQ, regVal);
/* Set the frequency policy */
regVal = 0x7FFFFFFF;
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY0_MASK1, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY1_MASK1, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY2_MASK1, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY3_MASK1, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY0_MASK2, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY1_MASK2, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY2_MASK2, regVal);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY3_MASK2, regVal);
/* start the frequency policy */
regVal = (KHUB_CLK_MGR_REG_POLICY_CTL_GO_MASK | KHUB_CLK_MGR_REG_POLICY_CTL_GO_AC_MASK);
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_POLICY_CTL, regVal);
}
static void AUDIOH_hw_setClk(u32 enable)
{
u32 regVal;
if (enable) {
/* Enable all the AUDIOH clocks, 26M, 156M, 2p4M, 6p5M */
regVal = KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_APB_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_APB_HW_SW_GATING_SEL_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_156M_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_156M_HW_SW_GATING_SEL_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_26M_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_26M_HW_SW_GATING_SEL_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_2P4M_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_2P4M_HW_SW_GATING_SEL_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_APB_HYST_VAL_MASK;
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_AUDIOH_CLKGATE, regVal);
} else {
/* Disable all the AUDIOH clocks, 26M, 156M, 2p4M, 6p5M */
regVal = KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_APB_HW_SW_GATING_SEL_MASK;
regVal &= ~KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_APB_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_156M_HW_SW_GATING_SEL_MASK;
regVal &= ~KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_156M_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_26M_HW_SW_GATING_SEL_MASK;
regVal &= ~KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_26M_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_2P4M_HW_SW_GATING_SEL_MASK;
regVal &= ~KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_2P4M_CLK_EN_MASK;
regVal |= KHUB_CLK_MGR_REG_AUDIOH_CLKGATE_AUDIOH_APB_HYST_VAL_MASK;
BRCM_WRITE_REG(KONA_HUB_CLK_BASE_VA, KHUB_CLK_MGR_REG_AUDIOH_CLKGATE, regVal);
}
}
/* Clock control functions */
#ifdef USE_AUDIOH_RDB_DMIC
static void ST_AUDIOH_hw_DMIC_Enable(int dmic)
#else
static void ST_AUDIOH_hw_DMIC_Enable(CHAL_HANDLE audiohandle, int dmic)
#endif
{
#ifdef USE_AUDIOH_RDB_DMIC
volatile u32 regVal;
regVal = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_ADC_CTL);
ST_DBG("GLUE_SELFTEST::AUDIOH_hw_DMIC_Enable() Enable interface DMIC%u(RDB)", dmic);
switch( dmic ) {
case 0:
regVal |= (AUDIOH_ADC_CTL_DMIC1_EN_MASK);
break;
case 1:
regVal |= (AUDIOH_ADC_CTL_DMIC2_EN_MASK);
break;
case 2:
regVal |= (AUDIOH_ADC_CTL_DMIC3_EN_MASK);
break;
case 3:
regVal |= (AUDIOH_ADC_CTL_DMIC4_EN_MASK);
break;
}
BRCM_WRITE_REG(KONA_AUDIOH_VA, AUDIOH_ADC_CTL, regVal);
#else
/* Enable DMIC paths */
ST_DBG("GLUE_SELFTEST::AUDIOH_hw_DMIC_Enable() Enable interface DMIC%u(RDB)", dmic);
switch( dmic ) {
case 0:
chal_audio_vinpath_digi_mic_enable(audiohandle, CHAL_AUDIO_CHANNEL_LEFT);
break;
case 1:
chal_audio_vinpath_digi_mic_enable(audiohandle, CHAL_AUDIO_CHANNEL_RIGHT);
break;
case 2:
chal_audio_nvinpath_digi_mic_enable(audiohandle, CHAL_AUDIO_CHANNEL_LEFT);
break;
case 3:
chal_audio_nvinpath_digi_mic_enable(audiohandle, CHAL_AUDIO_CHANNEL_RIGHT);
break;
}
#endif
/* Setup Clock */
AUDIOH_hw_clkInit();
AUDIOH_hw_setClk(1);
}
#ifdef USE_AUDIOH_RDB_DMIC
static void ST_AUDIOH_hw_DMIC_Disable(void)
#else
static void ST_AUDIOH_hw_DMIC_Disable(CHAL_HANDLE audiohandle)
#endif
{
volatile u32 regVal;
/* Disable all DMIC paths */
regVal = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_ADC_CTL);
regVal &= ~(AUDIOH_ADC_CTL_DMIC1_EN_MASK|AUDIOH_ADC_CTL_DMIC2_EN_MASK|AUDIOH_ADC_CTL_DMIC3_EN_MASK|AUDIOH_ADC_CTL_DMIC4_EN_MASK);
BRCM_WRITE_REG(KONA_AUDIOH_VA, AUDIOH_ADC_CTL, regVal);
}
static irqreturn_t GPIO_DigiMicSelftestEventFunction(int irq, void *dev_id)
{
/* Receive GPIO event */
DigiMicInterruptReceived = true;
ST_DBG("GLUE_SELFTEST::GPIO_DigiMicSelftestEventFunction(%u) ", irq);
disable_irq_nosync(irq);
return IRQ_HANDLED;
}
#define DIGIMIC_SUBTESTS_PER_MIC 1
#define MAX_DIGIMIC_IF_COUNT 2
#define MAX_DIGIMIC_COUNT 4
#define DIGIMIC_NUMBER_OF_SUBTESTS 4
#define DIGIMIC_COMM_TEST 0 /* First digimic test */
static void std_selftest_digimic(struct SelftestDevData_t *dev, struct SelftestUserCmdData_t *cmddata)
{
int Mic, MicIf;
int ret;
int i;
bool TestMic[MAX_DIGIMIC_COUNT];
/* int CLK_CONNECTION[MAX_DIGIMIC_IF_COUNT] = { ST_GPIO_DMIC0CLK, ST_GPIO_DMIC1CLK };*/
int DQ_CONNECTION[MAX_DIGIMIC_IF_COUNT] = { ST_GPIO_DMIC0DQ, ST_GPIO_DMIC1DQ };
enum PIN_NAME PMUX_CLK_CONNECTION[MAX_DIGIMIC_IF_COUNT] = { PN_DMIC0CLK, ST_PN_DMIC1CLK };
enum PIN_NAME PMUX_DQ_CONNECTION[MAX_DIGIMIC_IF_COUNT] = { PN_DMIC0DQ, ST_PN_DMIC1DQ };
enum PIN_FUNC PMUX_DMIC_MODE_CLK[MAX_DIGIMIC_IF_COUNT] = { PF_DMIC0CLK, PF_DMIC1CLK };
enum PIN_FUNC PMUX_DMIC_MODE_GPIO[MAX_DIGIMIC_IF_COUNT] = { PF_GPIO123, PF_GPIO33 };
/* enum PIN_FUNC PMUX_DMIC_MODE_DATA[MAX_DIGIMIC_IF_COUNT] = { PF_DMIC0DQ, PF_DMIC1DQ };*/
int MIC_IF[MAX_DIGIMIC_COUNT] = { 0, 0, 1, 1 };
struct pin_config StoredValue[4];
struct pin_config PIN_DMIC_Setup;
struct pin_config PIN_GPIO_Setup;
u8 StoredRegValue8[1];
#ifdef USE_AUDIOH_RDB_DMIC
u32 StoredRegValue32[1];
#else
CHAL_HANDLE audiohandle;
u8 StoredDMIC0Enable;
u8 StoredDMIC1Enable;
#endif
u8 Status[DIGIMIC_NUMBER_OF_SUBTESTS] = { ST_SELFTEST_OK, ST_SELFTEST_OK };
#if 1
AUDIOH_hw_clkInit();
AUDIOH_hw_setClk(1);
#endif
/* Pins: DMIC0CLK(GPIO123) Reg: PAD_CTRL - DMIC0CLK*/
/* DMIC0DQ(GPIO124) Reg: PAD_CTRL - DMIC0DQ*/
/* Registers: AUDIOH_ADC_CTL */
switch(cmddata->parm1) {
default:
case ST_SELFTEST_DIGIMIC_NONE:
TestMic[0] = false;
TestMic[1] = false;
case ST_SELFTEST_DIGIMIC_1MIC:
TestMic[0] = true;
TestMic[1] = false;
case ST_SELFTEST_DIGIMIC_2MICS:
TestMic[0] = true;
TestMic[1] = true;
}
/* Pins: DMIC1CLK(GPIO33) Reg: PAD_CTRL - GPIO33 */
/* DMIC1DQ(GPIO34) Reg: PAD_CTRL - GPIO34*/
/* Registers: AUDIOH_ADC_CTL */
switch(cmddata->parm2) {
default:
case ST_SELFTEST_DIGIMIC_NONE:
TestMic[2] = false;
TestMic[3] = false;
case ST_SELFTEST_DIGIMIC_1MIC:
TestMic[2] = true;
TestMic[3] = false;
case ST_SELFTEST_DIGIMIC_2MICS:
TestMic[2] = true;
TestMic[3] = true;
}
/* Store PMU register Values */
StoredRegValue8[0] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HV7OPMODCTRL);
/* Store GPIO setting registers */
StoredValue[0].name = PN_DMIC0CLK;
pinmux_get_pin_config(&StoredValue[0]);
StoredValue[0].name = PN_DMIC0DQ;
pinmux_get_pin_config(&StoredValue[1]);
StoredValue[0].name = PN_GPIO33;
pinmux_get_pin_config(&StoredValue[2]);
StoredValue[0].name = PN_GPIO34;
pinmux_get_pin_config(&StoredValue[3]);
#ifdef USE_AUDIOH_RDB_DMIC
/* Store DMIC setting registers */
StoredRegValue32[0] = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_ADC_CTL);
#else
audiohandle = chal_audio_init(KONA_AUDIOH_VA, KONA_SDT_BASE_VA);
StoredDMIC0Enable = chal_audio_vinpath_digi_mic_enable_read(audiohandle);
StoredDMIC1Enable = chal_audio_nvinpath_digi_mic_enable_read(audiohandle);
#endif
/* Actual test */
for (Mic = 0 ; Mic < MAX_DIGIMIC_COUNT ; Mic++) {
if (!TestMic[Mic]) {
Status[Mic*DIGIMIC_SUBTESTS_PER_MIC] = ST_SELFTEST_NOT_TESTED;
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Mic#%u Not Tested", Mic);
continue;
}
MicIf = MIC_IF[Mic];
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Mic#%u", Mic);
/* Subtest 3(6) - Connection test */
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Connection Test (%u) DQ = %u ", Mic, DQ_CONNECTION[MicIf]);
/*0. Power on microphone HVLDO7 (on PMU HVLDO7PMODCTRL) */
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HV7OPMODCTRL, 0x00); /* Turn on HVLDO7 in all cases b00000000 = 0x00 */
/*1. Setup DMIC0CLK as Mic clock output*/
PIN_GPIO_Setup.name = PMUX_DQ_CONNECTION[MicIf];
PIN_GPIO_Setup.func = PMUX_DMIC_MODE_GPIO[MicIf];
PIN_GPIO_Setup.reg.val = 0;
PIN_GPIO_Setup.reg.b.drv_sth = DRIVE_STRENGTH_8MA;
pinmux_set_pin_config(&PIN_GPIO_Setup);
ST_DBG("GLUE_SELFTEST:: DQ Setup 0x%X", PIN_GPIO_Setup.reg.val);
PIN_DMIC_Setup.name = PMUX_CLK_CONNECTION[MicIf];
PIN_DMIC_Setup.func = PMUX_DMIC_MODE_CLK[MicIf];
PIN_DMIC_Setup.reg.val = 0;
PIN_DMIC_Setup.reg.b.drv_sth = DRIVE_STRENGTH_8MA;
pinmux_set_pin_config(&PIN_DMIC_Setup);
ST_DBG("GLUE_SELFTEST:: CLK Setup 0x%X", PIN_DMIC_Setup.reg.val);
/* Enable Audio Clocks */
#ifdef USE_AUDIOH_RDB_DMIC
ST_AUDIOH_hw_DMIC_Enable(Mic);
#else
ST_AUDIOH_hw_DMIC_Enable(audiohandle, Mic);
#endif
mdelay(DMIC_SETTLING_TIME);
/*2. Setup DMICXDQ input */
/*3. Setup DMICXDQ to interrupt on rising edge*/
ret = gpio_request(DQ_CONNECTION[MicIf], "DMICDQ");
if (ret < 0) {
ST_DBG("GLUE_SELFTEST::gpio %u request failed", DQ_CONNECTION[MicIf]);
cmddata->testStatus = ST_SELFTEST_FAILED;
return;
}
DigiMicInterruptReceived = false;
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Set interrupt Mode(Input/Rising)");
gpio_direction_input(DQ_CONNECTION[MicIf]);
ret = request_irq(gpio_to_irq(DQ_CONNECTION[MicIf]),
GPIO_DigiMicSelftestEventFunction,
IRQF_TRIGGER_RISING,
"Digmimic Data",
0);
if (ret < 0) {
ST_DBG("GLUE_SELFTEST::gpio irq %u request failed", DQ_CONNECTION[MicIf]);
cmddata->testStatus = ST_SELFTEST_FAILED;
gpio_free(DQ_CONNECTION[MicIf]);
return;
}
/*4. Wait for interrupt for 10ms */
for (i = 0; i < 10 ; i++) {
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Interrrupt wait loop %u, Value = %u", i, gpio_get_value(DQ_CONNECTION[MicIf]));
mdelay(2);
if (DigiMicInterruptReceived == true)
break;
}
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Disable Interrupt");
disable_irq(gpio_to_irq(DQ_CONNECTION[MicIf]));
free_irq(gpio_to_irq(DQ_CONNECTION[MicIf]), 0);
gpio_free(DQ_CONNECTION[MicIf]);
if (DigiMicInterruptReceived == true) {
/* b. Interrupt received = > Continue to 5. */
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Interrupt Received");
Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST] = ST_SELFTEST_OK;
} else {
Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST] = ST_SELFTEST_BAD_CONNECTION;
/* a. Timeout = > No connection - Test failed*/
}
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() 3.1 Status[%u] = %u ", (Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST, Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST]);
if (Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST] == ST_SELFTEST_OK) {
/*5. Setup DMICXDQ to interrupt on falling edge*/
DigiMicInterruptReceived = false;
ret = gpio_request(DQ_CONNECTION[MicIf], "DMICDQ");
if (ret < 0) {
ST_DBG("GLUE_SELFTEST::gpio %u request failed", DQ_CONNECTION[MicIf]);
cmddata->testStatus = ST_SELFTEST_FAILED;
return;
}
gpio_direction_input(DQ_CONNECTION[MicIf]);
DigiMicInterruptReceived = false;
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Set interrupt Mode(Input/Falling)");
ret = request_irq(gpio_to_irq(DQ_CONNECTION[MicIf]),
GPIO_DigiMicSelftestEventFunction,
IRQF_TRIGGER_FALLING,
"Digmimic Data",
0);
if (ret < 0) {
ST_DBG("GLUE_SELFTEST::gpio irq %u request failed", DQ_CONNECTION[MicIf]);
cmddata->testStatus = ST_SELFTEST_FAILED;
gpio_free(DQ_CONNECTION[MicIf]);
return;
}
/*6. Wait for interrupt for 10ms */
for (i = 0; i < 10 ; i++) {
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Interrrupt wait loop %u, Value = %u", i, gpio_get_value(DQ_CONNECTION[MicIf]));
mdelay(2);
if (DigiMicInterruptReceived == true)
break;
}
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Disable Interrupt");
disable_irq(gpio_to_irq(DQ_CONNECTION[MicIf]));
free_irq(gpio_to_irq(DQ_CONNECTION[MicIf]), 0);
gpio_free(DQ_CONNECTION[MicIf]);
if (DigiMicInterruptReceived == true) {
/* b. Interrupt received = > ST_SELFTEST_OK */
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Interrupt Received");
Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST] = ST_SELFTEST_OK;
} else {
/* a. Timeout = > No connection - Test failed */
Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST] = ST_SELFTEST_BAD_CONNECTION;
}
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() 3.2 Status[%u] = %u", (Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST, Status[(Mic*DIGIMIC_SUBTESTS_PER_MIC)+DIGIMIC_COMM_TEST]);
}
ST_AUDIOH_hw_DMIC_Disable();
} /* Mic */
/* Restore PMU register values */
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HV7OPMODCTRL, (u16)StoredRegValue8[0]);
#ifdef USE_AUDIOH_RDB_DMIC
/* Store DMIC setting registers */
StoredRegValue32[0] = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_ADC_CTL);
#else
chal_audio_vinpath_digi_mic_enable(audiohandle, (u16)StoredDMIC0Enable);
chal_audio_nvinpath_digi_mic_enable(audiohandle, (u16)StoredDMIC1Enable);
#endif
/* Restore GPIO setting registers */
pinmux_set_pin_config(&StoredValue[0]);
pinmux_set_pin_config(&StoredValue[1]);
pinmux_set_pin_config(&StoredValue[2]);
pinmux_set_pin_config(&StoredValue[3]);
/* Fill out failures status code structure */
for (i = 0; i < DIGIMIC_NUMBER_OF_SUBTESTS; i++) {
cmddata->subtestStatus[i] = Status[i];
ST_DBG("GLUE_SELFTEST::std_selftest_digimic() Status[%u] = %u", i, Status[i]);
}
/* Find return code */
if (((Status[0] != 0) && (Status[0] != ST_SELFTEST_NOT_TESTED)) || ((Status[1] != 0) && (Status[1] != ST_SELFTEST_NOT_TESTED))) {
cmddata->subtestCount = DIGIMIC_NUMBER_OF_SUBTESTS;
cmddata->testStatus = ST_SELFTEST_FAILED;
} else {
cmddata->subtestCount = 0;
cmddata->testStatus = ST_SELFTEST_OK;
}
}
#endif
#if !defined(USE_AUDIOH_RDB_HS) && !defined(USE_AUDIOH_RDB_IHF)
typedef struct {
u32 AUDIOTX_TEST_EN;
u32 AUDIOTX_BB_STI;
u32 AUDIOTX_EP_DRV_STO;
} dac_ctrl_t;
static void st_audio_audiotx_set_dac_ctrl(CHAL_HANDLE audiohandle,
dac_ctrl_t *writedata)
{
u32 ctrl = 0;
ctrl |= (writedata->AUDIOTX_TEST_EN) & 3;
ctrl |= ((writedata->AUDIOTX_BB_STI) & 3) << 2;
chal_audio_audiotx_set_dac_ctrl(audiohandle, ctrl);
}
void st_audio_audiotx_get_dac_ctrl(CHAL_HANDLE audiohandle,
dac_ctrl_t *readdata)
{
u32 ctrl;
ctrl = chal_audio_audiotx_get_dac_ctrl(audiohandle);
readdata->AUDIOTX_TEST_EN = ctrl & 3;
readdata->AUDIOTX_BB_STI = (ctrl >> 2) & 3;
readdata->AUDIOTX_EP_DRV_STO = (ctrl >> 4) & 3;
}
#endif
#ifdef HEADSET_ST_SUPPORTED
static void std_selftest_headset(struct SelftestDevData_t *dev,
struct SelftestUserCmdData_t *cmddata)
{
u8 ResultArray[HA_NUMBER_OF_SUBTESTS] = {ST_SELFTEST_OK,
ST_SELFTEST_OK,
ST_SELFTEST_OK,
ST_SELFTEST_OK};
u8 ReadValue; /* Value read from PMU */
u8 ReadValue2; /* Value read from PMU */
u8 StoredRegValue8[7];
#ifdef USE_AUDIOH_RDB_HS
u32 StoredRegValue32[1];
#else
dac_ctrl_t Stored_dac_ctrl_Value;
dac_ctrl_t Dac_Ctrl;
CHAL_HANDLE audiohandle;
#endif
ST_DBG("GLUE_SELFTEST::std_selftest_headset() called.");
#if 1
AUDIOH_hw_clkInit();
AUDIOH_hw_setClk(1);
#endif
/* Store PMU register Values */
StoredRegValue8[0] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HSPGA1);
StoredRegValue8[1] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HSPGA2);
StoredRegValue8[2] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HSPGA3);
StoredRegValue8[3] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HSIST);
StoredRegValue8[4] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HSPUP1);
StoredRegValue8[5] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HSPUP2);
StoredRegValue8[6] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_PLLCTRL);
/* Store BB register Values */
#ifdef USE_AUDIOH_RDB_HS
StoredRegValue32[0] = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL);
#else
audiohandle = chal_audio_init(KONA_AUDIOH_VA, KONA_SDT_BASE_VA);
st_audio_audiotx_get_dac_ctrl(audiohandle, &Stored_dac_ctrl_Value);
st_audio_audiotx_get_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/**************************/
/* Subtest 1 + 2 + 3 + 4 */
/**************************/
ReadValue = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev, BCM59055_REG_PMUID);
ReadValue2 = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev, BCM59055_REG_PMUID2);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() PMU_ID = 0x%X, PMU_ID2 = 0x%X",
ReadValue, ReadValue2);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() RA[0] = %u,RA[1] = %u,RA[2] = %u,RA[3] = %u",
ResultArray[0], ResultArray[1], ResultArray[2], ResultArray[3]);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Dump before setup");
/* Setup */
bcm59055_hs_set_input_mode( 0, PMU_HS_DIFFERENTIAL_DC_COUPLED );
bcm59055_hs_set_gain(PMU_AUDIO_HS_BOTH,0);
bcm59055_audio_init();
bcm59055_hs_power(true);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Dump after setup ");
/* PMU Input test */
/**********/
/* TEST 1 */
/**********/
ST_DBG("GLUE_SELFTEST::std_selftest_headset() INPUT TEST");
ST_DBG("GLUE_SELFTEST::TEST 1");
/* 1. Enable test mode (driving buffer enabled) (i_hs_enst[1:0] = '11') on PMU */
bcm59055_audio_hs_testmode(PMU_TEST_READ_AND_ENABLE);
/*2. Disable Output (i_hs_enst = '0') on BB*/ /* AUDIOTX_TEST_EN[1:0] = '00' */
#ifdef USE_AUDIOH_RDB_HS
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_TEST_EN, BB_TEST_10_KOHM);
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_BB_STI, 0x00);
#else
Dac_Ctrl.AUDIOTX_TEST_EN = BB_TEST_10_KOHM;
Dac_Ctrl.AUDIOTX_BB_STI = 0x00;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*3. Set Output (i_hs_ist = '1') on PMU */
bcm59055_audio_hs_selftest_stimulus(0x01);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Dump before test");
/*4. Check result (o_hst_ist[3:0]). */
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Dump after test ");
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_hs_selftest_result(&ReadValue);
/* a. Bit High = > Check passed */
/* b. Bit Low = > Shorted to Ground*/
CHECKBIT_AND_ASSIGN_ERROR(0, HA_NUMBER_OF_SUBTESTS,
ReadValue, ResultArray, ST_SELFTEST_SHORTED_GROUND);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Test1 readvalue = 0x%X -> 0x%X",
ReadValue, (ReadValue>>PMU_HSOUT1_OFFSET_O_HS_IST));
ST_DBG("GLUE_SELFTEST::std_selftest_headset() RA[0] = %u,RA[1] = %u,RA[2] = %u,RA[3] = %u",
ResultArray[0], ResultArray[1], ResultArray[2], ResultArray[3]);
/**********/
/* TEST 2 */
/**********/
ST_DBG("GLUE_SELFTEST::TEST 2");
#ifdef USE_AUDIOH_RDB_HS
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL, AUDIOTX_BB_STI, 0x03);
#else
Dac_Ctrl.AUDIOTX_BB_STI = 0x03;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*5. Set Output (i_hs_ist = '0') on PMU*/
bcm59055_audio_hs_selftest_stimulus(0x00);
/*6. Check result (o_hst_ist[3:0]). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_hs_selftest_result(&ReadValue);
/* a. Bit Low = > Check passed */
/* b. Bit High = > Shorted to Power */
CHECKBIT_AND_ASSIGN_ERROR(1, HA_NUMBER_OF_SUBTESTS,
ReadValue,
ResultArray, ST_SELFTEST_SHORTED_POWER);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Test2 readvalue = 0x%X -> 0x%X",
ReadValue, (ReadValue>>PMU_HSOUT1_OFFSET_O_HS_IST));
ST_DBG("GLUE_SELFTEST::std_selftest_headset() RA[0] = %u,RA[1] = %u,RA[2] = %u,RA[3] = %u",
ResultArray[0], ResultArray[1], ResultArray[2], ResultArray[3]);
/* BB Output Test */
/**********/
/* TEST 3 */
/**********/
ST_DBG("GLUE_SELFTEST::std_selftest_headset() OUTPUT TEST");
ST_DBG("GLUE_SELFTEST::TEST 3");
/*1. Enable test mode (driving buffer disabled) (i_hs_enst[1:0] = '10') on PMU */
bcm59055_audio_hs_testmode(PMU_TEST_READ_AND_DISABLE);
#ifdef USE_AUDIOH_RDB_HS
/*2. Enable Output (i_hs_enst = '1') on BB */
/* AUDIOTX_TEST_EN[1:0] = '11' */
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_TEST_EN, BB_TEST_500_OHM);
/*3. Set Output (i_hs_ist = '1') on BB */
/* AUDIOTX_BB_STI[1:0] = '11' */
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_BB_STI , 0x03);
#else
/*2. Enable Output (i_hs_enst = '1') on BB */
/* AUDIOTX_TEST_EN[1:0] = '11' */
Dac_Ctrl.AUDIOTX_TEST_EN = BB_TEST_500_OHM;
/*3. Set Output (i_hs_ist = '1') on BB */
/* AUDIOTX_BB_STI[1:0] = '11' */
Dac_Ctrl.AUDIOTX_BB_STI = 0x03;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*4. Check result (o_hst_ist[3:0]). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_hs_selftest_result(&ReadValue);
/* a. Bit High = > Check passed */
/* b. Bit Low = > Shorted to Ground or Not connected*/
CHECKBIT_AND_ASSIGN_ERROR(0, HA_NUMBER_OF_SUBTESTS,
ReadValue, ResultArray,
ST_SELFTEST_BAD_CONNECTION_OR_GROUND);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Test3 readvalue = 0x%X -> 0x%X",
ReadValue, (ReadValue>>PMU_HSOUT1_OFFSET_O_HS_IST));
ST_DBG("GLUE_SELFTEST::std_selftest_headset() RA[0] = %u,RA[1] = %u,RA[2] = %u,RA[3] = %u",
ResultArray[0], ResultArray[1], ResultArray[2], ResultArray[3]);
/**********/
/* TEST 4 */
/**********/
ST_DBG("GLUE_SELFTEST::TEST 4");
/*5. Set Output (i_hs_ist = '0') on BB */ /* AUDIOTX_BB_STI[1:0] = '00' */
#ifdef USE_AUDIOH_RDB_HS
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA,
AUDIOH_DAC_CTRL, AUDIOTX_BB_STI , 0x00);
#else
Dac_Ctrl.AUDIOTX_BB_STI = 0x00;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*6. Check result (o_hst_ist[3:0]). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_hs_selftest_result(&ReadValue);
/* a. Bit Low = > Check passed */
/* b. Bit High = > Shorted to Power or Not connected */
CHECKBIT_AND_ASSIGN_ERROR(1, HA_NUMBER_OF_SUBTESTS,
ReadValue,
ResultArray,
ST_SELFTEST_BAD_CONNECTION_OR_POWER);
ST_DBG("GLUE_SELFTEST::std_selftest_headset() Test4 readvalue = 0x%X -> 0x%X",
ReadValue, (ReadValue>>PMU_HSOUT1_OFFSET_O_HS_IST));
ST_DBG("GLUE_SELFTEST::std_selftest_headset() RA[0] = %u,RA[1] = %u,RA[2] = %u,RA[3] = %u",
ResultArray[0], ResultArray[1], ResultArray[2], ResultArray[3]);
/* Restore PMU register values */
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HSPGA1,
StoredRegValue8[0]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HSPGA2,
StoredRegValue8[1]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HSPGA3,
StoredRegValue8[2]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HSIST,
StoredRegValue8[3]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HSPUP1,
StoredRegValue8[4]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HSPUP2,
StoredRegValue8[5]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_PLLCTRL,
StoredRegValue8[6]);
/* Restore BB register values */
#ifdef USE_AUDIOH_RDB_HS
BRCM_WRITE_REG(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL, StoredRegValue32[0]);
#else
st_audio_audiotx_set_dac_ctrl(audiohandle, &Stored_dac_ctrl_Value);
#endif
/* Fill out failures status code structure */
{
int i;
for (i = 0; i < HA_NUMBER_OF_SUBTESTS; i++) {
cmddata->subtestStatus[i] = ResultArray[HA_NUMBER_OF_SUBTESTS-1-i];
ST_DBG("GLUE_SELFTEST::std_selftest_headset() ResultArray[%u] = %u", HA_NUMBER_OF_SUBTESTS-1-i, ResultArray[HA_NUMBER_OF_SUBTESTS-1-i]);
}
}
/* Find return code */
if (ResultArray[0] || ResultArray[1] || ResultArray[2] || ResultArray[3]) {
cmddata->subtestCount = HA_NUMBER_OF_SUBTESTS;
cmddata->testStatus = ST_SELFTEST_FAILED;
} else {
cmddata->subtestCount = 0;
cmddata->testStatus = ST_SELFTEST_OK;
}
}
#endif
#ifdef IHF_ST_SUPPORTED
static void std_selftest_ihf(struct SelftestDevData_t *dev, struct SelftestUserCmdData_t *cmddata)
{
u8 ResultArray1[IHF_NUMBER_OF_SUBTESTS1] = {ST_SELFTEST_OK, ST_SELFTEST_OK};
u8 ResultArray2[IHF_NUMBER_OF_SUBTESTS2] = {ST_SELFTEST_OK, ST_SELFTEST_OK};
u8 ReadValue; /* Value read from PMU */
u8 StoredRegValue8[2];
#ifdef USE_AUDIOH_RDB_IHF
u32 StoredRegValue32[2];
#else
dac_ctrl_t Stored_dac_ctrl_Value;
dac_ctrl_t Dac_Ctrl;
u8 Stored_DacPower;
CHAL_HANDLE audiohandle;
#endif
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() called.");
#if 1
AUDIOH_hw_clkInit();
AUDIOH_hw_setClk(1);
#endif
/* Store PMU register Values */
StoredRegValue8[0] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_IHFSTIN);
StoredRegValue8[1] = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_IHFSTO);
/* Store BB register Values */
#ifdef USE_AUDIOH_RDB_IHF
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() TEST-0");
StoredRegValue32[0] = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() TEST-1");
StoredRegValue32[1] = BRCM_READ_REG(KONA_AUDIOH_VA, AUDIOH_IHF_PWR);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() TEST-2");
#else
audiohandle = chal_audio_init(KONA_AUDIOH_VA, KONA_SDT_BASE_VA);
st_audio_audiotx_get_dac_ctrl(audiohandle, &Stored_dac_ctrl_Value);
Stored_DacPower = chal_audio_ihfpath_get_dac_pwr(audiohandle);
#endif
/* Subtest 1 + 2 - IHF DAC */
/* PMU Input test */
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Init tests");
/* 1. Enable test mode (driving buffer enabled) (i_hs_enst[1:0] = '11') on PMU */
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Enable test mode");
bcm59055_audio_ihf_testmode(PMU_TEST_READ_AND_ENABLE);
/*2. Disable Output (i_hs_enst = '0') on BB*/ /* AUDIOTX_TEST_EN[1:0] = '00' */
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Disable Output");
#ifdef USE_AUDIOH_RDB_IHF
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_TEST_EN, BB_TEST_DISABLE);
#else
Dac_Ctrl.AUDIOTX_TEST_EN = BB_TEST_DISABLE;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*2a. Disable BB output drivers (High-Z) */
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Disable BB output drivers (High-Z)");
#ifdef USE_AUDIOH_RDB_IHF
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_IHF_PWR,
AUDIOTX_IHF_DACR_PD, 1);
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_IHF_PWR,
AUDIOTX_IHF_DACL_PD, 1);
#else
chal_audio_ihfpath_set_dac_pwr(audiohandle, 0);
#endif
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test 1.1");
/*3. Set Output (i_hs_ist = '1') on PMU */
bcm59055_audio_ihf_selftest_stimulus_input(0x02);
/*4. Check result (o_hst_ist[3:0]). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_ihf_selftest_result(&ReadValue);
/* a. Bit High = > Check passed */
/* b. Bit Low = > Shorted to Ground*/
CHECKBIT_AND_ASSIGN_ERROR(0, IHF_NUMBER_OF_SUBTESTS1,
ReadValue,
ResultArray1, ST_SELFTEST_SHORTED_GROUND);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test1 readvalue = 0x%X",
ReadValue);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test 1.2");
/*5. Set Output (i_hs_ist = '0') on PMU*/
bcm59055_audio_ihf_selftest_stimulus_input(0x00);
/*6. Check result (o_hst_ist[3:0]). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_ihf_selftest_result(&ReadValue);
/* a. Bit Low = > Check passed */
/* b. Bit High = > Shorted to Power */
CHECKBIT_AND_ASSIGN_ERROR(1, IHF_NUMBER_OF_SUBTESTS1, ReadValue, ResultArray1, ST_SELFTEST_SHORTED_POWER);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test2 readvalue = 0x%X",
ReadValue);
/* BB output test: */
/*1. Enable Output (Test_en[0:1] = '11') on BB */
#ifdef USE_AUDIOH_RDB_IHF
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_TEST_EN, BB_TEST_500_OHM);
#else
Dac_Ctrl.AUDIOTX_TEST_EN = BB_TEST_500_OHM;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*2. Enable test mode (Short or Open test) (i_IHFselftest_en[1:0] = '10') */
bcm59055_audio_ihf_testmode(PMU_TEST_READ_AND_DISABLE);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test 1.3");
/*3. Set Output (i_BB_sti = '11')*/
#ifdef USE_AUDIOH_RDB_IHF
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL, AUDIOTX_BB_STI, 0x03);
#else
Dac_Ctrl.AUDIOTX_BB_STI = 0x03;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*3a. Set (i_IHFsti = '0x')*/
bcm59055_audio_ihf_selftest_stimulus_input(0x00);
/*4. Check result (o_IHFsti). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_ihf_selftest_result(&ReadValue);
/* a. Bit High = > Check passed*/
/* b. Bit Low = > Shorted to Ground*/
CHECKBIT_AND_ASSIGN_ERROR(0, IHF_NUMBER_OF_SUBTESTS1,
ReadValue, ResultArray1, ST_SELFTEST_BAD_CONNECTION_OR_GROUND);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test 1.4");
/*5. Set Output (i_BB_sti = '00')*/
#ifdef USE_AUDIOH_RDB_IHF
BRCM_WRITE_REG_FIELD(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL,
AUDIOTX_BB_STI, 0x00);
#else
Dac_Ctrl.AUDIOTX_BB_STI = 0x00;
st_audio_audiotx_set_dac_ctrl(audiohandle, &Dac_Ctrl);
#endif
/*5a. Set (i_IHFsti = '0x')*/
bcm59055_audio_ihf_selftest_stimulus_input(0x00);
/*6. Check result (o_IHFsti). */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_ihf_selftest_result(&ReadValue);
/* a. Bit Low = > Check passed*/
/* b. Bit High = > Shorted to Supply*/
CHECKBIT_AND_ASSIGN_ERROR(1, IHF_NUMBER_OF_SUBTESTS1, ReadValue, ResultArray1, ST_SELFTEST_BAD_CONNECTION_OR_POWER);
/* Subtest 3 + 4 - IHF Output */
/*PMU Output Pins Test: */
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test 2.1");
/*1. Enable by setting i_IHFselftest_en[0] to 1. */
bcm59055_audio_ihf_testmode(PMU_TEST_ENABLE_NO_READ);
/*2. i_IHFsto[1:0] = '0x'*/
bcm59055_audio_ihf_selftest_stimulus_output(0x00);
/* Check */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_ihf_selftest_result(&ReadValue);
/* a. Check if o_IHFsto[1:0] == '00' = > No pull-up resistor from the output pins to Supply*/
/* b. Check if o_IHFsto[1:0] < >'00' = > Either or both output pins are short to Supply*/
CHECKBIT_AND_ASSIGN_ERROR(1, IHF_NUMBER_OF_SUBTESTS2,
ReadValue, ResultArray2, ST_SELFTEST_BAD_CONNECTION_OR_POWER);
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() Test 2.2");
/*3. i_IHFsto[1:0] = '1x'*/
bcm59055_audio_ihf_selftest_stimulus_output(0x02);
/* Check */
mdelay(AUDIO_SETTLING_TIME);
bcm59055_audio_ihf_selftest_result(&ReadValue);
/* a. Check o_IHFsto[1:0] = '00' = > No pull-down resistor from the output pins to ground*/
/* b. Check o_IHFsto[1:0] < >'00' = > Either or both output pins are short to ground*/
CHECKBIT_AND_ASSIGN_ERROR(1, IHF_NUMBER_OF_SUBTESTS2,
ReadValue, ResultArray2, ST_SELFTEST_BAD_CONNECTION_OR_GROUND);
/* Restore PMU register values */
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_IHFSTIN, StoredRegValue8[0]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_IHFSTO, StoredRegValue8[1]);
/* Restore BB register values */
#ifdef USE_AUDIOH_RDB_IHF
BRCM_WRITE_REG(KONA_AUDIOH_VA, AUDIOH_DAC_CTRL, StoredRegValue32[0]);
BRCM_WRITE_REG(KONA_AUDIOH_VA, AUDIOH_IHF_PWR, StoredRegValue32[1]);
#else
st_audio_audiotx_set_dac_ctrl(audiohandle, &Stored_dac_ctrl_Value);
chal_audio_ihfpath_set_dac_pwr(audiohandle, Stored_DacPower);
#endif
/* Fill out failures status code structure */
/* Subtest 1 + 2 - IHF DAC */
{
int i;
for (i = 0; i < IHF_NUMBER_OF_SUBTESTS1; i++) {
cmddata->subtestStatus[i] = ResultArray1[IHF_NUMBER_OF_SUBTESTS1-1-i];
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() ResultArray1[%u] = %u", IHF_NUMBER_OF_SUBTESTS1-1-i, ResultArray1[IHF_NUMBER_OF_SUBTESTS1-1-i]);
}
}
/* Subtest 3 + 4 - IHF Output */
{
int i;
for (i = 0; i < IHF_NUMBER_OF_SUBTESTS2; i++) {
cmddata->subtestStatus[i+IHF_NUMBER_OF_SUBTESTS1] = ResultArray2[IHF_NUMBER_OF_SUBTESTS2-1-i];
ST_DBG("GLUE_SELFTEST::std_selftest_ihf() ResultArray2[%u] = %u", IHF_NUMBER_OF_SUBTESTS2-1-i, ResultArray2[IHF_NUMBER_OF_SUBTESTS2-1-i]);
}
}
/* Find return code */
if (ResultArray1[0] || ResultArray1[1] ||
ResultArray2[0] || ResultArray2[1]) {
cmddata->subtestCount = IHF_NUMBER_OF_SUBTESTS1+IHF_NUMBER_OF_SUBTESTS2;
cmddata->testStatus = ST_SELFTEST_FAILED;
} else {
cmddata->subtestCount = 0;
cmddata->testStatus = ST_SELFTEST_OK;
}
}
#endif
#ifdef PMU_ST_SUPPORTED
/* Stuff thats should be in PMU driver header file */
#define PMU_HOSTCTRL3_SELF_TEST 0x20
#define PMU_HOSTCTRL3_BATRMTEST 0x40
/* Internal structures */
enum PMU_Pin_Index {
PMU_PIN_SCL_SDA,
PMU_PIN_PMU_INT,
PMU_PIN_BATRM_INT,
PMU_PIN_CLK32,
PMU_PIN_MAX
};
typedef bool (*Pin_Func_t)(struct SelftestDevData_t *dev);
typedef struct {
int index;
bool isCovered;
bool result;
Pin_Func_t testRoutine;
} Pin_Status;
/* Forwarded functions */
static bool PMU_Pin_SCL_SDA(struct SelftestDevData_t *dev); /* Subtest 1 */
static bool PMU_Pin_PMU_INT(struct SelftestDevData_t *dev); /* Subtest 2 */
static bool PMU_Pin_BATRM_INT(struct SelftestDevData_t *dev); /* Subtest 3 */
static bool PMU_Pin_CLK32(struct SelftestDevData_t *dev); /* Subtest 4 */
static bool PMU_Pin_SCL_SDA(struct SelftestDevData_t *dev)
{
/* Use DBI interrupt mask for testing */
u32 testingRegisterID = BCM59055_REG_INT14MSK;
u8 originalRegisterData = 0;
u8 valueToWrite = 0xAA;
u8 valueToRead = 0;
bool testResult = false;
ST_DBG("GLUE_SELFTEST::PMU_Pin_SCL_SDA() called.");
originalRegisterData = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
testingRegisterID);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, testingRegisterID,
valueToWrite);
valueToRead = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
testingRegisterID);
testResult = (valueToWrite == valueToRead) ? true : false;
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, testingRegisterID,
originalRegisterData);
ST_DBG("GLUE_SELFTEST::PMU_Pin_SCL_SDA() returned testResult = %u.", testResult);
return testResult;
}
/* PMU interrupt test */
static bool PMU_Pin_PMU_INT(struct SelftestDevData_t *dev)
{
int reading;
int i = 0;
do {
reading = bcm59055_saradc_request_rtm (0); /* VBAT */
/*printk (KERN_INFO "%s: reading %d", reading);*/
if (reading < 0) {
mdelay (20);
}
} while ((reading < 0) && (i++ < 5) && (reading != -EIO));
if (reading > 0 || reading == -EIO) {
return true;
}
return false;
}
static bool PMU_Pin_BATRM_INT(struct SelftestDevData_t *dev)
{
bool result = false;
int i = 0;
u32 batrm_n = 0;
u8 new_register_value = 0, old_register_value = 0;
u8 readback;
u32 StoredRegValue32[1];
ST_DBG("GLUE_SELFTEST::PMU_Pin_BATRM_INT() called.");
old_register_value = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HOSTCTRL3);
new_register_value = old_register_value;
StoredRegValue32[0] = BRCM_READ_REG(KONA_SIMI_VA, SIMI_DESDCR);
/*enable batrm selftest mode*/
new_register_value |= PMU_HOSTCTRL3_SELF_TEST;
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM590XX_REG_ENCODE(0x07,
BCM590XX_SLAVE1_I2C_ADDRESS), 0x38);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HOSTCTRL3,
new_register_value);
mdelay(1);
/*set the output data bit to high*/
new_register_value |= PMU_HOSTCTRL3_BATRMTEST;
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_HOSTCTRL3,
new_register_value);
readback = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HOSTCTRL3);
ST_DBG("GLUE_SELFTEST:: High test: BCM59055_REG_HOSTCTRL3 = 0x%X",
readback);
/* SETUP SIM */
/* Enable ESD clocks */
BRCM_WRITE_REG_FIELD(KONA_SIMI_VA, SIMI_DESDCR, SIM_ESD_EN, 1);
/* Disable ESD triggered by BATRM */
BRCM_WRITE_REG_FIELD(KONA_SIMI_VA, SIMI_DESDCR, SIM_BATRM_ESD_EN, 0);
/*get the state of the BAT_RM bit, make sure it is high*/
for (i = 0; i < 5; i++) {
/* Read via SIM interface */
batrm_n = BRCM_READ_REG_FIELD(KONA_SIMI_VA,
SIMI_DESDISR,
BATRM_N);
ST_DBG("GLUE_SELFTEST:: High test: batrm_n = %u", batrm_n);
if (0 != batrm_n) {
break;
}
mdelay(5);
}
if (0 != batrm_n) {
/*set the output data bit to low*/
new_register_value &= ~PMU_HOSTCTRL3_BATRMTEST;
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HOSTCTRL3, new_register_value);
readback = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HOSTCTRL3);
ST_DBG("GLUE_SELFTEST:: Low test: BCM59055_REG_HOSTCTRL3 = 0x%X",
readback);
mdelay(10);
/* Read via SIM interface */
batrm_n = BRCM_READ_REG_FIELD(KONA_SIMI_VA,
SIMI_DESDISR,
BATRM_N);
ST_DBG("GLUE_SELFTEST:: Low test: batrm_n = %u", batrm_n);
result = (batrm_n == 0) ? true : false;
}
BRCM_WRITE_REG(KONA_SIMI_VA, SIMI_DESDCR, StoredRegValue32[0]);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM590XX_REG_ENCODE(0x07,
BCM590XX_SLAVE1_I2C_ADDRESS), 0x38);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev,
BCM59055_REG_HOSTCTRL3,
old_register_value);
ST_DBG("GLUE_SELFTEST::PMU_Pin_BATRM_INT() returned %u.", result);
return result;
}
static bool PMU_Pin_CLK32(struct SelftestDevData_t *dev)
{
u32 oldValue = 0, newValue = 0;
int i = 0;
ST_DBG("GLUE_SELFTEST::PMU_Pin_CLK32() called.");
/*get the current down counter value, only the first 9 bits are used.*/
oldValue = BRCM_READ_REG(KONA_SLPTIMER_VA, SLPTIMER_SMTSTR);
for (i = 0; i < 5; i++) {
mdelay(1);
/*get the new current down counter value, check if changed*/
newValue = BRCM_READ_REG(KONA_SLPTIMER_VA, SLPTIMER_SMTSTR);
ST_DBG("GLUE_SELFTEST::PMU_Pin_CLK32::old_value = %u, new_value = %u.", oldValue, newValue);
if (oldValue != newValue) {
ST_DBG("GLUE_SELFTEST::PMU_Pin_CLK32() returned true.");
return true;
}
}
ST_DBG("GLUE_SELFTEST::PMU_Pin_CLK32() returned false.");
return false;
}
static void std_selftest_pmu(struct SelftestDevData_t *dev, struct SelftestUserCmdData_t *cmddata)
{
Pin_Status Selftest_PMU_Pin_Coverage[PMU_PIN_MAX] = {
{ PMU_PIN_SCL_SDA, true, false, PMU_Pin_SCL_SDA },
{ PMU_PIN_PMU_INT, true, false, PMU_Pin_PMU_INT},
{ PMU_PIN_BATRM_INT, true, false, PMU_Pin_BATRM_INT},
{ PMU_PIN_CLK32, true, false, PMU_Pin_CLK32}
};
int i = 0;
bool overallResult = true;
ST_DBG("GLUE_SELFTEST::hal_selftest_pmu() called.");
for (i = 0; i < PMU_PIN_MAX; i++) {
if (Selftest_PMU_Pin_Coverage[i].isCovered == true) {
if ((*(Selftest_PMU_Pin_Coverage[i].testRoutine))(dev) == true) {
Selftest_PMU_Pin_Coverage[i].result = true;
} else {
ST_DBG("GLUE_SELFTEST::hal_selftest_pmu()::failed test case index = %d", i);
if (overallResult == true) {
overallResult = false;
}
}
}
}
cmddata->subtestCount = 0;
if (overallResult != true) {
cmddata->subtestCount = PMU_PIN_MAX;
for (i = 0; i < PMU_PIN_MAX; i++) {
if ((Selftest_PMU_Pin_Coverage[i].isCovered == true)) {
cmddata->subtestStatus[i] = (Selftest_PMU_Pin_Coverage[i].result == true ? ST_SELFTEST_OK : ST_SELFTEST_FAILED);
}
}
}
if (!overallResult) {
ST_DBG("GLUE_SELFTEST::hal_selftest_pmu() returned ----------> ST_SELFTEST_FAILED");
cmddata->testStatus = ST_SELFTEST_FAILED;
return;
}
ST_DBG("GLUE_SELFTEST::hal_selftest_pmu() returned ----------> ST_SELFTEST_OK");
cmddata->testStatus = ST_SELFTEST_OK;
}
#else
static void std_selftest_pmu(struct SelftestDevData_t *dev, struct SelftestUserCmdData_t *cmddata)
{
ST_DBG("GLUE_SELFTEST::std_selftest_pmu() called.");
/*...........*/
/*....TBD....*/
/*...........*/
}
#endif
#ifdef GPS_TEST_SUPPORTED
/*---------------------------------------------------------------------------*/
/*! \brief ST_SELFTEST_control_gps_io.
* Self Test for gps control pins
*
* \param name - The logical name of the GenIO pin
* \param direction - Defines if read or write operation shall be performed
* \param state - Pointer to data type that contains the pin state
*
* \return - The outcome of the self test procedure
*/
static void std_selftest_control_gps_io(struct SelftestDevData_t *dev,
struct SelftestUserCmdData_t *cmddata)
{
u8 result = ST_SELFTEST_FAILED; /* set to default */
struct pin_config GPIOSetup;
int ret;
/* Input */
u8 name = cmddata->parm1;
u8 direction = cmddata->parm2;
u8 *state = (u8 *)&cmddata->parm3;
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () called -- ST_SELFTEST_GPS_READ/WRITE %x %x %x", name, direction, *state);
GPIOSetup.reg.val = 0;
GPIOSetup.reg.b.drv_sth = DRIVE_STRENGTH_2MA;
switch (name) {
case ST_SELFTEST_GPS_TXP:
if (GPS_PABLANK_Setup_as_GPIO == false) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_PABLANK_Setup_as_GPIO");
StoredValue_GPS_PABLANK.name = PN_GPS_PABLANK;
pinmux_get_pin_config(&StoredValue_GPS_PABLANK);
GPIOSetup.name = PN_GPS_PABLANK;
GPIOSetup.func = PF_GPIO98;
pinmux_set_pin_config(&GPIOSetup);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () 0x%08X",
StoredValue_GPS_PABLANK.reg.val);
ret = gpio_request(GPIO_GPS_PABLANK, "GPS PABLANK");
if (ret < 0) {
ST_DBG("GLUE_SELFTEST::gpio %u request failed",
GPIO_GPS_PABLANK);
/* dev_err(&pdev->dev, "Unable to request GPIO pin %d\n", GPIO_GPS_PABLANK);*/
result = ST_SELFTEST_FAILED;
}
GPS_PABLANK_Setup_as_GPIO = true;
}
switch (direction) {
case ST_SELFTEST_GPS_WRITE:{
switch (*state) {
case ST_SELFTEST_GPS_HIGH:
gpio_direction_output(GPIO_GPS_PABLANK, 1);
gpio_set_value(GPIO_GPS_PABLANK, 1);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_PABLANK - Write - High");
break;
case ST_SELFTEST_GPS_LOW:
gpio_direction_output(GPIO_GPS_PABLANK, 0);
gpio_set_value(GPIO_GPS_PABLANK, 0);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_PABLANK - Write - Low");
break;
case ST_SELFTEST_GPS_RELEASE:
default:
/* assume release state, defined in ISI */
if (GPS_PABLANK_Setup_as_GPIO == true) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_PABLANK - Restore");
pinmux_set_pin_config(&StoredValue_GPS_PABLANK);
gpio_free(GPIO_GPS_PABLANK);
GPS_PABLANK_Setup_as_GPIO = false;
}
break;
}
result = ST_SELFTEST_OK;
break;
}
case ST_SELFTEST_GPS_READ:
gpio_direction_input(GPIO_GPS_PABLANK);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_PABLANK - Read");
if (gpio_get_value(GPIO_GPS_PABLANK) == 1) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () >>>High");
*state = ST_SELFTEST_GPS_HIGH;
} else {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () >>>Low");
*state = ST_SELFTEST_GPS_LOW;
}
result = ST_SELFTEST_OK;
break;
default:
assert(false);
break;
}
break;
case ST_SELFTEST_GPS_TIMESTAMP:
if (GPS_TMARK_Setup_as_GPIO == false) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_TMARK_Setup_as_GPIO");
StoredValue_GPS_TMARK.name = PN_GPS_TMARK;
pinmux_get_pin_config(&StoredValue_GPS_TMARK);
GPIOSetup.name = PN_GPS_TMARK;
GPIOSetup.func = PF_GPIO97;
pinmux_set_pin_config(&GPIOSetup);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () 0x%08X",
StoredValue_GPS_TMARK.reg.val);
ret = gpio_request(GPIO_GPS_TMARK, "GPS TMARK");
if (ret < 0) {
ST_DBG("GLUE_SELFTEST::gpio %u request failed",
GPIO_GPS_PABLANK);
/* dev_err(&pdev->dev, "Unable to request GPIO pin %d\n", GPIO_GPS_PABLANK);*/
result = ST_SELFTEST_FAILED;
}
GPS_TMARK_Setup_as_GPIO = true;
}
switch (direction) {
case ST_SELFTEST_GPS_WRITE:{
switch (*state) {
case ST_SELFTEST_GPS_HIGH:
gpio_direction_output(GPIO_GPS_TMARK, 1);
gpio_set_value(GPIO_GPS_TMARK, 1);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_TMARK - Write - High");
break;
case ST_SELFTEST_GPS_LOW:
gpio_direction_output(GPIO_GPS_TMARK, 0);
gpio_set_value(GPIO_GPS_TMARK, 0);
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_TMARK - Write - Low");
break;
case ST_SELFTEST_GPS_RELEASE:
default:
/* assume release state, defined in ISI */
if (GPS_TMARK_Setup_as_GPIO == true) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_TMARK - Restore");
pinmux_set_pin_config(&StoredValue_GPS_TMARK);
gpio_free(GPIO_GPS_TMARK);
GPS_TMARK_Setup_as_GPIO = false;
}
break;
}
result = ST_SELFTEST_OK;
break;
}
case ST_SELFTEST_GPS_READ:
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () GPS_TMARK - Read");
gpio_direction_input(GPIO_GPS_TMARK);
if (gpio_get_value(GPIO_GPS_TMARK) == 1) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () >>>High");
*state = ST_SELFTEST_GPS_HIGH;
} else {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () >>>Low");
*state = ST_SELFTEST_GPS_LOW;
}
result = ST_SELFTEST_OK;
break;
default:
assert(false);
break;
}
break;
default:
result = ST_SELFTEST_NOT_SUPPORTED;
break;
}
if (ST_SELFTEST_OK == result) {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () returned -----> ST_SELFTEST_OK");
} else {
ST_DBG("GLUE_SELFTEST::std_selftest_control_gps_io () returned -----> ST_SELFTEST_FAILED");
}
cmddata->testStatus = result;
}
#endif
#ifdef USB_ST_SUPPORTED
static u8 hal_selftest_usb_charger_latch_ok = 0;
static u8 hal_selftest_usb_charger_called = 0;
static void std_selftest_usb_charger(struct SelftestDevData_t *dev,
struct SelftestUserCmdData_t *cmddata)
{
u8 mbc5_orig, mbc5_bcd_aon, i;
u8 status;
if (!hal_selftest_usb_charger_called) {
#ifdef NEED_TO_SIGNUP_FOR_EVENT_IN_LMP
status = HAL_EM_PMU_RegisterEventCB (PMU_DRV_CHGDET_LATCH, &hal_selftest_usb_charger_latch_cb);
#endif
ST_DBG("GLUE_SELFTEST::hal_selftest_usb_charger() Status: %d", status);
hal_selftest_usb_charger_called = 1;
}
hal_selftest_usb_charger_latch_ok = 0;
/* Set PMU into BCDLDO Always on in MBCCTRL5 [1] */
mbc5_orig = bcm590xx_reg_read(dev->bcm_5900xx_pmu_dev, BCM59055_REG_MBCCTRL5);
if (mbc5_orig & BCM59055_REG_MBCCTRL5_USB_DET_LDO_EN) {
/* LDO is already on. */
mbc5_bcd_aon = mbc5_orig & ~(BCM59055_REG_MBCCTRL5_USB_DET_LDO_EN);
ST_DBG("GLUE_SELFTEST::hal_selftest_usb_charger(); USB_DET_LDO is already on, orig = %x aon = %x", mbc5_orig, mbc5_bcd_aon);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_MBCCTRL5, mbc5_bcd_aon);
mdelay(5);
}
mbc5_bcd_aon = mbc5_orig | BCM59055_REG_MBCCTRL5_BCDLDO_AON | BCM59055_REG_MBCCTRL5_USB_DET_LDO_EN | BCM59055_REG_MBCCTRL5_BC11_EN;
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_MBCCTRL5, mbc5_bcd_aon);
ST_DBG("GLUE_SELFTEST::hal_selftest_usb_charger() MBCCTRL5 original %x, aon %x", mbc5_orig, mbc5_bcd_aon);
for (i = 0; i < 200; i++) {
/* wait for CHGDET_LATCH status */
mdelay(2);
if (hal_selftest_usb_charger_latch_ok)
break;
}
/* Restore MBCCTRL5 */
mdelay(25);
bcm590xx_reg_write(dev->bcm_5900xx_pmu_dev, BCM59055_REG_MBCCTRL5, mbc5_orig);
/* IF chp_typ == 0x01, test is working correctly. chp_typ is located in bits 4 and 5.*/
if (hal_selftest_usb_charger_latch_ok) {
ST_DBG("GLUE_SELFTEST::hal_selftest_usb_charger() Connection is good");
cmddata->subtestCount = 0;
cmddata->subtestStatus[i] = ST_SELFTEST_OK;
} else {
cmddata->subtestCount = 1;
cmddata->subtestStatus[i] = ST_SELFTEST_FAILED;
}
}
#endif
#ifdef ADC_ST_SUPPORTED
static void std_selftest_adc(struct SelftestDevData_t *dev,
struct SelftestUserCmdData_t *cmddata)
{
ST_DBG("GLUE_SELFTEST::std_selftest_adc () called.");
/*...........*/
/*....TBD....*/
/*...........*/
}
#endif
/********************************************************************/
/* Command Handling */
/********************************************************************/
static void SelftestHandleCommand(enum SelftestUSCmds_e cmd,
struct SelftestDevData_t *dev,
struct SelftestUserCmdData_t *cmddata)
{
ST_DBG("SelftestHandleCommand::Cmd:%u", cmddata->testId);
/* Handle Userspace Commands */
switch (cmd) {
#ifdef GPS_TEST_SUPPORTED
case ST_SUSC_GPS_TEST:
std_selftest_control_gps_io(dev, cmddata);
break;
#endif
#ifdef USB_ST_SUPPORTED
case ST_SUSC_USB_ST:
std_selftest_usb_charger(dev, cmddata);
break;
#endif
#ifdef ADC_ST_SUPPORTED
case ST_SUSC_ADC_ST:
std_selftest_adc(dev, cmddata);
break;
#endif
#ifdef DIGIMIC_SUPPORTED
case ST_SUSC_DIGIMIC:
ST_DBG("bcm_selftest_bb.c::SelftestHandleCommand::ST_SUSC_DIGIMIC");
std_selftest_digimic(dev, cmddata);
break;
#endif
#ifdef SLEEPCLOCK_SUPPORTED
case ST_SUSC_SLEEPCLOCK:
std_selftest_sleepclk(dev, cmddata);
break;
#endif
#ifdef HEADSET_ST_SUPPORTED
case ST_SUSC_HEADSET_ST:
std_selftest_headset(dev, cmddata);
break;
#endif
#ifdef IHF_ST_SUPPORTED
case ST_SUSC_IHF_ST:
std_selftest_ihf(dev, cmddata);
break;
#endif
#ifdef PMU_ST_SUPPORTED
case ST_SUSC_PMU_ST:
std_selftest_pmu(dev, cmddata);
break;
#endif
default:
cmddata->testStatus = ST_SELFTEST_NOT_SUPPORTED;
ST_DBG("Command not supported");
break;
}
}
/********************************************************************/
/* Selftest Sysfs file interface */
/********************************************************************/
static SelftestUserCmdData_t cmddata;
static ssize_t show_TestResult (struct device_driver *d, char * buf)
{
sprintf(buf, "%i %i %i %i %i %i %i %i %i %i %i %i %i",
cmddata.testId,
cmddata.testStatus,
cmddata.subtestCount,
cmddata.subtestStatus[0], cmddata.subtestStatus[1],
cmddata.subtestStatus[2], cmddata.subtestStatus[3],
cmddata.subtestStatus[4], cmddata.subtestStatus[5],
cmddata.subtestStatus[6], cmddata.subtestStatus[7],
cmddata.subtestStatus[8], cmddata.subtestStatus[9] );
return strlen(buf);
}
static ssize_t show_TestStart (struct device_driver *d, char * buf)
{
sprintf(buf,"%i %i %i %i)", cmddata.testId,
cmddata.parm1, cmddata.parm2, cmddata.parm3);
return strlen(buf);;
}
static ssize_t store_TestStart (struct device_driver *d, const char * buf, size_t count)
{
int TestId, Parm1, Parm2, Parm3;
struct SelftestDevData_t dev;
ST_DBG("store_TestStart - Message received");
dev.bcm_5900xx_pmu_dev = bcm590xx_dev;
if ( (sscanf(buf, "%i %i %i %i", &TestId, &Parm1, &Parm2, &Parm3 )) != 4)
return -EINVAL;
cmddata.testId = TestId;
cmddata.parm1 = Parm1;
cmddata.parm2 = Parm2;
cmddata.parm3 = Parm3;
ST_DBG("store_TestStart (%i, %i, %i, %i)", TestId, Parm1, Parm2, Parm3 );
SelftestHandleCommand((enum SelftestUSCmds_e)cmddata.testId, &dev, &cmddata);
return strnlen(buf, count);
}
static DRIVER_ATTR(TestResult, S_IRUGO, show_TestResult, NULL);
static DRIVER_ATTR(TestStart, S_IRUGO | S_IWUSR, show_TestStart, store_TestStart);
#define DRIVER_NAME "bcm59055-selftest"
/********************************************************************/
/* Selftest Procfs file interface */
/********************************************************************/
/***********************PMU PROC DEBUG Interface*********************/
static int selftest_open(struct inode *inode, struct file *file)
{
pr_debug("%s\n", __func__);
file->private_data = PDE(inode)->data;
return 0;
}
int selftest_release(struct inode *inode, struct file *file)
{
file->private_data = NULL;
return 0;
}
static long selftest_unlocked_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct SelftestUserCmdData_t cmddata;
struct SelftestDevData_t dev;
ST_DBG("Selftest command Received");
ST_DBG("Selftest copy_from_user");
dev.bcm_5900xx_pmu_dev = bcm590xx_dev;
if (copy_from_user((void *)&cmddata, (void*)arg,
sizeof(SelftestUserCmdData_t))) {
ST_DBG("Selftest copy_from_user Failed");
return -EFAULT;
}
cmddata.testId = cmd;
SelftestHandleCommand((enum SelftestUSCmds_e)cmd, &dev, &cmddata);
ST_DBG("Selftest copy_to_user");
if (copy_to_user ((void *)arg, (void*)&cmddata, sizeof(SelftestUserCmdData_t))) {
ST_DBG("Selftest copy_to_user Failed");
return -EFAULT;
}
return 0;
}
#define MAX_USER_INPUT_LEN 10
static ssize_t selftest_write(struct file *file, const char __user *buffer,
size_t len, loff_t *offset)
{
struct SelftestUserCmdData_t cmddata;
struct SelftestDevData_t dev;
if (len > MAX_USER_INPUT_LEN)
len = MAX_USER_INPUT_LEN;
dev.bcm_5900xx_pmu_dev = bcm590xx_dev;
cmddata.testId = buffer[0]-'a';
switch (cmddata.testId) {
case ST_SUSC_DIGIMIC:
cmddata.parm1 = 1; /* Enable DMIC 1 Test */
cmddata.parm2 = 1; /* Enable DMIC 2 Test */
break;
case ST_SUSC_GPS_TEST:
cmddata.parm1 = 0;
cmddata.parm2 = 0;
cmddata.parm3 = 0;
break;
default:
break;
}
SelftestHandleCommand(cmddata.testId, &dev, &cmddata);
if (cmddata.testStatus == 0) {
ST_DBG("Selftest OK");
} else {
ST_DBG("Selftest Failed (%u)", cmddata.testStatus);
}
*offset += len;
return len;
}
static const struct file_operations selftest_ops = {
.open = selftest_open,
.unlocked_ioctl = selftest_unlocked_ioctl,
.write = selftest_write,
.release = selftest_release,
.owner = THIS_MODULE,
};
/********************************************************************/
/* Selftest Drivers Stuff */
/********************************************************************/
/******************************************************************************
*
* Function Name: selftest_pmu_probe
*
* Desc: Called to perform module initialization when the module is loaded.
*
******************************************************************************/
static int __devinit selftest_pmu_probe(struct platform_device *pdev)
{
bcm590xx_dev = dev_get_drvdata(pdev->dev.parent);
ST_DBG("Selftest CSAPI driver probed");
/* Register proc interface */
proc_create_data("selftest", S_IRWXUGO, NULL,
&selftest_ops, NULL/*private data*/);
return 0;
}
static int __devexit selftest_pmu_remove(struct platform_device *pdev)
{
return 0;
}
struct platform_driver selftestpmu_driver = {
.probe = selftest_pmu_probe,
.remove = __devexit_p(selftest_pmu_remove),
.driver = {
.name = DRIVER_NAME,
}
};
#if 0
struct file_operations selftest_fops = {
.owner = THIS_MODULE,
.write = selftest_write,
.unlocked_ioctl = selftest_unlocked_ioctl,
.open = selftest_open,
.release = selftest_release,
};
struct miscdevice selftestpmu_miscdevice = {
.minor = MISC_DYNAMIC_MINOR,
.name = DRIVER_NAME,
.fops = &selftest_fops
};
#endif
/****************************************************************************
*
* selftest_pmu_init
*
* Called to perform module initialization when the module is loaded
*
***************************************************************************/
static int __init selftest_pmu_init(void)
{
/* Register driver */
platform_driver_register(&selftestpmu_driver);
#if 0
misc_register(&selftestpmu_miscdevice);
#endif
/* Register sysfs interface */
driver_create_file(&selftestpmu_driver.driver, &driver_attr_TestStart);
driver_create_file(&selftestpmu_driver.driver, &driver_attr_TestResult);
return 0;
}
/****************************************************************************
*
* selftest_pmu_exit
*
* Called to perform module cleanup when the module is unloaded.
*
***************************************************************************/
static void __exit selftest_pmu_exit(void)
{
platform_driver_unregister(&selftestpmu_driver);
driver_remove_file(&selftestpmu_driver.driver, &driver_attr_TestStart);
driver_remove_file(&selftestpmu_driver.driver, &driver_attr_TestResult);
}
module_init(selftest_pmu_init);
module_exit(selftest_pmu_exit);
MODULE_AUTHOR("PHERAGER");
MODULE_DESCRIPTION("BCM SELFTEST BB");
| gpl-2.0 |
aospan/media_tree | tools/perf/builtin-annotate.c | 42 | 10543 | /*
* builtin-annotate.c
*
* Builtin annotate command: Analyze the perf.data input file,
* look up and read DSOs and symbol information and display
* a histogram of results, along various sorting keys.
*/
#include "builtin.h"
#include "util/util.h"
#include "util/color.h"
#include <linux/list.h>
#include "util/cache.h"
#include <linux/rbtree.h>
#include "util/symbol.h"
#include "perf.h"
#include "util/debug.h"
#include "util/evlist.h"
#include "util/evsel.h"
#include "util/annotate.h"
#include "util/event.h"
#include <subcmd/parse-options.h>
#include "util/parse-events.h"
#include "util/thread.h"
#include "util/sort.h"
#include "util/hist.h"
#include "util/session.h"
#include "util/tool.h"
#include "util/data.h"
#include "arch/common.h"
#include <dlfcn.h>
#include <linux/bitmap.h>
struct perf_annotate {
struct perf_tool tool;
struct perf_session *session;
bool use_tui, use_stdio, use_gtk;
bool full_paths;
bool print_line;
bool skip_missing;
const char *sym_hist_filter;
const char *cpu_list;
DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
};
static int perf_evsel__add_sample(struct perf_evsel *evsel,
struct perf_sample *sample,
struct addr_location *al,
struct perf_annotate *ann)
{
struct hists *hists = evsel__hists(evsel);
struct hist_entry *he;
int ret;
if (ann->sym_hist_filter != NULL &&
(al->sym == NULL ||
strcmp(ann->sym_hist_filter, al->sym->name) != 0)) {
/* We're only interested in a symbol named sym_hist_filter */
/*
* FIXME: why isn't this done in the symbol_filter when loading
* the DSO?
*/
if (al->sym != NULL) {
rb_erase(&al->sym->rb_node,
&al->map->dso->symbols[al->map->type]);
symbol__delete(al->sym);
dso__reset_find_symbol_cache(al->map->dso);
}
return 0;
}
sample->period = 1;
sample->weight = 1;
he = __hists__add_entry(hists, al, NULL, NULL, NULL, sample, true);
if (he == NULL)
return -ENOMEM;
ret = hist_entry__inc_addr_samples(he, evsel->idx, al->addr);
hists__inc_nr_samples(hists, true);
return ret;
}
static int process_sample_event(struct perf_tool *tool,
union perf_event *event,
struct perf_sample *sample,
struct perf_evsel *evsel,
struct machine *machine)
{
struct perf_annotate *ann = container_of(tool, struct perf_annotate, tool);
struct addr_location al;
int ret = 0;
if (machine__resolve(machine, &al, sample) < 0) {
pr_warning("problem processing %d event, skipping it.\n",
event->header.type);
return -1;
}
if (ann->cpu_list && !test_bit(sample->cpu, ann->cpu_bitmap))
goto out_put;
if (!al.filtered && perf_evsel__add_sample(evsel, sample, &al, ann)) {
pr_warning("problem incrementing symbol count, "
"skipping event\n");
ret = -1;
}
out_put:
addr_location__put(&al);
return ret;
}
static int hist_entry__tty_annotate(struct hist_entry *he,
struct perf_evsel *evsel,
struct perf_annotate *ann)
{
return symbol__tty_annotate(he->ms.sym, he->ms.map, evsel,
ann->print_line, ann->full_paths, 0, 0);
}
static void hists__find_annotations(struct hists *hists,
struct perf_evsel *evsel,
struct perf_annotate *ann)
{
struct rb_node *nd = rb_first(&hists->entries), *next;
int key = K_RIGHT;
while (nd) {
struct hist_entry *he = rb_entry(nd, struct hist_entry, rb_node);
struct annotation *notes;
if (he->ms.sym == NULL || he->ms.map->dso->annotate_warned)
goto find_next;
notes = symbol__annotation(he->ms.sym);
if (notes->src == NULL) {
find_next:
if (key == K_LEFT)
nd = rb_prev(nd);
else
nd = rb_next(nd);
continue;
}
if (use_browser == 2) {
int ret;
int (*annotate)(struct hist_entry *he,
struct perf_evsel *evsel,
struct hist_browser_timer *hbt);
annotate = dlsym(perf_gtk_handle,
"hist_entry__gtk_annotate");
if (annotate == NULL) {
ui__error("GTK browser not found!\n");
return;
}
ret = annotate(he, evsel, NULL);
if (!ret || !ann->skip_missing)
return;
/* skip missing symbols */
nd = rb_next(nd);
} else if (use_browser == 1) {
key = hist_entry__tui_annotate(he, evsel, NULL);
switch (key) {
case -1:
if (!ann->skip_missing)
return;
/* fall through */
case K_RIGHT:
next = rb_next(nd);
break;
case K_LEFT:
next = rb_prev(nd);
break;
default:
return;
}
if (next != NULL)
nd = next;
} else {
hist_entry__tty_annotate(he, evsel, ann);
nd = rb_next(nd);
/*
* Since we have a hist_entry per IP for the same
* symbol, free he->ms.sym->src to signal we already
* processed this symbol.
*/
zfree(¬es->src->cycles_hist);
zfree(¬es->src);
}
}
}
static int __cmd_annotate(struct perf_annotate *ann)
{
int ret;
struct perf_session *session = ann->session;
struct perf_evsel *pos;
u64 total_nr_samples;
machines__set_symbol_filter(&session->machines, symbol__annotate_init);
if (ann->cpu_list) {
ret = perf_session__cpu_bitmap(session, ann->cpu_list,
ann->cpu_bitmap);
if (ret)
goto out;
}
if (!objdump_path) {
ret = perf_env__lookup_objdump(&session->header.env);
if (ret)
goto out;
}
ret = perf_session__process_events(session);
if (ret)
goto out;
if (dump_trace) {
perf_session__fprintf_nr_events(session, stdout);
perf_evlist__fprintf_nr_events(session->evlist, stdout);
goto out;
}
if (verbose > 3)
perf_session__fprintf(session, stdout);
if (verbose > 2)
perf_session__fprintf_dsos(session, stdout);
total_nr_samples = 0;
evlist__for_each(session->evlist, pos) {
struct hists *hists = evsel__hists(pos);
u32 nr_samples = hists->stats.nr_events[PERF_RECORD_SAMPLE];
if (nr_samples > 0) {
total_nr_samples += nr_samples;
hists__collapse_resort(hists, NULL);
/* Don't sort callchain */
perf_evsel__reset_sample_bit(pos, CALLCHAIN);
perf_evsel__output_resort(pos, NULL);
if (symbol_conf.event_group &&
!perf_evsel__is_group_leader(pos))
continue;
hists__find_annotations(hists, pos, ann);
}
}
if (total_nr_samples == 0) {
ui__error("The %s file has no samples!\n", session->file->path);
goto out;
}
if (use_browser == 2) {
void (*show_annotations)(void);
show_annotations = dlsym(perf_gtk_handle,
"perf_gtk__show_annotations");
if (show_annotations == NULL) {
ui__error("GTK browser not found!\n");
goto out;
}
show_annotations();
}
out:
return ret;
}
static const char * const annotate_usage[] = {
"perf annotate [<options>]",
NULL
};
int cmd_annotate(int argc, const char **argv, const char *prefix __maybe_unused)
{
struct perf_annotate annotate = {
.tool = {
.sample = process_sample_event,
.mmap = perf_event__process_mmap,
.mmap2 = perf_event__process_mmap2,
.comm = perf_event__process_comm,
.exit = perf_event__process_exit,
.fork = perf_event__process_fork,
.ordered_events = true,
.ordering_requires_timestamps = true,
},
};
struct perf_data_file file = {
.mode = PERF_DATA_MODE_READ,
};
const struct option options[] = {
OPT_STRING('i', "input", &input_name, "file",
"input file name"),
OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
"only consider symbols in these dsos"),
OPT_STRING('s', "symbol", &annotate.sym_hist_filter, "symbol",
"symbol to annotate"),
OPT_BOOLEAN('f', "force", &file.force, "don't complain, do it"),
OPT_INCR('v', "verbose", &verbose,
"be more verbose (show symbol address, etc)"),
OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
"dump raw trace in ASCII"),
OPT_BOOLEAN(0, "gtk", &annotate.use_gtk, "Use the GTK interface"),
OPT_BOOLEAN(0, "tui", &annotate.use_tui, "Use the TUI interface"),
OPT_BOOLEAN(0, "stdio", &annotate.use_stdio, "Use the stdio interface"),
OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
"file", "vmlinux pathname"),
OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
"load module symbols - WARNING: use only with -k and LIVE kernel"),
OPT_BOOLEAN('l', "print-line", &annotate.print_line,
"print matching source lines (may be slow)"),
OPT_BOOLEAN('P', "full-paths", &annotate.full_paths,
"Don't shorten the displayed pathnames"),
OPT_BOOLEAN(0, "skip-missing", &annotate.skip_missing,
"Skip symbols that cannot be annotated"),
OPT_STRING('C', "cpu", &annotate.cpu_list, "cpu", "list of cpus to profile"),
OPT_CALLBACK(0, "symfs", NULL, "directory",
"Look for files with symbols relative to this directory",
symbol__config_symfs),
OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
"Interleave source code with assembly code (default)"),
OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
"Display raw encoding of assembly instructions (default)"),
OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
"Specify disassembler style (e.g. -M intel for intel syntax)"),
OPT_STRING(0, "objdump", &objdump_path, "path",
"objdump binary to use for disassembly and annotations"),
OPT_BOOLEAN(0, "group", &symbol_conf.event_group,
"Show event group information together"),
OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
"Show a column with the sum of periods"),
OPT_END()
};
int ret = hists__init();
if (ret < 0)
return ret;
argc = parse_options(argc, argv, options, annotate_usage, 0);
if (argc) {
/*
* Special case: if there's an argument left then assume that
* it's a symbol filter:
*/
if (argc > 1)
usage_with_options(annotate_usage, options);
annotate.sym_hist_filter = argv[0];
}
file.path = input_name;
annotate.session = perf_session__new(&file, false, &annotate.tool);
if (annotate.session == NULL)
return -1;
symbol_conf.priv_size = sizeof(struct annotation);
symbol_conf.try_vmlinux_path = true;
ret = symbol__init(&annotate.session->header.env);
if (ret < 0)
goto out_delete;
if (setup_sorting(NULL) < 0)
usage_with_options(annotate_usage, options);
if (annotate.use_stdio)
use_browser = 0;
else if (annotate.use_tui)
use_browser = 1;
else if (annotate.use_gtk)
use_browser = 2;
setup_browser(true);
ret = __cmd_annotate(&annotate);
out_delete:
/*
* Speed up the exit process, for large files this can
* take quite a while.
*
* XXX Enable this when using valgrind or if we ever
* librarize this command.
*
* Also experiment with obstacks to see how much speed
* up we'll get here.
*
* perf_session__delete(session);
*/
return ret;
}
| gpl-2.0 |
zv/systemd | src/shared/sysctl-util.c | 42 | 2127 | /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <getopt.h>
#include "log.h"
#include "util.h"
#include "fileio.h"
#include "build.h"
#include "sysctl-util.h"
char *sysctl_normalize(char *s) {
char *n;
n = strpbrk(s, "/.");
/* If the first separator is a slash, the path is
* assumed to be normalized and slashes remain slashes
* and dots remains dots. */
if (!n || *n == '/')
return s;
/* Otherwise, dots become slashes and slashes become
* dots. Fun. */
while (n) {
if (*n == '.')
*n = '/';
else
*n = '.';
n = strpbrk(n + 1, "/.");
}
return s;
}
int sysctl_write(const char *property, const char *value) {
char *p;
assert(property);
assert(value);
log_debug("Setting '%s' to '%s'", property, value);
p = strjoina("/proc/sys/", property);
return write_string_file(p, value, 0);
}
int sysctl_read(const char *property, char **content) {
char *p;
assert(property);
assert(content);
p = strjoina("/proc/sys/", property);
return read_full_file(p, content, NULL);
}
| gpl-2.0 |
dancefire/hd806-kernel-android | drivers/firewire/core-cdev.c | 42 | 38861 | /*
* Char device for device raw access
*
* Copyright (C) 2005-2007 Kristian Hoegsberg <krh@bitplanet.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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/compat.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/firewire.h>
#include <linux/firewire-cdev.h>
#include <linux/idr.h>
#include <linux/irqflags.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/kref.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/time.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <asm/system.h>
#include "core.h"
struct client {
u32 version;
struct fw_device *device;
spinlock_t lock;
bool in_shutdown;
struct idr resource_idr;
struct list_head event_list;
wait_queue_head_t wait;
u64 bus_reset_closure;
struct fw_iso_context *iso_context;
u64 iso_closure;
struct fw_iso_buffer buffer;
unsigned long vm_start;
struct list_head link;
struct kref kref;
};
static inline void client_get(struct client *client)
{
kref_get(&client->kref);
}
static void client_release(struct kref *kref)
{
struct client *client = container_of(kref, struct client, kref);
fw_device_put(client->device);
kfree(client);
}
static void client_put(struct client *client)
{
kref_put(&client->kref, client_release);
}
struct client_resource;
typedef void (*client_resource_release_fn_t)(struct client *,
struct client_resource *);
struct client_resource {
client_resource_release_fn_t release;
int handle;
};
struct address_handler_resource {
struct client_resource resource;
struct fw_address_handler handler;
__u64 closure;
struct client *client;
};
struct outbound_transaction_resource {
struct client_resource resource;
struct fw_transaction transaction;
};
struct inbound_transaction_resource {
struct client_resource resource;
struct fw_request *request;
void *data;
size_t length;
};
struct descriptor_resource {
struct client_resource resource;
struct fw_descriptor descriptor;
u32 data[0];
};
struct iso_resource {
struct client_resource resource;
struct client *client;
/* Schedule work and access todo only with client->lock held. */
struct delayed_work work;
enum {ISO_RES_ALLOC, ISO_RES_REALLOC, ISO_RES_DEALLOC,
ISO_RES_ALLOC_ONCE, ISO_RES_DEALLOC_ONCE,} todo;
int generation;
u64 channels;
s32 bandwidth;
__be32 transaction_data[2];
struct iso_resource_event *e_alloc, *e_dealloc;
};
static void release_iso_resource(struct client *, struct client_resource *);
static void schedule_iso_resource(struct iso_resource *r, unsigned long delay)
{
client_get(r->client);
if (!schedule_delayed_work(&r->work, delay))
client_put(r->client);
}
static void schedule_if_iso_resource(struct client_resource *resource)
{
if (resource->release == release_iso_resource)
schedule_iso_resource(container_of(resource,
struct iso_resource, resource), 0);
}
/*
* dequeue_event() just kfree()'s the event, so the event has to be
* the first field in a struct XYZ_event.
*/
struct event {
struct { void *data; size_t size; } v[2];
struct list_head link;
};
struct bus_reset_event {
struct event event;
struct fw_cdev_event_bus_reset reset;
};
struct outbound_transaction_event {
struct event event;
struct client *client;
struct outbound_transaction_resource r;
struct fw_cdev_event_response response;
};
struct inbound_transaction_event {
struct event event;
struct fw_cdev_event_request request;
};
struct iso_interrupt_event {
struct event event;
struct fw_cdev_event_iso_interrupt interrupt;
};
struct iso_resource_event {
struct event event;
struct fw_cdev_event_iso_resource iso_resource;
};
static inline void __user *u64_to_uptr(__u64 value)
{
return (void __user *)(unsigned long)value;
}
static inline __u64 uptr_to_u64(void __user *ptr)
{
return (__u64)(unsigned long)ptr;
}
static int fw_device_op_open(struct inode *inode, struct file *file)
{
struct fw_device *device;
struct client *client;
device = fw_device_get_by_devt(inode->i_rdev);
if (device == NULL)
return -ENODEV;
if (fw_device_is_shutdown(device)) {
fw_device_put(device);
return -ENODEV;
}
client = kzalloc(sizeof(*client), GFP_KERNEL);
if (client == NULL) {
fw_device_put(device);
return -ENOMEM;
}
client->device = device;
spin_lock_init(&client->lock);
idr_init(&client->resource_idr);
INIT_LIST_HEAD(&client->event_list);
init_waitqueue_head(&client->wait);
kref_init(&client->kref);
file->private_data = client;
mutex_lock(&device->client_list_mutex);
list_add_tail(&client->link, &device->client_list);
mutex_unlock(&device->client_list_mutex);
return 0;
}
static void queue_event(struct client *client, struct event *event,
void *data0, size_t size0, void *data1, size_t size1)
{
unsigned long flags;
event->v[0].data = data0;
event->v[0].size = size0;
event->v[1].data = data1;
event->v[1].size = size1;
spin_lock_irqsave(&client->lock, flags);
if (client->in_shutdown)
kfree(event);
else
list_add_tail(&event->link, &client->event_list);
spin_unlock_irqrestore(&client->lock, flags);
wake_up_interruptible(&client->wait);
}
static int dequeue_event(struct client *client,
char __user *buffer, size_t count)
{
struct event *event;
size_t size, total;
int i, ret;
ret = wait_event_interruptible(client->wait,
!list_empty(&client->event_list) ||
fw_device_is_shutdown(client->device));
if (ret < 0)
return ret;
if (list_empty(&client->event_list) &&
fw_device_is_shutdown(client->device))
return -ENODEV;
spin_lock_irq(&client->lock);
event = list_first_entry(&client->event_list, struct event, link);
list_del(&event->link);
spin_unlock_irq(&client->lock);
total = 0;
for (i = 0; i < ARRAY_SIZE(event->v) && total < count; i++) {
size = min(event->v[i].size, count - total);
if (copy_to_user(buffer + total, event->v[i].data, size)) {
ret = -EFAULT;
goto out;
}
total += size;
}
ret = total;
out:
kfree(event);
return ret;
}
static ssize_t fw_device_op_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct client *client = file->private_data;
return dequeue_event(client, buffer, count);
}
static void fill_bus_reset_event(struct fw_cdev_event_bus_reset *event,
struct client *client)
{
struct fw_card *card = client->device->card;
spin_lock_irq(&card->lock);
event->closure = client->bus_reset_closure;
event->type = FW_CDEV_EVENT_BUS_RESET;
event->generation = client->device->generation;
event->node_id = client->device->node_id;
event->local_node_id = card->local_node->node_id;
event->bm_node_id = 0; /* FIXME: We don't track the BM. */
event->irm_node_id = card->irm_node->node_id;
event->root_node_id = card->root_node->node_id;
spin_unlock_irq(&card->lock);
}
static void for_each_client(struct fw_device *device,
void (*callback)(struct client *client))
{
struct client *c;
mutex_lock(&device->client_list_mutex);
list_for_each_entry(c, &device->client_list, link)
callback(c);
mutex_unlock(&device->client_list_mutex);
}
static int schedule_reallocations(int id, void *p, void *data)
{
schedule_if_iso_resource(p);
return 0;
}
static void queue_bus_reset_event(struct client *client)
{
struct bus_reset_event *e;
e = kzalloc(sizeof(*e), GFP_KERNEL);
if (e == NULL) {
fw_notify("Out of memory when allocating bus reset event\n");
return;
}
fill_bus_reset_event(&e->reset, client);
queue_event(client, &e->event,
&e->reset, sizeof(e->reset), NULL, 0);
spin_lock_irq(&client->lock);
idr_for_each(&client->resource_idr, schedule_reallocations, client);
spin_unlock_irq(&client->lock);
}
void fw_device_cdev_update(struct fw_device *device)
{
for_each_client(device, queue_bus_reset_event);
}
static void wake_up_client(struct client *client)
{
wake_up_interruptible(&client->wait);
}
void fw_device_cdev_remove(struct fw_device *device)
{
for_each_client(device, wake_up_client);
}
union ioctl_arg {
struct fw_cdev_get_info get_info;
struct fw_cdev_send_request send_request;
struct fw_cdev_allocate allocate;
struct fw_cdev_deallocate deallocate;
struct fw_cdev_send_response send_response;
struct fw_cdev_initiate_bus_reset initiate_bus_reset;
struct fw_cdev_add_descriptor add_descriptor;
struct fw_cdev_remove_descriptor remove_descriptor;
struct fw_cdev_create_iso_context create_iso_context;
struct fw_cdev_queue_iso queue_iso;
struct fw_cdev_start_iso start_iso;
struct fw_cdev_stop_iso stop_iso;
struct fw_cdev_get_cycle_timer get_cycle_timer;
struct fw_cdev_allocate_iso_resource allocate_iso_resource;
struct fw_cdev_send_stream_packet send_stream_packet;
struct fw_cdev_get_cycle_timer2 get_cycle_timer2;
};
static int ioctl_get_info(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_get_info *a = &arg->get_info;
struct fw_cdev_event_bus_reset bus_reset;
unsigned long ret = 0;
client->version = a->version;
a->version = FW_CDEV_VERSION;
a->card = client->device->card->index;
down_read(&fw_device_rwsem);
if (a->rom != 0) {
size_t want = a->rom_length;
size_t have = client->device->config_rom_length * 4;
ret = copy_to_user(u64_to_uptr(a->rom),
client->device->config_rom, min(want, have));
}
a->rom_length = client->device->config_rom_length * 4;
up_read(&fw_device_rwsem);
if (ret != 0)
return -EFAULT;
client->bus_reset_closure = a->bus_reset_closure;
if (a->bus_reset != 0) {
fill_bus_reset_event(&bus_reset, client);
if (copy_to_user(u64_to_uptr(a->bus_reset),
&bus_reset, sizeof(bus_reset)))
return -EFAULT;
}
return 0;
}
static int add_client_resource(struct client *client,
struct client_resource *resource, gfp_t gfp_mask)
{
unsigned long flags;
int ret;
retry:
if (idr_pre_get(&client->resource_idr, gfp_mask) == 0)
return -ENOMEM;
spin_lock_irqsave(&client->lock, flags);
if (client->in_shutdown)
ret = -ECANCELED;
else
ret = idr_get_new(&client->resource_idr, resource,
&resource->handle);
if (ret >= 0) {
client_get(client);
schedule_if_iso_resource(resource);
}
spin_unlock_irqrestore(&client->lock, flags);
if (ret == -EAGAIN)
goto retry;
return ret < 0 ? ret : 0;
}
static int release_client_resource(struct client *client, u32 handle,
client_resource_release_fn_t release,
struct client_resource **return_resource)
{
struct client_resource *resource;
spin_lock_irq(&client->lock);
if (client->in_shutdown)
resource = NULL;
else
resource = idr_find(&client->resource_idr, handle);
if (resource && resource->release == release)
idr_remove(&client->resource_idr, handle);
spin_unlock_irq(&client->lock);
if (!(resource && resource->release == release))
return -EINVAL;
if (return_resource)
*return_resource = resource;
else
resource->release(client, resource);
client_put(client);
return 0;
}
static void release_transaction(struct client *client,
struct client_resource *resource)
{
struct outbound_transaction_resource *r = container_of(resource,
struct outbound_transaction_resource, resource);
fw_cancel_transaction(client->device->card, &r->transaction);
}
static void complete_transaction(struct fw_card *card, int rcode,
void *payload, size_t length, void *data)
{
struct outbound_transaction_event *e = data;
struct fw_cdev_event_response *rsp = &e->response;
struct client *client = e->client;
unsigned long flags;
if (length < rsp->length)
rsp->length = length;
if (rcode == RCODE_COMPLETE)
memcpy(rsp->data, payload, rsp->length);
spin_lock_irqsave(&client->lock, flags);
/*
* 1. If called while in shutdown, the idr tree must be left untouched.
* The idr handle will be removed and the client reference will be
* dropped later.
* 2. If the call chain was release_client_resource ->
* release_transaction -> complete_transaction (instead of a normal
* conclusion of the transaction), i.e. if this resource was already
* unregistered from the idr, the client reference will be dropped
* by release_client_resource and we must not drop it here.
*/
if (!client->in_shutdown &&
idr_find(&client->resource_idr, e->r.resource.handle)) {
idr_remove(&client->resource_idr, e->r.resource.handle);
/* Drop the idr's reference */
client_put(client);
}
spin_unlock_irqrestore(&client->lock, flags);
rsp->type = FW_CDEV_EVENT_RESPONSE;
rsp->rcode = rcode;
/*
* In the case that sizeof(*rsp) doesn't align with the position of the
* data, and the read is short, preserve an extra copy of the data
* to stay compatible with a pre-2.6.27 bug. Since the bug is harmless
* for short reads and some apps depended on it, this is both safe
* and prudent for compatibility.
*/
if (rsp->length <= sizeof(*rsp) - offsetof(typeof(*rsp), data))
queue_event(client, &e->event, rsp, sizeof(*rsp),
rsp->data, rsp->length);
else
queue_event(client, &e->event, rsp, sizeof(*rsp) + rsp->length,
NULL, 0);
/* Drop the transaction callback's reference */
client_put(client);
}
static int init_request(struct client *client,
struct fw_cdev_send_request *request,
int destination_id, int speed)
{
struct outbound_transaction_event *e;
int ret;
if (request->tcode != TCODE_STREAM_DATA &&
(request->length > 4096 || request->length > 512 << speed))
return -EIO;
e = kmalloc(sizeof(*e) + request->length, GFP_KERNEL);
if (e == NULL)
return -ENOMEM;
e->client = client;
e->response.length = request->length;
e->response.closure = request->closure;
if (request->data &&
copy_from_user(e->response.data,
u64_to_uptr(request->data), request->length)) {
ret = -EFAULT;
goto failed;
}
e->r.resource.release = release_transaction;
ret = add_client_resource(client, &e->r.resource, GFP_KERNEL);
if (ret < 0)
goto failed;
/* Get a reference for the transaction callback */
client_get(client);
fw_send_request(client->device->card, &e->r.transaction,
request->tcode, destination_id, request->generation,
speed, request->offset, e->response.data,
request->length, complete_transaction, e);
return 0;
failed:
kfree(e);
return ret;
}
static int ioctl_send_request(struct client *client, union ioctl_arg *arg)
{
switch (arg->send_request.tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
case TCODE_WRITE_BLOCK_REQUEST:
case TCODE_READ_QUADLET_REQUEST:
case TCODE_READ_BLOCK_REQUEST:
case TCODE_LOCK_MASK_SWAP:
case TCODE_LOCK_COMPARE_SWAP:
case TCODE_LOCK_FETCH_ADD:
case TCODE_LOCK_LITTLE_ADD:
case TCODE_LOCK_BOUNDED_ADD:
case TCODE_LOCK_WRAP_ADD:
case TCODE_LOCK_VENDOR_DEPENDENT:
break;
default:
return -EINVAL;
}
return init_request(client, &arg->send_request, client->device->node_id,
client->device->max_speed);
}
static inline bool is_fcp_request(struct fw_request *request)
{
return request == NULL;
}
static void release_request(struct client *client,
struct client_resource *resource)
{
struct inbound_transaction_resource *r = container_of(resource,
struct inbound_transaction_resource, resource);
if (is_fcp_request(r->request))
kfree(r->data);
else
fw_send_response(client->device->card, r->request,
RCODE_CONFLICT_ERROR);
kfree(r);
}
static void handle_request(struct fw_card *card, struct fw_request *request,
int tcode, int destination, int source,
int generation, int speed,
unsigned long long offset,
void *payload, size_t length, void *callback_data)
{
struct address_handler_resource *handler = callback_data;
struct inbound_transaction_resource *r;
struct inbound_transaction_event *e;
void *fcp_frame = NULL;
int ret;
r = kmalloc(sizeof(*r), GFP_ATOMIC);
e = kmalloc(sizeof(*e), GFP_ATOMIC);
if (r == NULL || e == NULL)
goto failed;
r->request = request;
r->data = payload;
r->length = length;
if (is_fcp_request(request)) {
/*
* FIXME: Let core-transaction.c manage a
* single reference-counted copy?
*/
fcp_frame = kmemdup(payload, length, GFP_ATOMIC);
if (fcp_frame == NULL)
goto failed;
r->data = fcp_frame;
}
r->resource.release = release_request;
ret = add_client_resource(handler->client, &r->resource, GFP_ATOMIC);
if (ret < 0)
goto failed;
e->request.type = FW_CDEV_EVENT_REQUEST;
e->request.tcode = tcode;
e->request.offset = offset;
e->request.length = length;
e->request.handle = r->resource.handle;
e->request.closure = handler->closure;
queue_event(handler->client, &e->event,
&e->request, sizeof(e->request), r->data, length);
return;
failed:
kfree(r);
kfree(e);
kfree(fcp_frame);
if (!is_fcp_request(request))
fw_send_response(card, request, RCODE_CONFLICT_ERROR);
}
static void release_address_handler(struct client *client,
struct client_resource *resource)
{
struct address_handler_resource *r =
container_of(resource, struct address_handler_resource, resource);
fw_core_remove_address_handler(&r->handler);
kfree(r);
}
static int ioctl_allocate(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_allocate *a = &arg->allocate;
struct address_handler_resource *r;
struct fw_address_region region;
int ret;
r = kmalloc(sizeof(*r), GFP_KERNEL);
if (r == NULL)
return -ENOMEM;
region.start = a->offset;
region.end = a->offset + a->length;
r->handler.length = a->length;
r->handler.address_callback = handle_request;
r->handler.callback_data = r;
r->closure = a->closure;
r->client = client;
ret = fw_core_add_address_handler(&r->handler, ®ion);
if (ret < 0) {
kfree(r);
return ret;
}
r->resource.release = release_address_handler;
ret = add_client_resource(client, &r->resource, GFP_KERNEL);
if (ret < 0) {
release_address_handler(client, &r->resource);
return ret;
}
a->handle = r->resource.handle;
return 0;
}
static int ioctl_deallocate(struct client *client, union ioctl_arg *arg)
{
return release_client_resource(client, arg->deallocate.handle,
release_address_handler, NULL);
}
static int ioctl_send_response(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_send_response *a = &arg->send_response;
struct client_resource *resource;
struct inbound_transaction_resource *r;
int ret = 0;
if (release_client_resource(client, a->handle,
release_request, &resource) < 0)
return -EINVAL;
r = container_of(resource, struct inbound_transaction_resource,
resource);
if (is_fcp_request(r->request))
goto out;
if (a->length < r->length)
r->length = a->length;
if (copy_from_user(r->data, u64_to_uptr(a->data), r->length)) {
ret = -EFAULT;
kfree(r->request);
goto out;
}
fw_send_response(client->device->card, r->request, a->rcode);
out:
kfree(r);
return ret;
}
static int ioctl_initiate_bus_reset(struct client *client, union ioctl_arg *arg)
{
return fw_core_initiate_bus_reset(client->device->card,
arg->initiate_bus_reset.type == FW_CDEV_SHORT_RESET);
}
static void release_descriptor(struct client *client,
struct client_resource *resource)
{
struct descriptor_resource *r =
container_of(resource, struct descriptor_resource, resource);
fw_core_remove_descriptor(&r->descriptor);
kfree(r);
}
static int ioctl_add_descriptor(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_add_descriptor *a = &arg->add_descriptor;
struct descriptor_resource *r;
int ret;
/* Access policy: Allow this ioctl only on local nodes' device files. */
if (!client->device->is_local)
return -ENOSYS;
if (a->length > 256)
return -EINVAL;
r = kmalloc(sizeof(*r) + a->length * 4, GFP_KERNEL);
if (r == NULL)
return -ENOMEM;
if (copy_from_user(r->data, u64_to_uptr(a->data), a->length * 4)) {
ret = -EFAULT;
goto failed;
}
r->descriptor.length = a->length;
r->descriptor.immediate = a->immediate;
r->descriptor.key = a->key;
r->descriptor.data = r->data;
ret = fw_core_add_descriptor(&r->descriptor);
if (ret < 0)
goto failed;
r->resource.release = release_descriptor;
ret = add_client_resource(client, &r->resource, GFP_KERNEL);
if (ret < 0) {
fw_core_remove_descriptor(&r->descriptor);
goto failed;
}
a->handle = r->resource.handle;
return 0;
failed:
kfree(r);
return ret;
}
static int ioctl_remove_descriptor(struct client *client, union ioctl_arg *arg)
{
return release_client_resource(client, arg->remove_descriptor.handle,
release_descriptor, NULL);
}
static void iso_callback(struct fw_iso_context *context, u32 cycle,
size_t header_length, void *header, void *data)
{
struct client *client = data;
struct iso_interrupt_event *e;
e = kzalloc(sizeof(*e) + header_length, GFP_ATOMIC);
if (e == NULL)
return;
e->interrupt.type = FW_CDEV_EVENT_ISO_INTERRUPT;
e->interrupt.closure = client->iso_closure;
e->interrupt.cycle = cycle;
e->interrupt.header_length = header_length;
memcpy(e->interrupt.header, header, header_length);
queue_event(client, &e->event, &e->interrupt,
sizeof(e->interrupt) + header_length, NULL, 0);
}
static int ioctl_create_iso_context(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_create_iso_context *a = &arg->create_iso_context;
struct fw_iso_context *context;
/* We only support one context at this time. */
if (client->iso_context != NULL)
return -EBUSY;
if (a->channel > 63)
return -EINVAL;
switch (a->type) {
case FW_ISO_CONTEXT_RECEIVE:
if (a->header_size < 4 || (a->header_size & 3))
return -EINVAL;
break;
case FW_ISO_CONTEXT_TRANSMIT:
if (a->speed > SCODE_3200)
return -EINVAL;
break;
default:
return -EINVAL;
}
context = fw_iso_context_create(client->device->card, a->type,
a->channel, a->speed, a->header_size,
iso_callback, client);
if (IS_ERR(context))
return PTR_ERR(context);
client->iso_closure = a->closure;
client->iso_context = context;
/* We only support one context at this time. */
a->handle = 0;
return 0;
}
/* Macros for decoding the iso packet control header. */
#define GET_PAYLOAD_LENGTH(v) ((v) & 0xffff)
#define GET_INTERRUPT(v) (((v) >> 16) & 0x01)
#define GET_SKIP(v) (((v) >> 17) & 0x01)
#define GET_TAG(v) (((v) >> 18) & 0x03)
#define GET_SY(v) (((v) >> 20) & 0x0f)
#define GET_HEADER_LENGTH(v) (((v) >> 24) & 0xff)
static int ioctl_queue_iso(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_queue_iso *a = &arg->queue_iso;
struct fw_cdev_iso_packet __user *p, *end, *next;
struct fw_iso_context *ctx = client->iso_context;
unsigned long payload, buffer_end, header_length;
u32 control;
int count;
struct {
struct fw_iso_packet packet;
u8 header[256];
} u;
if (ctx == NULL || a->handle != 0)
return -EINVAL;
/*
* If the user passes a non-NULL data pointer, has mmap()'ed
* the iso buffer, and the pointer points inside the buffer,
* we setup the payload pointers accordingly. Otherwise we
* set them both to 0, which will still let packets with
* payload_length == 0 through. In other words, if no packets
* use the indirect payload, the iso buffer need not be mapped
* and the a->data pointer is ignored.
*/
payload = (unsigned long)a->data - client->vm_start;
buffer_end = client->buffer.page_count << PAGE_SHIFT;
if (a->data == 0 || client->buffer.pages == NULL ||
payload >= buffer_end) {
payload = 0;
buffer_end = 0;
}
p = (struct fw_cdev_iso_packet __user *)u64_to_uptr(a->packets);
if (!access_ok(VERIFY_READ, p, a->size))
return -EFAULT;
end = (void __user *)p + a->size;
count = 0;
while (p < end) {
if (get_user(control, &p->control))
return -EFAULT;
u.packet.payload_length = GET_PAYLOAD_LENGTH(control);
u.packet.interrupt = GET_INTERRUPT(control);
u.packet.skip = GET_SKIP(control);
u.packet.tag = GET_TAG(control);
u.packet.sy = GET_SY(control);
u.packet.header_length = GET_HEADER_LENGTH(control);
if (ctx->type == FW_ISO_CONTEXT_TRANSMIT) {
if (u.packet.header_length % 4 != 0)
return -EINVAL;
header_length = u.packet.header_length;
} else {
/*
* We require that header_length is a multiple of
* the fixed header size, ctx->header_size.
*/
if (ctx->header_size == 0) {
if (u.packet.header_length > 0)
return -EINVAL;
} else if (u.packet.header_length == 0 ||
u.packet.header_length % ctx->header_size != 0) {
return -EINVAL;
}
header_length = 0;
}
next = (struct fw_cdev_iso_packet __user *)
&p->header[header_length / 4];
if (next > end)
return -EINVAL;
if (__copy_from_user
(u.packet.header, p->header, header_length))
return -EFAULT;
if (u.packet.skip && ctx->type == FW_ISO_CONTEXT_TRANSMIT &&
u.packet.header_length + u.packet.payload_length > 0)
return -EINVAL;
if (payload + u.packet.payload_length > buffer_end)
return -EINVAL;
if (fw_iso_context_queue(ctx, &u.packet,
&client->buffer, payload))
break;
p = next;
payload += u.packet.payload_length;
count++;
}
a->size -= uptr_to_u64(p) - a->packets;
a->packets = uptr_to_u64(p);
a->data = client->vm_start + payload;
return count;
}
static int ioctl_start_iso(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_start_iso *a = &arg->start_iso;
if (client->iso_context == NULL || a->handle != 0)
return -EINVAL;
if (client->iso_context->type == FW_ISO_CONTEXT_RECEIVE &&
(a->tags == 0 || a->tags > 15 || a->sync > 15))
return -EINVAL;
return fw_iso_context_start(client->iso_context,
a->cycle, a->sync, a->tags);
}
static int ioctl_stop_iso(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_stop_iso *a = &arg->stop_iso;
if (client->iso_context == NULL || a->handle != 0)
return -EINVAL;
return fw_iso_context_stop(client->iso_context);
}
static int ioctl_get_cycle_timer2(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_get_cycle_timer2 *a = &arg->get_cycle_timer2;
struct fw_card *card = client->device->card;
struct timespec ts = {0, 0};
u32 cycle_time;
int ret = 0;
local_irq_disable();
cycle_time = card->driver->get_cycle_time(card);
switch (a->clk_id) {
case CLOCK_REALTIME: getnstimeofday(&ts); break;
case CLOCK_MONOTONIC: do_posix_clock_monotonic_gettime(&ts); break;
case CLOCK_MONOTONIC_RAW: getrawmonotonic(&ts); break;
default:
ret = -EINVAL;
}
local_irq_enable();
a->tv_sec = ts.tv_sec;
a->tv_nsec = ts.tv_nsec;
a->cycle_timer = cycle_time;
return ret;
}
static int ioctl_get_cycle_timer(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_get_cycle_timer *a = &arg->get_cycle_timer;
struct fw_cdev_get_cycle_timer2 ct2;
ct2.clk_id = CLOCK_REALTIME;
ioctl_get_cycle_timer2(client, (union ioctl_arg *)&ct2);
a->local_time = ct2.tv_sec * USEC_PER_SEC + ct2.tv_nsec / NSEC_PER_USEC;
a->cycle_timer = ct2.cycle_timer;
return 0;
}
static void iso_resource_work(struct work_struct *work)
{
struct iso_resource_event *e;
struct iso_resource *r =
container_of(work, struct iso_resource, work.work);
struct client *client = r->client;
int generation, channel, bandwidth, todo;
bool skip, free, success;
spin_lock_irq(&client->lock);
generation = client->device->generation;
todo = r->todo;
/* Allow 1000ms grace period for other reallocations. */
if (todo == ISO_RES_ALLOC &&
time_is_after_jiffies(client->device->card->reset_jiffies + HZ)) {
schedule_iso_resource(r, DIV_ROUND_UP(HZ, 3));
skip = true;
} else {
/* We could be called twice within the same generation. */
skip = todo == ISO_RES_REALLOC &&
r->generation == generation;
}
free = todo == ISO_RES_DEALLOC ||
todo == ISO_RES_ALLOC_ONCE ||
todo == ISO_RES_DEALLOC_ONCE;
r->generation = generation;
spin_unlock_irq(&client->lock);
if (skip)
goto out;
bandwidth = r->bandwidth;
fw_iso_resource_manage(client->device->card, generation,
r->channels, &channel, &bandwidth,
todo == ISO_RES_ALLOC ||
todo == ISO_RES_REALLOC ||
todo == ISO_RES_ALLOC_ONCE,
r->transaction_data);
/*
* Is this generation outdated already? As long as this resource sticks
* in the idr, it will be scheduled again for a newer generation or at
* shutdown.
*/
if (channel == -EAGAIN &&
(todo == ISO_RES_ALLOC || todo == ISO_RES_REALLOC))
goto out;
success = channel >= 0 || bandwidth > 0;
spin_lock_irq(&client->lock);
/*
* Transit from allocation to reallocation, except if the client
* requested deallocation in the meantime.
*/
if (r->todo == ISO_RES_ALLOC)
r->todo = ISO_RES_REALLOC;
/*
* Allocation or reallocation failure? Pull this resource out of the
* idr and prepare for deletion, unless the client is shutting down.
*/
if (r->todo == ISO_RES_REALLOC && !success &&
!client->in_shutdown &&
idr_find(&client->resource_idr, r->resource.handle)) {
idr_remove(&client->resource_idr, r->resource.handle);
client_put(client);
free = true;
}
spin_unlock_irq(&client->lock);
if (todo == ISO_RES_ALLOC && channel >= 0)
r->channels = 1ULL << channel;
if (todo == ISO_RES_REALLOC && success)
goto out;
if (todo == ISO_RES_ALLOC || todo == ISO_RES_ALLOC_ONCE) {
e = r->e_alloc;
r->e_alloc = NULL;
} else {
e = r->e_dealloc;
r->e_dealloc = NULL;
}
e->iso_resource.handle = r->resource.handle;
e->iso_resource.channel = channel;
e->iso_resource.bandwidth = bandwidth;
queue_event(client, &e->event,
&e->iso_resource, sizeof(e->iso_resource), NULL, 0);
if (free) {
cancel_delayed_work(&r->work);
kfree(r->e_alloc);
kfree(r->e_dealloc);
kfree(r);
}
out:
client_put(client);
}
static void release_iso_resource(struct client *client,
struct client_resource *resource)
{
struct iso_resource *r =
container_of(resource, struct iso_resource, resource);
spin_lock_irq(&client->lock);
r->todo = ISO_RES_DEALLOC;
schedule_iso_resource(r, 0);
spin_unlock_irq(&client->lock);
}
static int init_iso_resource(struct client *client,
struct fw_cdev_allocate_iso_resource *request, int todo)
{
struct iso_resource_event *e1, *e2;
struct iso_resource *r;
int ret;
if ((request->channels == 0 && request->bandwidth == 0) ||
request->bandwidth > BANDWIDTH_AVAILABLE_INITIAL ||
request->bandwidth < 0)
return -EINVAL;
r = kmalloc(sizeof(*r), GFP_KERNEL);
e1 = kmalloc(sizeof(*e1), GFP_KERNEL);
e2 = kmalloc(sizeof(*e2), GFP_KERNEL);
if (r == NULL || e1 == NULL || e2 == NULL) {
ret = -ENOMEM;
goto fail;
}
INIT_DELAYED_WORK(&r->work, iso_resource_work);
r->client = client;
r->todo = todo;
r->generation = -1;
r->channels = request->channels;
r->bandwidth = request->bandwidth;
r->e_alloc = e1;
r->e_dealloc = e2;
e1->iso_resource.closure = request->closure;
e1->iso_resource.type = FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED;
e2->iso_resource.closure = request->closure;
e2->iso_resource.type = FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED;
if (todo == ISO_RES_ALLOC) {
r->resource.release = release_iso_resource;
ret = add_client_resource(client, &r->resource, GFP_KERNEL);
if (ret < 0)
goto fail;
} else {
r->resource.release = NULL;
r->resource.handle = -1;
schedule_iso_resource(r, 0);
}
request->handle = r->resource.handle;
return 0;
fail:
kfree(r);
kfree(e1);
kfree(e2);
return ret;
}
static int ioctl_allocate_iso_resource(struct client *client,
union ioctl_arg *arg)
{
return init_iso_resource(client,
&arg->allocate_iso_resource, ISO_RES_ALLOC);
}
static int ioctl_deallocate_iso_resource(struct client *client,
union ioctl_arg *arg)
{
return release_client_resource(client,
arg->deallocate.handle, release_iso_resource, NULL);
}
static int ioctl_allocate_iso_resource_once(struct client *client,
union ioctl_arg *arg)
{
return init_iso_resource(client,
&arg->allocate_iso_resource, ISO_RES_ALLOC_ONCE);
}
static int ioctl_deallocate_iso_resource_once(struct client *client,
union ioctl_arg *arg)
{
return init_iso_resource(client,
&arg->allocate_iso_resource, ISO_RES_DEALLOC_ONCE);
}
/*
* Returns a speed code: Maximum speed to or from this device,
* limited by the device's link speed, the local node's link speed,
* and all PHY port speeds between the two links.
*/
static int ioctl_get_speed(struct client *client, union ioctl_arg *arg)
{
return client->device->max_speed;
}
static int ioctl_send_broadcast_request(struct client *client,
union ioctl_arg *arg)
{
struct fw_cdev_send_request *a = &arg->send_request;
switch (a->tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
case TCODE_WRITE_BLOCK_REQUEST:
break;
default:
return -EINVAL;
}
/* Security policy: Only allow accesses to Units Space. */
if (a->offset < CSR_REGISTER_BASE + CSR_CONFIG_ROM_END)
return -EACCES;
return init_request(client, a, LOCAL_BUS | 0x3f, SCODE_100);
}
static int ioctl_send_stream_packet(struct client *client, union ioctl_arg *arg)
{
struct fw_cdev_send_stream_packet *a = &arg->send_stream_packet;
struct fw_cdev_send_request request;
int dest;
if (a->speed > client->device->card->link_speed ||
a->length > 1024 << a->speed)
return -EIO;
if (a->tag > 3 || a->channel > 63 || a->sy > 15)
return -EINVAL;
dest = fw_stream_packet_destination_id(a->tag, a->channel, a->sy);
request.tcode = TCODE_STREAM_DATA;
request.length = a->length;
request.closure = a->closure;
request.data = a->data;
request.generation = a->generation;
return init_request(client, &request, dest, a->speed);
}
static int (* const ioctl_handlers[])(struct client *, union ioctl_arg *) = {
ioctl_get_info,
ioctl_send_request,
ioctl_allocate,
ioctl_deallocate,
ioctl_send_response,
ioctl_initiate_bus_reset,
ioctl_add_descriptor,
ioctl_remove_descriptor,
ioctl_create_iso_context,
ioctl_queue_iso,
ioctl_start_iso,
ioctl_stop_iso,
ioctl_get_cycle_timer,
ioctl_allocate_iso_resource,
ioctl_deallocate_iso_resource,
ioctl_allocate_iso_resource_once,
ioctl_deallocate_iso_resource_once,
ioctl_get_speed,
ioctl_send_broadcast_request,
ioctl_send_stream_packet,
ioctl_get_cycle_timer2,
};
static int dispatch_ioctl(struct client *client,
unsigned int cmd, void __user *arg)
{
union ioctl_arg buffer;
int ret;
if (fw_device_is_shutdown(client->device))
return -ENODEV;
if (_IOC_TYPE(cmd) != '#' ||
_IOC_NR(cmd) >= ARRAY_SIZE(ioctl_handlers) ||
_IOC_SIZE(cmd) > sizeof(buffer))
return -EINVAL;
if (_IOC_DIR(cmd) == _IOC_READ)
memset(&buffer, 0, _IOC_SIZE(cmd));
if (_IOC_DIR(cmd) & _IOC_WRITE)
if (copy_from_user(&buffer, arg, _IOC_SIZE(cmd)))
return -EFAULT;
ret = ioctl_handlers[_IOC_NR(cmd)](client, &buffer);
if (ret < 0)
return ret;
if (_IOC_DIR(cmd) & _IOC_READ)
if (copy_to_user(arg, &buffer, _IOC_SIZE(cmd)))
return -EFAULT;
return ret;
}
static long fw_device_op_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
return dispatch_ioctl(file->private_data, cmd, (void __user *)arg);
}
#ifdef CONFIG_COMPAT
static long fw_device_op_compat_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
return dispatch_ioctl(file->private_data, cmd, compat_ptr(arg));
}
#endif
static int fw_device_op_mmap(struct file *file, struct vm_area_struct *vma)
{
struct client *client = file->private_data;
enum dma_data_direction direction;
unsigned long size;
int page_count, ret;
if (fw_device_is_shutdown(client->device))
return -ENODEV;
/* FIXME: We could support multiple buffers, but we don't. */
if (client->buffer.pages != NULL)
return -EBUSY;
if (!(vma->vm_flags & VM_SHARED))
return -EINVAL;
if (vma->vm_start & ~PAGE_MASK)
return -EINVAL;
client->vm_start = vma->vm_start;
size = vma->vm_end - vma->vm_start;
page_count = size >> PAGE_SHIFT;
if (size & ~PAGE_MASK)
return -EINVAL;
if (vma->vm_flags & VM_WRITE)
direction = DMA_TO_DEVICE;
else
direction = DMA_FROM_DEVICE;
ret = fw_iso_buffer_init(&client->buffer, client->device->card,
page_count, direction);
if (ret < 0)
return ret;
ret = fw_iso_buffer_map(&client->buffer, vma);
if (ret < 0)
fw_iso_buffer_destroy(&client->buffer, client->device->card);
return ret;
}
static int shutdown_resource(int id, void *p, void *data)
{
struct client_resource *resource = p;
struct client *client = data;
resource->release(client, resource);
client_put(client);
return 0;
}
static int fw_device_op_release(struct inode *inode, struct file *file)
{
struct client *client = file->private_data;
struct event *event, *next_event;
mutex_lock(&client->device->client_list_mutex);
list_del(&client->link);
mutex_unlock(&client->device->client_list_mutex);
if (client->iso_context)
fw_iso_context_destroy(client->iso_context);
if (client->buffer.pages)
fw_iso_buffer_destroy(&client->buffer, client->device->card);
/* Freeze client->resource_idr and client->event_list */
spin_lock_irq(&client->lock);
client->in_shutdown = true;
spin_unlock_irq(&client->lock);
idr_for_each(&client->resource_idr, shutdown_resource, client);
idr_remove_all(&client->resource_idr);
idr_destroy(&client->resource_idr);
list_for_each_entry_safe(event, next_event, &client->event_list, link)
kfree(event);
client_put(client);
return 0;
}
static unsigned int fw_device_op_poll(struct file *file, poll_table * pt)
{
struct client *client = file->private_data;
unsigned int mask = 0;
poll_wait(file, &client->wait, pt);
if (fw_device_is_shutdown(client->device))
mask |= POLLHUP | POLLERR;
if (!list_empty(&client->event_list))
mask |= POLLIN | POLLRDNORM;
return mask;
}
const struct file_operations fw_device_ops = {
.owner = THIS_MODULE,
.open = fw_device_op_open,
.read = fw_device_op_read,
.unlocked_ioctl = fw_device_op_ioctl,
.poll = fw_device_op_poll,
.release = fw_device_op_release,
.mmap = fw_device_op_mmap,
#ifdef CONFIG_COMPAT
.compat_ioctl = fw_device_op_compat_ioctl,
#endif
};
| gpl-2.0 |
AndresGG/sn-8.4 | db4/hash/hash_meta.c | 42 | 2954 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1999-2009 Oracle. All rights reserved.
*
* $Id$
*/
#include "db_config.h"
#include "db_int.h"
#include "dbinc/db_page.h"
#include "dbinc/hash.h"
#include "dbinc/lock.h"
#include "dbinc/mp.h"
/*
* Acquire the meta-data page.
*
* PUBLIC: int __ham_get_meta __P((DBC *));
*/
int
__ham_get_meta(dbc)
DBC *dbc;
{
DB *dbp;
DB_MPOOLFILE *mpf;
HASH *hashp;
HASH_CURSOR *hcp;
int ret;
dbp = dbc->dbp;
mpf = dbp->mpf;
hashp = dbp->h_internal;
hcp = (HASH_CURSOR *)dbc->internal;
if ((ret = __db_lget(dbc, 0,
hashp->meta_pgno, DB_LOCK_READ, 0, &hcp->hlock)) != 0)
return (ret);
if ((ret = __memp_fget(mpf, &hashp->meta_pgno,
dbc->thread_info, dbc->txn, DB_MPOOL_CREATE, &hcp->hdr)) != 0)
(void)__LPUT(dbc, hcp->hlock);
return (ret);
}
/*
* Release the meta-data page.
*
* PUBLIC: int __ham_release_meta __P((DBC *));
*/
int
__ham_release_meta(dbc)
DBC *dbc;
{
DB_MPOOLFILE *mpf;
HASH_CURSOR *hcp;
int ret;
mpf = dbc->dbp->mpf;
hcp = (HASH_CURSOR *)dbc->internal;
if (hcp->hdr != NULL) {
if ((ret = __memp_fput(mpf,
dbc->thread_info, hcp->hdr, dbc->priority)) != 0)
return (ret);
hcp->hdr = NULL;
}
return (__TLPUT(dbc, hcp->hlock));
}
/*
* Mark the meta-data page dirty.
*
* PUBLIC: int __ham_dirty_meta __P((DBC *, u_int32_t));
*/
int
__ham_dirty_meta(dbc, flags)
DBC *dbc;
u_int32_t flags;
{
DB_MPOOLFILE *mpf;
HASH *hashp;
HASH_CURSOR *hcp;
int ret;
if (F_ISSET(dbc, DBC_OPD))
dbc = dbc->internal->pdbc;
hashp = dbc->dbp->h_internal;
hcp = (HASH_CURSOR *)dbc->internal;
if (hcp->hlock.mode == DB_LOCK_WRITE)
return (0);
mpf = dbc->dbp->mpf;
if ((ret = __db_lget(dbc, LCK_COUPLE, hashp->meta_pgno,
DB_LOCK_WRITE, DB_LOCK_NOWAIT, &hcp->hlock)) != 0) {
if (ret != DB_LOCK_NOTGRANTED && ret != DB_LOCK_DEADLOCK)
return (ret);
if ((ret = __memp_fput(mpf,
dbc->thread_info, hcp->hdr, dbc->priority)) != 0)
return (ret);
hcp->hdr = NULL;
if ((ret = __db_lget(dbc, LCK_COUPLE, hashp->meta_pgno,
DB_LOCK_WRITE, 0, &hcp->hlock)) != 0)
return (ret);
ret = __memp_fget(mpf, &hashp->meta_pgno,
dbc->thread_info, dbc->txn, DB_MPOOL_DIRTY, &hcp->hdr);
return (ret);
}
return (__memp_dirty(mpf,
&hcp->hdr, dbc->thread_info, dbc->txn, dbc->priority, flags));
}
/*
* Return the meta data page if it is saved in the cursor.
*
* PUBLIC: int __ham_return_meta __P((DBC *, u_int32_t, DBMETA **));
*/
int
__ham_return_meta(dbc, flags, metap)
DBC *dbc;
u_int32_t flags;
DBMETA **metap;
{
HASH_CURSOR *hcp;
int ret;
*metap = NULL;
if (F_ISSET(dbc, DBC_OPD))
dbc = dbc->internal->pdbc;
hcp = (HASH_CURSOR *)dbc->internal;
if (hcp->hdr == NULL || PGNO(hcp->hdr) != PGNO_BASE_MD)
return (0);
if (LF_ISSET(DB_MPOOL_DIRTY) &&
(ret = __ham_dirty_meta(dbc, flags)) != 0)
return (ret);
*metap = (DBMETA *)hcp->hdr;
return (0);
}
| gpl-2.0 |
fedya/aircam-openwrt | build_dir/linux-gm812x/linux-2.6.28.fa2/net/appletalk/aarp.c | 42 | 25369 | /*
* AARP: An implementation of the AppleTalk AARP protocol for
* Ethernet 'ELAP'.
*
* Alan Cox <Alan.Cox@linux.org>
*
* This doesn't fit cleanly with the IP arp. Potentially we can use
* the generic neighbour discovery code to clean this up.
*
* FIXME:
* We ought to handle the retransmits with a single list and a
* separate fast timer for when it is needed.
* Use neighbour discovery code.
* Token Ring Support.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*
* References:
* Inside AppleTalk (2nd Ed).
* Fixes:
* Jaume Grau - flush caches on AARP_PROBE
* Rob Newberry - Added proxy AARP and AARP proc fs,
* moved probing from DDP module.
* Arnaldo C. Melo - don't mangle rx packets
*
*/
#include <linux/if_arp.h>
#include <net/sock.h>
#include <net/datalink.h>
#include <net/psnap.h>
#include <linux/atalk.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
int sysctl_aarp_expiry_time = AARP_EXPIRY_TIME;
int sysctl_aarp_tick_time = AARP_TICK_TIME;
int sysctl_aarp_retransmit_limit = AARP_RETRANSMIT_LIMIT;
int sysctl_aarp_resolve_time = AARP_RESOLVE_TIME;
/* Lists of aarp entries */
/**
* struct aarp_entry - AARP entry
* @last_sent - Last time we xmitted the aarp request
* @packet_queue - Queue of frames wait for resolution
* @status - Used for proxy AARP
* expires_at - Entry expiry time
* target_addr - DDP Address
* dev - Device to use
* hwaddr - Physical i/f address of target/router
* xmit_count - When this hits 10 we give up
* next - Next entry in chain
*/
struct aarp_entry {
/* These first two are only used for unresolved entries */
unsigned long last_sent;
struct sk_buff_head packet_queue;
int status;
unsigned long expires_at;
struct atalk_addr target_addr;
struct net_device *dev;
char hwaddr[6];
unsigned short xmit_count;
struct aarp_entry *next;
};
/* Hashed list of resolved, unresolved and proxy entries */
static struct aarp_entry *resolved[AARP_HASH_SIZE];
static struct aarp_entry *unresolved[AARP_HASH_SIZE];
static struct aarp_entry *proxies[AARP_HASH_SIZE];
static int unresolved_count;
/* One lock protects it all. */
static DEFINE_RWLOCK(aarp_lock);
/* Used to walk the list and purge/kick entries. */
static struct timer_list aarp_timer;
/*
* Delete an aarp queue
*
* Must run under aarp_lock.
*/
static void __aarp_expire(struct aarp_entry *a)
{
skb_queue_purge(&a->packet_queue);
kfree(a);
}
/*
* Send an aarp queue entry request
*
* Must run under aarp_lock.
*/
static void __aarp_send_query(struct aarp_entry *a)
{
static unsigned char aarp_eth_multicast[ETH_ALEN] =
{ 0x09, 0x00, 0x07, 0xFF, 0xFF, 0xFF };
struct net_device *dev = a->dev;
struct elapaarp *eah;
int len = dev->hard_header_len + sizeof(*eah) + aarp_dl->header_length;
struct sk_buff *skb = alloc_skb(len, GFP_ATOMIC);
struct atalk_addr *sat = atalk_find_dev_addr(dev);
if (!skb)
return;
if (!sat) {
kfree_skb(skb);
return;
}
/* Set up the buffer */
skb_reserve(skb, dev->hard_header_len + aarp_dl->header_length);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb_put(skb, sizeof(*eah));
skb->protocol = htons(ETH_P_ATALK);
skb->dev = dev;
eah = aarp_hdr(skb);
/* Set up the ARP */
eah->hw_type = htons(AARP_HW_TYPE_ETHERNET);
eah->pa_type = htons(ETH_P_ATALK);
eah->hw_len = ETH_ALEN;
eah->pa_len = AARP_PA_ALEN;
eah->function = htons(AARP_REQUEST);
memcpy(eah->hw_src, dev->dev_addr, ETH_ALEN);
eah->pa_src_zero = 0;
eah->pa_src_net = sat->s_net;
eah->pa_src_node = sat->s_node;
memset(eah->hw_dst, '\0', ETH_ALEN);
eah->pa_dst_zero = 0;
eah->pa_dst_net = a->target_addr.s_net;
eah->pa_dst_node = a->target_addr.s_node;
/* Send it */
aarp_dl->request(aarp_dl, skb, aarp_eth_multicast);
/* Update the sending count */
a->xmit_count++;
a->last_sent = jiffies;
}
/* This runs under aarp_lock and in softint context, so only atomic memory
* allocations can be used. */
static void aarp_send_reply(struct net_device *dev, struct atalk_addr *us,
struct atalk_addr *them, unsigned char *sha)
{
struct elapaarp *eah;
int len = dev->hard_header_len + sizeof(*eah) + aarp_dl->header_length;
struct sk_buff *skb = alloc_skb(len, GFP_ATOMIC);
if (!skb)
return;
/* Set up the buffer */
skb_reserve(skb, dev->hard_header_len + aarp_dl->header_length);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb_put(skb, sizeof(*eah));
skb->protocol = htons(ETH_P_ATALK);
skb->dev = dev;
eah = aarp_hdr(skb);
/* Set up the ARP */
eah->hw_type = htons(AARP_HW_TYPE_ETHERNET);
eah->pa_type = htons(ETH_P_ATALK);
eah->hw_len = ETH_ALEN;
eah->pa_len = AARP_PA_ALEN;
eah->function = htons(AARP_REPLY);
memcpy(eah->hw_src, dev->dev_addr, ETH_ALEN);
eah->pa_src_zero = 0;
eah->pa_src_net = us->s_net;
eah->pa_src_node = us->s_node;
if (!sha)
memset(eah->hw_dst, '\0', ETH_ALEN);
else
memcpy(eah->hw_dst, sha, ETH_ALEN);
eah->pa_dst_zero = 0;
eah->pa_dst_net = them->s_net;
eah->pa_dst_node = them->s_node;
/* Send it */
aarp_dl->request(aarp_dl, skb, sha);
}
/*
* Send probe frames. Called from aarp_probe_network and
* aarp_proxy_probe_network.
*/
static void aarp_send_probe(struct net_device *dev, struct atalk_addr *us)
{
struct elapaarp *eah;
int len = dev->hard_header_len + sizeof(*eah) + aarp_dl->header_length;
struct sk_buff *skb = alloc_skb(len, GFP_ATOMIC);
static unsigned char aarp_eth_multicast[ETH_ALEN] =
{ 0x09, 0x00, 0x07, 0xFF, 0xFF, 0xFF };
if (!skb)
return;
/* Set up the buffer */
skb_reserve(skb, dev->hard_header_len + aarp_dl->header_length);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb_put(skb, sizeof(*eah));
skb->protocol = htons(ETH_P_ATALK);
skb->dev = dev;
eah = aarp_hdr(skb);
/* Set up the ARP */
eah->hw_type = htons(AARP_HW_TYPE_ETHERNET);
eah->pa_type = htons(ETH_P_ATALK);
eah->hw_len = ETH_ALEN;
eah->pa_len = AARP_PA_ALEN;
eah->function = htons(AARP_PROBE);
memcpy(eah->hw_src, dev->dev_addr, ETH_ALEN);
eah->pa_src_zero = 0;
eah->pa_src_net = us->s_net;
eah->pa_src_node = us->s_node;
memset(eah->hw_dst, '\0', ETH_ALEN);
eah->pa_dst_zero = 0;
eah->pa_dst_net = us->s_net;
eah->pa_dst_node = us->s_node;
/* Send it */
aarp_dl->request(aarp_dl, skb, aarp_eth_multicast);
}
/*
* Handle an aarp timer expire
*
* Must run under the aarp_lock.
*/
static void __aarp_expire_timer(struct aarp_entry **n)
{
struct aarp_entry *t;
while (*n)
/* Expired ? */
if (time_after(jiffies, (*n)->expires_at)) {
t = *n;
*n = (*n)->next;
__aarp_expire(t);
} else
n = &((*n)->next);
}
/*
* Kick all pending requests 5 times a second.
*
* Must run under the aarp_lock.
*/
static void __aarp_kick(struct aarp_entry **n)
{
struct aarp_entry *t;
while (*n)
/* Expired: if this will be the 11th tx, we delete instead. */
if ((*n)->xmit_count >= sysctl_aarp_retransmit_limit) {
t = *n;
*n = (*n)->next;
__aarp_expire(t);
} else {
__aarp_send_query(*n);
n = &((*n)->next);
}
}
/*
* A device has gone down. Take all entries referring to the device
* and remove them.
*
* Must run under the aarp_lock.
*/
static void __aarp_expire_device(struct aarp_entry **n, struct net_device *dev)
{
struct aarp_entry *t;
while (*n)
if ((*n)->dev == dev) {
t = *n;
*n = (*n)->next;
__aarp_expire(t);
} else
n = &((*n)->next);
}
/* Handle the timer event */
static void aarp_expire_timeout(unsigned long unused)
{
int ct;
write_lock_bh(&aarp_lock);
for (ct = 0; ct < AARP_HASH_SIZE; ct++) {
__aarp_expire_timer(&resolved[ct]);
__aarp_kick(&unresolved[ct]);
__aarp_expire_timer(&unresolved[ct]);
__aarp_expire_timer(&proxies[ct]);
}
write_unlock_bh(&aarp_lock);
mod_timer(&aarp_timer, jiffies +
(unresolved_count ? sysctl_aarp_tick_time :
sysctl_aarp_expiry_time));
}
/* Network device notifier chain handler. */
static int aarp_device_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = ptr;
int ct;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (event == NETDEV_DOWN) {
write_lock_bh(&aarp_lock);
for (ct = 0; ct < AARP_HASH_SIZE; ct++) {
__aarp_expire_device(&resolved[ct], dev);
__aarp_expire_device(&unresolved[ct], dev);
__aarp_expire_device(&proxies[ct], dev);
}
write_unlock_bh(&aarp_lock);
}
return NOTIFY_DONE;
}
/* Expire all entries in a hash chain */
static void __aarp_expire_all(struct aarp_entry **n)
{
struct aarp_entry *t;
while (*n) {
t = *n;
*n = (*n)->next;
__aarp_expire(t);
}
}
/* Cleanup all hash chains -- module unloading */
static void aarp_purge(void)
{
int ct;
write_lock_bh(&aarp_lock);
for (ct = 0; ct < AARP_HASH_SIZE; ct++) {
__aarp_expire_all(&resolved[ct]);
__aarp_expire_all(&unresolved[ct]);
__aarp_expire_all(&proxies[ct]);
}
write_unlock_bh(&aarp_lock);
}
/*
* Create a new aarp entry. This must use GFP_ATOMIC because it
* runs while holding spinlocks.
*/
static struct aarp_entry *aarp_alloc(void)
{
struct aarp_entry *a = kmalloc(sizeof(*a), GFP_ATOMIC);
if (a)
skb_queue_head_init(&a->packet_queue);
return a;
}
/*
* Find an entry. We might return an expired but not yet purged entry. We
* don't care as it will do no harm.
*
* This must run under the aarp_lock.
*/
static struct aarp_entry *__aarp_find_entry(struct aarp_entry *list,
struct net_device *dev,
struct atalk_addr *sat)
{
while (list) {
if (list->target_addr.s_net == sat->s_net &&
list->target_addr.s_node == sat->s_node &&
list->dev == dev)
break;
list = list->next;
}
return list;
}
/* Called from the DDP code, and thus must be exported. */
void aarp_proxy_remove(struct net_device *dev, struct atalk_addr *sa)
{
int hash = sa->s_node % (AARP_HASH_SIZE - 1);
struct aarp_entry *a;
write_lock_bh(&aarp_lock);
a = __aarp_find_entry(proxies[hash], dev, sa);
if (a)
a->expires_at = jiffies - 1;
write_unlock_bh(&aarp_lock);
}
/* This must run under aarp_lock. */
static struct atalk_addr *__aarp_proxy_find(struct net_device *dev,
struct atalk_addr *sa)
{
int hash = sa->s_node % (AARP_HASH_SIZE - 1);
struct aarp_entry *a = __aarp_find_entry(proxies[hash], dev, sa);
return a ? sa : NULL;
}
/*
* Probe a Phase 1 device or a device that requires its Net:Node to
* be set via an ioctl.
*/
static void aarp_send_probe_phase1(struct atalk_iface *iface)
{
struct ifreq atreq;
struct sockaddr_at *sa = (struct sockaddr_at *)&atreq.ifr_addr;
sa->sat_addr.s_node = iface->address.s_node;
sa->sat_addr.s_net = ntohs(iface->address.s_net);
/* We pass the Net:Node to the drivers/cards by a Device ioctl. */
if (!(iface->dev->do_ioctl(iface->dev, &atreq, SIOCSIFADDR))) {
(void)iface->dev->do_ioctl(iface->dev, &atreq, SIOCGIFADDR);
if (iface->address.s_net != htons(sa->sat_addr.s_net) ||
iface->address.s_node != sa->sat_addr.s_node)
iface->status |= ATIF_PROBE_FAIL;
iface->address.s_net = htons(sa->sat_addr.s_net);
iface->address.s_node = sa->sat_addr.s_node;
}
}
void aarp_probe_network(struct atalk_iface *atif)
{
if (atif->dev->type == ARPHRD_LOCALTLK ||
atif->dev->type == ARPHRD_PPP)
aarp_send_probe_phase1(atif);
else {
unsigned int count;
for (count = 0; count < AARP_RETRANSMIT_LIMIT; count++) {
aarp_send_probe(atif->dev, &atif->address);
/* Defer 1/10th */
msleep(100);
if (atif->status & ATIF_PROBE_FAIL)
break;
}
}
}
int aarp_proxy_probe_network(struct atalk_iface *atif, struct atalk_addr *sa)
{
int hash, retval = -EPROTONOSUPPORT;
struct aarp_entry *entry;
unsigned int count;
/*
* we don't currently support LocalTalk or PPP for proxy AARP;
* if someone wants to try and add it, have fun
*/
if (atif->dev->type == ARPHRD_LOCALTLK ||
atif->dev->type == ARPHRD_PPP)
goto out;
/*
* create a new AARP entry with the flags set to be published --
* we need this one to hang around even if it's in use
*/
entry = aarp_alloc();
retval = -ENOMEM;
if (!entry)
goto out;
entry->expires_at = -1;
entry->status = ATIF_PROBE;
entry->target_addr.s_node = sa->s_node;
entry->target_addr.s_net = sa->s_net;
entry->dev = atif->dev;
write_lock_bh(&aarp_lock);
hash = sa->s_node % (AARP_HASH_SIZE - 1);
entry->next = proxies[hash];
proxies[hash] = entry;
for (count = 0; count < AARP_RETRANSMIT_LIMIT; count++) {
aarp_send_probe(atif->dev, sa);
/* Defer 1/10th */
write_unlock_bh(&aarp_lock);
msleep(100);
write_lock_bh(&aarp_lock);
if (entry->status & ATIF_PROBE_FAIL)
break;
}
if (entry->status & ATIF_PROBE_FAIL) {
entry->expires_at = jiffies - 1; /* free the entry */
retval = -EADDRINUSE; /* return network full */
} else { /* clear the probing flag */
entry->status &= ~ATIF_PROBE;
retval = 1;
}
write_unlock_bh(&aarp_lock);
out:
return retval;
}
/* Send a DDP frame */
int aarp_send_ddp(struct net_device *dev, struct sk_buff *skb,
struct atalk_addr *sa, void *hwaddr)
{
static char ddp_eth_multicast[ETH_ALEN] =
{ 0x09, 0x00, 0x07, 0xFF, 0xFF, 0xFF };
int hash;
struct aarp_entry *a;
skb_reset_network_header(skb);
/* Check for LocalTalk first */
if (dev->type == ARPHRD_LOCALTLK) {
struct atalk_addr *at = atalk_find_dev_addr(dev);
struct ddpehdr *ddp = (struct ddpehdr *)skb->data;
int ft = 2;
/*
* Compressible ?
*
* IFF: src_net == dest_net == device_net
* (zero matches anything)
*/
if ((!ddp->deh_snet || at->s_net == ddp->deh_snet) &&
(!ddp->deh_dnet || at->s_net == ddp->deh_dnet)) {
skb_pull(skb, sizeof(*ddp) - 4);
/*
* The upper two remaining bytes are the port
* numbers we just happen to need. Now put the
* length in the lower two.
*/
*((__be16 *)skb->data) = htons(skb->len);
ft = 1;
}
/*
* Nice and easy. No AARP type protocols occur here so we can
* just shovel it out with a 3 byte LLAP header
*/
skb_push(skb, 3);
skb->data[0] = sa->s_node;
skb->data[1] = at->s_node;
skb->data[2] = ft;
skb->dev = dev;
goto sendit;
}
/* On a PPP link we neither compress nor aarp. */
if (dev->type == ARPHRD_PPP) {
skb->protocol = htons(ETH_P_PPPTALK);
skb->dev = dev;
goto sendit;
}
/* Non ELAP we cannot do. */
if (dev->type != ARPHRD_ETHER)
return -1;
skb->dev = dev;
skb->protocol = htons(ETH_P_ATALK);
hash = sa->s_node % (AARP_HASH_SIZE - 1);
/* Do we have a resolved entry? */
if (sa->s_node == ATADDR_BCAST) {
/* Send it */
ddp_dl->request(ddp_dl, skb, ddp_eth_multicast);
goto sent;
}
write_lock_bh(&aarp_lock);
a = __aarp_find_entry(resolved[hash], dev, sa);
if (a) { /* Return 1 and fill in the address */
a->expires_at = jiffies + (sysctl_aarp_expiry_time * 10);
ddp_dl->request(ddp_dl, skb, a->hwaddr);
write_unlock_bh(&aarp_lock);
goto sent;
}
/* Do we have an unresolved entry: This is the less common path */
a = __aarp_find_entry(unresolved[hash], dev, sa);
if (a) { /* Queue onto the unresolved queue */
skb_queue_tail(&a->packet_queue, skb);
goto out_unlock;
}
/* Allocate a new entry */
a = aarp_alloc();
if (!a) {
/* Whoops slipped... good job it's an unreliable protocol 8) */
write_unlock_bh(&aarp_lock);
return -1;
}
/* Set up the queue */
skb_queue_tail(&a->packet_queue, skb);
a->expires_at = jiffies + sysctl_aarp_resolve_time;
a->dev = dev;
a->next = unresolved[hash];
a->target_addr = *sa;
a->xmit_count = 0;
unresolved[hash] = a;
unresolved_count++;
/* Send an initial request for the address */
__aarp_send_query(a);
/*
* Switch to fast timer if needed (That is if this is the first
* unresolved entry to get added)
*/
if (unresolved_count == 1)
mod_timer(&aarp_timer, jiffies + sysctl_aarp_tick_time);
/* Now finally, it is safe to drop the lock. */
out_unlock:
write_unlock_bh(&aarp_lock);
/* Tell the ddp layer we have taken over for this frame. */
return 0;
sendit:
if (skb->sk)
skb->priority = skb->sk->sk_priority;
dev_queue_xmit(skb);
sent:
return 1;
}
/*
* An entry in the aarp unresolved queue has become resolved. Send
* all the frames queued under it.
*
* Must run under aarp_lock.
*/
static void __aarp_resolved(struct aarp_entry **list, struct aarp_entry *a,
int hash)
{
struct sk_buff *skb;
while (*list)
if (*list == a) {
unresolved_count--;
*list = a->next;
/* Move into the resolved list */
a->next = resolved[hash];
resolved[hash] = a;
/* Kick frames off */
while ((skb = skb_dequeue(&a->packet_queue)) != NULL) {
a->expires_at = jiffies +
sysctl_aarp_expiry_time * 10;
ddp_dl->request(ddp_dl, skb, a->hwaddr);
}
} else
list = &((*list)->next);
}
/*
* This is called by the SNAP driver whenever we see an AARP SNAP
* frame. We currently only support Ethernet.
*/
static int aarp_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct elapaarp *ea = aarp_hdr(skb);
int hash, ret = 0;
__u16 function;
struct aarp_entry *a;
struct atalk_addr sa, *ma, da;
struct atalk_iface *ifa;
if (!net_eq(dev_net(dev), &init_net))
goto out0;
/* We only do Ethernet SNAP AARP. */
if (dev->type != ARPHRD_ETHER)
goto out0;
/* Frame size ok? */
if (!skb_pull(skb, sizeof(*ea)))
goto out0;
function = ntohs(ea->function);
/* Sanity check fields. */
if (function < AARP_REQUEST || function > AARP_PROBE ||
ea->hw_len != ETH_ALEN || ea->pa_len != AARP_PA_ALEN ||
ea->pa_src_zero || ea->pa_dst_zero)
goto out0;
/* Looks good. */
hash = ea->pa_src_node % (AARP_HASH_SIZE - 1);
/* Build an address. */
sa.s_node = ea->pa_src_node;
sa.s_net = ea->pa_src_net;
/* Process the packet. Check for replies of me. */
ifa = atalk_find_dev(dev);
if (!ifa)
goto out1;
if (ifa->status & ATIF_PROBE &&
ifa->address.s_node == ea->pa_dst_node &&
ifa->address.s_net == ea->pa_dst_net) {
ifa->status |= ATIF_PROBE_FAIL; /* Fail the probe (in use) */
goto out1;
}
/* Check for replies of proxy AARP entries */
da.s_node = ea->pa_dst_node;
da.s_net = ea->pa_dst_net;
write_lock_bh(&aarp_lock);
a = __aarp_find_entry(proxies[hash], dev, &da);
if (a && a->status & ATIF_PROBE) {
a->status |= ATIF_PROBE_FAIL;
/*
* we do not respond to probe or request packets for
* this address while we are probing this address
*/
goto unlock;
}
switch (function) {
case AARP_REPLY:
if (!unresolved_count) /* Speed up */
break;
/* Find the entry. */
a = __aarp_find_entry(unresolved[hash], dev, &sa);
if (!a || dev != a->dev)
break;
/* We can fill one in - this is good. */
memcpy(a->hwaddr, ea->hw_src, ETH_ALEN);
__aarp_resolved(&unresolved[hash], a, hash);
if (!unresolved_count)
mod_timer(&aarp_timer,
jiffies + sysctl_aarp_expiry_time);
break;
case AARP_REQUEST:
case AARP_PROBE:
/*
* If it is my address set ma to my address and reply.
* We can treat probe and request the same. Probe
* simply means we shouldn't cache the querying host,
* as in a probe they are proposing an address not
* using one.
*
* Support for proxy-AARP added. We check if the
* address is one of our proxies before we toss the
* packet out.
*/
sa.s_node = ea->pa_dst_node;
sa.s_net = ea->pa_dst_net;
/* See if we have a matching proxy. */
ma = __aarp_proxy_find(dev, &sa);
if (!ma)
ma = &ifa->address;
else { /* We need to make a copy of the entry. */
da.s_node = sa.s_node;
da.s_net = da.s_net;
ma = &da;
}
if (function == AARP_PROBE) {
/*
* A probe implies someone trying to get an
* address. So as a precaution flush any
* entries we have for this address.
*/
a = __aarp_find_entry(resolved[sa.s_node %
(AARP_HASH_SIZE - 1)],
skb->dev, &sa);
/*
* Make it expire next tick - that avoids us
* getting into a probe/flush/learn/probe/
* flush/learn cycle during probing of a slow
* to respond host addr.
*/
if (a) {
a->expires_at = jiffies - 1;
mod_timer(&aarp_timer, jiffies +
sysctl_aarp_tick_time);
}
}
if (sa.s_node != ma->s_node)
break;
if (sa.s_net && ma->s_net && sa.s_net != ma->s_net)
break;
sa.s_node = ea->pa_src_node;
sa.s_net = ea->pa_src_net;
/* aarp_my_address has found the address to use for us.
*/
aarp_send_reply(dev, ma, &sa, ea->hw_src);
break;
}
unlock:
write_unlock_bh(&aarp_lock);
out1:
ret = 1;
out0:
kfree_skb(skb);
return ret;
}
static struct notifier_block aarp_notifier = {
.notifier_call = aarp_device_event,
};
static unsigned char aarp_snap_id[] = { 0x00, 0x00, 0x00, 0x80, 0xF3 };
void __init aarp_proto_init(void)
{
aarp_dl = register_snap_client(aarp_snap_id, aarp_rcv);
if (!aarp_dl)
printk(KERN_CRIT "Unable to register AARP with SNAP.\n");
setup_timer(&aarp_timer, aarp_expire_timeout, 0);
aarp_timer.expires = jiffies + sysctl_aarp_expiry_time;
add_timer(&aarp_timer);
register_netdevice_notifier(&aarp_notifier);
}
/* Remove the AARP entries associated with a device. */
void aarp_device_down(struct net_device *dev)
{
int ct;
write_lock_bh(&aarp_lock);
for (ct = 0; ct < AARP_HASH_SIZE; ct++) {
__aarp_expire_device(&resolved[ct], dev);
__aarp_expire_device(&unresolved[ct], dev);
__aarp_expire_device(&proxies[ct], dev);
}
write_unlock_bh(&aarp_lock);
}
#ifdef CONFIG_PROC_FS
struct aarp_iter_state {
int bucket;
struct aarp_entry **table;
};
/*
* Get the aarp entry that is in the chain described
* by the iterator.
* If pos is set then skip till that index.
* pos = 1 is the first entry
*/
static struct aarp_entry *iter_next(struct aarp_iter_state *iter, loff_t *pos)
{
int ct = iter->bucket;
struct aarp_entry **table = iter->table;
loff_t off = 0;
struct aarp_entry *entry;
rescan:
while(ct < AARP_HASH_SIZE) {
for (entry = table[ct]; entry; entry = entry->next) {
if (!pos || ++off == *pos) {
iter->table = table;
iter->bucket = ct;
return entry;
}
}
++ct;
}
if (table == resolved) {
ct = 0;
table = unresolved;
goto rescan;
}
if (table == unresolved) {
ct = 0;
table = proxies;
goto rescan;
}
return NULL;
}
static void *aarp_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(aarp_lock)
{
struct aarp_iter_state *iter = seq->private;
read_lock_bh(&aarp_lock);
iter->table = resolved;
iter->bucket = 0;
return *pos ? iter_next(iter, pos) : SEQ_START_TOKEN;
}
static void *aarp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct aarp_entry *entry = v;
struct aarp_iter_state *iter = seq->private;
++*pos;
/* first line after header */
if (v == SEQ_START_TOKEN)
entry = iter_next(iter, NULL);
/* next entry in current bucket */
else if (entry->next)
entry = entry->next;
/* next bucket or table */
else {
++iter->bucket;
entry = iter_next(iter, NULL);
}
return entry;
}
static void aarp_seq_stop(struct seq_file *seq, void *v)
__releases(aarp_lock)
{
read_unlock_bh(&aarp_lock);
}
static const char *dt2str(unsigned long ticks)
{
static char buf[32];
sprintf(buf, "%ld.%02ld", ticks / HZ, ((ticks % HZ) * 100 ) / HZ);
return buf;
}
static int aarp_seq_show(struct seq_file *seq, void *v)
{
struct aarp_iter_state *iter = seq->private;
struct aarp_entry *entry = v;
unsigned long now = jiffies;
DECLARE_MAC_BUF(mac);
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"Address Interface Hardware Address"
" Expires LastSend Retry Status\n");
else {
seq_printf(seq, "%04X:%02X %-12s",
ntohs(entry->target_addr.s_net),
(unsigned int) entry->target_addr.s_node,
entry->dev ? entry->dev->name : "????");
seq_printf(seq, "%s", print_mac(mac, entry->hwaddr));
seq_printf(seq, " %8s",
dt2str((long)entry->expires_at - (long)now));
if (iter->table == unresolved)
seq_printf(seq, " %8s %6hu",
dt2str(now - entry->last_sent),
entry->xmit_count);
else
seq_puts(seq, " ");
seq_printf(seq, " %s\n",
(iter->table == resolved) ? "resolved"
: (iter->table == unresolved) ? "unresolved"
: (iter->table == proxies) ? "proxies"
: "unknown");
}
return 0;
}
static const struct seq_operations aarp_seq_ops = {
.start = aarp_seq_start,
.next = aarp_seq_next,
.stop = aarp_seq_stop,
.show = aarp_seq_show,
};
static int aarp_seq_open(struct inode *inode, struct file *file)
{
return seq_open_private(file, &aarp_seq_ops,
sizeof(struct aarp_iter_state));
}
const struct file_operations atalk_seq_arp_fops = {
.owner = THIS_MODULE,
.open = aarp_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif
/* General module cleanup. Called from cleanup_module() in ddp.c. */
void aarp_cleanup_module(void)
{
del_timer_sync(&aarp_timer);
unregister_netdevice_notifier(&aarp_notifier);
unregister_snap_client(aarp_dl);
aarp_purge();
}
| gpl-2.0 |
swapnilxd/android_kernel_xiaomi_msm8956 | drivers/net/ethernet/msm/rndis_ipa.c | 42 | 84786 | /* Copyright (c) 2013-2015, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/atomic.h>
#include <linux/errno.h>
#include <linux/etherdevice.h>
#include <linux/debugfs.h>
#include <linux/in.h>
#include <linux/stddef.h>
#include <linux/ip.h>
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/msm_ipa.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/sched.h>
#include <linux/ipa.h>
#include <linux/random.h>
#include <linux/rndis_ipa.h>
#include <linux/workqueue.h>
#define DRV_NAME "RNDIS_IPA"
#define DEBUGFS_DIR_NAME "rndis_ipa"
#define DEBUGFS_AGGR_DIR_NAME "rndis_ipa_aggregation"
#define NETDEV_NAME "rndis"
#define DRV_RESOURCE_ID IPA_RM_RESOURCE_RNDIS_PROD
#define IPV4_HDR_NAME "rndis_eth_ipv4"
#define IPV6_HDR_NAME "rndis_eth_ipv6"
#define IPA_TO_USB_CLIENT IPA_CLIENT_USB_CONS
#define INACTIVITY_MSEC_DELAY 100
#define DEFAULT_OUTSTANDING_HIGH 64
#define DEFAULT_OUTSTANDING_LOW 32
#define DEBUGFS_TEMP_BUF_SIZE 4
#define RNDIS_IPA_PKT_TYPE 0x00000001
#define RNDIS_IPA_DFLT_RT_HDL 0
#define FROM_IPA_TO_USB_BAMDMA 4
#define FROM_USB_TO_IPA_BAMDMA 5
#define BAM_DMA_MAX_PKT_NUMBER 10
#define BAM_DMA_DATA_FIFO_SIZE \
(BAM_DMA_MAX_PKT_NUMBER* \
(ETH_FRAME_LEN + sizeof(struct rndis_pkt_hdr)))
#define BAM_DMA_DESC_FIFO_SIZE \
(BAM_DMA_MAX_PKT_NUMBER*(sizeof(struct sps_iovec)))
#define TX_TIMEOUT (5 * HZ)
#define MIN_TX_ERROR_SLEEP_PERIOD 500
#define DEFAULT_AGGR_TIME_LIMIT 1
#define DEFAULT_AGGR_PKT_LIMIT 0
#define RNDIS_IPA_ERROR(fmt, args...) \
pr_err(DRV_NAME "@%s@%d@ctx:%s: "\
fmt, __func__, __LINE__, current->comm, ## args)
#define RNDIS_IPA_DEBUG(fmt, args...) \
pr_debug("ctx: %s, "fmt, current->comm, ## args)
#define NULL_CHECK_RETVAL(ptr) \
do { \
if (!(ptr)) { \
RNDIS_IPA_ERROR("null pointer #ptr\n"); \
return -EINVAL; \
} \
} \
while (0)
#define NULL_CHECK_NO_RETVAL(ptr) \
do { \
if (!(ptr)) {\
RNDIS_IPA_ERROR("null pointer #ptr\n"); \
return; \
} \
} \
while (0)
#define RNDIS_HDR_OFST(field) offsetof(struct rndis_pkt_hdr, field)
#define RNDIS_IPA_LOG_ENTRY() RNDIS_IPA_DEBUG("begin\n")
#define RNDIS_IPA_LOG_EXIT() RNDIS_IPA_DEBUG("end\n")
/**
* enum rndis_ipa_state - specify the current driver internal state
* which is guarded by a state machine.
*
* The driver internal state changes due to its external API usage.
* The driver saves its internal state to guard from caller illegal
* call sequence.
* states:
* UNLOADED is the first state which is the default one and is also the state
* after the driver gets unloaded(cleanup).
* INITIALIZED is the driver state once it finished registering
* the network device and all internal data struct were initialized
* CONNECTED is the driver state once the USB pipes were connected to IPA
* UP is the driver state after the interface mode was set to UP but the
* pipes are not connected yet - this state is meta-stable state.
* CONNECTED_AND_UP is the driver state when the pipe were connected and
* the interface got UP request from the network stack. this is the driver
* idle operation state which allows it to transmit/receive data.
* INVALID is a state which is not allowed.
*/
enum rndis_ipa_state {
RNDIS_IPA_UNLOADED = 0,
RNDIS_IPA_INITIALIZED = 1,
RNDIS_IPA_CONNECTED = 2,
RNDIS_IPA_UP = 3,
RNDIS_IPA_CONNECTED_AND_UP = 4,
RNDIS_IPA_INVALID = 5,
};
/**
* enum rndis_ipa_operation - enumerations used to describe the API operation
*
* Those enums are used as input for the driver state machine.
*/
enum rndis_ipa_operation {
RNDIS_IPA_INITIALIZE,
RNDIS_IPA_CONNECT,
RNDIS_IPA_OPEN,
RNDIS_IPA_STOP,
RNDIS_IPA_DISCONNECT,
RNDIS_IPA_CLEANUP,
};
#define RNDIS_IPA_STATE_DEBUG(ctx) \
RNDIS_IPA_DEBUG("Driver state: %s\n",\
rndis_ipa_state_string(ctx->state));
/**
* struct rndis_loopback_pipe - hold all information needed for
* pipe loopback logic
*/
struct rndis_loopback_pipe {
struct sps_pipe *ipa_sps;
struct ipa_sps_params ipa_sps_connect;
struct ipa_connect_params ipa_connect_params;
struct sps_pipe *dma_sps;
struct sps_connect dma_connect;
struct sps_alloc_dma_chan dst_alloc;
struct sps_dma_chan ipa_sps_channel;
enum sps_mode mode;
u32 ipa_peer_bam_hdl;
u32 peer_pipe_index;
u32 ipa_drv_ep_hdl;
u32 ipa_pipe_index;
enum ipa_client_type ipa_client;
ipa_notify_cb ipa_callback;
struct ipa_ep_cfg *ipa_ep_cfg;
};
/**
* struct rndis_ipa_dev - main driver context parameters
*
* @net: network interface struct implemented by this driver
* @directory: debugfs directory for various debugging switches
* @tx_filter: flag that enable/disable Tx path to continue to IPA
* @tx_dropped: number of filtered out Tx packets
* @tx_dump_enable: dump all Tx packets
* @rx_filter: flag that enable/disable Rx path to continue to IPA
* @rx_dropped: number of filtered out Rx packets
* @rx_dump_enable: dump all Rx packets
* @icmp_filter: allow all ICMP packet to pass through the filters
* @rm_enable: flag that enable/disable Resource manager request prior to Tx
* @loopback_enable: flag that enable/disable USB stub loopback
* @deaggregation_enable: enable/disable IPA HW deaggregation logic
* @during_xmit_error: flags that indicate that the driver is in a middle
* of error handling in Tx path
* @usb_to_ipa_loopback_pipe: usb to ipa (Rx) pipe representation for loopback
* @ipa_to_usb_loopback_pipe: ipa to usb (Tx) pipe representation for loopback
* @bam_dma_hdl: handle representing bam-dma, used for loopback logic
* @directory: holds all debug flags used by the driver to allow cleanup
* for driver unload
* @eth_ipv4_hdr_hdl: saved handle for ipv4 header-insertion table
* @eth_ipv6_hdr_hdl: saved handle for ipv6 header-insertion table
* @usb_to_ipa_hdl: save handle for IPA pipe operations
* @ipa_to_usb_hdl: save handle for IPA pipe operations
* @outstanding_pkts: number of packets sent to IPA without TX complete ACKed
* @outstanding_high: number of outstanding packets allowed
* @outstanding_low: number of outstanding packets which shall cause
* to netdev queue start (after stopped due to outstanding_high reached)
* @error_msec_sleep_time: number of msec for sleeping in case of Tx error
* @state: current state of the driver
* @host_ethaddr: holds the tethered PC ethernet address
* @device_ethaddr: holds the device ethernet address
* @device_ready_notify: callback supplied by USB core driver
* This callback shall be called by the Netdev once the Netdev internal
* state is changed to RNDIS_IPA_CONNECTED_AND_UP
* @xmit_error_delayed_work: work item for cases where IPA driver Tx fails
*/
struct rndis_ipa_dev {
struct net_device *net;
u32 tx_filter;
u32 tx_dropped;
u32 tx_dump_enable;
u32 rx_filter;
u32 rx_dropped;
u32 rx_dump_enable;
u32 icmp_filter;
u32 rm_enable;
bool loopback_enable;
u32 deaggregation_enable;
u32 during_xmit_error;
struct rndis_loopback_pipe usb_to_ipa_loopback_pipe;
struct rndis_loopback_pipe ipa_to_usb_loopback_pipe;
u32 bam_dma_hdl;
struct dentry *directory;
uint32_t eth_ipv4_hdr_hdl;
uint32_t eth_ipv6_hdr_hdl;
u32 usb_to_ipa_hdl;
u32 ipa_to_usb_hdl;
atomic_t outstanding_pkts;
u32 outstanding_high;
u32 outstanding_low;
u32 error_msec_sleep_time;
enum rndis_ipa_state state;
u8 host_ethaddr[ETH_ALEN];
u8 device_ethaddr[ETH_ALEN];
void (*device_ready_notify)(void);
struct delayed_work xmit_error_delayed_work;
};
/**
* rndis_pkt_hdr - RNDIS_IPA representation of REMOTE_NDIS_PACKET_MSG
* @msg_type: for REMOTE_NDIS_PACKET_MSG this value should be 1
* @msg_len: total message length in bytes, including RNDIS header an payload
* @data_ofst: offset in bytes from start of the data_ofst to payload
* @data_len: payload size in bytes
* @zeroes: OOB place holder - not used for RNDIS_IPA.
*/
struct rndis_pkt_hdr {
__le32 msg_type;
__le32 msg_len;
__le32 data_ofst;
__le32 data_len;
__le32 zeroes[7];
} __packed__;
static int rndis_ipa_open(struct net_device *net);
static void rndis_ipa_packet_receive_notify(void *private,
enum ipa_dp_evt_type evt, unsigned long data);
static void rndis_ipa_tx_complete_notify(void *private,
enum ipa_dp_evt_type evt, unsigned long data);
static void rndis_ipa_tx_timeout(struct net_device *net);
static int rndis_ipa_stop(struct net_device *net);
static void rndis_ipa_enable_data_path(struct rndis_ipa_dev *rndis_ipa_ctx);
static struct sk_buff *rndis_encapsulate_skb(struct sk_buff *skb);
static void rndis_ipa_xmit_error(struct sk_buff *skb);
static void rndis_ipa_xmit_error_aftercare_wq(struct work_struct *work);
static void rndis_ipa_prepare_header_insertion(int eth_type,
const char *hdr_name, struct ipa_hdr_add *add_hdr,
const void *dst_mac, const void *src_mac);
static int rndis_ipa_hdrs_cfg(struct rndis_ipa_dev *rndis_ipa_ctx,
const void *dst_mac, const void *src_mac);
static int rndis_ipa_hdrs_destroy(struct rndis_ipa_dev *rndis_ipa_ctx);
static struct net_device_stats *rndis_ipa_get_stats(struct net_device *net);
static int rndis_ipa_register_properties(char *netdev_name);
static int rndis_ipa_deregister_properties(char *netdev_name);
static void rndis_ipa_rm_notify(void *user_data, enum ipa_rm_event event,
unsigned long data);
static int rndis_ipa_create_rm_resource(struct rndis_ipa_dev *rndis_ipa_ctx);
static int rndis_ipa_destory_rm_resource(struct rndis_ipa_dev *rndis_ipa_ctx);
static bool rx_filter(struct sk_buff *skb);
static bool tx_filter(struct sk_buff *skb);
static bool rm_enabled(struct rndis_ipa_dev *rndis_ipa_ctx);
static int resource_request(struct rndis_ipa_dev *rndis_ipa_ctx);
static void resource_release(struct rndis_ipa_dev *rndis_ipa_ctx);
static netdev_tx_t rndis_ipa_start_xmit(struct sk_buff *skb,
struct net_device *net);
static int rndis_ipa_loopback_pipe_create(
struct rndis_ipa_dev *rndis_ipa_ctx,
struct rndis_loopback_pipe *loopback_pipe);
static void rndis_ipa_destroy_loopback_pipe(
struct rndis_loopback_pipe *loopback_pipe);
static int rndis_ipa_create_loopback(struct rndis_ipa_dev *rndis_ipa_ctx);
static void rndis_ipa_destroy_loopback(struct rndis_ipa_dev *rndis_ipa_ctx);
static int rndis_ipa_setup_loopback(bool enable,
struct rndis_ipa_dev *rndis_ipa_ctx);
static int rndis_ipa_debugfs_loopback_open(struct inode *inode,
struct file *file);
static int rndis_ipa_debugfs_atomic_open(struct inode *inode,
struct file *file);
static int rndis_ipa_debugfs_aggr_open(struct inode *inode,
struct file *file);
static ssize_t rndis_ipa_debugfs_aggr_write(struct file *file,
const char __user *buf, size_t count, loff_t *ppos);
static ssize_t rndis_ipa_debugfs_loopback_write(struct file *file,
const char __user *buf, size_t count, loff_t *ppos);
static ssize_t rndis_ipa_debugfs_enable_write(struct file *file,
const char __user *buf, size_t count, loff_t *ppos);
static ssize_t rndis_ipa_debugfs_enable_read(struct file *file,
char __user *ubuf, size_t count, loff_t *ppos);
static ssize_t rndis_ipa_debugfs_loopback_read(struct file *file,
char __user *ubuf, size_t count, loff_t *ppos);
static ssize_t rndis_ipa_debugfs_atomic_read(struct file *file,
char __user *ubuf, size_t count, loff_t *ppos);
static void rndis_ipa_dump_skb(struct sk_buff *skb);
static int rndis_ipa_debugfs_init(struct rndis_ipa_dev *rndis_ipa_ctx);
static void rndis_ipa_debugfs_destroy(struct rndis_ipa_dev *rndis_ipa_ctx);
static int rndis_ipa_ep_registers_cfg(u32 usb_to_ipa_hdl,
u32 ipa_to_usb_hdl, u32 max_xfer_size_bytes_to_dev,
u32 max_xfer_size_bytes_to_host, u32 mtu,
bool deaggr_enable);
static int rndis_ipa_set_device_ethernet_addr(u8 *dev_ethaddr,
u8 device_ethaddr[]);
static enum rndis_ipa_state rndis_ipa_next_state(
enum rndis_ipa_state current_state,
enum rndis_ipa_operation operation);
static const char *rndis_ipa_state_string(enum rndis_ipa_state state);
static int rndis_ipa_init_module(void);
static void rndis_ipa_cleanup_module(void);
struct rndis_ipa_dev *rndis_ipa;
static const struct net_device_ops rndis_ipa_netdev_ops = {
.ndo_open = rndis_ipa_open,
.ndo_stop = rndis_ipa_stop,
.ndo_start_xmit = rndis_ipa_start_xmit,
.ndo_tx_timeout = rndis_ipa_tx_timeout,
.ndo_get_stats = rndis_ipa_get_stats,
.ndo_set_mac_address = eth_mac_addr,
};
const struct file_operations rndis_ipa_debugfs_atomic_ops = {
.open = rndis_ipa_debugfs_atomic_open,
.read = rndis_ipa_debugfs_atomic_read,
};
const struct file_operations rndis_ipa_loopback_ops = {
.open = rndis_ipa_debugfs_loopback_open,
.read = rndis_ipa_debugfs_loopback_read,
.write = rndis_ipa_debugfs_loopback_write,
};
const struct file_operations rndis_ipa_aggr_ops = {
.open = rndis_ipa_debugfs_aggr_open,
.write = rndis_ipa_debugfs_aggr_write,
};
static struct ipa_ep_cfg ipa_to_usb_ep_cfg = {
.mode = {
.mode = IPA_BASIC,
.dst = IPA_CLIENT_APPS_LAN_CONS,
},
.hdr = {
.hdr_len = ETH_HLEN + sizeof(struct rndis_pkt_hdr),
.hdr_ofst_metadata_valid = false,
.hdr_ofst_metadata = 0,
.hdr_additional_const_len = ETH_HLEN,
.hdr_ofst_pkt_size_valid = true,
.hdr_ofst_pkt_size = 3*sizeof(u32),
.hdr_a5_mux = false,
.hdr_remove_additional = false,
.hdr_metadata_reg_valid = false,
},
.hdr_ext = {
.hdr_pad_to_alignment = 0,
.hdr_total_len_or_pad_offset = 1*sizeof(u32),
.hdr_payload_len_inc_padding = false,
.hdr_total_len_or_pad = IPA_HDR_TOTAL_LEN,
.hdr_total_len_or_pad_valid = true,
.hdr_little_endian = true,
},
.aggr = {
.aggr_en = IPA_ENABLE_AGGR,
.aggr = IPA_GENERIC,
.aggr_byte_limit = 4,
.aggr_time_limit = DEFAULT_AGGR_TIME_LIMIT,
.aggr_pkt_limit = DEFAULT_AGGR_PKT_LIMIT
},
.deaggr = {
.deaggr_hdr_len = 0,
.packet_offset_valid = 0,
.packet_offset_location = 0,
.max_packet_len = 0,
},
.route = {
.rt_tbl_hdl = RNDIS_IPA_DFLT_RT_HDL,
},
.nat = {
.nat_en = IPA_SRC_NAT,
},
};
static struct ipa_ep_cfg usb_to_ipa_ep_cfg_deaggr_dis = {
.mode = {
.mode = IPA_BASIC,
.dst = IPA_CLIENT_APPS_LAN_CONS,
},
.hdr = {
.hdr_len = ETH_HLEN + sizeof(struct rndis_pkt_hdr),
.hdr_ofst_metadata_valid = false,
.hdr_ofst_metadata = 0,
.hdr_additional_const_len = 0,
.hdr_ofst_pkt_size_valid = true,
.hdr_ofst_pkt_size = 3*sizeof(u32) +
sizeof(struct rndis_pkt_hdr),
.hdr_a5_mux = false,
.hdr_remove_additional = false,
.hdr_metadata_reg_valid = false,
},
.hdr_ext = {
.hdr_pad_to_alignment = 0,
.hdr_total_len_or_pad_offset = 1*sizeof(u32),
.hdr_payload_len_inc_padding = false,
.hdr_total_len_or_pad = IPA_HDR_TOTAL_LEN,
.hdr_total_len_or_pad_valid = true,
.hdr_little_endian = true,
},
.aggr = {
.aggr_en = IPA_BYPASS_AGGR,
.aggr = 0,
.aggr_byte_limit = 0,
.aggr_time_limit = 0,
.aggr_pkt_limit = 0,
},
.deaggr = {
.deaggr_hdr_len = 0,
.packet_offset_valid = false,
.packet_offset_location = 0,
.max_packet_len = 0,
},
.route = {
.rt_tbl_hdl = RNDIS_IPA_DFLT_RT_HDL,
},
.nat = {
.nat_en = IPA_BYPASS_NAT,
},
};
static struct ipa_ep_cfg usb_to_ipa_ep_cfg_deaggr_en = {
.mode = {
.mode = IPA_BASIC,
.dst = IPA_CLIENT_APPS_LAN_CONS,
},
.hdr = {
.hdr_len = ETH_HLEN,
.hdr_ofst_metadata_valid = false,
.hdr_ofst_metadata = 0,
.hdr_additional_const_len = 0,
.hdr_ofst_pkt_size_valid = true,
.hdr_ofst_pkt_size = 3*sizeof(u32),
.hdr_a5_mux = false,
.hdr_remove_additional = false,
.hdr_metadata_reg_valid = false,
},
.hdr_ext = {
.hdr_pad_to_alignment = 0,
.hdr_total_len_or_pad_offset = 1*sizeof(u32),
.hdr_payload_len_inc_padding = false,
.hdr_total_len_or_pad = IPA_HDR_TOTAL_LEN,
.hdr_total_len_or_pad_valid = true,
.hdr_little_endian = true,
},
.aggr = {
.aggr_en = IPA_ENABLE_DEAGGR,
.aggr = IPA_GENERIC,
.aggr_byte_limit = 0,
.aggr_time_limit = 0,
.aggr_pkt_limit = 0,
},
.deaggr = {
.deaggr_hdr_len = sizeof(struct rndis_pkt_hdr),
.packet_offset_valid = true,
.packet_offset_location = 8,
.max_packet_len = 8192, /* Will be overridden*/
},
.route = {
.rt_tbl_hdl = RNDIS_IPA_DFLT_RT_HDL,
},
.nat = {
.nat_en = IPA_BYPASS_NAT,
},
};
/**
* rndis_template_hdr - RNDIS template structure for RNDIS_IPA SW insertion
* @msg_type: set for REMOTE_NDIS_PACKET_MSG (0x00000001)
* this value will be used for all data packets
* @msg_len: will add the skb length to get final size
* @data_ofst: this field value will not be changed
* @data_len: set as skb length to get final size
* @zeroes: make sure all OOB data is not used
*/
struct rndis_pkt_hdr rndis_template_hdr = {
.msg_type = RNDIS_IPA_PKT_TYPE,
.msg_len = sizeof(struct rndis_pkt_hdr),
.data_ofst = sizeof(struct rndis_pkt_hdr) - RNDIS_HDR_OFST(data_ofst),
.data_len = 0,
.zeroes = {0},
};
/**
* rndis_ipa_init() - create network device and initialize internal
* data structures
* @params: in/out parameters required for initialization,
* see "struct ipa_usb_init_params" for more details
*
* Shall be called prior to pipe connection.
* Detailed description:
* - allocate the network device
* - set default values for driver internal switches and stash them inside
* the netdev private field
* - set needed headroom for RNDIS header
* - create debugfs folder and files
* - create IPA resource manager client
* - set the ethernet address for the netdev to be added on SW Tx path
* - add header insertion rules for IPA driver (based on host/device Ethernet
* addresses given in input params and on RNDIS data template struct)
* - register tx/rx properties to IPA driver (will be later used
* by IPA configuration manager to configure rest of the IPA rules)
* - set the carrier state to "off" (until connect is called)
* - register the network device
* - set the out parameters
* - change driver internal state to INITIALIZED
*
* Returns negative errno, or zero on success
*/
int rndis_ipa_init(struct ipa_usb_init_params *params)
{
int result = 0;
struct net_device *net;
struct rndis_ipa_dev *rndis_ipa_ctx;
RNDIS_IPA_LOG_ENTRY();
RNDIS_IPA_DEBUG("%s initializing\n", DRV_NAME);
NULL_CHECK_RETVAL(params);
RNDIS_IPA_DEBUG("host_ethaddr=%pM, device_ethaddr=%pM\n",
params->host_ethaddr,
params->device_ethaddr);
net = alloc_etherdev(sizeof(struct rndis_ipa_dev));
if (!net) {
result = -ENOMEM;
RNDIS_IPA_ERROR("fail to allocate Ethernet device\n");
goto fail_alloc_etherdev;
}
RNDIS_IPA_DEBUG("network device was successfully allocated\n");
rndis_ipa_ctx = netdev_priv(net);
if (!rndis_ipa_ctx) {
result = -ENOMEM;
RNDIS_IPA_ERROR("fail to extract netdev priv\n");
goto fail_netdev_priv;
}
memset(rndis_ipa_ctx, 0, sizeof(*rndis_ipa_ctx));
RNDIS_IPA_DEBUG("rndis_ipa_ctx (private)=%p\n", rndis_ipa_ctx);
rndis_ipa_ctx->net = net;
rndis_ipa_ctx->tx_filter = false;
rndis_ipa_ctx->rx_filter = false;
rndis_ipa_ctx->icmp_filter = true;
rndis_ipa_ctx->rm_enable = true;
rndis_ipa_ctx->tx_dropped = 0;
rndis_ipa_ctx->rx_dropped = 0;
rndis_ipa_ctx->tx_dump_enable = false;
rndis_ipa_ctx->rx_dump_enable = false;
rndis_ipa_ctx->deaggregation_enable = false;
rndis_ipa_ctx->outstanding_high = DEFAULT_OUTSTANDING_HIGH;
rndis_ipa_ctx->outstanding_low = DEFAULT_OUTSTANDING_LOW;
atomic_set(&rndis_ipa_ctx->outstanding_pkts, 0);
memcpy(rndis_ipa_ctx->device_ethaddr, params->device_ethaddr,
sizeof(rndis_ipa_ctx->device_ethaddr));
memcpy(rndis_ipa_ctx->host_ethaddr, params->host_ethaddr,
sizeof(rndis_ipa_ctx->host_ethaddr));
INIT_DELAYED_WORK(&rndis_ipa_ctx->xmit_error_delayed_work,
rndis_ipa_xmit_error_aftercare_wq);
rndis_ipa_ctx->error_msec_sleep_time =
MIN_TX_ERROR_SLEEP_PERIOD;
RNDIS_IPA_DEBUG("internal data structures were set\n");
if (!params->device_ready_notify)
RNDIS_IPA_DEBUG("device_ready_notify() was not supplied\n");
rndis_ipa_ctx->device_ready_notify = params->device_ready_notify;
snprintf(net->name, sizeof(net->name), "%s%%d", NETDEV_NAME);
RNDIS_IPA_DEBUG("Setting network interface driver name to: %s\n",
net->name);
net->netdev_ops = &rndis_ipa_netdev_ops;
net->watchdog_timeo = TX_TIMEOUT;
net->needed_headroom = sizeof(rndis_template_hdr);
RNDIS_IPA_DEBUG("Needed headroom for RNDIS header set to %d\n",
net->needed_headroom);
result = rndis_ipa_debugfs_init(rndis_ipa_ctx);
if (result)
goto fail_debugfs;
RNDIS_IPA_DEBUG("debugfs entries were created\n");
result = rndis_ipa_set_device_ethernet_addr(net->dev_addr,
rndis_ipa_ctx->device_ethaddr);
if (result) {
RNDIS_IPA_ERROR("set device MAC failed\n");
goto fail_set_device_ethernet;
}
RNDIS_IPA_DEBUG("Device Ethernet address set %pM\n", net->dev_addr);
result = rndis_ipa_hdrs_cfg(rndis_ipa_ctx,
params->host_ethaddr,
params->device_ethaddr);
if (result) {
RNDIS_IPA_ERROR("fail on ipa hdrs set\n");
goto fail_hdrs_cfg;
}
RNDIS_IPA_DEBUG("IPA header-insertion configed for Ethernet+RNDIS\n");
result = rndis_ipa_register_properties(net->name);
if (result) {
RNDIS_IPA_ERROR("fail on properties set\n");
goto fail_register_tx;
}
RNDIS_IPA_DEBUG("2 TX and 2 RX properties were registered\n");
netif_carrier_off(net);
RNDIS_IPA_DEBUG("set carrier off until pipes are connected\n");
result = register_netdev(net);
if (result) {
RNDIS_IPA_ERROR("register_netdev failed: %d\n", result);
goto fail_register_netdev;
}
RNDIS_IPA_DEBUG("netdev:%s registration succeeded, index=%d\n",
net->name, net->ifindex);
rndis_ipa = rndis_ipa_ctx;
params->ipa_rx_notify = rndis_ipa_packet_receive_notify;
params->ipa_tx_notify = rndis_ipa_tx_complete_notify;
params->private = rndis_ipa_ctx;
params->skip_ep_cfg = false;
rndis_ipa_ctx->state = RNDIS_IPA_INITIALIZED;
RNDIS_IPA_STATE_DEBUG(rndis_ipa_ctx);
pr_info("RNDIS_IPA NetDev was initialized");
RNDIS_IPA_LOG_EXIT();
return 0;
fail_register_netdev:
rndis_ipa_deregister_properties(net->name);
fail_register_tx:
rndis_ipa_hdrs_destroy(rndis_ipa_ctx);
fail_set_device_ethernet:
fail_hdrs_cfg:
rndis_ipa_debugfs_destroy(rndis_ipa_ctx);
fail_debugfs:
fail_netdev_priv:
free_netdev(net);
fail_alloc_etherdev:
return result;
}
EXPORT_SYMBOL(rndis_ipa_init);
/**
* rndis_ipa_pipe_connect_notify() - notify rndis_ipa Netdev that the USB pipes
* were connected
* @usb_to_ipa_hdl: handle from IPA driver client for USB->IPA
* @ipa_to_usb_hdl: handle from IPA driver client for IPA->USB
* @private: same value that was set by init(), this parameter holds the
* network device pointer.
* @max_transfer_byte_size: RNDIS protocol specific, the maximum size that
* the host expect
* @max_packet_number: RNDIS protocol specific, the maximum packet number
* that the host expects
*
* Once USB driver finishes the pipe connection between IPA core
* and USB core this method shall be called in order to
* allow the driver to complete the data path configurations.
* Detailed description:
* - configure the IPA end-points register
* - notify the Linux kernel for "carrier_on"
* - change the driver internal state
*
* After this function is done the driver state changes to "Connected" or
* Connected and Up.
* This API is expected to be called after initialization() or
* after a call to disconnect().
*
* Returns negative errno, or zero on success
*/
int rndis_ipa_pipe_connect_notify(u32 usb_to_ipa_hdl,
u32 ipa_to_usb_hdl,
u32 max_xfer_size_bytes_to_dev,
u32 max_packet_number_to_dev,
u32 max_xfer_size_bytes_to_host,
void *private)
{
struct rndis_ipa_dev *rndis_ipa_ctx = private;
int next_state;
int result;
RNDIS_IPA_LOG_ENTRY();
NULL_CHECK_RETVAL(private);
RNDIS_IPA_DEBUG("usb_to_ipa_hdl=%d, ipa_to_usb_hdl=%d, private=0x%p\n",
usb_to_ipa_hdl, ipa_to_usb_hdl, private);
RNDIS_IPA_DEBUG("max_xfer_sz_to_dev=%d, max_pkt_num_to_dev=%d\n",
max_xfer_size_bytes_to_dev,
max_packet_number_to_dev);
RNDIS_IPA_DEBUG("max_xfer_sz_to_host=%d\n",
max_xfer_size_bytes_to_host);
next_state = rndis_ipa_next_state(rndis_ipa_ctx->state,
RNDIS_IPA_CONNECT);
if (next_state == RNDIS_IPA_INVALID) {
RNDIS_IPA_ERROR("use init()/disconnect() before connect()\n");
return -EPERM;
}
if (usb_to_ipa_hdl >= IPA_CLIENT_MAX) {
RNDIS_IPA_ERROR("usb_to_ipa_hdl(%d) - not valid ipa handle\n",
usb_to_ipa_hdl);
return -EINVAL;
}
if (ipa_to_usb_hdl >= IPA_CLIENT_MAX) {
RNDIS_IPA_ERROR("ipa_to_usb_hdl(%d) - not valid ipa handle\n",
ipa_to_usb_hdl);
return -EINVAL;
}
result = rndis_ipa_create_rm_resource(rndis_ipa_ctx);
if (result) {
RNDIS_IPA_ERROR("fail on RM create\n");
goto fail_create_rm;
}
RNDIS_IPA_DEBUG("RM resource was created\n");
rndis_ipa_ctx->ipa_to_usb_hdl = ipa_to_usb_hdl;
rndis_ipa_ctx->usb_to_ipa_hdl = usb_to_ipa_hdl;
if (max_packet_number_to_dev > 1)
rndis_ipa_ctx->deaggregation_enable = true;
else
rndis_ipa_ctx->deaggregation_enable = false;
result = rndis_ipa_ep_registers_cfg(usb_to_ipa_hdl,
ipa_to_usb_hdl,
max_xfer_size_bytes_to_dev,
max_xfer_size_bytes_to_host,
rndis_ipa_ctx->net->mtu,
rndis_ipa_ctx->deaggregation_enable);
if (result) {
RNDIS_IPA_ERROR("fail on ep cfg\n");
goto fail;
}
RNDIS_IPA_DEBUG("end-points configured\n");
netif_stop_queue(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("netif_stop_queue() was called\n");
netif_carrier_on(rndis_ipa_ctx->net);
if (!netif_carrier_ok(rndis_ipa_ctx->net)) {
RNDIS_IPA_ERROR("netif_carrier_ok error\n");
result = -EBUSY;
goto fail;
}
RNDIS_IPA_DEBUG("netif_carrier_on() was called\n");
rndis_ipa_ctx->state = next_state;
RNDIS_IPA_STATE_DEBUG(rndis_ipa_ctx);
if (next_state == RNDIS_IPA_CONNECTED_AND_UP)
rndis_ipa_enable_data_path(rndis_ipa_ctx);
else
RNDIS_IPA_DEBUG("queue shall be started after open()\n");
pr_info("RNDIS_IPA NetDev pipes were connected\n");
RNDIS_IPA_LOG_EXIT();
return 0;
fail:
rndis_ipa_destory_rm_resource(rndis_ipa_ctx);
fail_create_rm:
return result;
}
EXPORT_SYMBOL(rndis_ipa_pipe_connect_notify);
/**
* rndis_ipa_open() - notify Linux network stack to start sending packets
* @net: the network interface supplied by the network stack
*
* Linux uses this API to notify the driver that the network interface
* transitions to the up state.
* The driver will instruct the Linux network stack to start
* delivering data packets.
* The driver internal state shall be changed to Up or Connected and Up
*
* Returns negative errno, or zero on success
*/
static int rndis_ipa_open(struct net_device *net)
{
struct rndis_ipa_dev *rndis_ipa_ctx;
int next_state;
RNDIS_IPA_LOG_ENTRY();
rndis_ipa_ctx = netdev_priv(net);
next_state = rndis_ipa_next_state(rndis_ipa_ctx->state, RNDIS_IPA_OPEN);
if (next_state == RNDIS_IPA_INVALID) {
RNDIS_IPA_ERROR("can't bring driver up before initialize\n");
return -EPERM;
}
rndis_ipa_ctx->state = next_state;
RNDIS_IPA_STATE_DEBUG(rndis_ipa_ctx);
if (next_state == RNDIS_IPA_CONNECTED_AND_UP)
rndis_ipa_enable_data_path(rndis_ipa_ctx);
else
RNDIS_IPA_DEBUG("queue shall be started after connect()\n");
pr_info("RNDIS_IPA NetDev was opened\n");
RNDIS_IPA_LOG_EXIT();
return 0;
}
/**
* rndis_ipa_start_xmit() - send data from APPs to USB core via IPA core
* using SW path (Tx data path)
* Tx path for this Netdev is Apps-processor->IPA->USB
* @skb: packet received from Linux network stack destined for tethered PC
* @net: the network device being used to send this packet (rndis0)
*
* Several conditions needed in order to send the packet to IPA:
* - Transmit queue for the network driver is currently
* in "started" state
* - The driver internal state is in Connected and Up state.
* - Filters Tx switch are turned off
* - The IPA resource manager state for the driver producer client
* is "Granted" which implies that all the resources in the dependency
* graph are valid for data flow.
* - outstanding high boundary was not reached.
*
* In case the outstanding packets high boundary is reached, the driver will
* stop the send queue until enough packets are processed by
* the IPA core (based on calls to rndis_ipa_tx_complete_notify).
*
* In case all of the conditions are met, the network driver shall:
* - encapsulate the Ethernet packet with RNDIS header (REMOTE_NDIS_PACKET_MSG)
* - send the packet by using IPA Driver SW path (IP_PACKET_INIT)
* - Netdev status fields shall be updated based on the current Tx packet
*
* Returns NETDEV_TX_BUSY if retry should be made later,
* or NETDEV_TX_OK on success.
*/
static netdev_tx_t rndis_ipa_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
int ret;
netdev_tx_t status = NETDEV_TX_BUSY;
struct rndis_ipa_dev *rndis_ipa_ctx = netdev_priv(net);
net->trans_start = jiffies;
RNDIS_IPA_DEBUG("Tx, len=%d, skb->protocol=%d, outstanding=%d\n",
skb->len, skb->protocol,
atomic_read(&rndis_ipa_ctx->outstanding_pkts));
if (unlikely(netif_queue_stopped(net))) {
RNDIS_IPA_ERROR("interface queue is stopped\n");
goto out;
}
if (unlikely(rndis_ipa_ctx->tx_dump_enable))
rndis_ipa_dump_skb(skb);
if (unlikely(rndis_ipa_ctx->state != RNDIS_IPA_CONNECTED_AND_UP)) {
RNDIS_IPA_ERROR("Missing pipe connected and/or iface up\n");
return NETDEV_TX_BUSY;
}
if (unlikely(tx_filter(skb))) {
dev_kfree_skb_any(skb);
RNDIS_IPA_DEBUG("packet got filtered out on Tx path\n");
rndis_ipa_ctx->tx_dropped++;
status = NETDEV_TX_OK;
goto out;
}
ret = resource_request(rndis_ipa_ctx);
if (ret) {
RNDIS_IPA_DEBUG("Waiting to resource\n");
netif_stop_queue(net);
goto resource_busy;
}
if (atomic_read(&rndis_ipa_ctx->outstanding_pkts) >=
rndis_ipa_ctx->outstanding_high) {
RNDIS_IPA_DEBUG("Outstanding high boundary reached (%d)\n",
rndis_ipa_ctx->outstanding_high);
netif_stop_queue(net);
RNDIS_IPA_DEBUG("send queue was stopped\n");
status = NETDEV_TX_BUSY;
goto out;
}
skb = rndis_encapsulate_skb(skb);
ret = ipa_tx_dp(IPA_TO_USB_CLIENT, skb, NULL);
if (ret) {
RNDIS_IPA_ERROR("ipa transmit failed (%d)\n", ret);
goto fail_tx_packet;
}
atomic_inc(&rndis_ipa_ctx->outstanding_pkts);
status = NETDEV_TX_OK;
goto out;
fail_tx_packet:
rndis_ipa_xmit_error(skb);
out:
resource_release(rndis_ipa_ctx);
resource_busy:
RNDIS_IPA_DEBUG("packet Tx done - %s\n",
(status == NETDEV_TX_OK) ? "OK" : "FAIL");
return status;
}
/**
* rndis_ipa_tx_complete_notify() - notification for Netdev that the
* last packet was successfully sent
* @private: driver context stashed by IPA driver upon pipe connect
* @evt: event type (expected to be write-done event)
* @data: data provided with event (this is actually the skb that
* holds the sent packet)
*
* This function will be called on interrupt bottom halve deferred context.
* outstanding packets counter shall be decremented.
* Network stack send queue will be re-started in case low outstanding
* boundary is reached and queue was stopped before.
* At the end the skb shall be freed.
*/
static void rndis_ipa_tx_complete_notify(void *private,
enum ipa_dp_evt_type evt,
unsigned long data)
{
struct sk_buff *skb = (struct sk_buff *)data;
struct rndis_ipa_dev *rndis_ipa_ctx = private;
NULL_CHECK_NO_RETVAL(private);
RNDIS_IPA_DEBUG("Tx-complete, len=%d, skb->prot=%d, outstanding=%d\n",
skb->len, skb->protocol,
atomic_read(&rndis_ipa_ctx->outstanding_pkts));
if (unlikely((evt != IPA_WRITE_DONE))) {
RNDIS_IPA_ERROR("unsupported event on TX call-back\n");
return;
}
if (unlikely(rndis_ipa_ctx->state != RNDIS_IPA_CONNECTED_AND_UP)) {
RNDIS_IPA_DEBUG("dropping Tx-complete pkt, state=%s\n",
rndis_ipa_state_string(rndis_ipa_ctx->state));
goto out;
}
rndis_ipa_ctx->net->stats.tx_packets++;
rndis_ipa_ctx->net->stats.tx_bytes += skb->len;
atomic_dec(&rndis_ipa_ctx->outstanding_pkts);
if (netif_queue_stopped(rndis_ipa_ctx->net) &&
netif_carrier_ok(rndis_ipa_ctx->net) &&
atomic_read(&rndis_ipa_ctx->outstanding_pkts) <
(rndis_ipa_ctx->outstanding_low)) {
RNDIS_IPA_DEBUG("outstanding low boundary reached (%d)n",
rndis_ipa_ctx->outstanding_low);
netif_wake_queue(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("send queue was awaken\n");
}
out:
dev_kfree_skb_any(skb);
return;
}
static void rndis_ipa_tx_timeout(struct net_device *net)
{
struct rndis_ipa_dev *rndis_ipa_ctx = netdev_priv(net);
int outstanding = atomic_read(&rndis_ipa_ctx->outstanding_pkts);
RNDIS_IPA_ERROR("possible IPA stall was detected, %d outstanding\n",
outstanding);
net->stats.tx_errors++;
}
/**
* rndis_ipa_rm_notify() - callback supplied to IPA resource manager
* for grant/release events
* user_data: the driver context supplied to IPA resource manager during call
* to ipa_rm_create_resource().
* event: the event notified to us by IPA resource manager (Release/Grant)
* data: reserved field supplied by IPA resource manager
*
* This callback shall be called based on resource request/release sent
* to the IPA resource manager.
* In case the queue was stopped during EINPROGRESS for Tx path and the
* event received is Grant then the queue shall be restarted.
* In case the event notified is a release notification the netdev discard it.
*/
static void rndis_ipa_rm_notify(void *user_data, enum ipa_rm_event event,
unsigned long data)
{
struct rndis_ipa_dev *rndis_ipa_ctx = user_data;
RNDIS_IPA_LOG_ENTRY();
if (event == IPA_RM_RESOURCE_RELEASED) {
RNDIS_IPA_DEBUG("Resource Released\n");
return;
}
if (event != IPA_RM_RESOURCE_GRANTED) {
RNDIS_IPA_ERROR("Unexceoted event receieved from RM (%d\n)",
event);
return;
}
RNDIS_IPA_DEBUG("Resource Granted\n");
if (netif_queue_stopped(rndis_ipa_ctx->net)) {
RNDIS_IPA_DEBUG("starting queue\n");
netif_start_queue(rndis_ipa_ctx->net);
} else {
RNDIS_IPA_DEBUG("queue already awake\n");
}
RNDIS_IPA_LOG_EXIT();
}
/**
* rndis_ipa_packet_receive_notify() - Rx notify for packet sent from
* tethered PC (USB->IPA).
* is USB->IPA->Apps-processor
* @private: driver context
* @evt: event type
* @data: data provided with event
*
* Once IPA driver receives a packet from USB client this callback will be
* called from bottom-half interrupt handling context (ipa Rx workqueue).
*
* Packets that shall be sent to Apps processor may be of two types:
* 1) Packets that are destined for Apps (e.g: WEBSERVER running on Apps)
* 2) Exception packets that need special handling (based on IPA core
* configuration, e.g: new TCP session or any other packets that IPA core
* can't handle)
* If the next conditions are met, the packet shall be sent up to the
* Linux network stack:
* - Driver internal state is Connected and Up
* - Notification received from IPA driver meets the expected type
* for Rx packet
* -Filters Rx switch are turned off
*
* Prior to the sending to the network stack:
* - Netdev struct shall be stashed to the skb as required by the network stack
* - Ethernet header shall be removed (skb->data shall point to the Ethernet
* payload, Ethernet still stashed under MAC header).
* - The skb->pkt_protocol shall be set based on the ethernet destination
* address, Can be Broadcast, Multicast or Other-Host, The later
* pkt-types packets shall be dropped in case the Netdev is not
* in promisc mode.
* - Set the skb protocol field based on the EtherType field
*
* Netdev status fields shall be updated based on the current Rx packet
*/
static void rndis_ipa_packet_receive_notify(void *private,
enum ipa_dp_evt_type evt,
unsigned long data)
{
struct sk_buff *skb = (struct sk_buff *)data;
struct rndis_ipa_dev *rndis_ipa_ctx = private;
int result;
unsigned int packet_len = skb->len;
RNDIS_IPA_DEBUG("packet Rx, len=%d\n",
skb->len);
if (unlikely(rndis_ipa_ctx->rx_dump_enable))
rndis_ipa_dump_skb(skb);
if (unlikely(rndis_ipa_ctx->state != RNDIS_IPA_CONNECTED_AND_UP)) {
RNDIS_IPA_DEBUG("use connect()/up() before receive()\n");
RNDIS_IPA_DEBUG("packet dropped (length=%d)\n",
skb->len);
return;
}
if (evt != IPA_RECEIVE) {
RNDIS_IPA_ERROR("a none IPA_RECEIVE event in driver RX\n");
return;
}
if (!rndis_ipa_ctx->deaggregation_enable)
skb_pull(skb, sizeof(struct rndis_pkt_hdr));
skb->dev = rndis_ipa_ctx->net;
skb->protocol = eth_type_trans(skb, rndis_ipa_ctx->net);
if (rx_filter(skb)) {
RNDIS_IPA_DEBUG("packet got filtered out on RX path\n");
rndis_ipa_ctx->rx_dropped++;
dev_kfree_skb_any(skb);
return;
}
result = netif_rx_ni(skb);
if (result)
RNDIS_IPA_ERROR("fail on netif_rx_ni\n");
rndis_ipa_ctx->net->stats.rx_packets++;
rndis_ipa_ctx->net->stats.rx_bytes += packet_len;
return;
}
/** rndis_ipa_stop() - notify the network interface to stop
* sending/receiving data
* @net: the network device being stopped.
*
* This API is used by Linux network stack to notify the network driver that
* its state was changed to "down"
* The driver will stop the "send" queue and change its internal
* state to "Connected".
* The Netdev shall be returned to be "Up" after rndis_ipa_open().
*/
static int rndis_ipa_stop(struct net_device *net)
{
struct rndis_ipa_dev *rndis_ipa_ctx = netdev_priv(net);
int next_state;
RNDIS_IPA_LOG_ENTRY();
next_state = rndis_ipa_next_state(rndis_ipa_ctx->state, RNDIS_IPA_STOP);
if (next_state == RNDIS_IPA_INVALID) {
RNDIS_IPA_DEBUG("can't do network interface down without up\n");
return -EPERM;
}
netif_stop_queue(net);
pr_info("RNDIS_IPA NetDev queue is stopped\n");
rndis_ipa_ctx->state = next_state;
RNDIS_IPA_STATE_DEBUG(rndis_ipa_ctx);
RNDIS_IPA_LOG_EXIT();
return 0;
}
/** rndis_ipa_disconnect() - notify rndis_ipa Netdev that the USB pipes
* were disconnected
* @private: same value that was set by init(), this parameter holds the
* network device pointer.
*
* USB shall notify the Netdev after disconnecting the pipe.
* - The internal driver state shall returned to its previous
* state (Up or Initialized).
* - Linux network stack shall be informed for carrier off to notify
* user space for pipe disconnect
* - send queue shall be stopped
* During the transition between the pipe disconnection to
* the Netdev notification packets
* are expected to be dropped by IPA driver or IPA core.
*/
int rndis_ipa_pipe_disconnect_notify(void *private)
{
struct rndis_ipa_dev *rndis_ipa_ctx = private;
int next_state;
int outstanding_dropped_pkts;
int retval;
RNDIS_IPA_LOG_ENTRY();
NULL_CHECK_RETVAL(rndis_ipa_ctx);
RNDIS_IPA_DEBUG("private=0x%p\n", private);
next_state = rndis_ipa_next_state(rndis_ipa_ctx->state,
RNDIS_IPA_DISCONNECT);
if (next_state == RNDIS_IPA_INVALID) {
RNDIS_IPA_ERROR("can't disconnect before connect\n");
return -EPERM;
}
if (rndis_ipa_ctx->during_xmit_error) {
RNDIS_IPA_DEBUG("canceling xmit-error delayed work\n");
cancel_delayed_work_sync(
&rndis_ipa_ctx->xmit_error_delayed_work);
rndis_ipa_ctx->during_xmit_error = false;
}
netif_carrier_off(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("carrier_off notification was sent\n");
netif_stop_queue(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("queue stopped\n");
outstanding_dropped_pkts =
atomic_read(&rndis_ipa_ctx->outstanding_pkts);
rndis_ipa_ctx->net->stats.tx_dropped += outstanding_dropped_pkts;
atomic_set(&rndis_ipa_ctx->outstanding_pkts, 0);
retval = rndis_ipa_destory_rm_resource(rndis_ipa_ctx);
if (retval) {
RNDIS_IPA_ERROR("Fail to clean RM\n");
return retval;
}
RNDIS_IPA_DEBUG("RM was successfully destroyed\n");
rndis_ipa_ctx->state = next_state;
RNDIS_IPA_STATE_DEBUG(rndis_ipa_ctx);
pr_info("RNDIS_IPA NetDev pipes disconnected (%d outstanding clr)\n",
outstanding_dropped_pkts);
RNDIS_IPA_LOG_EXIT();
return 0;
}
EXPORT_SYMBOL(rndis_ipa_pipe_disconnect_notify);
/**
* rndis_ipa_cleanup() - unregister the network interface driver and free
* internal data structs.
* @private: same value that was set by init(), this
* parameter holds the network device pointer.
*
* This function shall be called once the network interface is not
* needed anymore, e.g: when the USB composition does not support it.
* This function shall be called after the pipes were disconnected.
* Detailed description:
* - remove header-insertion headers from IPA core
* - delete the driver dependency defined for IPA resource manager and
* destroy the producer resource.
* - remove the debugfs entries
* - deregister the network interface from Linux network stack
* - free all internal data structs
*
* It is assumed that no packets shall be sent through HW bridging
* during cleanup to avoid packets trying to add an header that is
* removed during cleanup (IPA configuration manager should have
* removed them at this point)
*/
void rndis_ipa_cleanup(void *private)
{
struct rndis_ipa_dev *rndis_ipa_ctx = private;
int next_state;
int retval;
RNDIS_IPA_LOG_ENTRY();
RNDIS_IPA_DEBUG("private=0x%p\n", private);
if (!rndis_ipa_ctx) {
RNDIS_IPA_ERROR("rndis_ipa_ctx NULL pointer\n");
return;
}
next_state = rndis_ipa_next_state(rndis_ipa_ctx->state,
RNDIS_IPA_CLEANUP);
if (next_state == RNDIS_IPA_INVALID) {
RNDIS_IPA_ERROR("use disconnect()before clean()\n");
return;
}
RNDIS_IPA_STATE_DEBUG(rndis_ipa_ctx);
retval = rndis_ipa_deregister_properties(rndis_ipa_ctx->net->name);
if (retval) {
RNDIS_IPA_ERROR("Fail to deregister Tx/Rx properties\n");
return;
}
RNDIS_IPA_DEBUG("deregister Tx/Rx properties was successful\n");
retval = rndis_ipa_hdrs_destroy(rndis_ipa_ctx);
if (retval)
RNDIS_IPA_ERROR(
"Failed removing RNDIS headers from IPA core. Continue anyway\n");
else
RNDIS_IPA_DEBUG("RNDIS headers were removed from IPA core\n");
rndis_ipa_debugfs_destroy(rndis_ipa_ctx);
RNDIS_IPA_DEBUG("debugfs remove was done\n");
unregister_netdev(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("netdev unregistered\n");
rndis_ipa_ctx->state = next_state;
free_netdev(rndis_ipa_ctx->net);
pr_info("RNDIS_IPA NetDev was cleaned\n");
RNDIS_IPA_LOG_EXIT();
return;
}
EXPORT_SYMBOL(rndis_ipa_cleanup);
static void rndis_ipa_enable_data_path(struct rndis_ipa_dev *rndis_ipa_ctx)
{
if (rndis_ipa_ctx->device_ready_notify) {
rndis_ipa_ctx->device_ready_notify();
RNDIS_IPA_DEBUG("USB device_ready_notify() was called\n");
} else {
RNDIS_IPA_DEBUG("device_ready_notify() not supplied\n");
}
netif_start_queue(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("netif_start_queue() was called\n");
}
static void rndis_ipa_xmit_error(struct sk_buff *skb)
{
bool retval;
struct rndis_ipa_dev *rndis_ipa_ctx = netdev_priv(skb->dev);
unsigned long delay_jiffies;
u8 rand_dealy_msec;
RNDIS_IPA_LOG_ENTRY();
RNDIS_IPA_DEBUG("starting Tx-queue backoff\n");
netif_stop_queue(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("netif_stop_queue was called\n");
skb_pull(skb, sizeof(rndis_template_hdr));
rndis_ipa_ctx->net->stats.tx_errors++;
get_random_bytes(&rand_dealy_msec, sizeof(rand_dealy_msec));
delay_jiffies = msecs_to_jiffies(
rndis_ipa_ctx->error_msec_sleep_time + rand_dealy_msec);
retval = schedule_delayed_work(
&rndis_ipa_ctx->xmit_error_delayed_work, delay_jiffies);
if (!retval) {
RNDIS_IPA_ERROR("fail to schedule delayed work\n");
netif_start_queue(rndis_ipa_ctx->net);
} else {
RNDIS_IPA_DEBUG("work scheduled to start Tx-queue in %d msec\n",
rndis_ipa_ctx->error_msec_sleep_time + rand_dealy_msec);
rndis_ipa_ctx->during_xmit_error = true;
}
RNDIS_IPA_LOG_EXIT();
}
static void rndis_ipa_xmit_error_aftercare_wq(struct work_struct *work)
{
struct rndis_ipa_dev *rndis_ipa_ctx;
struct delayed_work *delayed_work;
RNDIS_IPA_LOG_ENTRY();
RNDIS_IPA_DEBUG("Starting queue after xmit error\n");
delayed_work = to_delayed_work(work);
rndis_ipa_ctx = container_of(delayed_work, struct rndis_ipa_dev,
xmit_error_delayed_work);
if (unlikely(rndis_ipa_ctx->state != RNDIS_IPA_CONNECTED_AND_UP)) {
RNDIS_IPA_ERROR("error aftercare handling in bad state (%d)",
rndis_ipa_ctx->state);
return;
}
rndis_ipa_ctx->during_xmit_error = false;
netif_start_queue(rndis_ipa_ctx->net);
RNDIS_IPA_DEBUG("netif_start_queue() was called\n");
RNDIS_IPA_LOG_EXIT();
}
/**
* rndis_ipa_prepare_header_insertion() - prepare the header insertion request
* for IPA driver
* eth_type: the Ethernet type for this header-insertion header
* hdr_name: string that shall represent this header in IPA data base
* add_hdr: output for caller to be used with ipa_add_hdr() to configure
* the IPA core
* dst_mac: tethered PC MAC (Ethernet) address to be added to packets
* for IPA->USB pipe
* src_mac: device MAC (Ethernet) address to be added to packets
* for IPA->USB pipe
*
* This function shall build the header-insertion block request for a
* single Ethernet+RNDIS header)
* this header shall be inserted for packets processed by IPA
* and destined for USB client.
* This header shall be used for HW bridging for packets destined for
* tethered PC.
* For SW data-path, this header won't be used.
*/
static void rndis_ipa_prepare_header_insertion(int eth_type,
const char *hdr_name, struct ipa_hdr_add *add_hdr,
const void *dst_mac, const void *src_mac)
{
struct ethhdr *eth_hdr;
add_hdr->hdr_len = sizeof(rndis_template_hdr);
add_hdr->is_partial = false;
strlcpy(add_hdr->name, hdr_name, IPA_RESOURCE_NAME_MAX);
memcpy(add_hdr->hdr, &rndis_template_hdr, sizeof(rndis_template_hdr));
eth_hdr = (struct ethhdr *)(add_hdr->hdr + sizeof(rndis_template_hdr));
memcpy(eth_hdr->h_dest, dst_mac, ETH_ALEN);
memcpy(eth_hdr->h_source, src_mac, ETH_ALEN);
eth_hdr->h_proto = htons(eth_type);
add_hdr->hdr_len += ETH_HLEN;
add_hdr->is_eth2_ofst_valid = true;
add_hdr->eth2_ofst = sizeof(rndis_template_hdr);
add_hdr->type = IPA_HDR_L2_ETHERNET_II;
}
/**
* rndis_ipa_hdrs_cfg() - configure header insertion block in IPA core
* to allow HW bridging
* @rndis_ipa_ctx: main driver context
* @dst_mac: destination MAC address (tethered PC)
* @src_mac: source MAC address (MDM device)
*
* This function shall add 2 headers.
* One header for Ipv4 and one header for Ipv6.
* Both headers shall contain Ethernet header and RNDIS header, the only
* difference shall be in the EtherTye field.
* Headers will be committed to HW
*
* Returns negative errno, or zero on success
*/
static int rndis_ipa_hdrs_cfg(struct rndis_ipa_dev *rndis_ipa_ctx,
const void *dst_mac, const void *src_mac)
{
struct ipa_ioc_add_hdr *hdrs;
struct ipa_hdr_add *ipv4_hdr;
struct ipa_hdr_add *ipv6_hdr;
int result = 0;
RNDIS_IPA_LOG_ENTRY();
hdrs = kzalloc(sizeof(*hdrs) + sizeof(*ipv4_hdr) + sizeof(*ipv6_hdr),
GFP_KERNEL);
if (!hdrs) {
RNDIS_IPA_ERROR("mem allocation fail for header-insertion\n");
result = -ENOMEM;
goto fail_mem;
}
ipv4_hdr = &hdrs->hdr[0];
ipv6_hdr = &hdrs->hdr[1];
rndis_ipa_prepare_header_insertion(ETH_P_IP, IPV4_HDR_NAME,
ipv4_hdr, dst_mac, src_mac);
rndis_ipa_prepare_header_insertion(ETH_P_IPV6, IPV6_HDR_NAME,
ipv6_hdr, dst_mac, src_mac);
hdrs->commit = 1;
hdrs->num_hdrs = 2;
result = ipa_add_hdr(hdrs);
if (result) {
RNDIS_IPA_ERROR("Fail on Header-Insertion(%d)\n", result);
goto fail_add_hdr;
}
if (ipv4_hdr->status) {
RNDIS_IPA_ERROR("Fail on Header-Insertion ipv4(%d)\n",
ipv4_hdr->status);
result = ipv4_hdr->status;
goto fail_add_hdr;
}
if (ipv6_hdr->status) {
RNDIS_IPA_ERROR("Fail on Header-Insertion ipv6(%d)\n",
ipv6_hdr->status);
result = ipv6_hdr->status;
goto fail_add_hdr;
}
rndis_ipa_ctx->eth_ipv4_hdr_hdl = ipv4_hdr->hdr_hdl;
rndis_ipa_ctx->eth_ipv6_hdr_hdl = ipv6_hdr->hdr_hdl;
RNDIS_IPA_LOG_EXIT();
fail_add_hdr:
kfree(hdrs);
fail_mem:
return result;
}
/**
* rndis_ipa_hdrs_destroy() - remove the IPA core configuration done for
* the driver data path bridging.
* @rndis_ipa_ctx: the driver context
*
* Revert the work done on rndis_ipa_hdrs_cfg(), which is,
* remove 2 headers for Ethernet+RNDIS.
*/
static int rndis_ipa_hdrs_destroy(struct rndis_ipa_dev *rndis_ipa_ctx)
{
struct ipa_ioc_del_hdr *del_hdr;
struct ipa_hdr_del *ipv4;
struct ipa_hdr_del *ipv6;
int result;
del_hdr = kzalloc(sizeof(*del_hdr) + sizeof(*ipv4) +
sizeof(*ipv6), GFP_KERNEL);
if (!del_hdr) {
RNDIS_IPA_ERROR("memory allocation for del_hdr failed\n");
return -ENOMEM;
}
del_hdr->commit = 1;
del_hdr->num_hdls = 2;
ipv4 = &del_hdr->hdl[0];
ipv4->hdl = rndis_ipa_ctx->eth_ipv4_hdr_hdl;
ipv6 = &del_hdr->hdl[1];
ipv6->hdl = rndis_ipa_ctx->eth_ipv6_hdr_hdl;
result = ipa_del_hdr(del_hdr);
if (result || ipv4->status || ipv6->status)
RNDIS_IPA_ERROR("ipa_del_hdr failed\n");
else
RNDIS_IPA_DEBUG("hdrs deletion done\n");
kfree(del_hdr);
return result;
}
static struct net_device_stats *rndis_ipa_get_stats(struct net_device *net)
{
return &net->stats;
}
/**
* rndis_ipa_register_properties() - set Tx/Rx properties needed
* by IPA configuration manager
* @netdev_name: a string with the name of the network interface device
*
* Register Tx/Rx properties to allow user space configuration (IPA
* Configuration Manager):
*
* - Two Tx properties (IPA->USB): specify the header names and pipe number
* that shall be used by user space for header-addition configuration
* for ipv4/ipv6 packets flowing from IPA to USB for HW bridging data.
* That header-addition header is added by the Netdev and used by user
* space to close the the HW bridge by adding filtering and routing rules
* that point to this header.
*
* - Two Rx properties (USB->IPA): these properties shall be used by user space
* to configure the IPA core to identify the packets destined
* for Apps-processor by configuring the unicast rules destined for
* the Netdev IP address.
* This rules shall be added based on the attribute mask supplied at
* this function, that is, always hit rule.
*/
static int rndis_ipa_register_properties(char *netdev_name)
{
struct ipa_tx_intf tx_properties = {0};
struct ipa_ioc_tx_intf_prop properties[2] = { {0}, {0} };
struct ipa_ioc_tx_intf_prop *ipv4_property;
struct ipa_ioc_tx_intf_prop *ipv6_property;
struct ipa_ioc_rx_intf_prop rx_ioc_properties[2] = { {0}, {0} };
struct ipa_rx_intf rx_properties = {0};
struct ipa_ioc_rx_intf_prop *rx_ipv4_property;
struct ipa_ioc_rx_intf_prop *rx_ipv6_property;
int result = 0;
RNDIS_IPA_LOG_ENTRY();
tx_properties.prop = properties;
ipv4_property = &tx_properties.prop[0];
ipv4_property->ip = IPA_IP_v4;
ipv4_property->dst_pipe = IPA_TO_USB_CLIENT;
strlcpy(ipv4_property->hdr_name, IPV4_HDR_NAME,
IPA_RESOURCE_NAME_MAX);
ipv4_property->hdr_l2_type = IPA_HDR_L2_ETHERNET_II;
ipv6_property = &tx_properties.prop[1];
ipv6_property->ip = IPA_IP_v6;
ipv6_property->dst_pipe = IPA_TO_USB_CLIENT;
strlcpy(ipv6_property->hdr_name, IPV6_HDR_NAME,
IPA_RESOURCE_NAME_MAX);
ipv6_property->hdr_l2_type = IPA_HDR_L2_ETHERNET_II;
tx_properties.num_props = 2;
rx_properties.prop = rx_ioc_properties;
rx_ipv4_property = &rx_properties.prop[0];
rx_ipv4_property->ip = IPA_IP_v4;
rx_ipv4_property->attrib.attrib_mask = 0;
rx_ipv4_property->src_pipe = IPA_CLIENT_USB_PROD;
rx_ipv4_property->hdr_l2_type = IPA_HDR_L2_ETHERNET_II;
rx_ipv6_property = &rx_properties.prop[1];
rx_ipv6_property->ip = IPA_IP_v6;
rx_ipv6_property->attrib.attrib_mask = 0;
rx_ipv6_property->src_pipe = IPA_CLIENT_USB_PROD;
rx_ipv6_property->hdr_l2_type = IPA_HDR_L2_ETHERNET_II;
rx_properties.num_props = 2;
result = ipa_register_intf("rndis0", &tx_properties, &rx_properties);
if (result)
RNDIS_IPA_ERROR("fail on Tx/Rx properties registration\n");
else
RNDIS_IPA_DEBUG("Tx/Rx properties registration done\n");
RNDIS_IPA_LOG_EXIT();
return result;
}
/**
* rndis_ipa_deregister_properties() - remove the 2 Tx and 2 Rx properties
* @netdev_name: a string with the name of the network interface device
*
* This function revert the work done on rndis_ipa_register_properties().
*/
static int rndis_ipa_deregister_properties(char *netdev_name)
{
int result;
RNDIS_IPA_LOG_ENTRY();
result = ipa_deregister_intf(netdev_name);
if (result) {
RNDIS_IPA_DEBUG("Fail on Tx prop deregister\n");
return result;
}
RNDIS_IPA_LOG_EXIT();
return 0;
}
/**
* rndis_ipa_create_rm_resource() -creates the resource representing
* this Netdev and supply notification callback for resource event
* such as Grant/Release
* @rndis_ipa_ctx: this driver context
*
* In order make sure all needed resources are available during packet
* transmit this Netdev shall use Request/Release mechanism of
* the IPA resource manager.
* This mechanism shall iterate over a dependency graph and make sure
* all dependent entities are ready to for packet Tx
* transfer (Apps->IPA->USB).
* In this function the resource representing the Netdev is created
* in addition to the basic dependency between the Netdev and the USB client.
* Hence, USB client, is a dependency for the Netdev and may be notified in
* case of packet transmit from this Netdev to tethered Host.
* As implied from the "may" in the above sentence there is a scenario where
* the USB is not notified. This is done thanks to the IPA resource manager
* inactivity timer.
* The inactivity timer allow the Release requests to be delayed in order
* prevent ping-pong with the USB and other dependencies.
*/
static int rndis_ipa_create_rm_resource(struct rndis_ipa_dev *rndis_ipa_ctx)
{
struct ipa_rm_create_params create_params = {0};
struct ipa_rm_perf_profile profile;
int result;
RNDIS_IPA_LOG_ENTRY();
create_params.name = DRV_RESOURCE_ID;
create_params.reg_params.user_data = rndis_ipa_ctx;
create_params.reg_params.notify_cb = rndis_ipa_rm_notify;
result = ipa_rm_create_resource(&create_params);
if (result) {
RNDIS_IPA_ERROR("Fail on ipa_rm_create_resource\n");
goto fail_rm_create;
}
RNDIS_IPA_DEBUG("RM client was created\n");
profile.max_supported_bandwidth_mbps = IPA_APPS_MAX_BW_IN_MBPS;
ipa_rm_set_perf_profile(DRV_RESOURCE_ID, &profile);
result = ipa_rm_inactivity_timer_init(DRV_RESOURCE_ID,
INACTIVITY_MSEC_DELAY);
if (result) {
RNDIS_IPA_ERROR("Fail on ipa_rm_inactivity_timer_init\n");
goto fail_inactivity_timer;
}
RNDIS_IPA_DEBUG("rm_it client was created\n");
result = ipa_rm_add_dependency_sync(DRV_RESOURCE_ID,
IPA_RM_RESOURCE_USB_CONS);
if (result && result != -EINPROGRESS)
RNDIS_IPA_ERROR("unable to add RNDIS/USB dependency (%d)\n",
result);
else
RNDIS_IPA_DEBUG("RNDIS/USB dependency was set\n");
result = ipa_rm_add_dependency_sync(IPA_RM_RESOURCE_USB_PROD,
IPA_RM_RESOURCE_APPS_CONS);
if (result && result != -EINPROGRESS)
RNDIS_IPA_ERROR("unable to add USB/APPS dependency (%d)\n",
result);
else
RNDIS_IPA_DEBUG("USB/APPS dependency was set\n");
RNDIS_IPA_LOG_EXIT();
return 0;
fail_inactivity_timer:
fail_rm_create:
return result;
}
/**
* rndis_ipa_destroy_rm_resource() - delete the dependency and destroy
* the resource done on rndis_ipa_create_rm_resource()
* @rndis_ipa_ctx: this driver context
*
* This function shall delete the dependency create between
* the Netdev to the USB.
* In addition the inactivity time shall be destroy and the resource shall
* be deleted.
*/
static int rndis_ipa_destory_rm_resource(struct rndis_ipa_dev *rndis_ipa_ctx)
{
int result;
RNDIS_IPA_LOG_ENTRY();
result = ipa_rm_delete_dependency(DRV_RESOURCE_ID,
IPA_RM_RESOURCE_USB_CONS);
if (result && result != -EINPROGRESS) {
RNDIS_IPA_ERROR("Fail to delete RNDIS/USB dependency\n");
goto bail;
}
RNDIS_IPA_DEBUG("RNDIS/USB dependency was successfully deleted\n");
result = ipa_rm_delete_dependency(IPA_RM_RESOURCE_USB_PROD,
IPA_RM_RESOURCE_APPS_CONS);
if (result == -EINPROGRESS) {
RNDIS_IPA_DEBUG("RM dependency deletion is in progress");
} else if (result) {
RNDIS_IPA_ERROR("Fail to delete USB/APPS dependency\n");
goto bail;
} else {
RNDIS_IPA_DEBUG("USB/APPS dependency was deleted\n");
}
result = ipa_rm_inactivity_timer_destroy(DRV_RESOURCE_ID);
if (result) {
RNDIS_IPA_ERROR("Fail to destroy inactivity timern");
goto bail;
}
RNDIS_IPA_DEBUG("RM inactivity timer was successfully destroy\n");
result = ipa_rm_delete_resource(DRV_RESOURCE_ID);
if (result) {
RNDIS_IPA_ERROR("resource deletion failed\n");
goto bail;
}
RNDIS_IPA_DEBUG("Netdev RM resource was deleted (resid:%d)\n",
DRV_RESOURCE_ID);
RNDIS_IPA_LOG_EXIT();
bail:
return result;
}
/**
* resource_request() - request for the Netdev resource
* @rndis_ipa_ctx: main driver context
*
* This function shall send the IPA resource manager inactivity time a request
* to Grant the Netdev producer.
* In case the resource is already Granted the function shall return immediately
* and "pet" the inactivity timer.
* In case the resource was not already Granted this function shall
* return EINPROGRESS and the Netdev shall stop the send queue until
* the IPA resource manager notify it that the resource is
* granted (done in a differ context)
*/
static int resource_request(struct rndis_ipa_dev *rndis_ipa_ctx)
{
int result = 0;
if (!rm_enabled(rndis_ipa_ctx))
goto out;
result = ipa_rm_inactivity_timer_request_resource(
DRV_RESOURCE_ID);
out:
return result;
}
/**
* resource_release() - release the Netdev resource
* @rndis_ipa_ctx: main driver context
*
* start the inactivity timer count down.by using the IPA resource
* manager inactivity time.
* The actual resource release shall occur only if no request shall be done
* during the INACTIVITY_MSEC_DELAY.
*/
static void resource_release(struct rndis_ipa_dev *rndis_ipa_ctx)
{
if (!rm_enabled(rndis_ipa_ctx))
goto out;
ipa_rm_inactivity_timer_release_resource(DRV_RESOURCE_ID);
out:
return;
}
/**
* rndis_encapsulate_skb() - encapsulate the given Ethernet skb with
* an RNDIS header
* @skb: packet to be encapsulated with the RNDIS header
*
* Shall use a template header for RNDIS and update it with the given
* skb values.
* Ethernet is expected to be already encapsulate the packet.
*/
static struct sk_buff *rndis_encapsulate_skb(struct sk_buff *skb)
{
struct rndis_pkt_hdr *rndis_hdr;
int payload_byte_len = skb->len;
/* if there is no room in this skb, allocate a new one */
if (unlikely(skb_headroom(skb) < sizeof(rndis_template_hdr))) {
struct sk_buff *new_skb = skb_copy_expand(skb,
sizeof(rndis_template_hdr), 0, GFP_ATOMIC);
if (!new_skb) {
RNDIS_IPA_ERROR("no memory for skb expand\n");
return skb;
}
RNDIS_IPA_DEBUG("skb expanded. old %p new %p\n", skb, new_skb);
dev_kfree_skb_any(skb);
skb = new_skb;
}
/* make room at the head of the SKB to put the RNDIS header */
rndis_hdr = (struct rndis_pkt_hdr *)skb_push(skb,
sizeof(rndis_template_hdr));
memcpy(rndis_hdr, &rndis_template_hdr, sizeof(*rndis_hdr));
rndis_hdr->msg_len += payload_byte_len;
rndis_hdr->data_len += payload_byte_len;
return skb;
}
/**
* rx_filter() - logic that decide if the current skb is to be filtered out
* @skb: skb that may be sent up to the network stack
*
* This function shall do Rx packet filtering on the Netdev level.
*/
static bool rx_filter(struct sk_buff *skb)
{
struct rndis_ipa_dev *rndis_ipa_ctx = netdev_priv(skb->dev);
return rndis_ipa_ctx->rx_filter;
}
/**
* tx_filter() - logic that decide if the current skb is to be filtered out
* @skb: skb that may be sent to the USB core
*
* This function shall do Tx packet filtering on the Netdev level.
* ICMP filter bypass is possible to allow only ICMP packet to be
* sent (pings and etc)
*/
static bool tx_filter(struct sk_buff *skb)
{
struct rndis_ipa_dev *rndis_ipa_ctx = netdev_priv(skb->dev);
bool is_icmp;
if (likely(rndis_ipa_ctx->tx_filter == false))
return false;
is_icmp = (skb->protocol == htons(ETH_P_IP) &&
ip_hdr(skb)->protocol == IPPROTO_ICMP);
if ((rndis_ipa_ctx->icmp_filter == false) && is_icmp)
return false;
return true;
}
/**
* rm_enabled() - allow the use of resource manager Request/Release to
* be bypassed
* @rndis_ipa_ctx: main driver context
*
* By disabling the resource manager flag the Request for the Netdev resource
* shall be bypassed and the packet shall be sent.
* accordingly, Release request shall be bypass as well.
*/
static bool rm_enabled(struct rndis_ipa_dev *rndis_ipa_ctx)
{
return rndis_ipa_ctx->rm_enable;
}
/**
* rndis_ipa_ep_registers_cfg() - configure the USB endpoints
* @usb_to_ipa_hdl: handle received from ipa_connect which represents
* the USB to IPA end-point
* @ipa_to_usb_hdl: handle received from ipa_connect which represents
* the IPA to USB end-point
* @max_xfer_size_bytes_to_dev: the maximum size, in bytes, that the device
* expects to receive from the host. supplied on REMOTE_NDIS_INITIALIZE_CMPLT.
* @max_xfer_size_bytes_to_host: the maximum size, in bytes, that the host
* expects to receive from the device. supplied on REMOTE_NDIS_INITIALIZE_MSG.
* @mtu: the netdev MTU size, in bytes
*
* USB to IPA pipe:
* - de-aggregation
* - Remove Ethernet header
* - Remove RNDIS header
* - SRC NAT
* - Default routing(0)
* IPA to USB Pipe:
* - aggregation
* - Add Ethernet header
* - Add RNDIS header
*/
static int rndis_ipa_ep_registers_cfg(u32 usb_to_ipa_hdl,
u32 ipa_to_usb_hdl,
u32 max_xfer_size_bytes_to_dev,
u32 max_xfer_size_bytes_to_host,
u32 mtu,
bool deaggr_enable)
{
int result;
struct ipa_ep_cfg *usb_to_ipa_ep_cfg;
if (deaggr_enable) {
usb_to_ipa_ep_cfg = &usb_to_ipa_ep_cfg_deaggr_en;
RNDIS_IPA_DEBUG("deaggregation enabled\n");
} else {
usb_to_ipa_ep_cfg = &usb_to_ipa_ep_cfg_deaggr_dis;
RNDIS_IPA_DEBUG("deaggregation disabled\n");
}
usb_to_ipa_ep_cfg->deaggr.max_packet_len = max_xfer_size_bytes_to_dev;
result = ipa_cfg_ep(usb_to_ipa_hdl, usb_to_ipa_ep_cfg);
if (result) {
pr_err("failed to configure USB to IPA point\n");
return result;
}
RNDIS_IPA_DEBUG("IPA<-USB end-point configured\n");
ipa_to_usb_ep_cfg.aggr.aggr_byte_limit =
(max_xfer_size_bytes_to_host - mtu)/1024;
if (ipa_to_usb_ep_cfg.aggr.aggr_byte_limit == 0) {
ipa_to_usb_ep_cfg.aggr.aggr_time_limit = 0;
ipa_to_usb_ep_cfg.aggr.aggr_pkt_limit = 1;
} else {
ipa_to_usb_ep_cfg.aggr.aggr_time_limit =
DEFAULT_AGGR_TIME_LIMIT;
ipa_to_usb_ep_cfg.aggr.aggr_pkt_limit =
DEFAULT_AGGR_PKT_LIMIT;
}
RNDIS_IPA_DEBUG("RNDIS aggregation param:"
" en=%d"
" byte_limit=%d"
" time_limit=%d"
" pkt_limit=%d\n",
ipa_to_usb_ep_cfg.aggr.aggr_en,
ipa_to_usb_ep_cfg.aggr.aggr_byte_limit,
ipa_to_usb_ep_cfg.aggr.aggr_time_limit,
ipa_to_usb_ep_cfg.aggr.aggr_pkt_limit);
result = ipa_cfg_ep(ipa_to_usb_hdl, &ipa_to_usb_ep_cfg);
if (result) {
pr_err("failed to configure IPA to USB end-point\n");
return result;
}
RNDIS_IPA_DEBUG("IPA->USB end-point configured\n");
return 0;
}
/**
* rndis_ipa_set_device_ethernet_addr() - set device Ethernet address
* @dev_ethaddr: device Ethernet address
*
* Returns 0 for success, negative otherwise
*/
static int rndis_ipa_set_device_ethernet_addr(u8 *dev_ethaddr,
u8 device_ethaddr[])
{
if (!is_valid_ether_addr(device_ethaddr))
return -EINVAL;
memcpy(dev_ethaddr, device_ethaddr, ETH_ALEN);
return 0;
}
/** rndis_ipa_next_state - return the next state of the driver
* @current_state: the current state of the driver
* @operation: an enum which represent the operation being made on the driver
* by its API.
*
* This function implements the driver internal state machine.
* Its decisions are based on the driver current state and the operation
* being made.
* In case the operation is invalid this state machine will return
* the value RNDIS_IPA_INVALID to inform the caller for a forbidden sequence.
*/
static enum rndis_ipa_state rndis_ipa_next_state(
enum rndis_ipa_state current_state,
enum rndis_ipa_operation operation)
{
int next_state = RNDIS_IPA_INVALID;
switch (current_state) {
case RNDIS_IPA_UNLOADED:
if (operation == RNDIS_IPA_INITIALIZE)
next_state = RNDIS_IPA_INITIALIZED;
break;
case RNDIS_IPA_INITIALIZED:
if (operation == RNDIS_IPA_CONNECT)
next_state = RNDIS_IPA_CONNECTED;
else if (operation == RNDIS_IPA_OPEN)
next_state = RNDIS_IPA_UP;
else if (operation == RNDIS_IPA_CLEANUP)
next_state = RNDIS_IPA_UNLOADED;
break;
case RNDIS_IPA_CONNECTED:
if (operation == RNDIS_IPA_DISCONNECT)
next_state = RNDIS_IPA_INITIALIZED;
else if (operation == RNDIS_IPA_OPEN)
next_state = RNDIS_IPA_CONNECTED_AND_UP;
break;
case RNDIS_IPA_UP:
if (operation == RNDIS_IPA_STOP)
next_state = RNDIS_IPA_INITIALIZED;
else if (operation == RNDIS_IPA_CONNECT)
next_state = RNDIS_IPA_CONNECTED_AND_UP;
else if (operation == RNDIS_IPA_CLEANUP)
next_state = RNDIS_IPA_UNLOADED;
break;
case RNDIS_IPA_CONNECTED_AND_UP:
if (operation == RNDIS_IPA_STOP)
next_state = RNDIS_IPA_CONNECTED;
else if (operation == RNDIS_IPA_DISCONNECT)
next_state = RNDIS_IPA_UP;
break;
default:
RNDIS_IPA_ERROR("State is not supported\n");
WARN_ON(true);
break;
}
RNDIS_IPA_DEBUG("state transition ( %s -> %s )- %s\n",
rndis_ipa_state_string(current_state),
rndis_ipa_state_string(next_state) ,
next_state == RNDIS_IPA_INVALID ?
"Forbidden" : "Allowed");
return next_state;
}
/**
* rndis_ipa_state_string - return the state string representation
* @state: enum which describe the state
*/
static const char *rndis_ipa_state_string(enum rndis_ipa_state state)
{
switch (state) {
case RNDIS_IPA_UNLOADED:
return "RNDIS_IPA_UNLOADED";
case RNDIS_IPA_INITIALIZED:
return "RNDIS_IPA_INITIALIZED";
case RNDIS_IPA_CONNECTED:
return "RNDIS_IPA_CONNECTED";
case RNDIS_IPA_UP:
return "RNDIS_IPA_UP";
case RNDIS_IPA_CONNECTED_AND_UP:
return "RNDIS_IPA_CONNECTED_AND_UP";
default:
return "Not supported";
}
}
static void rndis_ipa_dump_skb(struct sk_buff *skb)
{
int i;
u32 *cur = (u32 *)skb->data;
u8 *byte;
RNDIS_IPA_DEBUG("packet dump start for skb->len=%d\n",
skb->len);
for (i = 0; i < (skb->len/4); i++) {
byte = (u8 *)(cur + i);
pr_info("%2d %08x %02x %02x %02x %02x\n",
i, *(cur + i),
byte[0], byte[1], byte[2], byte[3]);
}
RNDIS_IPA_DEBUG("packet dump ended for skb->len=%d\n",
skb->len);
}
/**
* Creates the root folder for the driver
*/
static int rndis_ipa_debugfs_init(struct rndis_ipa_dev *rndis_ipa_ctx)
{
const mode_t flags_read_write = S_IRUGO | S_IWUGO;
const mode_t flags_read_only = S_IRUGO;
const mode_t flags_write_only = S_IWUGO;
struct dentry *file;
struct dentry *aggr_directory;
RNDIS_IPA_LOG_ENTRY();
if (!rndis_ipa_ctx)
return -EINVAL;
rndis_ipa_ctx->directory = debugfs_create_dir(DEBUGFS_DIR_NAME, NULL);
if (!rndis_ipa_ctx->directory) {
RNDIS_IPA_ERROR("could not create debugfs directory entry\n");
goto fail_directory;
}
file = debugfs_create_bool("tx_filter", flags_read_write,
rndis_ipa_ctx->directory, &rndis_ipa_ctx->tx_filter);
if (!file) {
RNDIS_IPA_ERROR("could not create debugfs tx_filter file\n");
goto fail_file;
}
file = debugfs_create_bool("rx_filter", flags_read_write,
rndis_ipa_ctx->directory, &rndis_ipa_ctx->rx_filter);
if (!file) {
RNDIS_IPA_ERROR("could not create debugfs rx_filter file\n");
goto fail_file;
}
file = debugfs_create_bool("icmp_filter", flags_read_write,
rndis_ipa_ctx->directory, &rndis_ipa_ctx->icmp_filter);
if (!file) {
RNDIS_IPA_ERROR("could not create debugfs icmp_filter file\n");
goto fail_file;
}
file = debugfs_create_bool("rm_enable", flags_read_write,
rndis_ipa_ctx->directory, &rndis_ipa_ctx->rm_enable);
if (!file) {
RNDIS_IPA_ERROR("could not create debugfs rm file\n");
goto fail_file;
}
file = debugfs_create_u32("outstanding_high", flags_read_write,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->outstanding_high);
if (!file) {
RNDIS_IPA_ERROR("could not create outstanding_high file\n");
goto fail_file;
}
file = debugfs_create_u32("outstanding_low", flags_read_write,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->outstanding_low);
if (!file) {
RNDIS_IPA_ERROR("could not create outstanding_low file\n");
goto fail_file;
}
file = debugfs_create_file("outstanding", flags_read_only,
rndis_ipa_ctx->directory,
rndis_ipa_ctx, &rndis_ipa_debugfs_atomic_ops);
if (!file) {
RNDIS_IPA_ERROR("could not create outstanding file\n");
goto fail_file;
}
file = debugfs_create_file("loopback_enable", flags_read_write,
rndis_ipa_ctx->directory,
rndis_ipa_ctx, &rndis_ipa_loopback_ops);
if (!file) {
RNDIS_IPA_ERROR("could not create outstanding file\n");
goto fail_file;
}
file = debugfs_create_u8("state", flags_read_only,
rndis_ipa_ctx->directory, (u8 *)&rndis_ipa_ctx->state);
if (!file) {
RNDIS_IPA_ERROR("could not create state file\n");
goto fail_file;
}
file = debugfs_create_u32("tx_dropped", flags_read_only,
rndis_ipa_ctx->directory, &rndis_ipa_ctx->tx_dropped);
if (!file) {
RNDIS_IPA_ERROR("could not create tx_dropped file\n");
goto fail_file;
}
file = debugfs_create_u32("rx_dropped", flags_read_only,
rndis_ipa_ctx->directory, &rndis_ipa_ctx->rx_dropped);
if (!file) {
RNDIS_IPA_ERROR("could not create rx_dropped file\n");
goto fail_file;
}
aggr_directory = debugfs_create_dir(DEBUGFS_AGGR_DIR_NAME,
rndis_ipa_ctx->directory);
if (!aggr_directory) {
RNDIS_IPA_ERROR("could not create debugfs aggr entry\n");
goto fail_directory;
}
file = debugfs_create_file("aggr_value_set", flags_write_only,
aggr_directory,
rndis_ipa_ctx, &rndis_ipa_aggr_ops);
if (!file) {
RNDIS_IPA_ERROR("could not create aggr_value_set file\n");
goto fail_file;
}
file = debugfs_create_u8("aggr_enable", flags_read_write,
aggr_directory, (u8 *)&ipa_to_usb_ep_cfg.aggr.aggr_en);
if (!file) {
RNDIS_IPA_ERROR("could not create aggr_enable file\n");
goto fail_file;
}
file = debugfs_create_u8("aggr_type", flags_read_write,
aggr_directory, (u8 *)&ipa_to_usb_ep_cfg.aggr.aggr);
if (!file) {
RNDIS_IPA_ERROR("could not create aggr_type file\n");
goto fail_file;
}
file = debugfs_create_u32("aggr_byte_limit", flags_read_write,
aggr_directory,
&ipa_to_usb_ep_cfg.aggr.aggr_byte_limit);
if (!file) {
RNDIS_IPA_ERROR("could not create aggr_byte_limit file\n");
goto fail_file;
}
file = debugfs_create_u32("aggr_time_limit", flags_read_write,
aggr_directory,
&ipa_to_usb_ep_cfg.aggr.aggr_time_limit);
if (!file) {
RNDIS_IPA_ERROR("could not create aggr_time_limit file\n");
goto fail_file;
}
file = debugfs_create_u32("aggr_pkt_limit", flags_read_write,
aggr_directory,
&ipa_to_usb_ep_cfg.aggr.aggr_pkt_limit);
if (!file) {
RNDIS_IPA_ERROR("could not create aggr_pkt_limit file\n");
goto fail_file;
}
file = debugfs_create_bool("tx_dump_enable", flags_read_write,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->tx_dump_enable);
if (!file) {
RNDIS_IPA_ERROR("fail to create tx_dump_enable file\n");
goto fail_file;
}
file = debugfs_create_bool("rx_dump_enable", flags_read_write,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->rx_dump_enable);
if (!file) {
RNDIS_IPA_ERROR("fail to create rx_dump_enable file\n");
goto fail_file;
}
file = debugfs_create_bool("deaggregation_enable", flags_read_write,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->deaggregation_enable);
if (!file) {
RNDIS_IPA_ERROR("fail to create deaggregation_enable file\n");
goto fail_file;
}
file = debugfs_create_u32("error_msec_sleep_time", flags_read_write,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->error_msec_sleep_time);
if (!file) {
RNDIS_IPA_ERROR("fail to create error_msec_sleep_time file\n");
goto fail_file;
}
file = debugfs_create_bool("during_xmit_error", flags_read_only,
rndis_ipa_ctx->directory,
&rndis_ipa_ctx->during_xmit_error);
if (!file) {
RNDIS_IPA_ERROR("fail to create during_xmit_error file\n");
goto fail_file;
}
RNDIS_IPA_LOG_EXIT();
return 0;
fail_file:
debugfs_remove_recursive(rndis_ipa_ctx->directory);
fail_directory:
return -EFAULT;
}
static void rndis_ipa_debugfs_destroy(struct rndis_ipa_dev *rndis_ipa_ctx)
{
debugfs_remove_recursive(rndis_ipa_ctx->directory);
}
static int rndis_ipa_debugfs_aggr_open(struct inode *inode,
struct file *file)
{
struct rndis_ipa_dev *rndis_ipa_ctx = inode->i_private;
file->private_data = rndis_ipa_ctx;
return 0;
}
static ssize_t rndis_ipa_debugfs_aggr_write(struct file *file,
const char __user *buf, size_t count, loff_t *ppos)
{
struct rndis_ipa_dev *rndis_ipa_ctx = file->private_data;
int result;
result = ipa_cfg_ep(rndis_ipa_ctx->usb_to_ipa_hdl, &ipa_to_usb_ep_cfg);
if (result) {
pr_err("failed to re-configure USB to IPA point\n");
return result;
}
pr_info("IPA<-USB end-point re-configured\n");
return count;
}
static int rndis_ipa_debugfs_loopback_open(struct inode *inode,
struct file *file)
{
struct rndis_ipa_dev *rndis_ipa_ctx = inode->i_private;
file->private_data = rndis_ipa_ctx;
return 0;
}
static ssize_t rndis_ipa_debugfs_loopback_read(struct file *file,
char __user *ubuf, size_t count, loff_t *ppos)
{
int cnt;
struct rndis_ipa_dev *rndis_ipa_ctx = file->private_data;
file->private_data = &rndis_ipa_ctx->loopback_enable;
cnt = rndis_ipa_debugfs_enable_read(file,
ubuf, count, ppos);
return cnt;
}
static ssize_t rndis_ipa_debugfs_loopback_write(struct file *file,
const char __user *buf, size_t count, loff_t *ppos)
{
int retval;
int cnt;
struct rndis_ipa_dev *rndis_ipa_ctx = file->private_data;
bool old_state = rndis_ipa_ctx->loopback_enable;
file->private_data = &rndis_ipa_ctx->loopback_enable;
cnt = rndis_ipa_debugfs_enable_write(file,
buf, count, ppos);
RNDIS_IPA_DEBUG("loopback_enable was set to:%d->%d\n",
old_state, rndis_ipa_ctx->loopback_enable);
if (old_state == rndis_ipa_ctx->loopback_enable) {
RNDIS_IPA_ERROR("NOP - same state\n");
return cnt;
}
retval = rndis_ipa_setup_loopback(
rndis_ipa_ctx->loopback_enable,
rndis_ipa_ctx);
if (retval)
rndis_ipa_ctx->loopback_enable = old_state;
return cnt;
}
static int rndis_ipa_debugfs_atomic_open(struct inode *inode, struct file *file)
{
struct rndis_ipa_dev *rndis_ipa_ctx = inode->i_private;
RNDIS_IPA_LOG_ENTRY();
file->private_data = &(rndis_ipa_ctx->outstanding_pkts);
RNDIS_IPA_LOG_EXIT();
return 0;
}
static ssize_t rndis_ipa_debugfs_atomic_read(struct file *file,
char __user *ubuf, size_t count, loff_t *ppos)
{
int nbytes;
u8 atomic_str[DEBUGFS_TEMP_BUF_SIZE] = {0};
atomic_t *atomic_var = file->private_data;
RNDIS_IPA_LOG_ENTRY();
nbytes = scnprintf(atomic_str, sizeof(atomic_str), "%d\n",
atomic_read(atomic_var));
RNDIS_IPA_LOG_EXIT();
return simple_read_from_buffer(ubuf, count, ppos, atomic_str, nbytes);
}
static ssize_t rndis_ipa_debugfs_enable_read(struct file *file,
char __user *ubuf, size_t count, loff_t *ppos)
{
int nbytes;
int size = 0;
int ret;
loff_t pos;
u8 enable_str[sizeof(char)*3] = {0};
bool *enable = file->private_data;
pos = *ppos;
nbytes = scnprintf(enable_str, sizeof(enable_str), "%d\n", *enable);
ret = simple_read_from_buffer(ubuf, count, ppos, enable_str, nbytes);
if (ret < 0) {
RNDIS_IPA_ERROR("simple_read_from_buffer problem\n");
return ret;
}
size += ret;
count -= nbytes;
*ppos = pos + size;
return size;
}
static ssize_t rndis_ipa_debugfs_enable_write(struct file *file,
const char __user *buf, size_t count, loff_t *ppos)
{
unsigned long missing;
char input;
bool *enable = file->private_data;
if (count != sizeof(input) + 1) {
RNDIS_IPA_ERROR("wrong input length(%zd)\n", count);
return -EINVAL;
}
if (!buf) {
RNDIS_IPA_ERROR("Bad argument\n");
return -EINVAL;
}
missing = copy_from_user(&input, buf, 1);
if (missing)
return -EFAULT;
RNDIS_IPA_DEBUG("input received %c\n", input);
*enable = input - '0';
RNDIS_IPA_DEBUG("value was set to %d\n", *enable);
return count;
}
/**
* Connects IPA->BAMDMA
* This shall simulate the path from IPA to USB
* Allowing the driver TX path
*/
static int rndis_ipa_loopback_pipe_create(
struct rndis_ipa_dev *rndis_ipa_ctx,
struct rndis_loopback_pipe *loopback_pipe)
{
int retval;
RNDIS_IPA_LOG_ENTRY();
/* SPS pipe has two side handshake
* This is the first handshake of IPA->BAMDMA,
* This is the IPA side
*/
loopback_pipe->ipa_connect_params.client = loopback_pipe->ipa_client;
loopback_pipe->ipa_connect_params.client_bam_hdl =
rndis_ipa_ctx->bam_dma_hdl;
loopback_pipe->ipa_connect_params.client_ep_idx =
loopback_pipe->peer_pipe_index;
loopback_pipe->ipa_connect_params.desc_fifo_sz = BAM_DMA_DESC_FIFO_SIZE;
loopback_pipe->ipa_connect_params.data_fifo_sz = BAM_DMA_DATA_FIFO_SIZE;
loopback_pipe->ipa_connect_params.notify = loopback_pipe->ipa_callback;
loopback_pipe->ipa_connect_params.priv = rndis_ipa_ctx;
loopback_pipe->ipa_connect_params.ipa_ep_cfg =
*(loopback_pipe->ipa_ep_cfg);
/* loopback_pipe->ipa_sps_connect is out param */
retval = ipa_connect(&loopback_pipe->ipa_connect_params,
&loopback_pipe->ipa_sps_connect,
&loopback_pipe->ipa_drv_ep_hdl);
if (retval) {
RNDIS_IPA_ERROR("ipa_connect() fail (%d)", retval);
return retval;
}
RNDIS_IPA_DEBUG("ipa_connect() succeeded, ipa_drv_ep_hdl=%d",
loopback_pipe->ipa_drv_ep_hdl);
/* SPS pipe has two side handshake
* This is the second handshake of IPA->BAMDMA,
* This is the BAMDMA side
*/
loopback_pipe->dma_sps = sps_alloc_endpoint();
if (!loopback_pipe->dma_sps) {
RNDIS_IPA_ERROR("sps_alloc_endpoint() failed ");
retval = -ENOMEM;
goto fail_sps_alloc;
}
retval = sps_get_config(loopback_pipe->dma_sps,
&loopback_pipe->dma_connect);
if (retval) {
RNDIS_IPA_ERROR("sps_get_config() failed (%d)", retval);
goto fail_get_cfg;
}
/* Start setting the non IPA ep for SPS driver*/
loopback_pipe->dma_connect.mode = loopback_pipe->mode;
/* SPS_MODE_DEST: DMA end point is the dest (consumer) IPA->DMA */
if (loopback_pipe->mode == SPS_MODE_DEST) {
loopback_pipe->dma_connect.source =
loopback_pipe->ipa_sps_connect.ipa_bam_hdl;
loopback_pipe->dma_connect.src_pipe_index =
loopback_pipe->ipa_sps_connect.ipa_ep_idx;
loopback_pipe->dma_connect.destination =
rndis_ipa_ctx->bam_dma_hdl;
loopback_pipe->dma_connect.dest_pipe_index =
loopback_pipe->peer_pipe_index;
/* SPS_MODE_SRC: DMA end point is the source (producer) DMA->IPA */
} else {
loopback_pipe->dma_connect.source =
rndis_ipa_ctx->bam_dma_hdl;
loopback_pipe->dma_connect.src_pipe_index =
loopback_pipe->peer_pipe_index;
loopback_pipe->dma_connect.destination =
loopback_pipe->ipa_sps_connect.ipa_bam_hdl;
loopback_pipe->dma_connect.dest_pipe_index =
loopback_pipe->ipa_sps_connect.ipa_ep_idx;
}
loopback_pipe->dma_connect.desc = loopback_pipe->ipa_sps_connect.desc;
loopback_pipe->dma_connect.data = loopback_pipe->ipa_sps_connect.data;
loopback_pipe->dma_connect.event_thresh = 0x10;
/* BAM-to-BAM */
loopback_pipe->dma_connect.options = SPS_O_AUTO_ENABLE;
RNDIS_IPA_DEBUG("doing sps_connect() with - ");
RNDIS_IPA_DEBUG("src bam_hdl:0x%lx, src_pipe#:%d",
loopback_pipe->dma_connect.source,
loopback_pipe->dma_connect.src_pipe_index);
RNDIS_IPA_DEBUG("dst bam_hdl:0x%lx, dst_pipe#:%d",
loopback_pipe->dma_connect.destination,
loopback_pipe->dma_connect.dest_pipe_index);
retval = sps_connect(loopback_pipe->dma_sps,
&loopback_pipe->dma_connect);
if (retval) {
RNDIS_IPA_ERROR("sps_connect() fail for BAMDMA side (%d)",
retval);
goto fail_sps_connect;
}
RNDIS_IPA_LOG_EXIT();
return 0;
fail_sps_connect:
fail_get_cfg:
sps_free_endpoint(loopback_pipe->dma_sps);
fail_sps_alloc:
ipa_disconnect(loopback_pipe->ipa_drv_ep_hdl);
return retval;
}
static void rndis_ipa_destroy_loopback_pipe(
struct rndis_loopback_pipe *loopback_pipe)
{
sps_disconnect(loopback_pipe->dma_sps);
sps_free_endpoint(loopback_pipe->dma_sps);
}
/**
* rndis_ipa_create_loopback() - create a BAM-DMA loopback
* in order to replace the USB core
*/
static int rndis_ipa_create_loopback(struct rndis_ipa_dev *rndis_ipa_ctx)
{
/* The BAM handle should be use as
* source/destination in the sps_connect()
*/
int retval;
RNDIS_IPA_LOG_ENTRY();
retval = sps_ctrl_bam_dma_clk(true);
if (retval) {
RNDIS_IPA_ERROR("fail on enabling BAM-DMA clocks");
return -ENODEV;
}
/* Get BAM handle instead of USB handle */
rndis_ipa_ctx->bam_dma_hdl = sps_dma_get_bam_handle();
if (!rndis_ipa_ctx->bam_dma_hdl) {
RNDIS_IPA_ERROR("sps_dma_get_bam_handle() failed");
return -ENODEV;
}
RNDIS_IPA_DEBUG("sps_dma_get_bam_handle() succeeded (0x%x)",
rndis_ipa_ctx->bam_dma_hdl);
/* IPA<-BAMDMA, NetDev Rx path (BAMDMA is the USB stub) */
rndis_ipa_ctx->usb_to_ipa_loopback_pipe.ipa_client =
IPA_CLIENT_USB_PROD;
rndis_ipa_ctx->usb_to_ipa_loopback_pipe.peer_pipe_index =
FROM_USB_TO_IPA_BAMDMA;
/*DMA EP mode*/
rndis_ipa_ctx->usb_to_ipa_loopback_pipe.mode = SPS_MODE_SRC;
rndis_ipa_ctx->usb_to_ipa_loopback_pipe.ipa_ep_cfg =
&usb_to_ipa_ep_cfg_deaggr_en;
rndis_ipa_ctx->usb_to_ipa_loopback_pipe.ipa_callback =
rndis_ipa_packet_receive_notify;
RNDIS_IPA_DEBUG("setting up IPA<-BAMDAM pipe (RNDIS_IPA RX path)");
retval = rndis_ipa_loopback_pipe_create(rndis_ipa_ctx,
&rndis_ipa_ctx->usb_to_ipa_loopback_pipe);
if (retval) {
RNDIS_IPA_ERROR("fail to close IPA->BAMDAM pipe");
goto fail_to_usb;
}
RNDIS_IPA_DEBUG("IPA->BAMDAM pipe successfully connected (TX path)");
/* IPA->BAMDMA, NetDev Tx path (BAMDMA is the USB stub)*/
rndis_ipa_ctx->ipa_to_usb_loopback_pipe.ipa_client =
IPA_CLIENT_USB_CONS;
/*DMA EP mode*/
rndis_ipa_ctx->ipa_to_usb_loopback_pipe.mode = SPS_MODE_DEST;
rndis_ipa_ctx->ipa_to_usb_loopback_pipe.ipa_ep_cfg = &ipa_to_usb_ep_cfg;
rndis_ipa_ctx->ipa_to_usb_loopback_pipe.peer_pipe_index =
FROM_IPA_TO_USB_BAMDMA;
rndis_ipa_ctx->ipa_to_usb_loopback_pipe.ipa_callback =
rndis_ipa_tx_complete_notify;
RNDIS_IPA_DEBUG("setting up IPA->BAMDAM pipe (RNDIS_IPA TX path)");
retval = rndis_ipa_loopback_pipe_create(rndis_ipa_ctx,
&rndis_ipa_ctx->ipa_to_usb_loopback_pipe);
if (retval) {
RNDIS_IPA_ERROR("fail to close IPA<-BAMDAM pipe");
goto fail_from_usb;
}
RNDIS_IPA_DEBUG("IPA<-BAMDAM pipe successfully connected(RX path)");
RNDIS_IPA_LOG_EXIT();
return 0;
fail_from_usb:
rndis_ipa_destroy_loopback_pipe(
&rndis_ipa_ctx->usb_to_ipa_loopback_pipe);
fail_to_usb:
return retval;
}
static void rndis_ipa_destroy_loopback(struct rndis_ipa_dev *rndis_ipa_ctx)
{
rndis_ipa_destroy_loopback_pipe(
&rndis_ipa_ctx->ipa_to_usb_loopback_pipe);
rndis_ipa_destroy_loopback_pipe(
&rndis_ipa_ctx->usb_to_ipa_loopback_pipe);
sps_dma_free_bam_handle(rndis_ipa_ctx->bam_dma_hdl);
if (sps_ctrl_bam_dma_clk(false))
RNDIS_IPA_ERROR("fail to disable BAM-DMA clocks");
}
/**
* rndis_ipa_setup_loopback() - create/destroy a loopback on IPA HW
* (as USB pipes loopback) and notify RNDIS_IPA netdev for pipe connected
* @enable: flag that determines if the loopback should be created or destroyed
* @rndis_ipa_ctx: driver main context
*
* This function is the main loopback logic.
* It shall create/destory the loopback by using BAM-DMA and notify
* the netdev accordingly.
*/
static int rndis_ipa_setup_loopback(bool enable,
struct rndis_ipa_dev *rndis_ipa_ctx)
{
int retval;
if (!enable) {
rndis_ipa_destroy_loopback(rndis_ipa_ctx);
RNDIS_IPA_DEBUG("loopback destroy done");
retval = rndis_ipa_pipe_disconnect_notify(rndis_ipa_ctx);
if (retval) {
RNDIS_IPA_ERROR("connect notify fail");
return -ENODEV;
}
return 0;
}
RNDIS_IPA_DEBUG("creating loopback (instead of USB core)");
retval = rndis_ipa_create_loopback(rndis_ipa_ctx);
RNDIS_IPA_DEBUG("creating loopback- %s", (retval ? "FAIL" : "OK"));
if (retval) {
RNDIS_IPA_ERROR("Fail to connect loopback");
return -ENODEV;
}
retval = rndis_ipa_pipe_connect_notify(
rndis_ipa_ctx->usb_to_ipa_loopback_pipe.ipa_drv_ep_hdl,
rndis_ipa_ctx->ipa_to_usb_loopback_pipe.ipa_drv_ep_hdl,
BAM_DMA_DATA_FIFO_SIZE,
15,
BAM_DMA_DATA_FIFO_SIZE - rndis_ipa_ctx->net->mtu,
rndis_ipa_ctx);
if (retval) {
RNDIS_IPA_ERROR("connect notify fail");
return -ENODEV;
}
return 0;
}
static int rndis_ipa_init_module(void)
{
pr_info("RNDIS_IPA module is loaded.");
return 0;
}
static void rndis_ipa_cleanup_module(void)
{
pr_info("RNDIS_IPA module is unloaded.");
return;
}
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("RNDIS_IPA network interface");
late_initcall(rndis_ipa_init_module);
module_exit(rndis_ipa_cleanup_module);
| gpl-2.0 |
hellsgod/hells-Core-N5 | arch/s390/mm/pgtable.c | 42 | 23173 | /*
* Copyright IBM Corp. 2007,2011
* Author(s): Martin Schwidefsky <schwidefsky@de.ibm.com>
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/smp.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/quicklist.h>
#include <linux/rcupdate.h>
#include <linux/slab.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/mmu_context.h>
#ifndef CONFIG_64BIT
#define ALLOC_ORDER 1
#define FRAG_MASK 0x0f
#else
#define ALLOC_ORDER 2
#define FRAG_MASK 0x03
#endif
unsigned long *crst_table_alloc(struct mm_struct *mm)
{
struct page *page = alloc_pages(GFP_KERNEL, ALLOC_ORDER);
if (!page)
return NULL;
return (unsigned long *) page_to_phys(page);
}
void crst_table_free(struct mm_struct *mm, unsigned long *table)
{
free_pages((unsigned long) table, ALLOC_ORDER);
}
#ifdef CONFIG_64BIT
int crst_table_upgrade(struct mm_struct *mm, unsigned long limit)
{
unsigned long *table, *pgd;
unsigned long entry;
BUG_ON(limit > (1UL << 53));
repeat:
table = crst_table_alloc(mm);
if (!table)
return -ENOMEM;
spin_lock_bh(&mm->page_table_lock);
if (mm->context.asce_limit < limit) {
pgd = (unsigned long *) mm->pgd;
if (mm->context.asce_limit <= (1UL << 31)) {
entry = _REGION3_ENTRY_EMPTY;
mm->context.asce_limit = 1UL << 42;
mm->context.asce_bits = _ASCE_TABLE_LENGTH |
_ASCE_USER_BITS |
_ASCE_TYPE_REGION3;
} else {
entry = _REGION2_ENTRY_EMPTY;
mm->context.asce_limit = 1UL << 53;
mm->context.asce_bits = _ASCE_TABLE_LENGTH |
_ASCE_USER_BITS |
_ASCE_TYPE_REGION2;
}
crst_table_init(table, entry);
pgd_populate(mm, (pgd_t *) table, (pud_t *) pgd);
mm->pgd = (pgd_t *) table;
mm->task_size = mm->context.asce_limit;
table = NULL;
}
spin_unlock_bh(&mm->page_table_lock);
if (table)
crst_table_free(mm, table);
if (mm->context.asce_limit < limit)
goto repeat;
update_mm(mm, current);
return 0;
}
void crst_table_downgrade(struct mm_struct *mm, unsigned long limit)
{
pgd_t *pgd;
if (mm->context.asce_limit <= limit)
return;
__tlb_flush_mm(mm);
while (mm->context.asce_limit > limit) {
pgd = mm->pgd;
switch (pgd_val(*pgd) & _REGION_ENTRY_TYPE_MASK) {
case _REGION_ENTRY_TYPE_R2:
mm->context.asce_limit = 1UL << 42;
mm->context.asce_bits = _ASCE_TABLE_LENGTH |
_ASCE_USER_BITS |
_ASCE_TYPE_REGION3;
break;
case _REGION_ENTRY_TYPE_R3:
mm->context.asce_limit = 1UL << 31;
mm->context.asce_bits = _ASCE_TABLE_LENGTH |
_ASCE_USER_BITS |
_ASCE_TYPE_SEGMENT;
break;
default:
BUG();
}
mm->pgd = (pgd_t *) (pgd_val(*pgd) & _REGION_ENTRY_ORIGIN);
mm->task_size = mm->context.asce_limit;
crst_table_free(mm, (unsigned long *) pgd);
}
update_mm(mm, current);
}
#endif
#ifdef CONFIG_PGSTE
/**
* gmap_alloc - allocate a guest address space
* @mm: pointer to the parent mm_struct
*
* Returns a guest address space structure.
*/
struct gmap *gmap_alloc(struct mm_struct *mm)
{
struct gmap *gmap;
struct page *page;
unsigned long *table;
gmap = kzalloc(sizeof(struct gmap), GFP_KERNEL);
if (!gmap)
goto out;
INIT_LIST_HEAD(&gmap->crst_list);
gmap->mm = mm;
page = alloc_pages(GFP_KERNEL, ALLOC_ORDER);
if (!page)
goto out_free;
list_add(&page->lru, &gmap->crst_list);
table = (unsigned long *) page_to_phys(page);
crst_table_init(table, _REGION1_ENTRY_EMPTY);
gmap->table = table;
gmap->asce = _ASCE_TYPE_REGION1 | _ASCE_TABLE_LENGTH |
_ASCE_USER_BITS | __pa(table);
list_add(&gmap->list, &mm->context.gmap_list);
return gmap;
out_free:
kfree(gmap);
out:
return NULL;
}
EXPORT_SYMBOL_GPL(gmap_alloc);
static int gmap_unlink_segment(struct gmap *gmap, unsigned long *table)
{
struct gmap_pgtable *mp;
struct gmap_rmap *rmap;
struct page *page;
if (*table & _SEGMENT_ENTRY_INV)
return 0;
page = pfn_to_page(*table >> PAGE_SHIFT);
mp = (struct gmap_pgtable *) page->index;
list_for_each_entry(rmap, &mp->mapper, list) {
if (rmap->entry != table)
continue;
list_del(&rmap->list);
kfree(rmap);
break;
}
*table = _SEGMENT_ENTRY_INV | _SEGMENT_ENTRY_RO | mp->vmaddr;
return 1;
}
static void gmap_flush_tlb(struct gmap *gmap)
{
if (MACHINE_HAS_IDTE)
__tlb_flush_idte((unsigned long) gmap->table |
_ASCE_TYPE_REGION1);
else
__tlb_flush_global();
}
/**
* gmap_free - free a guest address space
* @gmap: pointer to the guest address space structure
*/
void gmap_free(struct gmap *gmap)
{
struct page *page, *next;
unsigned long *table;
int i;
/* Flush tlb. */
if (MACHINE_HAS_IDTE)
__tlb_flush_idte((unsigned long) gmap->table |
_ASCE_TYPE_REGION1);
else
__tlb_flush_global();
/* Free all segment & region tables. */
down_read(&gmap->mm->mmap_sem);
spin_lock(&gmap->mm->page_table_lock);
list_for_each_entry_safe(page, next, &gmap->crst_list, lru) {
table = (unsigned long *) page_to_phys(page);
if ((*table & _REGION_ENTRY_TYPE_MASK) == 0)
/* Remove gmap rmap structures for segment table. */
for (i = 0; i < PTRS_PER_PMD; i++, table++)
gmap_unlink_segment(gmap, table);
__free_pages(page, ALLOC_ORDER);
}
spin_unlock(&gmap->mm->page_table_lock);
up_read(&gmap->mm->mmap_sem);
list_del(&gmap->list);
kfree(gmap);
}
EXPORT_SYMBOL_GPL(gmap_free);
/**
* gmap_enable - switch primary space to the guest address space
* @gmap: pointer to the guest address space structure
*/
void gmap_enable(struct gmap *gmap)
{
S390_lowcore.gmap = (unsigned long) gmap;
}
EXPORT_SYMBOL_GPL(gmap_enable);
/**
* gmap_disable - switch back to the standard primary address space
* @gmap: pointer to the guest address space structure
*/
void gmap_disable(struct gmap *gmap)
{
S390_lowcore.gmap = 0UL;
}
EXPORT_SYMBOL_GPL(gmap_disable);
/*
* gmap_alloc_table is assumed to be called with mmap_sem held
*/
static int gmap_alloc_table(struct gmap *gmap,
unsigned long *table, unsigned long init)
{
struct page *page;
unsigned long *new;
/* since we dont free the gmap table until gmap_free we can unlock */
spin_unlock(&gmap->mm->page_table_lock);
page = alloc_pages(GFP_KERNEL, ALLOC_ORDER);
spin_lock(&gmap->mm->page_table_lock);
if (!page)
return -ENOMEM;
new = (unsigned long *) page_to_phys(page);
crst_table_init(new, init);
if (*table & _REGION_ENTRY_INV) {
list_add(&page->lru, &gmap->crst_list);
*table = (unsigned long) new | _REGION_ENTRY_LENGTH |
(*table & _REGION_ENTRY_TYPE_MASK);
} else
__free_pages(page, ALLOC_ORDER);
return 0;
}
/**
* gmap_unmap_segment - unmap segment from the guest address space
* @gmap: pointer to the guest address space structure
* @addr: address in the guest address space
* @len: length of the memory area to unmap
*
* Returns 0 if the unmap succeded, -EINVAL if not.
*/
int gmap_unmap_segment(struct gmap *gmap, unsigned long to, unsigned long len)
{
unsigned long *table;
unsigned long off;
int flush;
if ((to | len) & (PMD_SIZE - 1))
return -EINVAL;
if (len == 0 || to + len < to)
return -EINVAL;
flush = 0;
down_read(&gmap->mm->mmap_sem);
spin_lock(&gmap->mm->page_table_lock);
for (off = 0; off < len; off += PMD_SIZE) {
/* Walk the guest addr space page table */
table = gmap->table + (((to + off) >> 53) & 0x7ff);
if (*table & _REGION_ENTRY_INV)
goto out;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + (((to + off) >> 42) & 0x7ff);
if (*table & _REGION_ENTRY_INV)
goto out;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + (((to + off) >> 31) & 0x7ff);
if (*table & _REGION_ENTRY_INV)
goto out;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + (((to + off) >> 20) & 0x7ff);
/* Clear segment table entry in guest address space. */
flush |= gmap_unlink_segment(gmap, table);
*table = _SEGMENT_ENTRY_INV;
}
out:
spin_unlock(&gmap->mm->page_table_lock);
up_read(&gmap->mm->mmap_sem);
if (flush)
gmap_flush_tlb(gmap);
return 0;
}
EXPORT_SYMBOL_GPL(gmap_unmap_segment);
/**
* gmap_mmap_segment - map a segment to the guest address space
* @gmap: pointer to the guest address space structure
* @from: source address in the parent address space
* @to: target address in the guest address space
*
* Returns 0 if the mmap succeded, -EINVAL or -ENOMEM if not.
*/
int gmap_map_segment(struct gmap *gmap, unsigned long from,
unsigned long to, unsigned long len)
{
unsigned long *table;
unsigned long off;
int flush;
if ((from | to | len) & (PMD_SIZE - 1))
return -EINVAL;
if (len == 0 || from + len > PGDIR_SIZE ||
from + len < from || to + len < to)
return -EINVAL;
flush = 0;
down_read(&gmap->mm->mmap_sem);
spin_lock(&gmap->mm->page_table_lock);
for (off = 0; off < len; off += PMD_SIZE) {
/* Walk the gmap address space page table */
table = gmap->table + (((to + off) >> 53) & 0x7ff);
if ((*table & _REGION_ENTRY_INV) &&
gmap_alloc_table(gmap, table, _REGION2_ENTRY_EMPTY))
goto out_unmap;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + (((to + off) >> 42) & 0x7ff);
if ((*table & _REGION_ENTRY_INV) &&
gmap_alloc_table(gmap, table, _REGION3_ENTRY_EMPTY))
goto out_unmap;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + (((to + off) >> 31) & 0x7ff);
if ((*table & _REGION_ENTRY_INV) &&
gmap_alloc_table(gmap, table, _SEGMENT_ENTRY_EMPTY))
goto out_unmap;
table = (unsigned long *) (*table & _REGION_ENTRY_ORIGIN);
table = table + (((to + off) >> 20) & 0x7ff);
/* Store 'from' address in an invalid segment table entry. */
flush |= gmap_unlink_segment(gmap, table);
*table = _SEGMENT_ENTRY_INV | _SEGMENT_ENTRY_RO | (from + off);
}
spin_unlock(&gmap->mm->page_table_lock);
up_read(&gmap->mm->mmap_sem);
if (flush)
gmap_flush_tlb(gmap);
return 0;
out_unmap:
spin_unlock(&gmap->mm->page_table_lock);
up_read(&gmap->mm->mmap_sem);
gmap_unmap_segment(gmap, to, len);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(gmap_map_segment);
/*
* this function is assumed to be called with mmap_sem held
*/
unsigned long __gmap_fault(unsigned long address, struct gmap *gmap)
{
unsigned long *table, vmaddr, segment;
struct mm_struct *mm;
struct gmap_pgtable *mp;
struct gmap_rmap *rmap;
struct vm_area_struct *vma;
struct page *page;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
current->thread.gmap_addr = address;
mm = gmap->mm;
/* Walk the gmap address space page table */
table = gmap->table + ((address >> 53) & 0x7ff);
if (unlikely(*table & _REGION_ENTRY_INV))
return -EFAULT;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + ((address >> 42) & 0x7ff);
if (unlikely(*table & _REGION_ENTRY_INV))
return -EFAULT;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + ((address >> 31) & 0x7ff);
if (unlikely(*table & _REGION_ENTRY_INV))
return -EFAULT;
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + ((address >> 20) & 0x7ff);
/* Convert the gmap address to an mm address. */
segment = *table;
if (likely(!(segment & _SEGMENT_ENTRY_INV))) {
page = pfn_to_page(segment >> PAGE_SHIFT);
mp = (struct gmap_pgtable *) page->index;
return mp->vmaddr | (address & ~PMD_MASK);
} else if (segment & _SEGMENT_ENTRY_RO) {
vmaddr = segment & _SEGMENT_ENTRY_ORIGIN;
vma = find_vma(mm, vmaddr);
if (!vma || vma->vm_start > vmaddr)
return -EFAULT;
/* Walk the parent mm page table */
pgd = pgd_offset(mm, vmaddr);
pud = pud_alloc(mm, pgd, vmaddr);
if (!pud)
return -ENOMEM;
pmd = pmd_alloc(mm, pud, vmaddr);
if (!pmd)
return -ENOMEM;
if (!pmd_present(*pmd) &&
__pte_alloc(mm, vma, pmd, vmaddr))
return -ENOMEM;
/* pmd now points to a valid segment table entry. */
rmap = kmalloc(sizeof(*rmap), GFP_KERNEL|__GFP_REPEAT);
if (!rmap)
return -ENOMEM;
/* Link gmap segment table entry location to page table. */
page = pmd_page(*pmd);
mp = (struct gmap_pgtable *) page->index;
rmap->entry = table;
spin_lock(&mm->page_table_lock);
list_add(&rmap->list, &mp->mapper);
spin_unlock(&mm->page_table_lock);
/* Set gmap segment table entry to page table. */
*table = pmd_val(*pmd) & PAGE_MASK;
return vmaddr | (address & ~PMD_MASK);
}
return -EFAULT;
}
unsigned long gmap_fault(unsigned long address, struct gmap *gmap)
{
unsigned long rc;
down_read(&gmap->mm->mmap_sem);
rc = __gmap_fault(address, gmap);
up_read(&gmap->mm->mmap_sem);
return rc;
}
EXPORT_SYMBOL_GPL(gmap_fault);
void gmap_discard(unsigned long from, unsigned long to, struct gmap *gmap)
{
unsigned long *table, address, size;
struct vm_area_struct *vma;
struct gmap_pgtable *mp;
struct page *page;
down_read(&gmap->mm->mmap_sem);
address = from;
while (address < to) {
/* Walk the gmap address space page table */
table = gmap->table + ((address >> 53) & 0x7ff);
if (unlikely(*table & _REGION_ENTRY_INV)) {
address = (address + PMD_SIZE) & PMD_MASK;
continue;
}
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + ((address >> 42) & 0x7ff);
if (unlikely(*table & _REGION_ENTRY_INV)) {
address = (address + PMD_SIZE) & PMD_MASK;
continue;
}
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + ((address >> 31) & 0x7ff);
if (unlikely(*table & _REGION_ENTRY_INV)) {
address = (address + PMD_SIZE) & PMD_MASK;
continue;
}
table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
table = table + ((address >> 20) & 0x7ff);
if (unlikely(*table & _SEGMENT_ENTRY_INV)) {
address = (address + PMD_SIZE) & PMD_MASK;
continue;
}
page = pfn_to_page(*table >> PAGE_SHIFT);
mp = (struct gmap_pgtable *) page->index;
vma = find_vma(gmap->mm, mp->vmaddr);
size = min(to - address, PMD_SIZE - (address & ~PMD_MASK));
zap_page_range(vma, mp->vmaddr | (address & ~PMD_MASK),
size, NULL);
address = (address + PMD_SIZE) & PMD_MASK;
}
up_read(&gmap->mm->mmap_sem);
}
EXPORT_SYMBOL_GPL(gmap_discard);
void gmap_unmap_notifier(struct mm_struct *mm, unsigned long *table)
{
struct gmap_rmap *rmap, *next;
struct gmap_pgtable *mp;
struct page *page;
int flush;
flush = 0;
spin_lock(&mm->page_table_lock);
page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
mp = (struct gmap_pgtable *) page->index;
list_for_each_entry_safe(rmap, next, &mp->mapper, list) {
*rmap->entry =
_SEGMENT_ENTRY_INV | _SEGMENT_ENTRY_RO | mp->vmaddr;
list_del(&rmap->list);
kfree(rmap);
flush = 1;
}
spin_unlock(&mm->page_table_lock);
if (flush)
__tlb_flush_global();
}
static inline unsigned long *page_table_alloc_pgste(struct mm_struct *mm,
unsigned long vmaddr)
{
struct page *page;
unsigned long *table;
struct gmap_pgtable *mp;
page = alloc_page(GFP_KERNEL|__GFP_REPEAT);
if (!page)
return NULL;
mp = kmalloc(sizeof(*mp), GFP_KERNEL|__GFP_REPEAT);
if (!mp) {
__free_page(page);
return NULL;
}
pgtable_page_ctor(page);
mp->vmaddr = vmaddr & PMD_MASK;
INIT_LIST_HEAD(&mp->mapper);
page->index = (unsigned long) mp;
atomic_set(&page->_mapcount, 3);
table = (unsigned long *) page_to_phys(page);
clear_table(table, _PAGE_TYPE_EMPTY, PAGE_SIZE/2);
clear_table(table + PTRS_PER_PTE, 0, PAGE_SIZE/2);
return table;
}
static inline void page_table_free_pgste(unsigned long *table)
{
struct page *page;
struct gmap_pgtable *mp;
page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
mp = (struct gmap_pgtable *) page->index;
BUG_ON(!list_empty(&mp->mapper));
pgtable_page_dtor(page);
atomic_set(&page->_mapcount, -1);
kfree(mp);
__free_page(page);
}
#else /* CONFIG_PGSTE */
static inline unsigned long *page_table_alloc_pgste(struct mm_struct *mm,
unsigned long vmaddr)
{
return NULL;
}
static inline void page_table_free_pgste(unsigned long *table)
{
}
static inline void gmap_unmap_notifier(struct mm_struct *mm,
unsigned long *table)
{
}
#endif /* CONFIG_PGSTE */
static inline unsigned int atomic_xor_bits(atomic_t *v, unsigned int bits)
{
unsigned int old, new;
do {
old = atomic_read(v);
new = old ^ bits;
} while (atomic_cmpxchg(v, old, new) != old);
return new;
}
/*
* page table entry allocation/free routines.
*/
unsigned long *page_table_alloc(struct mm_struct *mm, unsigned long vmaddr)
{
struct page *page;
unsigned long *table;
unsigned int mask, bit;
if (mm_has_pgste(mm))
return page_table_alloc_pgste(mm, vmaddr);
/* Allocate fragments of a 4K page as 1K/2K page table */
spin_lock_bh(&mm->context.list_lock);
mask = FRAG_MASK;
if (!list_empty(&mm->context.pgtable_list)) {
page = list_first_entry(&mm->context.pgtable_list,
struct page, lru);
table = (unsigned long *) page_to_phys(page);
mask = atomic_read(&page->_mapcount);
mask = mask | (mask >> 4);
}
if ((mask & FRAG_MASK) == FRAG_MASK) {
spin_unlock_bh(&mm->context.list_lock);
page = alloc_page(GFP_KERNEL|__GFP_REPEAT);
if (!page)
return NULL;
pgtable_page_ctor(page);
atomic_set(&page->_mapcount, 1);
table = (unsigned long *) page_to_phys(page);
clear_table(table, _PAGE_TYPE_EMPTY, PAGE_SIZE);
spin_lock_bh(&mm->context.list_lock);
list_add(&page->lru, &mm->context.pgtable_list);
} else {
for (bit = 1; mask & bit; bit <<= 1)
table += PTRS_PER_PTE;
mask = atomic_xor_bits(&page->_mapcount, bit);
if ((mask & FRAG_MASK) == FRAG_MASK)
list_del(&page->lru);
}
spin_unlock_bh(&mm->context.list_lock);
return table;
}
void page_table_free(struct mm_struct *mm, unsigned long *table)
{
struct page *page;
unsigned int bit, mask;
if (mm_has_pgste(mm)) {
gmap_unmap_notifier(mm, table);
return page_table_free_pgste(table);
}
/* Free 1K/2K page table fragment of a 4K page */
page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
bit = 1 << ((__pa(table) & ~PAGE_MASK)/(PTRS_PER_PTE*sizeof(pte_t)));
spin_lock_bh(&mm->context.list_lock);
if ((atomic_read(&page->_mapcount) & FRAG_MASK) != FRAG_MASK)
list_del(&page->lru);
mask = atomic_xor_bits(&page->_mapcount, bit);
if (mask & FRAG_MASK)
list_add(&page->lru, &mm->context.pgtable_list);
spin_unlock_bh(&mm->context.list_lock);
if (mask == 0) {
pgtable_page_dtor(page);
atomic_set(&page->_mapcount, -1);
__free_page(page);
}
}
static void __page_table_free_rcu(void *table, unsigned bit)
{
struct page *page;
if (bit == FRAG_MASK)
return page_table_free_pgste(table);
/* Free 1K/2K page table fragment of a 4K page */
page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
if (atomic_xor_bits(&page->_mapcount, bit) == 0) {
pgtable_page_dtor(page);
atomic_set(&page->_mapcount, -1);
__free_page(page);
}
}
void page_table_free_rcu(struct mmu_gather *tlb, unsigned long *table)
{
struct mm_struct *mm;
struct page *page;
unsigned int bit, mask;
mm = tlb->mm;
if (mm_has_pgste(mm)) {
gmap_unmap_notifier(mm, table);
table = (unsigned long *) (__pa(table) | FRAG_MASK);
tlb_remove_table(tlb, table);
return;
}
bit = 1 << ((__pa(table) & ~PAGE_MASK) / (PTRS_PER_PTE*sizeof(pte_t)));
page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
spin_lock_bh(&mm->context.list_lock);
if ((atomic_read(&page->_mapcount) & FRAG_MASK) != FRAG_MASK)
list_del(&page->lru);
mask = atomic_xor_bits(&page->_mapcount, bit | (bit << 4));
if (mask & FRAG_MASK)
list_add_tail(&page->lru, &mm->context.pgtable_list);
spin_unlock_bh(&mm->context.list_lock);
table = (unsigned long *) (__pa(table) | (bit << 4));
tlb_remove_table(tlb, table);
}
void __tlb_remove_table(void *_table)
{
const unsigned long mask = (FRAG_MASK << 4) | FRAG_MASK;
void *table = (void *)((unsigned long) _table & ~mask);
unsigned type = (unsigned long) _table & mask;
if (type)
__page_table_free_rcu(table, type);
else
free_pages((unsigned long) table, ALLOC_ORDER);
}
static void tlb_remove_table_smp_sync(void *arg)
{
/* Simply deliver the interrupt */
}
static void tlb_remove_table_one(void *table)
{
/*
* This isn't an RCU grace period and hence the page-tables cannot be
* assumed to be actually RCU-freed.
*
* It is however sufficient for software page-table walkers that rely
* on IRQ disabling. See the comment near struct mmu_table_batch.
*/
smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
__tlb_remove_table(table);
}
static void tlb_remove_table_rcu(struct rcu_head *head)
{
struct mmu_table_batch *batch;
int i;
batch = container_of(head, struct mmu_table_batch, rcu);
for (i = 0; i < batch->nr; i++)
__tlb_remove_table(batch->tables[i]);
free_page((unsigned long)batch);
}
void tlb_table_flush(struct mmu_gather *tlb)
{
struct mmu_table_batch **batch = &tlb->batch;
if (*batch) {
__tlb_flush_mm(tlb->mm);
call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
*batch = NULL;
}
}
void tlb_remove_table(struct mmu_gather *tlb, void *table)
{
struct mmu_table_batch **batch = &tlb->batch;
if (*batch == NULL) {
*batch = (struct mmu_table_batch *)
__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
if (*batch == NULL) {
__tlb_flush_mm(tlb->mm);
tlb_remove_table_one(table);
return;
}
(*batch)->nr = 0;
}
(*batch)->tables[(*batch)->nr++] = table;
if ((*batch)->nr == MAX_TABLE_BATCH)
tlb_table_flush(tlb);
}
/*
* switch on pgstes for its userspace process (for kvm)
*/
int s390_enable_sie(void)
{
struct task_struct *tsk = current;
struct mm_struct *mm, *old_mm;
/* Do we have switched amode? If no, we cannot do sie */
if (user_mode == HOME_SPACE_MODE)
return -EINVAL;
/* Do we have pgstes? if yes, we are done */
if (mm_has_pgste(tsk->mm))
return 0;
/* lets check if we are allowed to replace the mm */
task_lock(tsk);
if (!tsk->mm || atomic_read(&tsk->mm->mm_users) > 1 ||
#ifdef CONFIG_AIO
tsk->mm->ioctx_rtree.rnode ||
#endif
tsk->mm != tsk->active_mm) {
task_unlock(tsk);
return -EINVAL;
}
task_unlock(tsk);
/* we copy the mm and let dup_mm create the page tables with_pgstes */
tsk->mm->context.alloc_pgste = 1;
mm = dup_mm(tsk);
tsk->mm->context.alloc_pgste = 0;
if (!mm)
return -ENOMEM;
/* Now lets check again if something happened */
task_lock(tsk);
if (!tsk->mm || atomic_read(&tsk->mm->mm_users) > 1 ||
#ifdef CONFIG_AIO
tsk->mm->ioctx_rtree.rnode ||
#endif
tsk->mm != tsk->active_mm) {
mmput(mm);
task_unlock(tsk);
return -EINVAL;
}
/* ok, we are alone. No ptrace, no threads, etc. */
old_mm = tsk->mm;
tsk->mm = tsk->active_mm = mm;
preempt_disable();
update_mm(mm, tsk);
atomic_inc(&mm->context.attach_count);
atomic_dec(&old_mm->context.attach_count);
cpumask_set_cpu(smp_processor_id(), mm_cpumask(mm));
preempt_enable();
task_unlock(tsk);
mmput(old_mm);
return 0;
}
EXPORT_SYMBOL_GPL(s390_enable_sie);
#if defined(CONFIG_DEBUG_PAGEALLOC) && defined(CONFIG_HIBERNATION)
bool kernel_page_present(struct page *page)
{
unsigned long addr;
int cc;
addr = page_to_phys(page);
asm volatile(
" lra %1,0(%1)\n"
" ipm %0\n"
" srl %0,28"
: "=d" (cc), "+a" (addr) : : "cc");
return cc == 0;
}
#endif /* CONFIG_HIBERNATION && CONFIG_DEBUG_PAGEALLOC */
| gpl-2.0 |
carbonsoft/kernel | drivers/usb/misc/ldusb.c | 554 | 23779 | /**
* Generic USB driver for report based interrupt in/out devices
* like LD Didactic's USB devices. LD Didactic's USB devices are
* HID devices which do not use HID report definitons (they use
* raw interrupt in and our reports only for communication).
*
* This driver uses a ring buffer for time critical reading of
* interrupt in reports and provides read and write methods for
* raw interrupt reports (similar to the Windows HID driver).
* Devices based on the book USB COMPLETE by Jan Axelson may need
* such a compatibility to the Windows HID driver.
*
* Copyright (C) 2005 Michael Hund <mhund@ld-didactic.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.
*
* Derived from Lego USB Tower driver
* Copyright (C) 2003 David Glance <advidgsf@sourceforge.net>
* 2001-2004 Juergen Stuber <starblue@users.sourceforge.net>
*
* V0.1 (mh) Initial version
* V0.11 (mh) Added raw support for HID 1.0 devices (no interrupt out endpoint)
* V0.12 (mh) Added kmalloc check for string buffer
* V0.13 (mh) Added support for LD X-Ray and Machine Test System
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/poll.h>
/* Define these values to match your devices */
#define USB_VENDOR_ID_LD 0x0f11 /* USB Vendor ID of LD Didactic GmbH */
#define USB_DEVICE_ID_LD_CASSY 0x1000 /* USB Product ID of CASSY-S */
#define USB_DEVICE_ID_LD_POCKETCASSY 0x1010 /* USB Product ID of Pocket-CASSY */
#define USB_DEVICE_ID_LD_MOBILECASSY 0x1020 /* USB Product ID of Mobile-CASSY */
#define USB_DEVICE_ID_LD_JWM 0x1080 /* USB Product ID of Joule and Wattmeter */
#define USB_DEVICE_ID_LD_DMMP 0x1081 /* USB Product ID of Digital Multimeter P (reserved) */
#define USB_DEVICE_ID_LD_UMIP 0x1090 /* USB Product ID of UMI P */
#define USB_DEVICE_ID_LD_XRAY1 0x1100 /* USB Product ID of X-Ray Apparatus */
#define USB_DEVICE_ID_LD_XRAY2 0x1101 /* USB Product ID of X-Ray Apparatus */
#define USB_DEVICE_ID_LD_VIDEOCOM 0x1200 /* USB Product ID of VideoCom */
#define USB_DEVICE_ID_LD_COM3LAB 0x2000 /* USB Product ID of COM3LAB */
#define USB_DEVICE_ID_LD_TELEPORT 0x2010 /* USB Product ID of Terminal Adapter */
#define USB_DEVICE_ID_LD_NETWORKANALYSER 0x2020 /* USB Product ID of Network Analyser */
#define USB_DEVICE_ID_LD_POWERCONTROL 0x2030 /* USB Product ID of Converter Control Unit */
#define USB_DEVICE_ID_LD_MACHINETEST 0x2040 /* USB Product ID of Machine Test System */
#define USB_VENDOR_ID_VERNIER 0x08f7
#define USB_DEVICE_ID_VERNIER_GOTEMP 0x0002
#define USB_DEVICE_ID_VERNIER_SKIP 0x0003
#define USB_DEVICE_ID_VERNIER_CYCLOPS 0x0004
#define USB_DEVICE_ID_VERNIER_LCSPEC 0x0006
#ifdef CONFIG_USB_DYNAMIC_MINORS
#define USB_LD_MINOR_BASE 0
#else
#define USB_LD_MINOR_BASE 176
#endif
/* table of devices that work with this driver */
static struct usb_device_id ld_usb_table [] = {
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_CASSY) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POCKETCASSY) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOBILECASSY) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_JWM) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_DMMP) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIP) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_XRAY1) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_XRAY2) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_VIDEOCOM) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_COM3LAB) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_TELEPORT) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_NETWORKANALYSER) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POWERCONTROL) },
{ USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MACHINETEST) },
{ USB_DEVICE(USB_VENDOR_ID_VERNIER, USB_DEVICE_ID_VERNIER_GOTEMP) },
{ USB_DEVICE(USB_VENDOR_ID_VERNIER, USB_DEVICE_ID_VERNIER_SKIP) },
{ USB_DEVICE(USB_VENDOR_ID_VERNIER, USB_DEVICE_ID_VERNIER_CYCLOPS) },
{ USB_DEVICE(USB_VENDOR_ID_VERNIER, USB_DEVICE_ID_VERNIER_LCSPEC) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, ld_usb_table);
MODULE_VERSION("V0.13");
MODULE_AUTHOR("Michael Hund <mhund@ld-didactic.de>");
MODULE_DESCRIPTION("LD USB Driver");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("LD USB Devices");
#ifdef CONFIG_USB_DEBUG
static int debug = 1;
#else
static int debug = 0;
#endif
/* Use our own dbg macro */
#define dbg_info(dev, format, arg...) do { if (debug) dev_info(dev , format , ## arg); } while (0)
/* Module parameters */
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
/* All interrupt in transfers are collected in a ring buffer to
* avoid racing conditions and get better performance of the driver.
*/
static int ring_buffer_size = 128;
module_param(ring_buffer_size, int, 0);
MODULE_PARM_DESC(ring_buffer_size, "Read ring buffer size in reports");
/* The write_buffer can contain more than one interrupt out transfer.
*/
static int write_buffer_size = 10;
module_param(write_buffer_size, int, 0);
MODULE_PARM_DESC(write_buffer_size, "Write buffer size in reports");
/* As of kernel version 2.6.4 ehci-hcd uses an
* "only one interrupt transfer per frame" shortcut
* to simplify the scheduling of periodic transfers.
* This conflicts with our standard 1ms intervals for in and out URBs.
* We use default intervals of 2ms for in and 2ms for out transfers,
* which should be fast enough.
* Increase the interval to allow more devices that do interrupt transfers,
* or set to 1 to use the standard interval from the endpoint descriptors.
*/
static int min_interrupt_in_interval = 2;
module_param(min_interrupt_in_interval, int, 0);
MODULE_PARM_DESC(min_interrupt_in_interval, "Minimum interrupt in interval in ms");
static int min_interrupt_out_interval = 2;
module_param(min_interrupt_out_interval, int, 0);
MODULE_PARM_DESC(min_interrupt_out_interval, "Minimum interrupt out interval in ms");
/* Structure to hold all of our device specific stuff */
struct ld_usb {
struct mutex mutex; /* locks this structure */
struct usb_interface* intf; /* save off the usb interface pointer */
int open_count; /* number of times this port has been opened */
char* ring_buffer;
unsigned int ring_head;
unsigned int ring_tail;
wait_queue_head_t read_wait;
wait_queue_head_t write_wait;
char* interrupt_in_buffer;
struct usb_endpoint_descriptor* interrupt_in_endpoint;
struct urb* interrupt_in_urb;
int interrupt_in_interval;
size_t interrupt_in_endpoint_size;
int interrupt_in_running;
int interrupt_in_done;
int buffer_overflow;
spinlock_t rbsl;
char* interrupt_out_buffer;
struct usb_endpoint_descriptor* interrupt_out_endpoint;
struct urb* interrupt_out_urb;
int interrupt_out_interval;
size_t interrupt_out_endpoint_size;
int interrupt_out_busy;
};
static struct usb_driver ld_usb_driver;
/**
* ld_usb_abort_transfers
* aborts transfers and frees associated data structures
*/
static void ld_usb_abort_transfers(struct ld_usb *dev)
{
/* shutdown transfer */
if (dev->interrupt_in_running) {
dev->interrupt_in_running = 0;
if (dev->intf)
usb_kill_urb(dev->interrupt_in_urb);
}
if (dev->interrupt_out_busy)
if (dev->intf)
usb_kill_urb(dev->interrupt_out_urb);
}
/**
* ld_usb_delete
*/
static void ld_usb_delete(struct ld_usb *dev)
{
ld_usb_abort_transfers(dev);
/* free data structures */
usb_free_urb(dev->interrupt_in_urb);
usb_free_urb(dev->interrupt_out_urb);
kfree(dev->ring_buffer);
kfree(dev->interrupt_in_buffer);
kfree(dev->interrupt_out_buffer);
kfree(dev);
}
/**
* ld_usb_interrupt_in_callback
*/
static void ld_usb_interrupt_in_callback(struct urb *urb)
{
struct ld_usb *dev = urb->context;
size_t *actual_buffer;
unsigned int next_ring_head;
int status = urb->status;
int retval;
if (status) {
if (status == -ENOENT ||
status == -ECONNRESET ||
status == -ESHUTDOWN) {
goto exit;
} else {
dbg_info(&dev->intf->dev, "%s: nonzero status received: %d\n",
__func__, status);
spin_lock(&dev->rbsl);
goto resubmit; /* maybe we can recover */
}
}
spin_lock(&dev->rbsl);
if (urb->actual_length > 0) {
next_ring_head = (dev->ring_head+1) % ring_buffer_size;
if (next_ring_head != dev->ring_tail) {
actual_buffer = (size_t*)(dev->ring_buffer + dev->ring_head*(sizeof(size_t)+dev->interrupt_in_endpoint_size));
/* actual_buffer gets urb->actual_length + interrupt_in_buffer */
*actual_buffer = urb->actual_length;
memcpy(actual_buffer+1, dev->interrupt_in_buffer, urb->actual_length);
dev->ring_head = next_ring_head;
dbg_info(&dev->intf->dev, "%s: received %d bytes\n",
__func__, urb->actual_length);
} else {
dev_warn(&dev->intf->dev,
"Ring buffer overflow, %d bytes dropped\n",
urb->actual_length);
dev->buffer_overflow = 1;
}
}
resubmit:
/* resubmit if we're still running */
if (dev->interrupt_in_running && !dev->buffer_overflow && dev->intf) {
retval = usb_submit_urb(dev->interrupt_in_urb, GFP_ATOMIC);
if (retval) {
dev_err(&dev->intf->dev,
"usb_submit_urb failed (%d)\n", retval);
dev->buffer_overflow = 1;
}
}
spin_unlock(&dev->rbsl);
exit:
dev->interrupt_in_done = 1;
wake_up_interruptible(&dev->read_wait);
}
/**
* ld_usb_interrupt_out_callback
*/
static void ld_usb_interrupt_out_callback(struct urb *urb)
{
struct ld_usb *dev = urb->context;
int status = urb->status;
/* sync/async unlink faults aren't errors */
if (status && !(status == -ENOENT ||
status == -ECONNRESET ||
status == -ESHUTDOWN))
dbg_info(&dev->intf->dev,
"%s - nonzero write interrupt status received: %d\n",
__func__, status);
dev->interrupt_out_busy = 0;
wake_up_interruptible(&dev->write_wait);
}
/**
* ld_usb_open
*/
static int ld_usb_open(struct inode *inode, struct file *file)
{
struct ld_usb *dev;
int subminor;
int retval;
struct usb_interface *interface;
nonseekable_open(inode, file);
subminor = iminor(inode);
interface = usb_find_interface(&ld_usb_driver, subminor);
if (!interface) {
err("%s - error, can't find device for minor %d\n",
__func__, subminor);
return -ENODEV;
}
dev = usb_get_intfdata(interface);
if (!dev)
return -ENODEV;
/* lock this device */
if (mutex_lock_interruptible(&dev->mutex))
return -ERESTARTSYS;
/* allow opening only once */
if (dev->open_count) {
retval = -EBUSY;
goto unlock_exit;
}
dev->open_count = 1;
/* initialize in direction */
dev->ring_head = 0;
dev->ring_tail = 0;
dev->buffer_overflow = 0;
usb_fill_int_urb(dev->interrupt_in_urb,
interface_to_usbdev(interface),
usb_rcvintpipe(interface_to_usbdev(interface),
dev->interrupt_in_endpoint->bEndpointAddress),
dev->interrupt_in_buffer,
dev->interrupt_in_endpoint_size,
ld_usb_interrupt_in_callback,
dev,
dev->interrupt_in_interval);
dev->interrupt_in_running = 1;
dev->interrupt_in_done = 0;
retval = usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL);
if (retval) {
dev_err(&interface->dev, "Couldn't submit interrupt_in_urb %d\n", retval);
dev->interrupt_in_running = 0;
dev->open_count = 0;
goto unlock_exit;
}
/* save device in the file's private structure */
file->private_data = dev;
unlock_exit:
mutex_unlock(&dev->mutex);
return retval;
}
/**
* ld_usb_release
*/
static int ld_usb_release(struct inode *inode, struct file *file)
{
struct ld_usb *dev;
int retval = 0;
dev = file->private_data;
if (dev == NULL) {
retval = -ENODEV;
goto exit;
}
if (mutex_lock_interruptible(&dev->mutex)) {
retval = -ERESTARTSYS;
goto exit;
}
if (dev->open_count != 1) {
retval = -ENODEV;
goto unlock_exit;
}
if (dev->intf == NULL) {
/* the device was unplugged before the file was released */
mutex_unlock(&dev->mutex);
/* unlock here as ld_usb_delete frees dev */
ld_usb_delete(dev);
goto exit;
}
/* wait until write transfer is finished */
if (dev->interrupt_out_busy)
wait_event_interruptible_timeout(dev->write_wait, !dev->interrupt_out_busy, 2 * HZ);
ld_usb_abort_transfers(dev);
dev->open_count = 0;
unlock_exit:
mutex_unlock(&dev->mutex);
exit:
return retval;
}
/**
* ld_usb_poll
*/
static unsigned int ld_usb_poll(struct file *file, poll_table *wait)
{
struct ld_usb *dev;
unsigned int mask = 0;
dev = file->private_data;
if (!dev->intf)
return POLLERR | POLLHUP;
poll_wait(file, &dev->read_wait, wait);
poll_wait(file, &dev->write_wait, wait);
if (dev->ring_head != dev->ring_tail)
mask |= POLLIN | POLLRDNORM;
if (!dev->interrupt_out_busy)
mask |= POLLOUT | POLLWRNORM;
return mask;
}
/**
* ld_usb_read
*/
static ssize_t ld_usb_read(struct file *file, char __user *buffer, size_t count,
loff_t *ppos)
{
struct ld_usb *dev;
size_t *actual_buffer;
size_t bytes_to_read;
int retval = 0;
int rv;
dev = file->private_data;
/* verify that we actually have some data to read */
if (count == 0)
goto exit;
/* lock this object */
if (mutex_lock_interruptible(&dev->mutex)) {
retval = -ERESTARTSYS;
goto exit;
}
/* verify that the device wasn't unplugged */
if (dev->intf == NULL) {
retval = -ENODEV;
err("No device or device unplugged %d\n", retval);
goto unlock_exit;
}
/* wait for data */
spin_lock_irq(&dev->rbsl);
if (dev->ring_head == dev->ring_tail) {
dev->interrupt_in_done = 0;
spin_unlock_irq(&dev->rbsl);
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto unlock_exit;
}
retval = wait_event_interruptible(dev->read_wait, dev->interrupt_in_done);
if (retval < 0)
goto unlock_exit;
} else {
spin_unlock_irq(&dev->rbsl);
}
/* actual_buffer contains actual_length + interrupt_in_buffer */
actual_buffer = (size_t*)(dev->ring_buffer + dev->ring_tail*(sizeof(size_t)+dev->interrupt_in_endpoint_size));
bytes_to_read = min(count, *actual_buffer);
if (bytes_to_read < *actual_buffer)
dev_warn(&dev->intf->dev, "Read buffer overflow, %zd bytes dropped\n",
*actual_buffer-bytes_to_read);
/* copy one interrupt_in_buffer from ring_buffer into userspace */
if (copy_to_user(buffer, actual_buffer+1, bytes_to_read)) {
retval = -EFAULT;
goto unlock_exit;
}
dev->ring_tail = (dev->ring_tail+1) % ring_buffer_size;
retval = bytes_to_read;
spin_lock_irq(&dev->rbsl);
if (dev->buffer_overflow) {
dev->buffer_overflow = 0;
spin_unlock_irq(&dev->rbsl);
rv = usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL);
if (rv < 0)
dev->buffer_overflow = 1;
} else {
spin_unlock_irq(&dev->rbsl);
}
unlock_exit:
/* unlock the device */
mutex_unlock(&dev->mutex);
exit:
return retval;
}
/**
* ld_usb_write
*/
static ssize_t ld_usb_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
struct ld_usb *dev;
size_t bytes_to_write;
int retval = 0;
dev = file->private_data;
/* verify that we actually have some data to write */
if (count == 0)
goto exit;
/* lock this object */
if (mutex_lock_interruptible(&dev->mutex)) {
retval = -ERESTARTSYS;
goto exit;
}
/* verify that the device wasn't unplugged */
if (dev->intf == NULL) {
retval = -ENODEV;
err("No device or device unplugged %d\n", retval);
goto unlock_exit;
}
/* wait until previous transfer is finished */
if (dev->interrupt_out_busy) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto unlock_exit;
}
retval = wait_event_interruptible(dev->write_wait, !dev->interrupt_out_busy);
if (retval < 0) {
goto unlock_exit;
}
}
/* write the data into interrupt_out_buffer from userspace */
bytes_to_write = min(count, write_buffer_size*dev->interrupt_out_endpoint_size);
if (bytes_to_write < count)
dev_warn(&dev->intf->dev, "Write buffer overflow, %zd bytes dropped\n",count-bytes_to_write);
dbg_info(&dev->intf->dev, "%s: count = %zd, bytes_to_write = %zd\n", __func__, count, bytes_to_write);
if (copy_from_user(dev->interrupt_out_buffer, buffer, bytes_to_write)) {
retval = -EFAULT;
goto unlock_exit;
}
if (dev->interrupt_out_endpoint == NULL) {
/* try HID_REQ_SET_REPORT=9 on control_endpoint instead of interrupt_out_endpoint */
retval = usb_control_msg(interface_to_usbdev(dev->intf),
usb_sndctrlpipe(interface_to_usbdev(dev->intf), 0),
9,
USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT,
1 << 8, 0,
dev->interrupt_out_buffer,
bytes_to_write,
USB_CTRL_SET_TIMEOUT * HZ);
if (retval < 0)
err("Couldn't submit HID_REQ_SET_REPORT %d\n", retval);
goto unlock_exit;
}
/* send off the urb */
usb_fill_int_urb(dev->interrupt_out_urb,
interface_to_usbdev(dev->intf),
usb_sndintpipe(interface_to_usbdev(dev->intf),
dev->interrupt_out_endpoint->bEndpointAddress),
dev->interrupt_out_buffer,
bytes_to_write,
ld_usb_interrupt_out_callback,
dev,
dev->interrupt_out_interval);
dev->interrupt_out_busy = 1;
wmb();
retval = usb_submit_urb(dev->interrupt_out_urb, GFP_KERNEL);
if (retval) {
dev->interrupt_out_busy = 0;
err("Couldn't submit interrupt_out_urb %d\n", retval);
goto unlock_exit;
}
retval = bytes_to_write;
unlock_exit:
/* unlock the device */
mutex_unlock(&dev->mutex);
exit:
return retval;
}
/* file operations needed when we register this driver */
static const struct file_operations ld_usb_fops = {
.owner = THIS_MODULE,
.read = ld_usb_read,
.write = ld_usb_write,
.open = ld_usb_open,
.release = ld_usb_release,
.poll = ld_usb_poll,
};
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with the driver core
*/
static struct usb_class_driver ld_usb_class = {
.name = "ldusb%d",
.fops = &ld_usb_fops,
.minor_base = USB_LD_MINOR_BASE,
};
/**
* ld_usb_probe
*
* Called by the usb core when a new device is connected that it thinks
* this driver might be interested in.
*/
static int ld_usb_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct ld_usb *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
char *buffer;
int i;
int retval = -ENOMEM;
/* allocate memory for our device state and intialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL) {
dev_err(&intf->dev, "Out of memory\n");
goto exit;
}
mutex_init(&dev->mutex);
spin_lock_init(&dev->rbsl);
dev->intf = intf;
init_waitqueue_head(&dev->read_wait);
init_waitqueue_head(&dev->write_wait);
/* workaround for early firmware versions on fast computers */
if ((le16_to_cpu(udev->descriptor.idVendor) == USB_VENDOR_ID_LD) &&
((le16_to_cpu(udev->descriptor.idProduct) == USB_DEVICE_ID_LD_CASSY) ||
(le16_to_cpu(udev->descriptor.idProduct) == USB_DEVICE_ID_LD_COM3LAB)) &&
(le16_to_cpu(udev->descriptor.bcdDevice) <= 0x103)) {
buffer = kmalloc(256, GFP_KERNEL);
if (buffer == NULL) {
dev_err(&intf->dev, "Couldn't allocate string buffer\n");
goto error;
}
/* usb_string makes SETUP+STALL to leave always ControlReadLoop */
usb_string(udev, 255, buffer, 256);
kfree(buffer);
}
iface_desc = intf->cur_altsetting;
/* set up the endpoint information */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_is_int_in(endpoint))
dev->interrupt_in_endpoint = endpoint;
if (usb_endpoint_is_int_out(endpoint))
dev->interrupt_out_endpoint = endpoint;
}
if (dev->interrupt_in_endpoint == NULL) {
dev_err(&intf->dev, "Interrupt in endpoint not found\n");
goto error;
}
if (dev->interrupt_out_endpoint == NULL)
dev_warn(&intf->dev, "Interrupt out endpoint not found (using control endpoint instead)\n");
dev->interrupt_in_endpoint_size = le16_to_cpu(dev->interrupt_in_endpoint->wMaxPacketSize);
dev->ring_buffer = kmalloc(ring_buffer_size*(sizeof(size_t)+dev->interrupt_in_endpoint_size), GFP_KERNEL);
if (!dev->ring_buffer) {
dev_err(&intf->dev, "Couldn't allocate ring_buffer\n");
goto error;
}
dev->interrupt_in_buffer = kmalloc(dev->interrupt_in_endpoint_size, GFP_KERNEL);
if (!dev->interrupt_in_buffer) {
dev_err(&intf->dev, "Couldn't allocate interrupt_in_buffer\n");
goto error;
}
dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_in_urb) {
dev_err(&intf->dev, "Couldn't allocate interrupt_in_urb\n");
goto error;
}
dev->interrupt_out_endpoint_size = dev->interrupt_out_endpoint ? le16_to_cpu(dev->interrupt_out_endpoint->wMaxPacketSize) :
udev->descriptor.bMaxPacketSize0;
dev->interrupt_out_buffer = kmalloc(write_buffer_size*dev->interrupt_out_endpoint_size, GFP_KERNEL);
if (!dev->interrupt_out_buffer) {
dev_err(&intf->dev, "Couldn't allocate interrupt_out_buffer\n");
goto error;
}
dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_out_urb) {
dev_err(&intf->dev, "Couldn't allocate interrupt_out_urb\n");
goto error;
}
dev->interrupt_in_interval = min_interrupt_in_interval > dev->interrupt_in_endpoint->bInterval ? min_interrupt_in_interval : dev->interrupt_in_endpoint->bInterval;
if (dev->interrupt_out_endpoint)
dev->interrupt_out_interval = min_interrupt_out_interval > dev->interrupt_out_endpoint->bInterval ? min_interrupt_out_interval : dev->interrupt_out_endpoint->bInterval;
/* we can register the device now, as it is ready */
usb_set_intfdata(intf, dev);
retval = usb_register_dev(intf, &ld_usb_class);
if (retval) {
/* something prevented us from registering this driver */
dev_err(&intf->dev, "Not able to get a minor for this device.\n");
usb_set_intfdata(intf, NULL);
goto error;
}
/* let the user know what node this device is now attached to */
dev_info(&intf->dev, "LD USB Device #%d now attached to major %d minor %d\n",
(intf->minor - USB_LD_MINOR_BASE), USB_MAJOR, intf->minor);
exit:
return retval;
error:
ld_usb_delete(dev);
return retval;
}
/**
* ld_usb_disconnect
*
* Called by the usb core when the device is removed from the system.
*/
static void ld_usb_disconnect(struct usb_interface *intf)
{
struct ld_usb *dev;
int minor;
dev = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
minor = intf->minor;
/* give back our minor */
usb_deregister_dev(intf, &ld_usb_class);
mutex_lock(&dev->mutex);
/* if the device is not opened, then we clean up right now */
if (!dev->open_count) {
mutex_unlock(&dev->mutex);
ld_usb_delete(dev);
} else {
dev->intf = NULL;
/* wake up pollers */
wake_up_interruptible_all(&dev->read_wait);
wake_up_interruptible_all(&dev->write_wait);
mutex_unlock(&dev->mutex);
}
dev_info(&intf->dev, "LD USB Device #%d now disconnected\n",
(minor - USB_LD_MINOR_BASE));
}
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver ld_usb_driver = {
.name = "ldusb",
.probe = ld_usb_probe,
.disconnect = ld_usb_disconnect,
.id_table = ld_usb_table,
};
/**
* ld_usb_init
*/
static int __init ld_usb_init(void)
{
int retval;
/* register this driver with the USB subsystem */
retval = usb_register(&ld_usb_driver);
if (retval)
err("usb_register failed for the "__FILE__" driver. Error number %d\n", retval);
return retval;
}
/**
* ld_usb_exit
*/
static void __exit ld_usb_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&ld_usb_driver);
}
module_init(ld_usb_init);
module_exit(ld_usb_exit);
| gpl-2.0 |
cile/pyramid-kernel | drivers/scsi/bfa/bfa_ioc.c | 810 | 45697 | /*
* Copyright (c) 2005-2009 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) 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 <bfa.h>
#include <bfa_ioc.h>
#include <bfa_fwimg_priv.h>
#include <cna/bfa_cna_trcmod.h>
#include <cs/bfa_debug.h>
#include <bfi/bfi_ioc.h>
#include <bfi/bfi_ctreg.h>
#include <aen/bfa_aen_ioc.h>
#include <aen/bfa_aen.h>
#include <log/bfa_log_hal.h>
#include <defs/bfa_defs_pci.h>
BFA_TRC_FILE(CNA, IOC);
/**
* IOC local definitions
*/
#define BFA_IOC_TOV 2000 /* msecs */
#define BFA_IOC_HWSEM_TOV 500 /* msecs */
#define BFA_IOC_HB_TOV 500 /* msecs */
#define BFA_IOC_HWINIT_MAX 2
#define BFA_IOC_FWIMG_MINSZ (16 * 1024)
#define BFA_IOC_TOV_RECOVER BFA_IOC_HB_TOV
#define bfa_ioc_timer_start(__ioc) \
bfa_timer_begin((__ioc)->timer_mod, &(__ioc)->ioc_timer, \
bfa_ioc_timeout, (__ioc), BFA_IOC_TOV)
#define bfa_ioc_timer_stop(__ioc) bfa_timer_stop(&(__ioc)->ioc_timer)
#define BFA_DBG_FWTRC_ENTS (BFI_IOC_TRC_ENTS)
#define BFA_DBG_FWTRC_LEN \
(BFA_DBG_FWTRC_ENTS * sizeof(struct bfa_trc_s) + \
(sizeof(struct bfa_trc_mod_s) - \
BFA_TRC_MAX * sizeof(struct bfa_trc_s)))
#define BFA_DBG_FWTRC_OFF(_fn) (BFI_IOC_TRC_OFF + BFA_DBG_FWTRC_LEN * (_fn))
/**
* Asic specific macros : see bfa_hw_cb.c and bfa_hw_ct.c for details.
*/
#define bfa_ioc_firmware_lock(__ioc) \
((__ioc)->ioc_hwif->ioc_firmware_lock(__ioc))
#define bfa_ioc_firmware_unlock(__ioc) \
((__ioc)->ioc_hwif->ioc_firmware_unlock(__ioc))
#define bfa_ioc_fwimg_get_chunk(__ioc, __off) \
((__ioc)->ioc_hwif->ioc_fwimg_get_chunk(__ioc, __off))
#define bfa_ioc_fwimg_get_size(__ioc) \
((__ioc)->ioc_hwif->ioc_fwimg_get_size(__ioc))
#define bfa_ioc_reg_init(__ioc) ((__ioc)->ioc_hwif->ioc_reg_init(__ioc))
#define bfa_ioc_map_port(__ioc) ((__ioc)->ioc_hwif->ioc_map_port(__ioc))
#define bfa_ioc_notify_hbfail(__ioc) \
((__ioc)->ioc_hwif->ioc_notify_hbfail(__ioc))
bfa_boolean_t bfa_auto_recover = BFA_TRUE;
/*
* forward declarations
*/
static void bfa_ioc_aen_post(struct bfa_ioc_s *bfa,
enum bfa_ioc_aen_event event);
static void bfa_ioc_hw_sem_get(struct bfa_ioc_s *ioc);
static void bfa_ioc_hw_sem_get_cancel(struct bfa_ioc_s *ioc);
static void bfa_ioc_hwinit(struct bfa_ioc_s *ioc, bfa_boolean_t force);
static void bfa_ioc_timeout(void *ioc);
static void bfa_ioc_send_enable(struct bfa_ioc_s *ioc);
static void bfa_ioc_send_disable(struct bfa_ioc_s *ioc);
static void bfa_ioc_send_getattr(struct bfa_ioc_s *ioc);
static void bfa_ioc_hb_monitor(struct bfa_ioc_s *ioc);
static void bfa_ioc_hb_stop(struct bfa_ioc_s *ioc);
static void bfa_ioc_reset(struct bfa_ioc_s *ioc, bfa_boolean_t force);
static void bfa_ioc_mbox_poll(struct bfa_ioc_s *ioc);
static void bfa_ioc_mbox_hbfail(struct bfa_ioc_s *ioc);
static void bfa_ioc_recover(struct bfa_ioc_s *ioc);
static void bfa_ioc_disable_comp(struct bfa_ioc_s *ioc);
static void bfa_ioc_lpu_stop(struct bfa_ioc_s *ioc);
/**
* bfa_ioc_sm
*/
/**
* IOC state machine events
*/
enum ioc_event {
IOC_E_ENABLE = 1, /* IOC enable request */
IOC_E_DISABLE = 2, /* IOC disable request */
IOC_E_TIMEOUT = 3, /* f/w response timeout */
IOC_E_FWREADY = 4, /* f/w initialization done */
IOC_E_FWRSP_GETATTR = 5, /* IOC get attribute response */
IOC_E_FWRSP_ENABLE = 6, /* enable f/w response */
IOC_E_FWRSP_DISABLE = 7, /* disable f/w response */
IOC_E_HBFAIL = 8, /* heartbeat failure */
IOC_E_HWERROR = 9, /* hardware error interrupt */
IOC_E_SEMLOCKED = 10, /* h/w semaphore is locked */
IOC_E_DETACH = 11, /* driver detach cleanup */
};
bfa_fsm_state_decl(bfa_ioc, reset, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, fwcheck, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, mismatch, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, semwait, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, hwinit, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, enabling, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, getattr, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, op, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, initfail, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, hbfail, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, disabling, struct bfa_ioc_s, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, disabled, struct bfa_ioc_s, enum ioc_event);
static struct bfa_sm_table_s ioc_sm_table[] = {
{BFA_SM(bfa_ioc_sm_reset), BFA_IOC_RESET},
{BFA_SM(bfa_ioc_sm_fwcheck), BFA_IOC_FWMISMATCH},
{BFA_SM(bfa_ioc_sm_mismatch), BFA_IOC_FWMISMATCH},
{BFA_SM(bfa_ioc_sm_semwait), BFA_IOC_SEMWAIT},
{BFA_SM(bfa_ioc_sm_hwinit), BFA_IOC_HWINIT},
{BFA_SM(bfa_ioc_sm_enabling), BFA_IOC_HWINIT},
{BFA_SM(bfa_ioc_sm_getattr), BFA_IOC_GETATTR},
{BFA_SM(bfa_ioc_sm_op), BFA_IOC_OPERATIONAL},
{BFA_SM(bfa_ioc_sm_initfail), BFA_IOC_INITFAIL},
{BFA_SM(bfa_ioc_sm_hbfail), BFA_IOC_HBFAIL},
{BFA_SM(bfa_ioc_sm_disabling), BFA_IOC_DISABLING},
{BFA_SM(bfa_ioc_sm_disabled), BFA_IOC_DISABLED},
};
/**
* Reset entry actions -- initialize state machine
*/
static void
bfa_ioc_sm_reset_entry(struct bfa_ioc_s *ioc)
{
ioc->retry_count = 0;
ioc->auto_recover = bfa_auto_recover;
}
/**
* Beginning state. IOC is in reset state.
*/
static void
bfa_ioc_sm_reset(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_ENABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_fwcheck);
break;
case IOC_E_DISABLE:
bfa_ioc_disable_comp(ioc);
break;
case IOC_E_DETACH:
break;
default:
bfa_sm_fault(ioc, event);
}
}
/**
* Semaphore should be acquired for version check.
*/
static void
bfa_ioc_sm_fwcheck_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_hw_sem_get(ioc);
}
/**
* Awaiting h/w semaphore to continue with version check.
*/
static void
bfa_ioc_sm_fwcheck(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_SEMLOCKED:
if (bfa_ioc_firmware_lock(ioc)) {
ioc->retry_count = 0;
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwinit);
} else {
bfa_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_mismatch);
}
break;
case IOC_E_DISABLE:
bfa_ioc_disable_comp(ioc);
/*
* fall through
*/
case IOC_E_DETACH:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
break;
case IOC_E_FWREADY:
break;
default:
bfa_sm_fault(ioc, event);
}
}
/**
* Notify enable completion callback and generate mismatch AEN.
*/
static void
bfa_ioc_sm_mismatch_entry(struct bfa_ioc_s *ioc)
{
/**
* Provide enable completion callback and AEN notification only once.
*/
if (ioc->retry_count == 0) {
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_ioc_aen_post(ioc, BFA_IOC_AEN_FWMISMATCH);
}
ioc->retry_count++;
bfa_ioc_timer_start(ioc);
}
/**
* Awaiting firmware version match.
*/
static void
bfa_ioc_sm_mismatch(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_TIMEOUT:
bfa_fsm_set_state(ioc, bfa_ioc_sm_fwcheck);
break;
case IOC_E_DISABLE:
bfa_ioc_disable_comp(ioc);
/*
* fall through
*/
case IOC_E_DETACH:
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
break;
case IOC_E_FWREADY:
break;
default:
bfa_sm_fault(ioc, event);
}
}
/**
* Request for semaphore.
*/
static void
bfa_ioc_sm_semwait_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_hw_sem_get(ioc);
}
/**
* Awaiting semaphore for h/w initialzation.
*/
static void
bfa_ioc_sm_semwait(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_SEMLOCKED:
ioc->retry_count = 0;
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwinit);
break;
case IOC_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_hwinit_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_timer_start(ioc);
bfa_ioc_reset(ioc, BFA_FALSE);
}
/**
* Hardware is being initialized. Interrupts are enabled.
* Holding hardware semaphore lock.
*/
static void
bfa_ioc_sm_hwinit(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_FWREADY:
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_enabling);
break;
case IOC_E_HWERROR:
bfa_ioc_timer_stop(ioc);
/*
* fall through
*/
case IOC_E_TIMEOUT:
ioc->retry_count++;
if (ioc->retry_count < BFA_IOC_HWINIT_MAX) {
bfa_ioc_timer_start(ioc);
bfa_ioc_reset(ioc, BFA_TRUE);
break;
}
bfa_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_initfail);
break;
case IOC_E_DISABLE:
bfa_ioc_hw_sem_release(ioc);
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_enabling_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_timer_start(ioc);
bfa_ioc_send_enable(ioc);
}
/**
* Host IOC function is being enabled, awaiting response from firmware.
* Semaphore is acquired.
*/
static void
bfa_ioc_sm_enabling(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_FWRSP_ENABLE:
bfa_ioc_timer_stop(ioc);
bfa_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_getattr);
break;
case IOC_E_HWERROR:
bfa_ioc_timer_stop(ioc);
/*
* fall through
*/
case IOC_E_TIMEOUT:
ioc->retry_count++;
if (ioc->retry_count < BFA_IOC_HWINIT_MAX) {
bfa_reg_write(ioc->ioc_regs.ioc_fwstate,
BFI_IOC_UNINIT);
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwinit);
break;
}
bfa_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_initfail);
break;
case IOC_E_DISABLE:
bfa_ioc_timer_stop(ioc);
bfa_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
case IOC_E_FWREADY:
bfa_ioc_send_enable(ioc);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_getattr_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_timer_start(ioc);
bfa_ioc_send_getattr(ioc);
}
/**
* IOC configuration in progress. Timer is active.
*/
static void
bfa_ioc_sm_getattr(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_FWRSP_GETATTR:
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_op);
break;
case IOC_E_HWERROR:
bfa_ioc_timer_stop(ioc);
/*
* fall through
*/
case IOC_E_TIMEOUT:
bfa_fsm_set_state(ioc, bfa_ioc_sm_initfail);
break;
case IOC_E_DISABLE:
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_op_entry(struct bfa_ioc_s *ioc)
{
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_OK);
bfa_ioc_hb_monitor(ioc);
bfa_ioc_aen_post(ioc, BFA_IOC_AEN_ENABLE);
}
static void
bfa_ioc_sm_op(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_ENABLE:
break;
case IOC_E_DISABLE:
bfa_ioc_hb_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_HWERROR:
case IOC_E_FWREADY:
/**
* Hard error or IOC recovery by other function.
* Treat it same as heartbeat failure.
*/
bfa_ioc_hb_stop(ioc);
/*
* !!! fall through !!!
*/
case IOC_E_HBFAIL:
bfa_fsm_set_state(ioc, bfa_ioc_sm_hbfail);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_disabling_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_aen_post(ioc, BFA_IOC_AEN_DISABLE);
bfa_ioc_timer_start(ioc);
bfa_ioc_send_disable(ioc);
}
/**
* IOC is being disabled
*/
static void
bfa_ioc_sm_disabling(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_FWRSP_DISABLE:
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
case IOC_E_HWERROR:
bfa_ioc_timer_stop(ioc);
/*
* !!! fall through !!!
*/
case IOC_E_TIMEOUT:
bfa_reg_write(ioc->ioc_regs.ioc_fwstate, BFI_IOC_FAIL);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
default:
bfa_sm_fault(ioc, event);
}
}
/**
* IOC disable completion entry.
*/
static void
bfa_ioc_sm_disabled_entry(struct bfa_ioc_s *ioc)
{
bfa_ioc_disable_comp(ioc);
}
static void
bfa_ioc_sm_disabled(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_ENABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_semwait);
break;
case IOC_E_DISABLE:
ioc->cbfn->disable_cbfn(ioc->bfa);
break;
case IOC_E_FWREADY:
break;
case IOC_E_DETACH:
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_initfail_entry(struct bfa_ioc_s *ioc)
{
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_ioc_timer_start(ioc);
}
/**
* Hardware initialization failed.
*/
static void
bfa_ioc_sm_initfail(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_DISABLE:
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
case IOC_E_DETACH:
bfa_ioc_timer_stop(ioc);
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
break;
case IOC_E_TIMEOUT:
bfa_fsm_set_state(ioc, bfa_ioc_sm_semwait);
break;
default:
bfa_sm_fault(ioc, event);
}
}
static void
bfa_ioc_sm_hbfail_entry(struct bfa_ioc_s *ioc)
{
struct list_head *qe;
struct bfa_ioc_hbfail_notify_s *notify;
/**
* Mark IOC as failed in hardware and stop firmware.
*/
bfa_ioc_lpu_stop(ioc);
bfa_reg_write(ioc->ioc_regs.ioc_fwstate, BFI_IOC_FAIL);
/**
* Notify other functions on HB failure.
*/
bfa_ioc_notify_hbfail(ioc);
/**
* Notify driver and common modules registered for notification.
*/
ioc->cbfn->hbfail_cbfn(ioc->bfa);
list_for_each(qe, &ioc->hb_notify_q) {
notify = (struct bfa_ioc_hbfail_notify_s *)qe;
notify->cbfn(notify->cbarg);
}
/**
* Flush any queued up mailbox requests.
*/
bfa_ioc_mbox_hbfail(ioc);
bfa_ioc_aen_post(ioc, BFA_IOC_AEN_HBFAIL);
/**
* Trigger auto-recovery after a delay.
*/
if (ioc->auto_recover) {
bfa_timer_begin(ioc->timer_mod, &ioc->ioc_timer,
bfa_ioc_timeout, ioc, BFA_IOC_TOV_RECOVER);
}
}
/**
* IOC heartbeat failure.
*/
static void
bfa_ioc_sm_hbfail(struct bfa_ioc_s *ioc, enum ioc_event event)
{
bfa_trc(ioc, event);
switch (event) {
case IOC_E_ENABLE:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
break;
case IOC_E_DISABLE:
if (ioc->auto_recover)
bfa_ioc_timer_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
case IOC_E_TIMEOUT:
bfa_fsm_set_state(ioc, bfa_ioc_sm_semwait);
break;
case IOC_E_FWREADY:
/**
* Recovery is already initiated by other function.
*/
break;
case IOC_E_HWERROR:
/*
* HB failure notification, ignore.
*/
break;
default:
bfa_sm_fault(ioc, event);
}
}
/**
* bfa_ioc_pvt BFA IOC private functions
*/
static void
bfa_ioc_disable_comp(struct bfa_ioc_s *ioc)
{
struct list_head *qe;
struct bfa_ioc_hbfail_notify_s *notify;
ioc->cbfn->disable_cbfn(ioc->bfa);
/**
* Notify common modules registered for notification.
*/
list_for_each(qe, &ioc->hb_notify_q) {
notify = (struct bfa_ioc_hbfail_notify_s *)qe;
notify->cbfn(notify->cbarg);
}
}
void
bfa_ioc_sem_timeout(void *ioc_arg)
{
struct bfa_ioc_s *ioc = (struct bfa_ioc_s *)ioc_arg;
bfa_ioc_hw_sem_get(ioc);
}
bfa_boolean_t
bfa_ioc_sem_get(bfa_os_addr_t sem_reg)
{
u32 r32;
int cnt = 0;
#define BFA_SEM_SPINCNT 3000
r32 = bfa_reg_read(sem_reg);
while (r32 && (cnt < BFA_SEM_SPINCNT)) {
cnt++;
bfa_os_udelay(2);
r32 = bfa_reg_read(sem_reg);
}
if (r32 == 0)
return BFA_TRUE;
bfa_assert(cnt < BFA_SEM_SPINCNT);
return BFA_FALSE;
}
void
bfa_ioc_sem_release(bfa_os_addr_t sem_reg)
{
bfa_reg_write(sem_reg, 1);
}
static void
bfa_ioc_hw_sem_get(struct bfa_ioc_s *ioc)
{
u32 r32;
/**
* First read to the semaphore register will return 0, subsequent reads
* will return 1. Semaphore is released by writing 1 to the register
*/
r32 = bfa_reg_read(ioc->ioc_regs.ioc_sem_reg);
if (r32 == 0) {
bfa_fsm_send_event(ioc, IOC_E_SEMLOCKED);
return;
}
bfa_timer_begin(ioc->timer_mod, &ioc->sem_timer, bfa_ioc_sem_timeout,
ioc, BFA_IOC_HWSEM_TOV);
}
void
bfa_ioc_hw_sem_release(struct bfa_ioc_s *ioc)
{
bfa_reg_write(ioc->ioc_regs.ioc_sem_reg, 1);
}
static void
bfa_ioc_hw_sem_get_cancel(struct bfa_ioc_s *ioc)
{
bfa_timer_stop(&ioc->sem_timer);
}
/**
* Initialize LPU local memory (aka secondary memory / SRAM)
*/
static void
bfa_ioc_lmem_init(struct bfa_ioc_s *ioc)
{
u32 pss_ctl;
int i;
#define PSS_LMEM_INIT_TIME 10000
pss_ctl = bfa_reg_read(ioc->ioc_regs.pss_ctl_reg);
pss_ctl &= ~__PSS_LMEM_RESET;
pss_ctl |= __PSS_LMEM_INIT_EN;
pss_ctl |= __PSS_I2C_CLK_DIV(3UL); /* i2c workaround 12.5khz clock */
bfa_reg_write(ioc->ioc_regs.pss_ctl_reg, pss_ctl);
/**
* wait for memory initialization to be complete
*/
i = 0;
do {
pss_ctl = bfa_reg_read(ioc->ioc_regs.pss_ctl_reg);
i++;
} while (!(pss_ctl & __PSS_LMEM_INIT_DONE) && (i < PSS_LMEM_INIT_TIME));
/**
* If memory initialization is not successful, IOC timeout will catch
* such failures.
*/
bfa_assert(pss_ctl & __PSS_LMEM_INIT_DONE);
bfa_trc(ioc, pss_ctl);
pss_ctl &= ~(__PSS_LMEM_INIT_DONE | __PSS_LMEM_INIT_EN);
bfa_reg_write(ioc->ioc_regs.pss_ctl_reg, pss_ctl);
}
static void
bfa_ioc_lpu_start(struct bfa_ioc_s *ioc)
{
u32 pss_ctl;
/**
* Take processor out of reset.
*/
pss_ctl = bfa_reg_read(ioc->ioc_regs.pss_ctl_reg);
pss_ctl &= ~__PSS_LPU0_RESET;
bfa_reg_write(ioc->ioc_regs.pss_ctl_reg, pss_ctl);
}
static void
bfa_ioc_lpu_stop(struct bfa_ioc_s *ioc)
{
u32 pss_ctl;
/**
* Put processors in reset.
*/
pss_ctl = bfa_reg_read(ioc->ioc_regs.pss_ctl_reg);
pss_ctl |= (__PSS_LPU0_RESET | __PSS_LPU1_RESET);
bfa_reg_write(ioc->ioc_regs.pss_ctl_reg, pss_ctl);
}
/**
* Get driver and firmware versions.
*/
void
bfa_ioc_fwver_get(struct bfa_ioc_s *ioc, struct bfi_ioc_image_hdr_s *fwhdr)
{
u32 pgnum, pgoff;
u32 loff = 0;
int i;
u32 *fwsig = (u32 *) fwhdr;
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
pgoff = bfa_ioc_smem_pgoff(ioc, loff);
bfa_reg_write(ioc->ioc_regs.host_page_num_fn, pgnum);
for (i = 0; i < (sizeof(struct bfi_ioc_image_hdr_s) / sizeof(u32));
i++) {
fwsig[i] = bfa_mem_read(ioc->ioc_regs.smem_page_start, loff);
loff += sizeof(u32);
}
}
/**
* Returns TRUE if same.
*/
bfa_boolean_t
bfa_ioc_fwver_cmp(struct bfa_ioc_s *ioc, struct bfi_ioc_image_hdr_s *fwhdr)
{
struct bfi_ioc_image_hdr_s *drv_fwhdr;
int i;
drv_fwhdr =
(struct bfi_ioc_image_hdr_s *)bfa_ioc_fwimg_get_chunk(ioc, 0);
for (i = 0; i < BFI_IOC_MD5SUM_SZ; i++) {
if (fwhdr->md5sum[i] != drv_fwhdr->md5sum[i]) {
bfa_trc(ioc, i);
bfa_trc(ioc, fwhdr->md5sum[i]);
bfa_trc(ioc, drv_fwhdr->md5sum[i]);
return BFA_FALSE;
}
}
bfa_trc(ioc, fwhdr->md5sum[0]);
return BFA_TRUE;
}
/**
* Return true if current running version is valid. Firmware signature and
* execution context (driver/bios) must match.
*/
static bfa_boolean_t
bfa_ioc_fwver_valid(struct bfa_ioc_s *ioc)
{
struct bfi_ioc_image_hdr_s fwhdr, *drv_fwhdr;
/**
* If bios/efi boot (flash based) -- return true
*/
if (bfa_ioc_fwimg_get_size(ioc) < BFA_IOC_FWIMG_MINSZ)
return BFA_TRUE;
bfa_ioc_fwver_get(ioc, &fwhdr);
drv_fwhdr =
(struct bfi_ioc_image_hdr_s *)bfa_ioc_fwimg_get_chunk(ioc, 0);
if (fwhdr.signature != drv_fwhdr->signature) {
bfa_trc(ioc, fwhdr.signature);
bfa_trc(ioc, drv_fwhdr->signature);
return BFA_FALSE;
}
if (fwhdr.exec != drv_fwhdr->exec) {
bfa_trc(ioc, fwhdr.exec);
bfa_trc(ioc, drv_fwhdr->exec);
return BFA_FALSE;
}
return bfa_ioc_fwver_cmp(ioc, &fwhdr);
}
/**
* Conditionally flush any pending message from firmware at start.
*/
static void
bfa_ioc_msgflush(struct bfa_ioc_s *ioc)
{
u32 r32;
r32 = bfa_reg_read(ioc->ioc_regs.lpu_mbox_cmd);
if (r32)
bfa_reg_write(ioc->ioc_regs.lpu_mbox_cmd, 1);
}
static void
bfa_ioc_hwinit(struct bfa_ioc_s *ioc, bfa_boolean_t force)
{
enum bfi_ioc_state ioc_fwstate;
bfa_boolean_t fwvalid;
ioc_fwstate = bfa_reg_read(ioc->ioc_regs.ioc_fwstate);
if (force)
ioc_fwstate = BFI_IOC_UNINIT;
bfa_trc(ioc, ioc_fwstate);
/**
* check if firmware is valid
*/
fwvalid = (ioc_fwstate == BFI_IOC_UNINIT) ?
BFA_FALSE : bfa_ioc_fwver_valid(ioc);
if (!fwvalid) {
bfa_ioc_boot(ioc, BFI_BOOT_TYPE_NORMAL, ioc->pcidev.device_id);
return;
}
/**
* If hardware initialization is in progress (initialized by other IOC),
* just wait for an initialization completion interrupt.
*/
if (ioc_fwstate == BFI_IOC_INITING) {
bfa_trc(ioc, ioc_fwstate);
ioc->cbfn->reset_cbfn(ioc->bfa);
return;
}
/**
* If IOC function is disabled and firmware version is same,
* just re-enable IOC.
*/
if (ioc_fwstate == BFI_IOC_DISABLED || ioc_fwstate == BFI_IOC_OP) {
bfa_trc(ioc, ioc_fwstate);
/**
* When using MSI-X any pending firmware ready event should
* be flushed. Otherwise MSI-X interrupts are not delivered.
*/
bfa_ioc_msgflush(ioc);
ioc->cbfn->reset_cbfn(ioc->bfa);
bfa_fsm_send_event(ioc, IOC_E_FWREADY);
return;
}
/**
* Initialize the h/w for any other states.
*/
bfa_ioc_boot(ioc, BFI_BOOT_TYPE_NORMAL, ioc->pcidev.device_id);
}
static void
bfa_ioc_timeout(void *ioc_arg)
{
struct bfa_ioc_s *ioc = (struct bfa_ioc_s *)ioc_arg;
bfa_trc(ioc, 0);
bfa_fsm_send_event(ioc, IOC_E_TIMEOUT);
}
void
bfa_ioc_mbox_send(struct bfa_ioc_s *ioc, void *ioc_msg, int len)
{
u32 *msgp = (u32 *) ioc_msg;
u32 i;
bfa_trc(ioc, msgp[0]);
bfa_trc(ioc, len);
bfa_assert(len <= BFI_IOC_MSGLEN_MAX);
/*
* first write msg to mailbox registers
*/
for (i = 0; i < len / sizeof(u32); i++)
bfa_reg_write(ioc->ioc_regs.hfn_mbox + i * sizeof(u32),
bfa_os_wtole(msgp[i]));
for (; i < BFI_IOC_MSGLEN_MAX / sizeof(u32); i++)
bfa_reg_write(ioc->ioc_regs.hfn_mbox + i * sizeof(u32), 0);
/*
* write 1 to mailbox CMD to trigger LPU event
*/
bfa_reg_write(ioc->ioc_regs.hfn_mbox_cmd, 1);
(void)bfa_reg_read(ioc->ioc_regs.hfn_mbox_cmd);
}
static void
bfa_ioc_send_enable(struct bfa_ioc_s *ioc)
{
struct bfi_ioc_ctrl_req_s enable_req;
bfi_h2i_set(enable_req.mh, BFI_MC_IOC, BFI_IOC_H2I_ENABLE_REQ,
bfa_ioc_portid(ioc));
enable_req.ioc_class = ioc->ioc_mc;
bfa_ioc_mbox_send(ioc, &enable_req, sizeof(struct bfi_ioc_ctrl_req_s));
}
static void
bfa_ioc_send_disable(struct bfa_ioc_s *ioc)
{
struct bfi_ioc_ctrl_req_s disable_req;
bfi_h2i_set(disable_req.mh, BFI_MC_IOC, BFI_IOC_H2I_DISABLE_REQ,
bfa_ioc_portid(ioc));
bfa_ioc_mbox_send(ioc, &disable_req, sizeof(struct bfi_ioc_ctrl_req_s));
}
static void
bfa_ioc_send_getattr(struct bfa_ioc_s *ioc)
{
struct bfi_ioc_getattr_req_s attr_req;
bfi_h2i_set(attr_req.mh, BFI_MC_IOC, BFI_IOC_H2I_GETATTR_REQ,
bfa_ioc_portid(ioc));
bfa_dma_be_addr_set(attr_req.attr_addr, ioc->attr_dma.pa);
bfa_ioc_mbox_send(ioc, &attr_req, sizeof(attr_req));
}
static void
bfa_ioc_hb_check(void *cbarg)
{
struct bfa_ioc_s *ioc = cbarg;
u32 hb_count;
hb_count = bfa_reg_read(ioc->ioc_regs.heartbeat);
if (ioc->hb_count == hb_count) {
bfa_log(ioc->logm, BFA_LOG_HAL_HEARTBEAT_FAILURE,
hb_count);
bfa_ioc_recover(ioc);
return;
} else {
ioc->hb_count = hb_count;
}
bfa_ioc_mbox_poll(ioc);
bfa_timer_begin(ioc->timer_mod, &ioc->ioc_timer, bfa_ioc_hb_check,
ioc, BFA_IOC_HB_TOV);
}
static void
bfa_ioc_hb_monitor(struct bfa_ioc_s *ioc)
{
ioc->hb_count = bfa_reg_read(ioc->ioc_regs.heartbeat);
bfa_timer_begin(ioc->timer_mod, &ioc->ioc_timer, bfa_ioc_hb_check, ioc,
BFA_IOC_HB_TOV);
}
static void
bfa_ioc_hb_stop(struct bfa_ioc_s *ioc)
{
bfa_timer_stop(&ioc->ioc_timer);
}
/**
* Initiate a full firmware download.
*/
static void
bfa_ioc_download_fw(struct bfa_ioc_s *ioc, u32 boot_type,
u32 boot_param)
{
u32 *fwimg;
u32 pgnum, pgoff;
u32 loff = 0;
u32 chunkno = 0;
u32 i;
/**
* Initialize LMEM first before code download
*/
bfa_ioc_lmem_init(ioc);
/**
* Flash based firmware boot
*/
bfa_trc(ioc, bfa_ioc_fwimg_get_size(ioc));
if (bfa_ioc_fwimg_get_size(ioc) < BFA_IOC_FWIMG_MINSZ)
boot_type = BFI_BOOT_TYPE_FLASH;
fwimg = bfa_ioc_fwimg_get_chunk(ioc, chunkno);
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
pgoff = bfa_ioc_smem_pgoff(ioc, loff);
bfa_reg_write(ioc->ioc_regs.host_page_num_fn, pgnum);
for (i = 0; i < bfa_ioc_fwimg_get_size(ioc); i++) {
if (BFA_IOC_FLASH_CHUNK_NO(i) != chunkno) {
chunkno = BFA_IOC_FLASH_CHUNK_NO(i);
fwimg = bfa_ioc_fwimg_get_chunk(ioc,
BFA_IOC_FLASH_CHUNK_ADDR(chunkno));
}
/**
* write smem
*/
bfa_mem_write(ioc->ioc_regs.smem_page_start, loff,
fwimg[BFA_IOC_FLASH_OFFSET_IN_CHUNK(i)]);
loff += sizeof(u32);
/**
* handle page offset wrap around
*/
loff = PSS_SMEM_PGOFF(loff);
if (loff == 0) {
pgnum++;
bfa_reg_write(ioc->ioc_regs.host_page_num_fn, pgnum);
}
}
bfa_reg_write(ioc->ioc_regs.host_page_num_fn,
bfa_ioc_smem_pgnum(ioc, 0));
/*
* Set boot type and boot param at the end.
*/
bfa_mem_write(ioc->ioc_regs.smem_page_start, BFI_BOOT_TYPE_OFF,
bfa_os_swap32(boot_type));
bfa_mem_write(ioc->ioc_regs.smem_page_start, BFI_BOOT_PARAM_OFF,
bfa_os_swap32(boot_param));
}
static void
bfa_ioc_reset(struct bfa_ioc_s *ioc, bfa_boolean_t force)
{
bfa_ioc_hwinit(ioc, force);
}
/**
* Update BFA configuration from firmware configuration.
*/
static void
bfa_ioc_getattr_reply(struct bfa_ioc_s *ioc)
{
struct bfi_ioc_attr_s *attr = ioc->attr;
attr->adapter_prop = bfa_os_ntohl(attr->adapter_prop);
attr->maxfrsize = bfa_os_ntohs(attr->maxfrsize);
bfa_fsm_send_event(ioc, IOC_E_FWRSP_GETATTR);
}
/**
* Attach time initialization of mbox logic.
*/
static void
bfa_ioc_mbox_attach(struct bfa_ioc_s *ioc)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
int mc;
INIT_LIST_HEAD(&mod->cmd_q);
for (mc = 0; mc < BFI_MC_MAX; mc++) {
mod->mbhdlr[mc].cbfn = NULL;
mod->mbhdlr[mc].cbarg = ioc->bfa;
}
}
/**
* Mbox poll timer -- restarts any pending mailbox requests.
*/
static void
bfa_ioc_mbox_poll(struct bfa_ioc_s *ioc)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
struct bfa_mbox_cmd_s *cmd;
u32 stat;
/**
* If no command pending, do nothing
*/
if (list_empty(&mod->cmd_q))
return;
/**
* If previous command is not yet fetched by firmware, do nothing
*/
stat = bfa_reg_read(ioc->ioc_regs.hfn_mbox_cmd);
if (stat)
return;
/**
* Enqueue command to firmware.
*/
bfa_q_deq(&mod->cmd_q, &cmd);
bfa_ioc_mbox_send(ioc, cmd->msg, sizeof(cmd->msg));
}
/**
* Cleanup any pending requests.
*/
static void
bfa_ioc_mbox_hbfail(struct bfa_ioc_s *ioc)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
struct bfa_mbox_cmd_s *cmd;
while (!list_empty(&mod->cmd_q))
bfa_q_deq(&mod->cmd_q, &cmd);
}
/**
* bfa_ioc_public
*/
/**
* Interface used by diag module to do firmware boot with memory test
* as the entry vector.
*/
void
bfa_ioc_boot(struct bfa_ioc_s *ioc, u32 boot_type, u32 boot_param)
{
bfa_os_addr_t rb;
bfa_ioc_stats(ioc, ioc_boots);
if (bfa_ioc_pll_init(ioc) != BFA_STATUS_OK)
return;
/**
* Initialize IOC state of all functions on a chip reset.
*/
rb = ioc->pcidev.pci_bar_kva;
if (boot_param == BFI_BOOT_TYPE_MEMTEST) {
bfa_reg_write((rb + BFA_IOC0_STATE_REG), BFI_IOC_MEMTEST);
bfa_reg_write((rb + BFA_IOC1_STATE_REG), BFI_IOC_MEMTEST);
} else {
bfa_reg_write((rb + BFA_IOC0_STATE_REG), BFI_IOC_INITING);
bfa_reg_write((rb + BFA_IOC1_STATE_REG), BFI_IOC_INITING);
}
bfa_ioc_download_fw(ioc, boot_type, boot_param);
/**
* Enable interrupts just before starting LPU
*/
ioc->cbfn->reset_cbfn(ioc->bfa);
bfa_ioc_lpu_start(ioc);
}
/**
* Enable/disable IOC failure auto recovery.
*/
void
bfa_ioc_auto_recover(bfa_boolean_t auto_recover)
{
bfa_auto_recover = auto_recover;
}
bfa_boolean_t
bfa_ioc_is_operational(struct bfa_ioc_s *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_op);
}
void
bfa_ioc_msgget(struct bfa_ioc_s *ioc, void *mbmsg)
{
u32 *msgp = mbmsg;
u32 r32;
int i;
/**
* read the MBOX msg
*/
for (i = 0; i < (sizeof(union bfi_ioc_i2h_msg_u) / sizeof(u32));
i++) {
r32 = bfa_reg_read(ioc->ioc_regs.lpu_mbox +
i * sizeof(u32));
msgp[i] = bfa_os_htonl(r32);
}
/**
* turn off mailbox interrupt by clearing mailbox status
*/
bfa_reg_write(ioc->ioc_regs.lpu_mbox_cmd, 1);
bfa_reg_read(ioc->ioc_regs.lpu_mbox_cmd);
}
void
bfa_ioc_isr(struct bfa_ioc_s *ioc, struct bfi_mbmsg_s *m)
{
union bfi_ioc_i2h_msg_u *msg;
msg = (union bfi_ioc_i2h_msg_u *)m;
bfa_ioc_stats(ioc, ioc_isrs);
switch (msg->mh.msg_id) {
case BFI_IOC_I2H_HBEAT:
break;
case BFI_IOC_I2H_READY_EVENT:
bfa_fsm_send_event(ioc, IOC_E_FWREADY);
break;
case BFI_IOC_I2H_ENABLE_REPLY:
bfa_fsm_send_event(ioc, IOC_E_FWRSP_ENABLE);
break;
case BFI_IOC_I2H_DISABLE_REPLY:
bfa_fsm_send_event(ioc, IOC_E_FWRSP_DISABLE);
break;
case BFI_IOC_I2H_GETATTR_REPLY:
bfa_ioc_getattr_reply(ioc);
break;
default:
bfa_trc(ioc, msg->mh.msg_id);
bfa_assert(0);
}
}
/**
* IOC attach time initialization and setup.
*
* @param[in] ioc memory for IOC
* @param[in] bfa driver instance structure
* @param[in] trcmod kernel trace module
* @param[in] aen kernel aen event module
* @param[in] logm kernel logging module
*/
void
bfa_ioc_attach(struct bfa_ioc_s *ioc, void *bfa, struct bfa_ioc_cbfn_s *cbfn,
struct bfa_timer_mod_s *timer_mod, struct bfa_trc_mod_s *trcmod,
struct bfa_aen_s *aen, struct bfa_log_mod_s *logm)
{
ioc->bfa = bfa;
ioc->cbfn = cbfn;
ioc->timer_mod = timer_mod;
ioc->trcmod = trcmod;
ioc->aen = aen;
ioc->logm = logm;
ioc->fcmode = BFA_FALSE;
ioc->pllinit = BFA_FALSE;
ioc->dbg_fwsave_once = BFA_TRUE;
bfa_ioc_mbox_attach(ioc);
INIT_LIST_HEAD(&ioc->hb_notify_q);
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
}
/**
* Driver detach time IOC cleanup.
*/
void
bfa_ioc_detach(struct bfa_ioc_s *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_DETACH);
}
/**
* Setup IOC PCI properties.
*
* @param[in] pcidev PCI device information for this IOC
*/
void
bfa_ioc_pci_init(struct bfa_ioc_s *ioc, struct bfa_pcidev_s *pcidev,
enum bfi_mclass mc)
{
ioc->ioc_mc = mc;
ioc->pcidev = *pcidev;
ioc->ctdev = (ioc->pcidev.device_id == BFA_PCI_DEVICE_ID_CT);
ioc->cna = ioc->ctdev && !ioc->fcmode;
/**
* Set asic specific interfaces. See bfa_ioc_cb.c and bfa_ioc_ct.c
*/
if (ioc->ctdev)
bfa_ioc_set_ct_hwif(ioc);
else
bfa_ioc_set_cb_hwif(ioc);
bfa_ioc_map_port(ioc);
bfa_ioc_reg_init(ioc);
}
/**
* Initialize IOC dma memory
*
* @param[in] dm_kva kernel virtual address of IOC dma memory
* @param[in] dm_pa physical address of IOC dma memory
*/
void
bfa_ioc_mem_claim(struct bfa_ioc_s *ioc, u8 *dm_kva, u64 dm_pa)
{
/**
* dma memory for firmware attribute
*/
ioc->attr_dma.kva = dm_kva;
ioc->attr_dma.pa = dm_pa;
ioc->attr = (struct bfi_ioc_attr_s *)dm_kva;
}
/**
* Return size of dma memory required.
*/
u32
bfa_ioc_meminfo(void)
{
return BFA_ROUNDUP(sizeof(struct bfi_ioc_attr_s), BFA_DMA_ALIGN_SZ);
}
void
bfa_ioc_enable(struct bfa_ioc_s *ioc)
{
bfa_ioc_stats(ioc, ioc_enables);
ioc->dbg_fwsave_once = BFA_TRUE;
bfa_fsm_send_event(ioc, IOC_E_ENABLE);
}
void
bfa_ioc_disable(struct bfa_ioc_s *ioc)
{
bfa_ioc_stats(ioc, ioc_disables);
bfa_fsm_send_event(ioc, IOC_E_DISABLE);
}
/**
* Returns memory required for saving firmware trace in case of crash.
* Driver must call this interface to allocate memory required for
* automatic saving of firmware trace. Driver should call
* bfa_ioc_debug_memclaim() right after bfa_ioc_attach() to setup this
* trace memory.
*/
int
bfa_ioc_debug_trcsz(bfa_boolean_t auto_recover)
{
return (auto_recover) ? BFA_DBG_FWTRC_LEN : 0;
}
/**
* Initialize memory for saving firmware trace. Driver must initialize
* trace memory before call bfa_ioc_enable().
*/
void
bfa_ioc_debug_memclaim(struct bfa_ioc_s *ioc, void *dbg_fwsave)
{
ioc->dbg_fwsave = dbg_fwsave;
ioc->dbg_fwsave_len = bfa_ioc_debug_trcsz(ioc->auto_recover);
}
u32
bfa_ioc_smem_pgnum(struct bfa_ioc_s *ioc, u32 fmaddr)
{
return PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, fmaddr);
}
u32
bfa_ioc_smem_pgoff(struct bfa_ioc_s *ioc, u32 fmaddr)
{
return PSS_SMEM_PGOFF(fmaddr);
}
/**
* Register mailbox message handler functions
*
* @param[in] ioc IOC instance
* @param[in] mcfuncs message class handler functions
*/
void
bfa_ioc_mbox_register(struct bfa_ioc_s *ioc, bfa_ioc_mbox_mcfunc_t *mcfuncs)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
int mc;
for (mc = 0; mc < BFI_MC_MAX; mc++)
mod->mbhdlr[mc].cbfn = mcfuncs[mc];
}
/**
* Register mailbox message handler function, to be called by common modules
*/
void
bfa_ioc_mbox_regisr(struct bfa_ioc_s *ioc, enum bfi_mclass mc,
bfa_ioc_mbox_mcfunc_t cbfn, void *cbarg)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
mod->mbhdlr[mc].cbfn = cbfn;
mod->mbhdlr[mc].cbarg = cbarg;
}
/**
* Queue a mailbox command request to firmware. Waits if mailbox is busy.
* Responsibility of caller to serialize
*
* @param[in] ioc IOC instance
* @param[i] cmd Mailbox command
*/
void
bfa_ioc_mbox_queue(struct bfa_ioc_s *ioc, struct bfa_mbox_cmd_s *cmd)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
u32 stat;
/**
* If a previous command is pending, queue new command
*/
if (!list_empty(&mod->cmd_q)) {
list_add_tail(&cmd->qe, &mod->cmd_q);
return;
}
/**
* If mailbox is busy, queue command for poll timer
*/
stat = bfa_reg_read(ioc->ioc_regs.hfn_mbox_cmd);
if (stat) {
list_add_tail(&cmd->qe, &mod->cmd_q);
return;
}
/**
* mailbox is free -- queue command to firmware
*/
bfa_ioc_mbox_send(ioc, cmd->msg, sizeof(cmd->msg));
}
/**
* Handle mailbox interrupts
*/
void
bfa_ioc_mbox_isr(struct bfa_ioc_s *ioc)
{
struct bfa_ioc_mbox_mod_s *mod = &ioc->mbox_mod;
struct bfi_mbmsg_s m;
int mc;
bfa_ioc_msgget(ioc, &m);
/**
* Treat IOC message class as special.
*/
mc = m.mh.msg_class;
if (mc == BFI_MC_IOC) {
bfa_ioc_isr(ioc, &m);
return;
}
if ((mc > BFI_MC_MAX) || (mod->mbhdlr[mc].cbfn == NULL))
return;
mod->mbhdlr[mc].cbfn(mod->mbhdlr[mc].cbarg, &m);
}
void
bfa_ioc_error_isr(struct bfa_ioc_s *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_HWERROR);
}
#ifndef BFA_BIOS_BUILD
/**
* return true if IOC is disabled
*/
bfa_boolean_t
bfa_ioc_is_disabled(struct bfa_ioc_s *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabling)
|| bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabled);
}
/**
* return true if IOC firmware is different.
*/
bfa_boolean_t
bfa_ioc_fw_mismatch(struct bfa_ioc_s *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_reset)
|| bfa_fsm_cmp_state(ioc, bfa_ioc_sm_fwcheck)
|| bfa_fsm_cmp_state(ioc, bfa_ioc_sm_mismatch);
}
#define bfa_ioc_state_disabled(__sm) \
(((__sm) == BFI_IOC_UNINIT) || \
((__sm) == BFI_IOC_INITING) || \
((__sm) == BFI_IOC_HWINIT) || \
((__sm) == BFI_IOC_DISABLED) || \
((__sm) == BFI_IOC_FAIL) || \
((__sm) == BFI_IOC_CFG_DISABLED))
/**
* Check if adapter is disabled -- both IOCs should be in a disabled
* state.
*/
bfa_boolean_t
bfa_ioc_adapter_is_disabled(struct bfa_ioc_s *ioc)
{
u32 ioc_state;
bfa_os_addr_t rb = ioc->pcidev.pci_bar_kva;
if (!bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabled))
return BFA_FALSE;
ioc_state = bfa_reg_read(rb + BFA_IOC0_STATE_REG);
if (!bfa_ioc_state_disabled(ioc_state))
return BFA_FALSE;
ioc_state = bfa_reg_read(rb + BFA_IOC1_STATE_REG);
if (!bfa_ioc_state_disabled(ioc_state))
return BFA_FALSE;
return BFA_TRUE;
}
/**
* Add to IOC heartbeat failure notification queue. To be used by common
* modules such as
*/
void
bfa_ioc_hbfail_register(struct bfa_ioc_s *ioc,
struct bfa_ioc_hbfail_notify_s *notify)
{
list_add_tail(¬ify->qe, &ioc->hb_notify_q);
}
#define BFA_MFG_NAME "Brocade"
void
bfa_ioc_get_adapter_attr(struct bfa_ioc_s *ioc,
struct bfa_adapter_attr_s *ad_attr)
{
struct bfi_ioc_attr_s *ioc_attr;
ioc_attr = ioc->attr;
bfa_ioc_get_adapter_serial_num(ioc, ad_attr->serial_num);
bfa_ioc_get_adapter_fw_ver(ioc, ad_attr->fw_ver);
bfa_ioc_get_adapter_optrom_ver(ioc, ad_attr->optrom_ver);
bfa_ioc_get_adapter_manufacturer(ioc, ad_attr->manufacturer);
bfa_os_memcpy(&ad_attr->vpd, &ioc_attr->vpd,
sizeof(struct bfa_mfg_vpd_s));
ad_attr->nports = bfa_ioc_get_nports(ioc);
ad_attr->max_speed = bfa_ioc_speed_sup(ioc);
bfa_ioc_get_adapter_model(ioc, ad_attr->model);
/* For now, model descr uses same model string */
bfa_ioc_get_adapter_model(ioc, ad_attr->model_descr);
if (BFI_ADAPTER_IS_SPECIAL(ioc_attr->adapter_prop))
ad_attr->prototype = 1;
else
ad_attr->prototype = 0;
ad_attr->pwwn = bfa_ioc_get_pwwn(ioc);
ad_attr->mac = bfa_ioc_get_mac(ioc);
ad_attr->pcie_gen = ioc_attr->pcie_gen;
ad_attr->pcie_lanes = ioc_attr->pcie_lanes;
ad_attr->pcie_lanes_orig = ioc_attr->pcie_lanes_orig;
ad_attr->asic_rev = ioc_attr->asic_rev;
bfa_ioc_get_pci_chip_rev(ioc, ad_attr->hw_ver);
ad_attr->cna_capable = ioc->cna;
}
enum bfa_ioc_type_e
bfa_ioc_get_type(struct bfa_ioc_s *ioc)
{
if (!ioc->ctdev || ioc->fcmode)
return BFA_IOC_TYPE_FC;
else if (ioc->ioc_mc == BFI_MC_IOCFC)
return BFA_IOC_TYPE_FCoE;
else if (ioc->ioc_mc == BFI_MC_LL)
return BFA_IOC_TYPE_LL;
else {
bfa_assert(ioc->ioc_mc == BFI_MC_LL);
return BFA_IOC_TYPE_LL;
}
}
void
bfa_ioc_get_adapter_serial_num(struct bfa_ioc_s *ioc, char *serial_num)
{
bfa_os_memset((void *)serial_num, 0, BFA_ADAPTER_SERIAL_NUM_LEN);
bfa_os_memcpy((void *)serial_num,
(void *)ioc->attr->brcd_serialnum,
BFA_ADAPTER_SERIAL_NUM_LEN);
}
void
bfa_ioc_get_adapter_fw_ver(struct bfa_ioc_s *ioc, char *fw_ver)
{
bfa_os_memset((void *)fw_ver, 0, BFA_VERSION_LEN);
bfa_os_memcpy(fw_ver, ioc->attr->fw_version, BFA_VERSION_LEN);
}
void
bfa_ioc_get_pci_chip_rev(struct bfa_ioc_s *ioc, char *chip_rev)
{
bfa_assert(chip_rev);
bfa_os_memset((void *)chip_rev, 0, BFA_IOC_CHIP_REV_LEN);
chip_rev[0] = 'R';
chip_rev[1] = 'e';
chip_rev[2] = 'v';
chip_rev[3] = '-';
chip_rev[4] = ioc->attr->asic_rev;
chip_rev[5] = '\0';
}
void
bfa_ioc_get_adapter_optrom_ver(struct bfa_ioc_s *ioc, char *optrom_ver)
{
bfa_os_memset((void *)optrom_ver, 0, BFA_VERSION_LEN);
bfa_os_memcpy(optrom_ver, ioc->attr->optrom_version,
BFA_VERSION_LEN);
}
void
bfa_ioc_get_adapter_manufacturer(struct bfa_ioc_s *ioc, char *manufacturer)
{
bfa_os_memset((void *)manufacturer, 0, BFA_ADAPTER_MFG_NAME_LEN);
bfa_os_memcpy(manufacturer, BFA_MFG_NAME, BFA_ADAPTER_MFG_NAME_LEN);
}
void
bfa_ioc_get_adapter_model(struct bfa_ioc_s *ioc, char *model)
{
struct bfi_ioc_attr_s *ioc_attr;
u8 nports;
u8 max_speed;
bfa_assert(model);
bfa_os_memset((void *)model, 0, BFA_ADAPTER_MODEL_NAME_LEN);
ioc_attr = ioc->attr;
nports = bfa_ioc_get_nports(ioc);
max_speed = bfa_ioc_speed_sup(ioc);
/**
* model name
*/
if (max_speed == 10) {
strcpy(model, "BR-10?0");
model[5] = '0' + nports;
} else {
strcpy(model, "Brocade-??5");
model[8] = '0' + max_speed;
model[9] = '0' + nports;
}
}
enum bfa_ioc_state
bfa_ioc_get_state(struct bfa_ioc_s *ioc)
{
return bfa_sm_to_state(ioc_sm_table, ioc->fsm);
}
void
bfa_ioc_get_attr(struct bfa_ioc_s *ioc, struct bfa_ioc_attr_s *ioc_attr)
{
bfa_os_memset((void *)ioc_attr, 0, sizeof(struct bfa_ioc_attr_s));
ioc_attr->state = bfa_ioc_get_state(ioc);
ioc_attr->port_id = ioc->port_id;
ioc_attr->ioc_type = bfa_ioc_get_type(ioc);
bfa_ioc_get_adapter_attr(ioc, &ioc_attr->adapter_attr);
ioc_attr->pci_attr.device_id = ioc->pcidev.device_id;
ioc_attr->pci_attr.pcifn = ioc->pcidev.pci_func;
bfa_ioc_get_pci_chip_rev(ioc, ioc_attr->pci_attr.chip_rev);
}
/**
* hal_wwn_public
*/
wwn_t
bfa_ioc_get_pwwn(struct bfa_ioc_s *ioc)
{
union {
wwn_t wwn;
u8 byte[sizeof(wwn_t)];
}
w;
w.wwn = ioc->attr->mfg_wwn;
if (bfa_ioc_portid(ioc) == 1)
w.byte[7]++;
return w.wwn;
}
wwn_t
bfa_ioc_get_nwwn(struct bfa_ioc_s *ioc)
{
union {
wwn_t wwn;
u8 byte[sizeof(wwn_t)];
}
w;
w.wwn = ioc->attr->mfg_wwn;
if (bfa_ioc_portid(ioc) == 1)
w.byte[7]++;
w.byte[0] = 0x20;
return w.wwn;
}
wwn_t
bfa_ioc_get_wwn_naa5(struct bfa_ioc_s *ioc, u16 inst)
{
union {
wwn_t wwn;
u8 byte[sizeof(wwn_t)];
}
w , w5;
bfa_trc(ioc, inst);
w.wwn = ioc->attr->mfg_wwn;
w5.byte[0] = 0x50 | w.byte[2] >> 4;
w5.byte[1] = w.byte[2] << 4 | w.byte[3] >> 4;
w5.byte[2] = w.byte[3] << 4 | w.byte[4] >> 4;
w5.byte[3] = w.byte[4] << 4 | w.byte[5] >> 4;
w5.byte[4] = w.byte[5] << 4 | w.byte[6] >> 4;
w5.byte[5] = w.byte[6] << 4 | w.byte[7] >> 4;
w5.byte[6] = w.byte[7] << 4 | (inst & 0x0f00) >> 8;
w5.byte[7] = (inst & 0xff);
return w5.wwn;
}
u64
bfa_ioc_get_adid(struct bfa_ioc_s *ioc)
{
return ioc->attr->mfg_wwn;
}
mac_t
bfa_ioc_get_mac(struct bfa_ioc_s *ioc)
{
mac_t mac;
mac = ioc->attr->mfg_mac;
mac.mac[MAC_ADDRLEN - 1] += bfa_ioc_pcifn(ioc);
return mac;
}
void
bfa_ioc_set_fcmode(struct bfa_ioc_s *ioc)
{
ioc->fcmode = BFA_TRUE;
ioc->port_id = bfa_ioc_pcifn(ioc);
}
bfa_boolean_t
bfa_ioc_get_fcmode(struct bfa_ioc_s *ioc)
{
return ioc->fcmode || (ioc->pcidev.device_id != BFA_PCI_DEVICE_ID_CT);
}
/**
* Send AEN notification
*/
static void
bfa_ioc_aen_post(struct bfa_ioc_s *ioc, enum bfa_ioc_aen_event event)
{
union bfa_aen_data_u aen_data;
struct bfa_log_mod_s *logmod = ioc->logm;
s32 inst_num = 0;
enum bfa_ioc_type_e ioc_type;
bfa_log(logmod, BFA_LOG_CREATE_ID(BFA_AEN_CAT_IOC, event), inst_num);
memset(&aen_data.ioc.pwwn, 0, sizeof(aen_data.ioc.pwwn));
memset(&aen_data.ioc.mac, 0, sizeof(aen_data.ioc.mac));
ioc_type = bfa_ioc_get_type(ioc);
switch (ioc_type) {
case BFA_IOC_TYPE_FC:
aen_data.ioc.pwwn = bfa_ioc_get_pwwn(ioc);
break;
case BFA_IOC_TYPE_FCoE:
aen_data.ioc.pwwn = bfa_ioc_get_pwwn(ioc);
aen_data.ioc.mac = bfa_ioc_get_mac(ioc);
break;
case BFA_IOC_TYPE_LL:
aen_data.ioc.mac = bfa_ioc_get_mac(ioc);
break;
default:
bfa_assert(ioc_type == BFA_IOC_TYPE_FC);
break;
}
aen_data.ioc.ioc_type = ioc_type;
}
/**
* Retrieve saved firmware trace from a prior IOC failure.
*/
bfa_status_t
bfa_ioc_debug_fwsave(struct bfa_ioc_s *ioc, void *trcdata, int *trclen)
{
int tlen;
if (ioc->dbg_fwsave_len == 0)
return BFA_STATUS_ENOFSAVE;
tlen = *trclen;
if (tlen > ioc->dbg_fwsave_len)
tlen = ioc->dbg_fwsave_len;
bfa_os_memcpy(trcdata, ioc->dbg_fwsave, tlen);
*trclen = tlen;
return BFA_STATUS_OK;
}
/**
* Clear saved firmware trace
*/
void
bfa_ioc_debug_fwsave_clear(struct bfa_ioc_s *ioc)
{
ioc->dbg_fwsave_once = BFA_TRUE;
}
/**
* Retrieve saved firmware trace from a prior IOC failure.
*/
bfa_status_t
bfa_ioc_debug_fwtrc(struct bfa_ioc_s *ioc, void *trcdata, int *trclen)
{
u32 pgnum;
u32 loff = BFA_DBG_FWTRC_OFF(bfa_ioc_portid(ioc));
int i, tlen;
u32 *tbuf = trcdata, r32;
bfa_trc(ioc, *trclen);
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
loff = bfa_ioc_smem_pgoff(ioc, loff);
/*
* Hold semaphore to serialize pll init and fwtrc.
*/
if (BFA_FALSE == bfa_ioc_sem_get(ioc->ioc_regs.ioc_init_sem_reg))
return BFA_STATUS_FAILED;
bfa_reg_write(ioc->ioc_regs.host_page_num_fn, pgnum);
tlen = *trclen;
if (tlen > BFA_DBG_FWTRC_LEN)
tlen = BFA_DBG_FWTRC_LEN;
tlen /= sizeof(u32);
bfa_trc(ioc, tlen);
for (i = 0; i < tlen; i++) {
r32 = bfa_mem_read(ioc->ioc_regs.smem_page_start, loff);
tbuf[i] = bfa_os_ntohl(r32);
loff += sizeof(u32);
/**
* handle page offset wrap around
*/
loff = PSS_SMEM_PGOFF(loff);
if (loff == 0) {
pgnum++;
bfa_reg_write(ioc->ioc_regs.host_page_num_fn, pgnum);
}
}
bfa_reg_write(ioc->ioc_regs.host_page_num_fn,
bfa_ioc_smem_pgnum(ioc, 0));
/*
* release semaphore.
*/
bfa_ioc_sem_release(ioc->ioc_regs.ioc_init_sem_reg);
bfa_trc(ioc, pgnum);
*trclen = tlen * sizeof(u32);
return BFA_STATUS_OK;
}
/**
* Save firmware trace if configured.
*/
static void
bfa_ioc_debug_save(struct bfa_ioc_s *ioc)
{
int tlen;
if (ioc->dbg_fwsave_len) {
tlen = ioc->dbg_fwsave_len;
bfa_ioc_debug_fwtrc(ioc, ioc->dbg_fwsave, &tlen);
}
}
/**
* Firmware failure detected. Start recovery actions.
*/
static void
bfa_ioc_recover(struct bfa_ioc_s *ioc)
{
if (ioc->dbg_fwsave_once) {
ioc->dbg_fwsave_once = BFA_FALSE;
bfa_ioc_debug_save(ioc);
}
bfa_ioc_stats(ioc, ioc_hbfails);
bfa_fsm_send_event(ioc, IOC_E_HBFAIL);
}
#else
static void
bfa_ioc_aen_post(struct bfa_ioc_s *ioc, enum bfa_ioc_aen_event event)
{
}
static void
bfa_ioc_recover(struct bfa_ioc_s *ioc)
{
bfa_assert(0);
}
#endif
| gpl-2.0 |
smipi1/elce2015-tiny-linux | drivers/video/fbdev/pmag-ba-fb.c | 1834 | 6626 | /*
* linux/drivers/video/pmag-ba-fb.c
*
* PMAG-BA TURBOchannel Color Frame Buffer (CFB) card support,
* derived from:
* "HP300 Topcat framebuffer support (derived from macfb of all things)
* Phil Blundell <philb@gnu.org> 1998", the original code can be
* found in the file hpfb.c in the same directory.
*
* Based on digital document:
* "PMAG-BA TURBOchannel Color Frame Buffer
* Functional Specification", Revision 1.2, August 27, 1990
*
* DECstation related code Copyright (C) 1999, 2000, 2001 by
* Michael Engel <engel@unix-ag.org>,
* Karsten Merker <merker@linuxtag.org> and
* Harald Koerfgen.
* Copyright (c) 2005, 2006 Maciej W. Rozycki
* Copyright (c) 2005 James Simmons
*
* 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/compiler.h>
#include <linux/errno.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/tc.h>
#include <linux/types.h>
#include <asm/io.h>
#include <video/pmag-ba-fb.h>
struct pmagbafb_par {
volatile void __iomem *mmio;
volatile u32 __iomem *dac;
};
static struct fb_var_screeninfo pmagbafb_defined = {
.xres = 1024,
.yres = 864,
.xres_virtual = 1024,
.yres_virtual = 864,
.bits_per_pixel = 8,
.red.length = 8,
.green.length = 8,
.blue.length = 8,
.activate = FB_ACTIVATE_NOW,
.height = -1,
.width = -1,
.accel_flags = FB_ACCEL_NONE,
.pixclock = 14452,
.left_margin = 116,
.right_margin = 12,
.upper_margin = 34,
.lower_margin = 12,
.hsync_len = 128,
.vsync_len = 3,
.sync = FB_SYNC_ON_GREEN,
.vmode = FB_VMODE_NONINTERLACED,
};
static struct fb_fix_screeninfo pmagbafb_fix = {
.id = "PMAG-BA",
.smem_len = (1024 * 1024),
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_PSEUDOCOLOR,
.line_length = 1024,
.mmio_len = PMAG_BA_SIZE - PMAG_BA_BT459,
};
static inline void dac_write(struct pmagbafb_par *par, unsigned int reg, u8 v)
{
writeb(v, par->dac + reg / 4);
}
static inline u8 dac_read(struct pmagbafb_par *par, unsigned int reg)
{
return readb(par->dac + reg / 4);
}
/*
* Set the palette.
*/
static int pmagbafb_setcolreg(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
unsigned int transp, struct fb_info *info)
{
struct pmagbafb_par *par = info->par;
if (regno >= info->cmap.len)
return 1;
red >>= 8; /* The cmap fields are 16 bits */
green >>= 8; /* wide, but the hardware colormap */
blue >>= 8; /* registers are only 8 bits wide */
mb();
dac_write(par, BT459_ADDR_LO, regno);
dac_write(par, BT459_ADDR_HI, 0x00);
wmb();
dac_write(par, BT459_CMAP, red);
wmb();
dac_write(par, BT459_CMAP, green);
wmb();
dac_write(par, BT459_CMAP, blue);
return 0;
}
static struct fb_ops pmagbafb_ops = {
.owner = THIS_MODULE,
.fb_setcolreg = pmagbafb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
/*
* Turn the hardware cursor off.
*/
static void __init pmagbafb_erase_cursor(struct fb_info *info)
{
struct pmagbafb_par *par = info->par;
mb();
dac_write(par, BT459_ADDR_LO, 0x00);
dac_write(par, BT459_ADDR_HI, 0x03);
wmb();
dac_write(par, BT459_DATA, 0x00);
}
static int pmagbafb_probe(struct device *dev)
{
struct tc_dev *tdev = to_tc_dev(dev);
resource_size_t start, len;
struct fb_info *info;
struct pmagbafb_par *par;
int err;
info = framebuffer_alloc(sizeof(struct pmagbafb_par), dev);
if (!info) {
printk(KERN_ERR "%s: Cannot allocate memory\n", dev_name(dev));
return -ENOMEM;
}
par = info->par;
dev_set_drvdata(dev, info);
if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) {
printk(KERN_ERR "%s: Cannot allocate color map\n",
dev_name(dev));
err = -ENOMEM;
goto err_alloc;
}
info->fbops = &pmagbafb_ops;
info->fix = pmagbafb_fix;
info->var = pmagbafb_defined;
info->flags = FBINFO_DEFAULT;
/* Request the I/O MEM resource. */
start = tdev->resource.start;
len = tdev->resource.end - start + 1;
if (!request_mem_region(start, len, dev_name(dev))) {
printk(KERN_ERR "%s: Cannot reserve FB region\n",
dev_name(dev));
err = -EBUSY;
goto err_cmap;
}
/* MMIO mapping setup. */
info->fix.mmio_start = start;
par->mmio = ioremap_nocache(info->fix.mmio_start, info->fix.mmio_len);
if (!par->mmio) {
printk(KERN_ERR "%s: Cannot map MMIO\n", dev_name(dev));
err = -ENOMEM;
goto err_resource;
}
par->dac = par->mmio + PMAG_BA_BT459;
/* Frame buffer mapping setup. */
info->fix.smem_start = start + PMAG_BA_FBMEM;
info->screen_base = ioremap_nocache(info->fix.smem_start,
info->fix.smem_len);
if (!info->screen_base) {
printk(KERN_ERR "%s: Cannot map FB\n", dev_name(dev));
err = -ENOMEM;
goto err_mmio_map;
}
info->screen_size = info->fix.smem_len;
pmagbafb_erase_cursor(info);
err = register_framebuffer(info);
if (err < 0) {
printk(KERN_ERR "%s: Cannot register framebuffer\n",
dev_name(dev));
goto err_smem_map;
}
get_device(dev);
fb_info(info, "%s frame buffer device at %s\n",
info->fix.id, dev_name(dev));
return 0;
err_smem_map:
iounmap(info->screen_base);
err_mmio_map:
iounmap(par->mmio);
err_resource:
release_mem_region(start, len);
err_cmap:
fb_dealloc_cmap(&info->cmap);
err_alloc:
framebuffer_release(info);
return err;
}
static int __exit pmagbafb_remove(struct device *dev)
{
struct tc_dev *tdev = to_tc_dev(dev);
struct fb_info *info = dev_get_drvdata(dev);
struct pmagbafb_par *par = info->par;
resource_size_t start, len;
put_device(dev);
unregister_framebuffer(info);
iounmap(info->screen_base);
iounmap(par->mmio);
start = tdev->resource.start;
len = tdev->resource.end - start + 1;
release_mem_region(start, len);
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
return 0;
}
/*
* Initialize the framebuffer.
*/
static const struct tc_device_id pmagbafb_tc_table[] = {
{ "DEC ", "PMAG-BA " },
{ }
};
MODULE_DEVICE_TABLE(tc, pmagbafb_tc_table);
static struct tc_driver pmagbafb_driver = {
.id_table = pmagbafb_tc_table,
.driver = {
.name = "pmagbafb",
.bus = &tc_bus_type,
.probe = pmagbafb_probe,
.remove = __exit_p(pmagbafb_remove),
},
};
static int __init pmagbafb_init(void)
{
#ifndef MODULE
if (fb_get_options("pmagbafb", NULL))
return -ENXIO;
#endif
return tc_register_driver(&pmagbafb_driver);
}
static void __exit pmagbafb_exit(void)
{
tc_unregister_driver(&pmagbafb_driver);
}
module_init(pmagbafb_init);
module_exit(pmagbafb_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
djvoleur/S6_UniPR_BOI1 | drivers/staging/comedi/drivers/das16m1.c | 2090 | 19255 | /*
comedi/drivers/das16m1.c
CIO-DAS16/M1 driver
Author: Frank Mori Hess, based on code from the das16
driver.
Copyright (C) 2001 Frank Mori Hess <fmhess@users.sourceforge.net>
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************
*/
/*
Driver: das16m1
Description: CIO-DAS16/M1
Author: Frank Mori Hess <fmhess@users.sourceforge.net>
Devices: [Measurement Computing] CIO-DAS16/M1 (das16m1)
Status: works
This driver supports a single board - the CIO-DAS16/M1.
As far as I know, there are no other boards that have
the same register layout. Even the CIO-DAS16/M1/16 is
significantly different.
I was _barely_ able to reach the full 1 MHz capability
of this board, using a hard real-time interrupt
(set the TRIG_RT flag in your struct comedi_cmd and use
rtlinux or RTAI). The board can't do dma, so the bottleneck is
pulling the data across the ISA bus. I timed the interrupt
handler, and it took my computer ~470 microseconds to pull 512
samples from the board. So at 1 Mhz sampling rate,
expect your CPU to be spending almost all of its
time in the interrupt handler.
This board has some unusual restrictions for its channel/gain list. If the
list has 2 or more channels in it, then two conditions must be satisfied:
(1) - even/odd channels must appear at even/odd indices in the list
(2) - the list must have an even number of entries.
Options:
[0] - base io address
[1] - irq (optional, but you probably want it)
irq can be omitted, although the cmd interface will not work without it.
*/
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include "../comedidev.h"
#include "8255.h"
#include "8253.h"
#include "comedi_fc.h"
#define DAS16M1_SIZE 16
#define DAS16M1_SIZE2 8
#define DAS16M1_XTAL 100 /* 10 MHz master clock */
#define FIFO_SIZE 1024 /* 1024 sample fifo */
/*
CIO-DAS16_M1.pdf
"cio-das16/m1"
0 a/d bits 0-3, mux start 12 bit
1 a/d bits 4-11 unused
2 status control
3 di 4 bit do 4 bit
4 unused clear interrupt
5 interrupt, pacer
6 channel/gain queue address
7 channel/gain queue data
89ab 8254
cdef 8254
400 8255
404-407 8254
*/
#define DAS16M1_AI 0 /* 16-bit wide register */
#define AI_CHAN(x) ((x) & 0xf)
#define DAS16M1_CS 2
#define EXT_TRIG_BIT 0x1
#define OVRUN 0x20
#define IRQDATA 0x80
#define DAS16M1_DIO 3
#define DAS16M1_CLEAR_INTR 4
#define DAS16M1_INTR_CONTROL 5
#define EXT_PACER 0x2
#define INT_PACER 0x3
#define PACER_MASK 0x3
#define INTE 0x80
#define DAS16M1_QUEUE_ADDR 6
#define DAS16M1_QUEUE_DATA 7
#define Q_CHAN(x) ((x) & 0x7)
#define Q_RANGE(x) (((x) & 0xf) << 4)
#define UNIPOLAR 0x40
#define DAS16M1_8254_FIRST 0x8
#define DAS16M1_8254_FIRST_CNTRL 0xb
#define TOTAL_CLEAR 0x30
#define DAS16M1_8254_SECOND 0xc
#define DAS16M1_82C55 0x400
#define DAS16M1_8254_THIRD 0x404
static const struct comedi_lrange range_das16m1 = { 9,
{
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
BIP_RANGE(0.625),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
UNI_RANGE(1.25),
BIP_RANGE(10),
}
};
struct das16m1_private_struct {
unsigned int control_state;
volatile unsigned int adc_count; /* number of samples completed */
/* initial value in lower half of hardware conversion counter,
* needed to keep track of whether new count has been loaded into
* counter yet (loaded by first sample conversion) */
u16 initial_hw_count;
short ai_buffer[FIFO_SIZE];
unsigned int do_bits; /* saves status of digital output bits */
unsigned int divisor1; /* divides master clock to obtain conversion speed */
unsigned int divisor2; /* divides master clock to obtain conversion speed */
unsigned long extra_iobase;
};
static inline short munge_sample(short data)
{
return (data >> 4) & 0xfff;
}
static void munge_sample_array(short *array, unsigned int num_elements)
{
unsigned int i;
for (i = 0; i < num_elements; i++)
array[i] = munge_sample(array[i]);
}
static int das16m1_cmd_test(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
struct das16m1_private_struct *devpriv = dev->private;
unsigned int err = 0, tmp, i;
/* Step 1 : check if triggers are trivially valid */
err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_EXT);
err |= cfc_check_trigger_src(&cmd->scan_begin_src, TRIG_FOLLOW);
err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_TIMER | TRIG_EXT);
err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
if (err)
return 1;
/* Step 2a : make sure trigger sources are unique */
err |= cfc_check_trigger_is_unique(cmd->start_src);
err |= cfc_check_trigger_is_unique(cmd->convert_src);
err |= cfc_check_trigger_is_unique(cmd->stop_src);
/* Step 2b : and mutually compatible */
if (err)
return 2;
/* Step 3: check if arguments are trivially valid */
err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
if (cmd->scan_begin_src == TRIG_FOLLOW) /* internal trigger */
err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
if (cmd->convert_src == TRIG_TIMER)
err |= cfc_check_trigger_arg_min(&cmd->convert_arg, 1000);
err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
if (cmd->stop_src == TRIG_COUNT) {
/* any count is allowed */
} else {
/* TRIG_NONE */
err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
}
if (err)
return 3;
/* step 4: fix up arguments */
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
/* calculate counter values that give desired timing */
i8253_cascade_ns_to_timer_2div(DAS16M1_XTAL,
&(devpriv->divisor1),
&(devpriv->divisor2),
&(cmd->convert_arg),
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
}
if (err)
return 4;
/* check chanlist against board's peculiarities */
if (cmd->chanlist && cmd->chanlist_len > 1) {
for (i = 0; i < cmd->chanlist_len; i++) {
/* even/odd channels must go into even/odd queue addresses */
if ((i % 2) != (CR_CHAN(cmd->chanlist[i]) % 2)) {
comedi_error(dev, "bad chanlist:\n"
" even/odd channels must go have even/odd chanlist indices");
err++;
}
}
if ((cmd->chanlist_len % 2) != 0) {
comedi_error(dev,
"chanlist must be of even length or length 1");
err++;
}
}
if (err)
return 5;
return 0;
}
/* This function takes a time in nanoseconds and sets the *
* 2 pacer clocks to the closest frequency possible. It also *
* returns the actual sampling period. */
static unsigned int das16m1_set_pacer(struct comedi_device *dev,
unsigned int ns, int rounding_flags)
{
struct das16m1_private_struct *devpriv = dev->private;
i8253_cascade_ns_to_timer_2div(DAS16M1_XTAL, &(devpriv->divisor1),
&(devpriv->divisor2), &ns,
rounding_flags & TRIG_ROUND_MASK);
/* Write the values of ctr1 and ctr2 into counters 1 and 2 */
i8254_load(dev->iobase + DAS16M1_8254_SECOND, 0, 1, devpriv->divisor1,
2);
i8254_load(dev->iobase + DAS16M1_8254_SECOND, 0, 2, devpriv->divisor2,
2);
return ns;
}
static int das16m1_cmd_exec(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct das16m1_private_struct *devpriv = dev->private;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
unsigned int byte, i;
if (dev->irq == 0) {
comedi_error(dev, "irq required to execute comedi_cmd");
return -1;
}
/* disable interrupts and internal pacer */
devpriv->control_state &= ~INTE & ~PACER_MASK;
outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
/* set software count */
devpriv->adc_count = 0;
/* Initialize lower half of hardware counter, used to determine how
* many samples are in fifo. Value doesn't actually load into counter
* until counter's next clock (the next a/d conversion) */
i8254_load(dev->iobase + DAS16M1_8254_FIRST, 0, 1, 0, 2);
/* remember current reading of counter so we know when counter has
* actually been loaded */
devpriv->initial_hw_count =
i8254_read(dev->iobase + DAS16M1_8254_FIRST, 0, 1);
/* setup channel/gain queue */
for (i = 0; i < cmd->chanlist_len; i++) {
outb(i, dev->iobase + DAS16M1_QUEUE_ADDR);
byte =
Q_CHAN(CR_CHAN(cmd->chanlist[i])) |
Q_RANGE(CR_RANGE(cmd->chanlist[i]));
outb(byte, dev->iobase + DAS16M1_QUEUE_DATA);
}
/* set counter mode and counts */
cmd->convert_arg =
das16m1_set_pacer(dev, cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
/* set control & status register */
byte = 0;
/* if we are using external start trigger (also board dislikes having
* both start and conversion triggers external simultaneously) */
if (cmd->start_src == TRIG_EXT && cmd->convert_src != TRIG_EXT)
byte |= EXT_TRIG_BIT;
outb(byte, dev->iobase + DAS16M1_CS);
/* clear interrupt bit */
outb(0, dev->iobase + DAS16M1_CLEAR_INTR);
/* enable interrupts and internal pacer */
devpriv->control_state &= ~PACER_MASK;
if (cmd->convert_src == TRIG_TIMER)
devpriv->control_state |= INT_PACER;
else
devpriv->control_state |= EXT_PACER;
devpriv->control_state |= INTE;
outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
return 0;
}
static int das16m1_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct das16m1_private_struct *devpriv = dev->private;
devpriv->control_state &= ~INTE & ~PACER_MASK;
outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
return 0;
}
static int das16m1_ai_rinsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct das16m1_private_struct *devpriv = dev->private;
int i, n;
int byte;
const int timeout = 1000;
/* disable interrupts and internal pacer */
devpriv->control_state &= ~INTE & ~PACER_MASK;
outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
/* setup channel/gain queue */
outb(0, dev->iobase + DAS16M1_QUEUE_ADDR);
byte =
Q_CHAN(CR_CHAN(insn->chanspec)) | Q_RANGE(CR_RANGE(insn->chanspec));
outb(byte, dev->iobase + DAS16M1_QUEUE_DATA);
for (n = 0; n < insn->n; n++) {
/* clear IRQDATA bit */
outb(0, dev->iobase + DAS16M1_CLEAR_INTR);
/* trigger conversion */
outb(0, dev->iobase);
for (i = 0; i < timeout; i++) {
if (inb(dev->iobase + DAS16M1_CS) & IRQDATA)
break;
}
if (i == timeout) {
comedi_error(dev, "timeout");
return -ETIME;
}
data[n] = munge_sample(inw(dev->iobase));
}
return n;
}
static int das16m1_di_rbits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int bits;
bits = inb(dev->iobase + DAS16M1_DIO) & 0xf;
data[1] = bits;
data[0] = 0;
return insn->n;
}
static int das16m1_do_wbits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct das16m1_private_struct *devpriv = dev->private;
unsigned int wbits;
/* only set bits that have been masked */
data[0] &= 0xf;
wbits = devpriv->do_bits;
/* zero bits that have been masked */
wbits &= ~data[0];
/* set masked bits */
wbits |= data[0] & data[1];
devpriv->do_bits = wbits;
data[1] = wbits;
outb(devpriv->do_bits, dev->iobase + DAS16M1_DIO);
return insn->n;
}
static void das16m1_handler(struct comedi_device *dev, unsigned int status)
{
struct das16m1_private_struct *devpriv = dev->private;
struct comedi_subdevice *s;
struct comedi_async *async;
struct comedi_cmd *cmd;
u16 num_samples;
u16 hw_counter;
s = dev->read_subdev;
async = s->async;
async->events = 0;
cmd = &async->cmd;
/* figure out how many samples are in fifo */
hw_counter = i8254_read(dev->iobase + DAS16M1_8254_FIRST, 0, 1);
/* make sure hardware counter reading is not bogus due to initial value
* not having been loaded yet */
if (devpriv->adc_count == 0 && hw_counter == devpriv->initial_hw_count) {
num_samples = 0;
} else {
/* The calculation of num_samples looks odd, but it uses the following facts.
* 16 bit hardware counter is initialized with value of zero (which really
* means 0x1000). The counter decrements by one on each conversion
* (when the counter decrements from zero it goes to 0xffff). num_samples
* is a 16 bit variable, so it will roll over in a similar fashion to the
* hardware counter. Work it out, and this is what you get. */
num_samples = -hw_counter - devpriv->adc_count;
}
/* check if we only need some of the points */
if (cmd->stop_src == TRIG_COUNT) {
if (num_samples > cmd->stop_arg * cmd->chanlist_len)
num_samples = cmd->stop_arg * cmd->chanlist_len;
}
/* make sure we dont try to get too many points if fifo has overrun */
if (num_samples > FIFO_SIZE)
num_samples = FIFO_SIZE;
insw(dev->iobase, devpriv->ai_buffer, num_samples);
munge_sample_array(devpriv->ai_buffer, num_samples);
cfc_write_array_to_buffer(s, devpriv->ai_buffer,
num_samples * sizeof(short));
devpriv->adc_count += num_samples;
if (cmd->stop_src == TRIG_COUNT) {
if (devpriv->adc_count >= cmd->stop_arg * cmd->chanlist_len) { /* end of acquisition */
das16m1_cancel(dev, s);
async->events |= COMEDI_CB_EOA;
}
}
/* this probably won't catch overruns since the card doesn't generate
* overrun interrupts, but we might as well try */
if (status & OVRUN) {
das16m1_cancel(dev, s);
async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_error(dev, "fifo overflow");
}
comedi_event(dev, s);
}
static int das16m1_poll(struct comedi_device *dev, struct comedi_subdevice *s)
{
unsigned long flags;
unsigned int status;
/* prevent race with interrupt handler */
spin_lock_irqsave(&dev->spinlock, flags);
status = inb(dev->iobase + DAS16M1_CS);
das16m1_handler(dev, status);
spin_unlock_irqrestore(&dev->spinlock, flags);
return s->async->buf_write_count - s->async->buf_read_count;
}
static irqreturn_t das16m1_interrupt(int irq, void *d)
{
int status;
struct comedi_device *dev = d;
if (!dev->attached) {
comedi_error(dev, "premature interrupt");
return IRQ_HANDLED;
}
/* prevent race with comedi_poll() */
spin_lock(&dev->spinlock);
status = inb(dev->iobase + DAS16M1_CS);
if ((status & (IRQDATA | OVRUN)) == 0) {
comedi_error(dev, "spurious interrupt");
spin_unlock(&dev->spinlock);
return IRQ_NONE;
}
das16m1_handler(dev, status);
/* clear interrupt */
outb(0, dev->iobase + DAS16M1_CLEAR_INTR);
spin_unlock(&dev->spinlock);
return IRQ_HANDLED;
}
static int das16m1_irq_bits(unsigned int irq)
{
int ret;
switch (irq) {
case 10:
ret = 0x0;
break;
case 11:
ret = 0x1;
break;
case 12:
ret = 0x2;
break;
case 15:
ret = 0x3;
break;
case 2:
ret = 0x4;
break;
case 3:
ret = 0x5;
break;
case 5:
ret = 0x6;
break;
case 7:
ret = 0x7;
break;
default:
return -1;
break;
}
return ret << 4;
}
/*
* Options list:
* 0 I/O base
* 1 IRQ
*/
static int das16m1_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct das16m1_private_struct *devpriv;
struct comedi_subdevice *s;
int ret;
unsigned int irq;
devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
if (!devpriv)
return -ENOMEM;
dev->private = devpriv;
ret = comedi_request_region(dev, it->options[0], DAS16M1_SIZE);
if (ret)
return ret;
/* Request an additional region for the 8255 */
ret = __comedi_request_region(dev, dev->iobase + DAS16M1_82C55,
DAS16M1_SIZE2);
if (ret)
return ret;
devpriv->extra_iobase = dev->iobase + DAS16M1_82C55;
/* now for the irq */
irq = it->options[1];
/* make sure it is valid */
if (das16m1_irq_bits(irq) >= 0) {
ret = request_irq(irq, das16m1_interrupt, 0,
dev->driver->driver_name, dev);
if (ret < 0)
return ret;
dev->irq = irq;
printk
("irq %u\n", irq);
} else if (irq == 0) {
printk
(", no irq\n");
} else {
comedi_error(dev, "invalid irq\n"
" valid irqs are 2, 3, 5, 7, 10, 11, 12, or 15\n");
return -EINVAL;
}
ret = comedi_alloc_subdevices(dev, 4);
if (ret)
return ret;
s = &dev->subdevices[0];
dev->read_subdev = s;
/* ai */
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_CMD_READ;
s->n_chan = 8;
s->subdev_flags = SDF_DIFF;
s->len_chanlist = 256;
s->maxdata = (1 << 12) - 1;
s->range_table = &range_das16m1;
s->insn_read = das16m1_ai_rinsn;
s->do_cmdtest = das16m1_cmd_test;
s->do_cmd = das16m1_cmd_exec;
s->cancel = das16m1_cancel;
s->poll = das16m1_poll;
s = &dev->subdevices[1];
/* di */
s->type = COMEDI_SUBD_DI;
s->subdev_flags = SDF_READABLE;
s->n_chan = 4;
s->maxdata = 1;
s->range_table = &range_digital;
s->insn_bits = das16m1_di_rbits;
s = &dev->subdevices[2];
/* do */
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = 4;
s->maxdata = 1;
s->range_table = &range_digital;
s->insn_bits = das16m1_do_wbits;
s = &dev->subdevices[3];
/* 8255 */
ret = subdev_8255_init(dev, s, NULL, devpriv->extra_iobase);
if (ret)
return ret;
/* disable upper half of hardware conversion counter so it doesn't mess with us */
outb(TOTAL_CLEAR, dev->iobase + DAS16M1_8254_FIRST_CNTRL);
/* initialize digital output lines */
outb(devpriv->do_bits, dev->iobase + DAS16M1_DIO);
/* set the interrupt level */
if (dev->irq)
devpriv->control_state = das16m1_irq_bits(dev->irq);
else
devpriv->control_state = 0;
outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
return 0;
}
static void das16m1_detach(struct comedi_device *dev)
{
struct das16m1_private_struct *devpriv = dev->private;
comedi_spriv_free(dev, 3);
if (devpriv && devpriv->extra_iobase)
release_region(devpriv->extra_iobase, DAS16M1_SIZE2);
comedi_legacy_detach(dev);
}
static struct comedi_driver das16m1_driver = {
.driver_name = "das16m1",
.module = THIS_MODULE,
.attach = das16m1_attach,
.detach = das16m1_detach,
};
module_comedi_driver(das16m1_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jashasweejena/VibeKernel | drivers/staging/comedi/drivers/addi_apci_3xxx.c | 2090 | 23747 | #include <linux/pci.h>
#include "../comedidev.h"
#include "comedi_fc.h"
#include "amcc_s5933.h"
#include "addi-data/addi_common.h"
#include "addi-data/addi_eeprom.c"
#include "addi-data/hwdrv_apci3xxx.c"
#include "addi-data/addi_common.c"
enum apci3xxx_boardid {
BOARD_APCI3000_16,
BOARD_APCI3000_8,
BOARD_APCI3000_4,
BOARD_APCI3006_16,
BOARD_APCI3006_8,
BOARD_APCI3006_4,
BOARD_APCI3010_16,
BOARD_APCI3010_8,
BOARD_APCI3010_4,
BOARD_APCI3016_16,
BOARD_APCI3016_8,
BOARD_APCI3016_4,
BOARD_APCI3100_16_4,
BOARD_APCI3100_8_4,
BOARD_APCI3106_16_4,
BOARD_APCI3106_8_4,
BOARD_APCI3110_16_4,
BOARD_APCI3110_8_4,
BOARD_APCI3116_16_4,
BOARD_APCI3116_8_4,
BOARD_APCI3003,
BOARD_APCI3002_16,
BOARD_APCI3002_8,
BOARD_APCI3002_4,
BOARD_APCI3500,
};
static const struct addi_board apci3xxx_boardtypes[] = {
[BOARD_APCI3000_16] = {
.pc_DriverName = "apci3000-16",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_AiMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3000_8] = {
.pc_DriverName = "apci3000-8",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_AiMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3000_4] = {
.pc_DriverName = "apci3000-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 4,
.i_NbrAiChannelDiff = 2,
.i_AiChannelList = 4,
.i_AiMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3006_16] = {
.pc_DriverName = "apci3006-16",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3006_8] = {
.pc_DriverName = "apci3006-8",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3006_4] = {
.pc_DriverName = "apci3006-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 4,
.i_NbrAiChannelDiff = 2,
.i_AiChannelList = 4,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3010_16] = {
.pc_DriverName = "apci3010-16",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_AiMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3010_8] = {
.pc_DriverName = "apci3010-8",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_AiMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3010_4] = {
.pc_DriverName = "apci3010-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 4,
.i_NbrAiChannelDiff = 2,
.i_AiChannelList = 4,
.i_AiMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3016_16] = {
.pc_DriverName = "apci3016-16",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3016_8] = {
.pc_DriverName = "apci3016-8",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3016_4] = {
.pc_DriverName = "apci3016-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 4,
.i_NbrAiChannelDiff = 2,
.i_AiChannelList = 4,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3100_16_4] = {
.pc_DriverName = "apci3100-16-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 4095,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3100_8_4] = {
.pc_DriverName = "apci3100-8-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 4095,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3106_16_4] = {
.pc_DriverName = "apci3106-16-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 65535,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3106_8_4] = {
.pc_DriverName = "apci3106-8-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 65535,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 10000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3110_16_4] = {
.pc_DriverName = "apci3110-16-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 4095,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3110_8_4] = {
.pc_DriverName = "apci3110-8-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 4095,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3116_16_4] = {
.pc_DriverName = "apci3116-16-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 16,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 16,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 65535,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3116_8_4] = {
.pc_DriverName = "apci3116-8-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannel = 8,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 8,
.i_NbrAoChannel = 4,
.i_AiMaxdata = 65535,
.i_AoMaxdata = 4095,
.pr_AiRangelist = &range_apci3XXX_ai,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.i_NbrTTLChannel = 24,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
[BOARD_APCI3003] = {
.pc_DriverName = "apci3003",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 4,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.b_AvailableConvertUnit = 7,
.ui_MinAcquisitiontimeNs = 2500,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
},
[BOARD_APCI3002_16] = {
.pc_DriverName = "apci3002-16",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannelDiff = 16,
.i_AiChannelList = 16,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
},
[BOARD_APCI3002_8] = {
.pc_DriverName = "apci3002-8",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannelDiff = 8,
.i_AiChannelList = 8,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
},
[BOARD_APCI3002_4] = {
.pc_DriverName = "apci3002-4",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAiChannelDiff = 4,
.i_AiChannelList = 4,
.i_AiMaxdata = 65535,
.pr_AiRangelist = &range_apci3XXX_ai,
.i_NbrDiChannel = 4,
.i_NbrDoChannel = 4,
.i_DoMaxdata = 1,
.b_AvailableConvertUnit = 6,
.ui_MinAcquisitiontimeNs = 5000,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ai_config = i_APCI3XXX_InsnConfigAnalogInput,
.ai_read = i_APCI3XXX_InsnReadAnalogInput,
.di_bits = apci3xxx_di_insn_bits,
.do_bits = apci3xxx_do_insn_bits,
},
[BOARD_APCI3500] = {
.pc_DriverName = "apci3500",
.i_IorangeBase1 = 256,
.i_PCIEeprom = ADDIDATA_NO_EEPROM,
.pc_EepromChip = ADDIDATA_9054,
.i_NbrAoChannel = 4,
.i_AoMaxdata = 4095,
.pr_AoRangelist = &range_apci3XXX_ao,
.i_NbrTTLChannel = 24,
.interrupt = v_APCI3XXX_Interrupt,
.reset = i_APCI3XXX_Reset,
.ao_write = i_APCI3XXX_InsnWriteAnalogOutput,
.ttl_config = i_APCI3XXX_InsnConfigInitTTLIO,
.ttl_bits = i_APCI3XXX_InsnBitsTTLIO,
.ttl_read = i_APCI3XXX_InsnReadTTLIO,
.ttl_write = i_APCI3XXX_InsnWriteTTLIO,
},
};
static int apci3xxx_auto_attach(struct comedi_device *dev,
unsigned long context)
{
const struct addi_board *board = NULL;
if (context < ARRAY_SIZE(apci3xxx_boardtypes))
board = &apci3xxx_boardtypes[context];
if (!board)
return -ENODEV;
dev->board_ptr = board;
return addi_auto_attach(dev, context);
}
static struct comedi_driver apci3xxx_driver = {
.driver_name = "addi_apci_3xxx",
.module = THIS_MODULE,
.auto_attach = apci3xxx_auto_attach,
.detach = i_ADDI_Detach,
};
static int apci3xxx_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
return comedi_pci_auto_config(dev, &apci3xxx_driver, id->driver_data);
}
static DEFINE_PCI_DEVICE_TABLE(apci3xxx_pci_table) = {
{ PCI_VDEVICE(ADDIDATA, 0x3010), BOARD_APCI3000_16 },
{ PCI_VDEVICE(ADDIDATA, 0x300f), BOARD_APCI3000_8 },
{ PCI_VDEVICE(ADDIDATA, 0x300e), BOARD_APCI3000_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3013), BOARD_APCI3006_16 },
{ PCI_VDEVICE(ADDIDATA, 0x3014), BOARD_APCI3006_8 },
{ PCI_VDEVICE(ADDIDATA, 0x3015), BOARD_APCI3006_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3016), BOARD_APCI3010_16 },
{ PCI_VDEVICE(ADDIDATA, 0x3017), BOARD_APCI3010_8 },
{ PCI_VDEVICE(ADDIDATA, 0x3018), BOARD_APCI3010_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3019), BOARD_APCI3016_16 },
{ PCI_VDEVICE(ADDIDATA, 0x301a), BOARD_APCI3016_8 },
{ PCI_VDEVICE(ADDIDATA, 0x301b), BOARD_APCI3016_4 },
{ PCI_VDEVICE(ADDIDATA, 0x301c), BOARD_APCI3100_16_4 },
{ PCI_VDEVICE(ADDIDATA, 0x301d), BOARD_APCI3100_8_4 },
{ PCI_VDEVICE(ADDIDATA, 0x301e), BOARD_APCI3106_16_4 },
{ PCI_VDEVICE(ADDIDATA, 0x301f), BOARD_APCI3106_8_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3020), BOARD_APCI3110_16_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3021), BOARD_APCI3110_8_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3022), BOARD_APCI3116_16_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3023), BOARD_APCI3116_8_4 },
{ PCI_VDEVICE(ADDIDATA, 0x300B), BOARD_APCI3003 },
{ PCI_VDEVICE(ADDIDATA, 0x3002), BOARD_APCI3002_16 },
{ PCI_VDEVICE(ADDIDATA, 0x3003), BOARD_APCI3002_8 },
{ PCI_VDEVICE(ADDIDATA, 0x3004), BOARD_APCI3002_4 },
{ PCI_VDEVICE(ADDIDATA, 0x3024), BOARD_APCI3500 },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, apci3xxx_pci_table);
static struct pci_driver apci3xxx_pci_driver = {
.name = "addi_apci_3xxx",
.id_table = apci3xxx_pci_table,
.probe = apci3xxx_pci_probe,
.remove = comedi_pci_auto_unconfig,
};
module_comedi_pci_driver(apci3xxx_driver, apci3xxx_pci_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
HRTKernel/Hacker_Kernel_SM-G920P | drivers/staging/comedi/drivers/ni_labpc_cs.c | 2090 | 4454 | /*
comedi/drivers/ni_labpc_cs.c
Driver for National Instruments daqcard-1200 boards
Copyright (C) 2001, 2002, 2003 Frank Mori Hess <fmhess@users.sourceforge.net>
PCMCIA crap is adapted from dummy_cs.c 1.31 2001/08/24 12:13:13
from the pcmcia package.
The initial developer of the pcmcia dummy_cs.c code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds.
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: ni_labpc_cs
Description: National Instruments Lab-PC (& compatibles)
Author: Frank Mori Hess <fmhess@users.sourceforge.net>
Devices: [National Instruments] DAQCard-1200 (daqcard-1200)
Status: works
Thanks go to Fredrik Lingvall for much testing and perseverance in
helping to debug daqcard-1200 support.
The 1200 series boards have onboard calibration dacs for correcting
analog input/output offsets and gains. The proper settings for these
caldacs are stored on the board's eeprom. To read the caldac values
from the eeprom and store them into a file that can be then be used by
comedilib, use the comedi_calibrate program.
Configuration options:
none
The daqcard-1200 has quirky chanlist requirements
when scanning multiple channels. Multiple channel scan
sequence must start at highest channel, then decrement down to
channel 0. Chanlists consisting of all one channel
are also legal, and allow you to pace conversions in bursts.
*/
/*
NI manuals:
340988a (daqcard-1200)
*/
#include "../comedidev.h"
#include <linux/delay.h>
#include <linux/slab.h>
#include "8253.h"
#include "8255.h"
#include "comedi_fc.h"
#include "ni_labpc.h"
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
static const struct labpc_boardinfo labpc_cs_boards[] = {
{
.name = "daqcard-1200",
.device_id = 0x103,
.ai_speed = 10000,
.register_layout = labpc_1200_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = labpc_1200_ai_gain_bits,
},
};
static int labpc_auto_attach(struct comedi_device *dev,
unsigned long context)
{
struct pcmcia_device *link = comedi_to_pcmcia_dev(dev);
struct labpc_private *devpriv;
int ret;
/* The ni_labpc driver needs the board_ptr */
dev->board_ptr = &labpc_cs_boards[0];
link->config_flags |= CONF_AUTO_SET_IO |
CONF_ENABLE_IRQ | CONF_ENABLE_PULSE_IRQ;
ret = comedi_pcmcia_enable(dev, NULL);
if (ret)
return ret;
dev->iobase = link->resource[0]->start;
if (!link->irq)
return -EINVAL;
devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
if (!devpriv)
return -ENOMEM;
dev->private = devpriv;
return labpc_common_attach(dev, link->irq, IRQF_SHARED);
}
static void labpc_detach(struct comedi_device *dev)
{
labpc_common_detach(dev);
comedi_pcmcia_disable(dev);
}
static struct comedi_driver driver_labpc_cs = {
.driver_name = "ni_labpc_cs",
.module = THIS_MODULE,
.auto_attach = labpc_auto_attach,
.detach = labpc_detach,
};
static int labpc_cs_attach(struct pcmcia_device *link)
{
return comedi_pcmcia_auto_config(link, &driver_labpc_cs);
}
static const struct pcmcia_device_id labpc_cs_ids[] = {
PCMCIA_DEVICE_MANF_CARD(0x010b, 0x0103), /* daqcard-1200 */
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, labpc_cs_ids);
static struct pcmcia_driver labpc_cs_driver = {
.name = "daqcard-1200",
.owner = THIS_MODULE,
.id_table = labpc_cs_ids,
.probe = labpc_cs_attach,
.remove = comedi_pcmcia_auto_unconfig,
};
module_comedi_pcmcia_driver(driver_labpc_cs, labpc_cs_driver);
MODULE_DESCRIPTION("Comedi driver for National Instruments Lab-PC");
MODULE_AUTHOR("Frank Mori Hess <fmhess@users.sourceforge.net>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Jimmyk422/android_kernel_samsung_iconvmu | arch/arm/plat-versatile/clcd.c | 10794 | 3956 | #include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/amba/bus.h>
#include <linux/amba/clcd.h>
#include <plat/clcd.h>
static struct clcd_panel vga = {
.mode = {
.name = "VGA",
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 39721,
.left_margin = 40,
.right_margin = 24,
.upper_margin = 32,
.lower_margin = 11,
.hsync_len = 96,
.vsync_len = 2,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
.width = -1,
.height = -1,
.tim2 = TIM2_BCD | TIM2_IPC,
.cntl = CNTL_LCDTFT | CNTL_BGR | CNTL_LCDVCOMP(1),
.caps = CLCD_CAP_5551 | CLCD_CAP_565 | CLCD_CAP_888,
.bpp = 16,
};
static struct clcd_panel xvga = {
.mode = {
.name = "XVGA",
.refresh = 60,
.xres = 1024,
.yres = 768,
.pixclock = 15748,
.left_margin = 152,
.right_margin = 48,
.upper_margin = 23,
.lower_margin = 3,
.hsync_len = 104,
.vsync_len = 4,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
.width = -1,
.height = -1,
.tim2 = TIM2_BCD | TIM2_IPC,
.cntl = CNTL_LCDTFT | CNTL_BGR | CNTL_LCDVCOMP(1),
.caps = CLCD_CAP_5551 | CLCD_CAP_565 | CLCD_CAP_888,
.bpp = 16,
};
/* Sanyo TM38QV67A02A - 3.8 inch QVGA (320x240) Color TFT */
static struct clcd_panel sanyo_tm38qv67a02a = {
.mode = {
.name = "Sanyo TM38QV67A02A",
.refresh = 116,
.xres = 320,
.yres = 240,
.pixclock = 100000,
.left_margin = 6,
.right_margin = 6,
.upper_margin = 5,
.lower_margin = 5,
.hsync_len = 6,
.vsync_len = 6,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
.width = -1,
.height = -1,
.tim2 = TIM2_BCD,
.cntl = CNTL_LCDTFT | CNTL_BGR | CNTL_LCDVCOMP(1),
.caps = CLCD_CAP_5551,
.bpp = 16,
};
static struct clcd_panel sanyo_2_5_in = {
.mode = {
.name = "Sanyo QVGA Portrait",
.refresh = 116,
.xres = 240,
.yres = 320,
.pixclock = 100000,
.left_margin = 20,
.right_margin = 10,
.upper_margin = 2,
.lower_margin = 2,
.hsync_len = 10,
.vsync_len = 2,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
.vmode = FB_VMODE_NONINTERLACED,
},
.width = -1,
.height = -1,
.tim2 = TIM2_IVS | TIM2_IHS | TIM2_IPC,
.cntl = CNTL_LCDTFT | CNTL_BGR | CNTL_LCDVCOMP(1),
.caps = CLCD_CAP_5551,
.bpp = 16,
};
/* Epson L2F50113T00 - 2.2 inch 176x220 Color TFT */
static struct clcd_panel epson_l2f50113t00 = {
.mode = {
.name = "Epson L2F50113T00",
.refresh = 390,
.xres = 176,
.yres = 220,
.pixclock = 62500,
.left_margin = 3,
.right_margin = 2,
.upper_margin = 1,
.lower_margin = 0,
.hsync_len = 3,
.vsync_len = 2,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
.width = -1,
.height = -1,
.tim2 = TIM2_BCD | TIM2_IPC,
.cntl = CNTL_LCDTFT | CNTL_BGR | CNTL_LCDVCOMP(1),
.caps = CLCD_CAP_5551,
.bpp = 16,
};
static struct clcd_panel *panels[] = {
&vga,
&xvga,
&sanyo_tm38qv67a02a,
&sanyo_2_5_in,
&epson_l2f50113t00,
};
struct clcd_panel *versatile_clcd_get_panel(const char *name)
{
int i;
for (i = 0; i < ARRAY_SIZE(panels); i++)
if (strcmp(panels[i]->mode.name, name) == 0)
break;
if (i < ARRAY_SIZE(panels))
return panels[i];
pr_err("CLCD: couldn't get parameters for panel %s\n", name);
return NULL;
}
int versatile_clcd_setup_dma(struct clcd_fb *fb, unsigned long framesize)
{
dma_addr_t dma;
fb->fb.screen_base = dma_alloc_writecombine(&fb->dev->dev, framesize,
&dma, GFP_KERNEL);
if (!fb->fb.screen_base) {
pr_err("CLCD: unable to map framebuffer\n");
return -ENOMEM;
}
fb->fb.fix.smem_start = dma;
fb->fb.fix.smem_len = framesize;
return 0;
}
int versatile_clcd_mmap_dma(struct clcd_fb *fb, struct vm_area_struct *vma)
{
return dma_mmap_writecombine(&fb->dev->dev, vma,
fb->fb.screen_base,
fb->fb.fix.smem_start,
fb->fb.fix.smem_len);
}
void versatile_clcd_remove_dma(struct clcd_fb *fb)
{
dma_free_writecombine(&fb->dev->dev, fb->fb.fix.smem_len,
fb->fb.screen_base, fb->fb.fix.smem_start);
}
| gpl-2.0 |
kurainooni/rk30-kernel | Documentation/filesystems/configfs/configfs_example_explicit.c | 12074 | 12614 | /*
* vim: noexpandtab ts=8 sts=0 sw=8:
*
* configfs_example_explicit.c - This file is a demonstration module
* containing a number of configfs subsystems. It explicitly defines
* each structure without using the helper macros defined in
* configfs.h.
*
* 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 021110-1307, USA.
*
* Based on sysfs:
* sysfs is Copyright (C) 2001, 2002, 2003 Patrick Mochel
*
* configfs Copyright (C) 2005 Oracle. All rights reserved.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/configfs.h>
/*
* 01-childless
*
* This first example is a childless subsystem. It cannot create
* any config_items. It just has attributes.
*
* Note that we are enclosing the configfs_subsystem inside a container.
* This is not necessary if a subsystem has no attributes directly
* on the subsystem. See the next example, 02-simple-children, for
* such a subsystem.
*/
struct childless {
struct configfs_subsystem subsys;
int showme;
int storeme;
};
struct childless_attribute {
struct configfs_attribute attr;
ssize_t (*show)(struct childless *, char *);
ssize_t (*store)(struct childless *, const char *, size_t);
};
static inline struct childless *to_childless(struct config_item *item)
{
return item ? container_of(to_configfs_subsystem(to_config_group(item)), struct childless, subsys) : NULL;
}
static ssize_t childless_showme_read(struct childless *childless,
char *page)
{
ssize_t pos;
pos = sprintf(page, "%d\n", childless->showme);
childless->showme++;
return pos;
}
static ssize_t childless_storeme_read(struct childless *childless,
char *page)
{
return sprintf(page, "%d\n", childless->storeme);
}
static ssize_t childless_storeme_write(struct childless *childless,
const char *page,
size_t count)
{
unsigned long tmp;
char *p = (char *) page;
tmp = simple_strtoul(p, &p, 10);
if ((*p != '\0') && (*p != '\n'))
return -EINVAL;
if (tmp > INT_MAX)
return -ERANGE;
childless->storeme = tmp;
return count;
}
static ssize_t childless_description_read(struct childless *childless,
char *page)
{
return sprintf(page,
"[01-childless]\n"
"\n"
"The childless subsystem is the simplest possible subsystem in\n"
"configfs. It does not support the creation of child config_items.\n"
"It only has a few attributes. In fact, it isn't much different\n"
"than a directory in /proc.\n");
}
static struct childless_attribute childless_attr_showme = {
.attr = { .ca_owner = THIS_MODULE, .ca_name = "showme", .ca_mode = S_IRUGO },
.show = childless_showme_read,
};
static struct childless_attribute childless_attr_storeme = {
.attr = { .ca_owner = THIS_MODULE, .ca_name = "storeme", .ca_mode = S_IRUGO | S_IWUSR },
.show = childless_storeme_read,
.store = childless_storeme_write,
};
static struct childless_attribute childless_attr_description = {
.attr = { .ca_owner = THIS_MODULE, .ca_name = "description", .ca_mode = S_IRUGO },
.show = childless_description_read,
};
static struct configfs_attribute *childless_attrs[] = {
&childless_attr_showme.attr,
&childless_attr_storeme.attr,
&childless_attr_description.attr,
NULL,
};
static ssize_t childless_attr_show(struct config_item *item,
struct configfs_attribute *attr,
char *page)
{
struct childless *childless = to_childless(item);
struct childless_attribute *childless_attr =
container_of(attr, struct childless_attribute, attr);
ssize_t ret = 0;
if (childless_attr->show)
ret = childless_attr->show(childless, page);
return ret;
}
static ssize_t childless_attr_store(struct config_item *item,
struct configfs_attribute *attr,
const char *page, size_t count)
{
struct childless *childless = to_childless(item);
struct childless_attribute *childless_attr =
container_of(attr, struct childless_attribute, attr);
ssize_t ret = -EINVAL;
if (childless_attr->store)
ret = childless_attr->store(childless, page, count);
return ret;
}
static struct configfs_item_operations childless_item_ops = {
.show_attribute = childless_attr_show,
.store_attribute = childless_attr_store,
};
static struct config_item_type childless_type = {
.ct_item_ops = &childless_item_ops,
.ct_attrs = childless_attrs,
.ct_owner = THIS_MODULE,
};
static struct childless childless_subsys = {
.subsys = {
.su_group = {
.cg_item = {
.ci_namebuf = "01-childless",
.ci_type = &childless_type,
},
},
},
};
/* ----------------------------------------------------------------- */
/*
* 02-simple-children
*
* This example merely has a simple one-attribute child. Note that
* there is no extra attribute structure, as the child's attribute is
* known from the get-go. Also, there is no container for the
* subsystem, as it has no attributes of its own.
*/
struct simple_child {
struct config_item item;
int storeme;
};
static inline struct simple_child *to_simple_child(struct config_item *item)
{
return item ? container_of(item, struct simple_child, item) : NULL;
}
static struct configfs_attribute simple_child_attr_storeme = {
.ca_owner = THIS_MODULE,
.ca_name = "storeme",
.ca_mode = S_IRUGO | S_IWUSR,
};
static struct configfs_attribute *simple_child_attrs[] = {
&simple_child_attr_storeme,
NULL,
};
static ssize_t simple_child_attr_show(struct config_item *item,
struct configfs_attribute *attr,
char *page)
{
ssize_t count;
struct simple_child *simple_child = to_simple_child(item);
count = sprintf(page, "%d\n", simple_child->storeme);
return count;
}
static ssize_t simple_child_attr_store(struct config_item *item,
struct configfs_attribute *attr,
const char *page, size_t count)
{
struct simple_child *simple_child = to_simple_child(item);
unsigned long tmp;
char *p = (char *) page;
tmp = simple_strtoul(p, &p, 10);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
if (tmp > INT_MAX)
return -ERANGE;
simple_child->storeme = tmp;
return count;
}
static void simple_child_release(struct config_item *item)
{
kfree(to_simple_child(item));
}
static struct configfs_item_operations simple_child_item_ops = {
.release = simple_child_release,
.show_attribute = simple_child_attr_show,
.store_attribute = simple_child_attr_store,
};
static struct config_item_type simple_child_type = {
.ct_item_ops = &simple_child_item_ops,
.ct_attrs = simple_child_attrs,
.ct_owner = THIS_MODULE,
};
struct simple_children {
struct config_group group;
};
static inline struct simple_children *to_simple_children(struct config_item *item)
{
return item ? container_of(to_config_group(item), struct simple_children, group) : NULL;
}
static struct config_item *simple_children_make_item(struct config_group *group, const char *name)
{
struct simple_child *simple_child;
simple_child = kzalloc(sizeof(struct simple_child), GFP_KERNEL);
if (!simple_child)
return ERR_PTR(-ENOMEM);
config_item_init_type_name(&simple_child->item, name,
&simple_child_type);
simple_child->storeme = 0;
return &simple_child->item;
}
static struct configfs_attribute simple_children_attr_description = {
.ca_owner = THIS_MODULE,
.ca_name = "description",
.ca_mode = S_IRUGO,
};
static struct configfs_attribute *simple_children_attrs[] = {
&simple_children_attr_description,
NULL,
};
static ssize_t simple_children_attr_show(struct config_item *item,
struct configfs_attribute *attr,
char *page)
{
return sprintf(page,
"[02-simple-children]\n"
"\n"
"This subsystem allows the creation of child config_items. These\n"
"items have only one attribute that is readable and writeable.\n");
}
static void simple_children_release(struct config_item *item)
{
kfree(to_simple_children(item));
}
static struct configfs_item_operations simple_children_item_ops = {
.release = simple_children_release,
.show_attribute = simple_children_attr_show,
};
/*
* Note that, since no extra work is required on ->drop_item(),
* no ->drop_item() is provided.
*/
static struct configfs_group_operations simple_children_group_ops = {
.make_item = simple_children_make_item,
};
static struct config_item_type simple_children_type = {
.ct_item_ops = &simple_children_item_ops,
.ct_group_ops = &simple_children_group_ops,
.ct_attrs = simple_children_attrs,
.ct_owner = THIS_MODULE,
};
static struct configfs_subsystem simple_children_subsys = {
.su_group = {
.cg_item = {
.ci_namebuf = "02-simple-children",
.ci_type = &simple_children_type,
},
},
};
/* ----------------------------------------------------------------- */
/*
* 03-group-children
*
* This example reuses the simple_children group from above. However,
* the simple_children group is not the subsystem itself, it is a
* child of the subsystem. Creation of a group in the subsystem creates
* a new simple_children group. That group can then have simple_child
* children of its own.
*/
static struct config_group *group_children_make_group(struct config_group *group, const char *name)
{
struct simple_children *simple_children;
simple_children = kzalloc(sizeof(struct simple_children),
GFP_KERNEL);
if (!simple_children)
return ERR_PTR(-ENOMEM);
config_group_init_type_name(&simple_children->group, name,
&simple_children_type);
return &simple_children->group;
}
static struct configfs_attribute group_children_attr_description = {
.ca_owner = THIS_MODULE,
.ca_name = "description",
.ca_mode = S_IRUGO,
};
static struct configfs_attribute *group_children_attrs[] = {
&group_children_attr_description,
NULL,
};
static ssize_t group_children_attr_show(struct config_item *item,
struct configfs_attribute *attr,
char *page)
{
return sprintf(page,
"[03-group-children]\n"
"\n"
"This subsystem allows the creation of child config_groups. These\n"
"groups are like the subsystem simple-children.\n");
}
static struct configfs_item_operations group_children_item_ops = {
.show_attribute = group_children_attr_show,
};
/*
* Note that, since no extra work is required on ->drop_item(),
* no ->drop_item() is provided.
*/
static struct configfs_group_operations group_children_group_ops = {
.make_group = group_children_make_group,
};
static struct config_item_type group_children_type = {
.ct_item_ops = &group_children_item_ops,
.ct_group_ops = &group_children_group_ops,
.ct_attrs = group_children_attrs,
.ct_owner = THIS_MODULE,
};
static struct configfs_subsystem group_children_subsys = {
.su_group = {
.cg_item = {
.ci_namebuf = "03-group-children",
.ci_type = &group_children_type,
},
},
};
/* ----------------------------------------------------------------- */
/*
* We're now done with our subsystem definitions.
* For convenience in this module, here's a list of them all. It
* allows the init function to easily register them. Most modules
* will only have one subsystem, and will only call register_subsystem
* on it directly.
*/
static struct configfs_subsystem *example_subsys[] = {
&childless_subsys.subsys,
&simple_children_subsys,
&group_children_subsys,
NULL,
};
static int __init configfs_example_init(void)
{
int ret;
int i;
struct configfs_subsystem *subsys;
for (i = 0; example_subsys[i]; i++) {
subsys = example_subsys[i];
config_group_init(&subsys->su_group);
mutex_init(&subsys->su_mutex);
ret = configfs_register_subsystem(subsys);
if (ret) {
printk(KERN_ERR "Error %d while registering subsystem %s\n",
ret,
subsys->su_group.cg_item.ci_namebuf);
goto out_unregister;
}
}
return 0;
out_unregister:
for (i--; i >= 0; i--)
configfs_unregister_subsystem(example_subsys[i]);
return ret;
}
static void __exit configfs_example_exit(void)
{
int i;
for (i = 0; example_subsys[i]; i++)
configfs_unregister_subsystem(example_subsys[i]);
}
module_init(configfs_example_init);
module_exit(configfs_example_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
tjbrandt/Project-Fjord | drivers/usb/host/fhci-q.c | 13866 | 7107 | /*
* Freescale QUICC Engine USB Host Controller Driver
*
* Copyright (c) Freescale Semicondutor, Inc. 2006.
* Shlomi Gridish <gridish@freescale.com>
* Jerry Huang <Chang-Ming.Huang@freescale.com>
* Copyright (c) Logic Product Development, Inc. 2007
* Peter Barada <peterb@logicpd.com>
* Copyright (c) MontaVista Software, Inc. 2008.
* Anton Vorontsov <avorontsov@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include "fhci.h"
/* maps the hardware error code to the USB error code */
static int status_to_error(u32 status)
{
if (status == USB_TD_OK)
return 0;
else if (status & USB_TD_RX_ER_CRC)
return -EILSEQ;
else if (status & USB_TD_RX_ER_NONOCT)
return -EPROTO;
else if (status & USB_TD_RX_ER_OVERUN)
return -ECOMM;
else if (status & USB_TD_RX_ER_BITSTUFF)
return -EPROTO;
else if (status & USB_TD_RX_ER_PID)
return -EILSEQ;
else if (status & (USB_TD_TX_ER_NAK | USB_TD_TX_ER_TIMEOUT))
return -ETIMEDOUT;
else if (status & USB_TD_TX_ER_STALL)
return -EPIPE;
else if (status & USB_TD_TX_ER_UNDERUN)
return -ENOSR;
else if (status & USB_TD_RX_DATA_UNDERUN)
return -EREMOTEIO;
else if (status & USB_TD_RX_DATA_OVERUN)
return -EOVERFLOW;
else
return -EINVAL;
}
void fhci_add_td_to_frame(struct fhci_time_frame *frame, struct td *td)
{
list_add_tail(&td->frame_lh, &frame->tds_list);
}
void fhci_add_tds_to_ed(struct ed *ed, struct td **td_list, int number)
{
int i;
for (i = 0; i < number; i++) {
struct td *td = td_list[i];
list_add_tail(&td->node, &ed->td_list);
}
if (ed->td_head == NULL)
ed->td_head = td_list[0];
}
static struct td *peek_td_from_ed(struct ed *ed)
{
struct td *td;
if (!list_empty(&ed->td_list))
td = list_entry(ed->td_list.next, struct td, node);
else
td = NULL;
return td;
}
struct td *fhci_remove_td_from_frame(struct fhci_time_frame *frame)
{
struct td *td;
if (!list_empty(&frame->tds_list)) {
td = list_entry(frame->tds_list.next, struct td, frame_lh);
list_del_init(frame->tds_list.next);
} else
td = NULL;
return td;
}
struct td *fhci_peek_td_from_frame(struct fhci_time_frame *frame)
{
struct td *td;
if (!list_empty(&frame->tds_list))
td = list_entry(frame->tds_list.next, struct td, frame_lh);
else
td = NULL;
return td;
}
struct td *fhci_remove_td_from_ed(struct ed *ed)
{
struct td *td;
if (!list_empty(&ed->td_list)) {
td = list_entry(ed->td_list.next, struct td, node);
list_del_init(ed->td_list.next);
/* if this TD was the ED's head, find next TD */
if (!list_empty(&ed->td_list))
ed->td_head = list_entry(ed->td_list.next, struct td,
node);
else
ed->td_head = NULL;
} else
td = NULL;
return td;
}
struct td *fhci_remove_td_from_done_list(struct fhci_controller_list *p_list)
{
struct td *td;
if (!list_empty(&p_list->done_list)) {
td = list_entry(p_list->done_list.next, struct td, node);
list_del_init(p_list->done_list.next);
} else
td = NULL;
return td;
}
void fhci_move_td_from_ed_to_done_list(struct fhci_usb *usb, struct ed *ed)
{
struct td *td;
td = ed->td_head;
list_del_init(&td->node);
/* If this TD was the ED's head,find next TD */
if (!list_empty(&ed->td_list))
ed->td_head = list_entry(ed->td_list.next, struct td, node);
else {
ed->td_head = NULL;
ed->state = FHCI_ED_SKIP;
}
ed->toggle_carry = td->toggle;
list_add_tail(&td->node, &usb->hc_list->done_list);
if (td->ioc)
usb->transfer_confirm(usb->fhci);
}
/* free done FHCI URB resource such as ED and TD */
static void free_urb_priv(struct fhci_hcd *fhci, struct urb *urb)
{
int i;
struct urb_priv *urb_priv = urb->hcpriv;
struct ed *ed = urb_priv->ed;
for (i = 0; i < urb_priv->num_of_tds; i++) {
list_del_init(&urb_priv->tds[i]->node);
fhci_recycle_empty_td(fhci, urb_priv->tds[i]);
}
/* if this TD was the ED's head,find the next TD */
if (!list_empty(&ed->td_list))
ed->td_head = list_entry(ed->td_list.next, struct td, node);
else
ed->td_head = NULL;
kfree(urb_priv->tds);
kfree(urb_priv);
urb->hcpriv = NULL;
/* if this TD was the ED's head,find next TD */
if (ed->td_head == NULL)
list_del_init(&ed->node);
fhci->active_urbs--;
}
/* this routine called to complete and free done URB */
void fhci_urb_complete_free(struct fhci_hcd *fhci, struct urb *urb)
{
free_urb_priv(fhci, urb);
if (urb->status == -EINPROGRESS) {
if (urb->actual_length != urb->transfer_buffer_length &&
urb->transfer_flags & URB_SHORT_NOT_OK)
urb->status = -EREMOTEIO;
else
urb->status = 0;
}
usb_hcd_unlink_urb_from_ep(fhci_to_hcd(fhci), urb);
spin_unlock(&fhci->lock);
usb_hcd_giveback_urb(fhci_to_hcd(fhci), urb, urb->status);
spin_lock(&fhci->lock);
}
/*
* caculate transfer length/stats and update the urb
* Precondition: irqsafe(only for urb-?status locking)
*/
void fhci_done_td(struct urb *urb, struct td *td)
{
struct ed *ed = td->ed;
u32 cc = td->status;
/* ISO...drivers see per-TD length/status */
if (ed->mode == FHCI_TF_ISO) {
u32 len;
if (!(urb->transfer_flags & URB_SHORT_NOT_OK &&
cc == USB_TD_RX_DATA_UNDERUN))
cc = USB_TD_OK;
if (usb_pipeout(urb->pipe))
len = urb->iso_frame_desc[td->iso_index].length;
else
len = td->actual_len;
urb->actual_length += len;
urb->iso_frame_desc[td->iso_index].actual_length = len;
urb->iso_frame_desc[td->iso_index].status =
status_to_error(cc);
}
/* BULK,INT,CONTROL... drivers see aggregate length/status,
* except that "setup" bytes aren't counted and "short" transfers
* might not be reported as errors.
*/
else {
if (td->error_cnt >= 3)
urb->error_count = 3;
/* control endpoint only have soft stalls */
/* update packet status if needed(short may be ok) */
if (!(urb->transfer_flags & URB_SHORT_NOT_OK) &&
cc == USB_TD_RX_DATA_UNDERUN) {
ed->state = FHCI_ED_OPER;
cc = USB_TD_OK;
}
if (cc != USB_TD_OK) {
if (urb->status == -EINPROGRESS)
urb->status = status_to_error(cc);
}
/* count all non-empty packets except control SETUP packet */
if (td->type != FHCI_TA_SETUP || td->iso_index != 0)
urb->actual_length += td->actual_len;
}
}
/* there are some pedning request to unlink */
void fhci_del_ed_list(struct fhci_hcd *fhci, struct ed *ed)
{
struct td *td = peek_td_from_ed(ed);
struct urb *urb = td->urb;
struct urb_priv *urb_priv = urb->hcpriv;
if (urb_priv->state == URB_DEL) {
td = fhci_remove_td_from_ed(ed);
/* HC may have partly processed this TD */
if (td->status != USB_TD_INPROGRESS)
fhci_done_td(urb, td);
/* URB is done;clean up */
if (++(urb_priv->tds_cnt) == urb_priv->num_of_tds)
fhci_urb_complete_free(fhci, urb);
}
}
| gpl-2.0 |
Xluco/kernel_smp601 | drivers/media/video/exynos/fimc-is-mc2/fimc-is-sec-i2c.c | 43 | 3853 | /*
* Samsung Exynos5 SoC series FIMC-IS eeprom i2c driver
*
* exynos5 fimc-is eeprom i2c functions
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd
*
* 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/i2c.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/version.h>
#include <linux/gpio.h>
#include <linux/clk.h>
#include <linux/regulator/consumer.h>
#include <linux/videodev2.h>
#include <linux/videodev2_exynos_camera.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/platform_device.h>
#include <mach/regs-gpio.h>
#include <mach/regs-clock.h>
#include <mach/exynos-clock.h>
#include <plat/clock.h>
#include <plat/gpio-cfg.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-device.h>
#include <media/v4l2-subdev.h>
#include <media/exynos_fimc_is_sensor.h>
#include "fimc-is-sec-i2c.h"
#define SEC_CAMERA_EEPROM_ID 11
#define SEC_CAMERA_EEPROM_NAME "cameraeeprom"
struct i2c_client *camera_eeprom_i2c_client;
int fimc_is_sec_i2c_read(unsigned char *saddr, unsigned char *sbuf, int size)
{
int ret;
struct i2c_msg msg[2];
ret = 0;
if (!camera_eeprom_i2c_client) {
printk(KERN_ERR "%s : Could not find client!!\n", __func__);
return -ENODEV;
}
if (!camera_eeprom_i2c_client->adapter) {
printk(KERN_ERR "%s : Could not find adapter!\n", __func__);
return -ENODEV;
}
/* set eeprom address */
msg[0].addr = camera_eeprom_i2c_client->addr;
msg[0].flags = 0; /* write */
msg[0].len = 2;
msg[0].buf = saddr;
/* 2. I2C operation for reading data. */
msg[1].addr = camera_eeprom_i2c_client->addr;
msg[1].flags = I2C_M_RD;
msg[1].len = size;
msg[1].buf = sbuf;
ret = i2c_transfer(camera_eeprom_i2c_client->adapter, msg, 2);
if (ret < 0) {
printk(KERN_ERR "%s : i2c transfer fail\n", __func__);
}
return ret;
}
int fimc_is_sec_i2c_write(unsigned char *saddr, unsigned char *sbuf, int size)
{
struct i2c_msg msg[1];
int ret;
ret = 0;
if (!camera_eeprom_i2c_client) {
printk(KERN_ERR "%s : Could not find client!!\n", __func__);
return -ENODEV;
}
if (!camera_eeprom_i2c_client->adapter) {
printk(KERN_ERR "%s : Could not find adapter!\n", __func__);
return -ENODEV;
}
msg->addr = camera_eeprom_i2c_client->addr;
msg->flags = 0;
msg->len = size;
msg->buf = sbuf;
ret = i2c_transfer(camera_eeprom_i2c_client->adapter, msg, 1);
if (ret < 0) {
printk(KERN_ERR "%s : i2c transfer fail\n", __func__);
}
return ret;
}
static int __devinit fimc_is_sec_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
camera_eeprom_i2c_client = client;
printk(KERN_INFO "%s : Probe success!!\n", __func__);
printk(KERN_INFO "%s : Client addr %d\n", __func__, client->addr);
return 0;
}
static int __devexit fimc_is_sec_i2c_remove(struct i2c_client *client)
{
return 0;
}
static const struct i2c_device_id camera_eeprom_id[] = {
{ SEC_CAMERA_EEPROM_NAME, 0 },
};
MODULE_DEVICE_TABLE(i2c, camera_eeprom_id);
static struct i2c_driver camera_eeprom_i2c_driver = {
.driver = {
.name = SEC_CAMERA_EEPROM_NAME,
},
.id_table = camera_eeprom_id,
.probe = fimc_is_sec_i2c_probe,
.remove = fimc_is_sec_i2c_remove,
};
static int __init fimc_is_sec_i2c_init(void)
{
printk(KERN_INFO "%s : module init Enter\n", __func__);
return i2c_add_driver(&camera_eeprom_i2c_driver);
}
static void __exit fimc_is_sec_i2c_exit(void)
{
printk(KERN_INFO "%s : module exit\n", __func__);
i2c_del_driver(&camera_eeprom_i2c_driver);
}
module_init(fimc_is_sec_i2c_init);
module_exit(fimc_is_sec_i2c_exit);
MODULE_AUTHOR("Donghyun Chang <dh348.chang@samsung.com>");
MODULE_DESCRIPTION("FIMC-IS EEPROM I2C driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
RyanMallon/linux-ep93xx | drivers/leds/leds-netxbig.c | 43 | 10873 | /*
* leds-netxbig.c - Driver for the 2Big and 5Big Network series LEDs
*
* Copyright (C) 2010 LaCie
*
* Author: Simon Guinot <sguinot@lacie.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/leds.h>
#include <linux/platform_data/leds-kirkwood-netxbig.h>
/*
* GPIO extension bus.
*/
static DEFINE_SPINLOCK(gpio_ext_lock);
static void gpio_ext_set_addr(struct netxbig_gpio_ext *gpio_ext, int addr)
{
int pin;
for (pin = 0; pin < gpio_ext->num_addr; pin++)
gpio_set_value(gpio_ext->addr[pin], (addr >> pin) & 1);
}
static void gpio_ext_set_data(struct netxbig_gpio_ext *gpio_ext, int data)
{
int pin;
for (pin = 0; pin < gpio_ext->num_data; pin++)
gpio_set_value(gpio_ext->data[pin], (data >> pin) & 1);
}
static void gpio_ext_enable_select(struct netxbig_gpio_ext *gpio_ext)
{
/* Enable select is done on the raising edge. */
gpio_set_value(gpio_ext->enable, 0);
gpio_set_value(gpio_ext->enable, 1);
}
static void gpio_ext_set_value(struct netxbig_gpio_ext *gpio_ext,
int addr, int value)
{
unsigned long flags;
spin_lock_irqsave(&gpio_ext_lock, flags);
gpio_ext_set_addr(gpio_ext, addr);
gpio_ext_set_data(gpio_ext, value);
gpio_ext_enable_select(gpio_ext);
spin_unlock_irqrestore(&gpio_ext_lock, flags);
}
static int __devinit gpio_ext_init(struct netxbig_gpio_ext *gpio_ext)
{
int err;
int i;
if (unlikely(!gpio_ext))
return -EINVAL;
/* Configure address GPIOs. */
for (i = 0; i < gpio_ext->num_addr; i++) {
err = gpio_request_one(gpio_ext->addr[i], GPIOF_OUT_INIT_LOW,
"GPIO extension addr");
if (err)
goto err_free_addr;
}
/* Configure data GPIOs. */
for (i = 0; i < gpio_ext->num_data; i++) {
err = gpio_request_one(gpio_ext->data[i], GPIOF_OUT_INIT_LOW,
"GPIO extension data");
if (err)
goto err_free_data;
}
/* Configure "enable select" GPIO. */
err = gpio_request_one(gpio_ext->enable, GPIOF_OUT_INIT_LOW,
"GPIO extension enable");
if (err)
goto err_free_data;
return 0;
err_free_data:
for (i = i - 1; i >= 0; i--)
gpio_free(gpio_ext->data[i]);
i = gpio_ext->num_addr;
err_free_addr:
for (i = i - 1; i >= 0; i--)
gpio_free(gpio_ext->addr[i]);
return err;
}
static void gpio_ext_free(struct netxbig_gpio_ext *gpio_ext)
{
int i;
gpio_free(gpio_ext->enable);
for (i = gpio_ext->num_addr - 1; i >= 0; i--)
gpio_free(gpio_ext->addr[i]);
for (i = gpio_ext->num_data - 1; i >= 0; i--)
gpio_free(gpio_ext->data[i]);
}
/*
* Class LED driver.
*/
struct netxbig_led_data {
struct netxbig_gpio_ext *gpio_ext;
struct led_classdev cdev;
int mode_addr;
int *mode_val;
int bright_addr;
int bright_max;
struct netxbig_led_timer *timer;
int num_timer;
enum netxbig_led_mode mode;
int sata;
spinlock_t lock;
};
static int netxbig_led_get_timer_mode(enum netxbig_led_mode *mode,
unsigned long delay_on,
unsigned long delay_off,
struct netxbig_led_timer *timer,
int num_timer)
{
int i;
for (i = 0; i < num_timer; i++) {
if (timer[i].delay_on == delay_on &&
timer[i].delay_off == delay_off) {
*mode = timer[i].mode;
return 0;
}
}
return -EINVAL;
}
static int netxbig_led_blink_set(struct led_classdev *led_cdev,
unsigned long *delay_on,
unsigned long *delay_off)
{
struct netxbig_led_data *led_dat =
container_of(led_cdev, struct netxbig_led_data, cdev);
enum netxbig_led_mode mode;
int mode_val;
int ret;
/* Look for a LED mode with the requested timer frequency. */
ret = netxbig_led_get_timer_mode(&mode, *delay_on, *delay_off,
led_dat->timer, led_dat->num_timer);
if (ret < 0)
return ret;
mode_val = led_dat->mode_val[mode];
if (mode_val == NETXBIG_LED_INVALID_MODE)
return -EINVAL;
spin_lock_irq(&led_dat->lock);
gpio_ext_set_value(led_dat->gpio_ext, led_dat->mode_addr, mode_val);
led_dat->mode = mode;
spin_unlock_irq(&led_dat->lock);
return 0;
}
static void netxbig_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct netxbig_led_data *led_dat =
container_of(led_cdev, struct netxbig_led_data, cdev);
enum netxbig_led_mode mode;
int mode_val, bright_val;
int set_brightness = 1;
unsigned long flags;
spin_lock_irqsave(&led_dat->lock, flags);
if (value == LED_OFF) {
mode = NETXBIG_LED_OFF;
set_brightness = 0;
} else {
if (led_dat->sata)
mode = NETXBIG_LED_SATA;
else if (led_dat->mode == NETXBIG_LED_OFF)
mode = NETXBIG_LED_ON;
else /* Keep 'timer' mode. */
mode = led_dat->mode;
}
mode_val = led_dat->mode_val[mode];
gpio_ext_set_value(led_dat->gpio_ext, led_dat->mode_addr, mode_val);
led_dat->mode = mode;
/*
* Note that the brightness register is shared between all the
* SATA LEDs. So, change the brightness setting for a single
* SATA LED will affect all the others.
*/
if (set_brightness) {
bright_val = DIV_ROUND_UP(value * led_dat->bright_max,
LED_FULL);
gpio_ext_set_value(led_dat->gpio_ext,
led_dat->bright_addr, bright_val);
}
spin_unlock_irqrestore(&led_dat->lock, flags);
}
static ssize_t netxbig_led_sata_store(struct device *dev,
struct device_attribute *attr,
const char *buff, size_t count)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct netxbig_led_data *led_dat =
container_of(led_cdev, struct netxbig_led_data, cdev);
unsigned long enable;
enum netxbig_led_mode mode;
int mode_val;
int ret;
ret = strict_strtoul(buff, 10, &enable);
if (ret < 0)
return ret;
enable = !!enable;
spin_lock_irq(&led_dat->lock);
if (led_dat->sata == enable) {
ret = count;
goto exit_unlock;
}
if (led_dat->mode != NETXBIG_LED_ON &&
led_dat->mode != NETXBIG_LED_SATA)
mode = led_dat->mode; /* Keep modes 'off' and 'timer'. */
else if (enable)
mode = NETXBIG_LED_SATA;
else
mode = NETXBIG_LED_ON;
mode_val = led_dat->mode_val[mode];
if (mode_val == NETXBIG_LED_INVALID_MODE) {
ret = -EINVAL;
goto exit_unlock;
}
gpio_ext_set_value(led_dat->gpio_ext, led_dat->mode_addr, mode_val);
led_dat->mode = mode;
led_dat->sata = enable;
ret = count;
exit_unlock:
spin_unlock_irq(&led_dat->lock);
return ret;
}
static ssize_t netxbig_led_sata_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct netxbig_led_data *led_dat =
container_of(led_cdev, struct netxbig_led_data, cdev);
return sprintf(buf, "%d\n", led_dat->sata);
}
static DEVICE_ATTR(sata, 0644, netxbig_led_sata_show, netxbig_led_sata_store);
static void delete_netxbig_led(struct netxbig_led_data *led_dat)
{
if (led_dat->mode_val[NETXBIG_LED_SATA] != NETXBIG_LED_INVALID_MODE)
device_remove_file(led_dat->cdev.dev, &dev_attr_sata);
led_classdev_unregister(&led_dat->cdev);
}
static int __devinit
create_netxbig_led(struct platform_device *pdev,
struct netxbig_led_data *led_dat,
const struct netxbig_led *template)
{
struct netxbig_led_platform_data *pdata = pdev->dev.platform_data;
int ret;
spin_lock_init(&led_dat->lock);
led_dat->gpio_ext = pdata->gpio_ext;
led_dat->cdev.name = template->name;
led_dat->cdev.default_trigger = template->default_trigger;
led_dat->cdev.blink_set = netxbig_led_blink_set;
led_dat->cdev.brightness_set = netxbig_led_set;
/*
* Because the GPIO extension bus don't allow to read registers
* value, there is no way to probe the LED initial state.
* So, the initial sysfs LED value for the "brightness" and "sata"
* attributes are inconsistent.
*
* Note that the initial LED state can't be reconfigured.
* The reason is that the LED behaviour must stay uniform during
* the whole boot process (bootloader+linux).
*/
led_dat->sata = 0;
led_dat->cdev.brightness = LED_OFF;
led_dat->cdev.flags |= LED_CORE_SUSPENDRESUME;
led_dat->mode_addr = template->mode_addr;
led_dat->mode_val = template->mode_val;
led_dat->bright_addr = template->bright_addr;
led_dat->bright_max = (1 << pdata->gpio_ext->num_data) - 1;
led_dat->timer = pdata->timer;
led_dat->num_timer = pdata->num_timer;
ret = led_classdev_register(&pdev->dev, &led_dat->cdev);
if (ret < 0)
return ret;
/*
* If available, expose the SATA activity blink capability through
* a "sata" sysfs attribute.
*/
if (led_dat->mode_val[NETXBIG_LED_SATA] != NETXBIG_LED_INVALID_MODE) {
ret = device_create_file(led_dat->cdev.dev, &dev_attr_sata);
if (ret)
led_classdev_unregister(&led_dat->cdev);
}
return ret;
}
static int __devinit netxbig_led_probe(struct platform_device *pdev)
{
struct netxbig_led_platform_data *pdata = pdev->dev.platform_data;
struct netxbig_led_data *leds_data;
int i;
int ret;
if (!pdata)
return -EINVAL;
leds_data = devm_kzalloc(&pdev->dev,
sizeof(struct netxbig_led_data) * pdata->num_leds, GFP_KERNEL);
if (!leds_data)
return -ENOMEM;
ret = gpio_ext_init(pdata->gpio_ext);
if (ret < 0)
return ret;
for (i = 0; i < pdata->num_leds; i++) {
ret = create_netxbig_led(pdev, &leds_data[i], &pdata->leds[i]);
if (ret < 0)
goto err_free_leds;
}
platform_set_drvdata(pdev, leds_data);
return 0;
err_free_leds:
for (i = i - 1; i >= 0; i--)
delete_netxbig_led(&leds_data[i]);
gpio_ext_free(pdata->gpio_ext);
return ret;
}
static int __devexit netxbig_led_remove(struct platform_device *pdev)
{
struct netxbig_led_platform_data *pdata = pdev->dev.platform_data;
struct netxbig_led_data *leds_data;
int i;
leds_data = platform_get_drvdata(pdev);
for (i = 0; i < pdata->num_leds; i++)
delete_netxbig_led(&leds_data[i]);
gpio_ext_free(pdata->gpio_ext);
return 0;
}
static struct platform_driver netxbig_led_driver = {
.probe = netxbig_led_probe,
.remove = __devexit_p(netxbig_led_remove),
.driver = {
.name = "leds-netxbig",
.owner = THIS_MODULE,
},
};
module_platform_driver(netxbig_led_driver);
MODULE_AUTHOR("Simon Guinot <sguinot@lacie.com>");
MODULE_DESCRIPTION("LED driver for LaCie xBig Network boards");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:leds-netxbig");
| gpl-2.0 |
flar2/bulletproof-flo | drivers/gpu/msm/z180.c | 43 | 27864 | /* Copyright (c) 2002,2007-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/sched.h>
#include "kgsl.h"
#include "kgsl_cffdump.h"
#include "kgsl_sharedmem.h"
#include "z180.h"
#include "z180_reg.h"
#include "z180_trace.h"
#define DRIVER_VERSION_MAJOR 3
#define DRIVER_VERSION_MINOR 1
#define GSL_VGC_INT_MASK \
(REG_VGC_IRQSTATUS__MH_MASK | \
REG_VGC_IRQSTATUS__G2D_MASK | \
REG_VGC_IRQSTATUS__FIFO_MASK)
#define VGV3_NEXTCMD_JUMP 0x01
#define VGV3_NEXTCMD_NEXTCMD_FSHIFT 12
#define VGV3_NEXTCMD_NEXTCMD_FMASK 0x7
#define VGV3_CONTROL_MARKADD_FSHIFT 0
#define VGV3_CONTROL_MARKADD_FMASK 0xfff
#define Z180_MARKER_SIZE 10
#define Z180_CALL_CMD 0x1000
#define Z180_MARKER_CMD 0x8000
#define Z180_STREAM_END_CMD 0x9000
#define Z180_STREAM_PACKET 0x7C000176
#define Z180_STREAM_PACKET_CALL 0x7C000275
#define NUMTEXUNITS 4
#define TEXUNITREGCOUNT 25
#define VG_REGCOUNT 0x39
#define PACKETSIZE_BEGIN 3
#define PACKETSIZE_G2DCOLOR 2
#define PACKETSIZE_TEXUNIT (TEXUNITREGCOUNT * 2)
#define PACKETSIZE_REG (VG_REGCOUNT * 2)
#define PACKETSIZE_STATE (PACKETSIZE_TEXUNIT * NUMTEXUNITS + \
PACKETSIZE_REG + PACKETSIZE_BEGIN + \
PACKETSIZE_G2DCOLOR)
#define PACKETSIZE_STATESTREAM (ALIGN((PACKETSIZE_STATE * \
sizeof(unsigned int)), 32) / \
sizeof(unsigned int))
#define Z180_INVALID_CONTEXT UINT_MAX
/* z180 MH arbiter config*/
#define Z180_CFG_MHARB \
(0x10 \
| (0 << MH_ARBITER_CONFIG__SAME_PAGE_GRANULARITY__SHIFT) \
| (1 << MH_ARBITER_CONFIG__L1_ARB_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__L1_ARB_HOLD_ENABLE__SHIFT) \
| (0 << MH_ARBITER_CONFIG__L2_ARB_CONTROL__SHIFT) \
| (1 << MH_ARBITER_CONFIG__PAGE_SIZE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__TC_REORDER_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__TC_ARB_HOLD_ENABLE__SHIFT) \
| (0 << MH_ARBITER_CONFIG__IN_FLIGHT_LIMIT_ENABLE__SHIFT) \
| (0x8 << MH_ARBITER_CONFIG__IN_FLIGHT_LIMIT__SHIFT) \
| (1 << MH_ARBITER_CONFIG__CP_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__VGT_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__TC_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__RB_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__PA_CLNT_ENABLE__SHIFT))
#define Z180_TIMESTAMP_EPSILON 20000
#define Z180_IDLE_COUNT_MAX 1000000
enum z180_cmdwindow_type {
Z180_CMDWINDOW_2D = 0x00000000,
Z180_CMDWINDOW_MMU = 0x00000002,
};
#define Z180_CMDWINDOW_TARGET_MASK 0x000000FF
#define Z180_CMDWINDOW_ADDR_MASK 0x00FFFF00
#define Z180_CMDWINDOW_TARGET_SHIFT 0
#define Z180_CMDWINDOW_ADDR_SHIFT 8
static int z180_init(struct kgsl_device *device);
static int z180_start(struct kgsl_device *device);
static int z180_stop(struct kgsl_device *device);
static int z180_wait(struct kgsl_device *device,
struct kgsl_context *context,
unsigned int timestamp,
unsigned int msecs);
static void z180_regread(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int *value);
static void z180_regwrite(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int value);
static void z180_cmdwindow_write(struct kgsl_device *device,
unsigned int addr,
unsigned int data);
#define Z180_MMU_CONFIG \
(0x01 \
| (MMU_CONFIG << MH_MMU_CONFIG__RB_W_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_W_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R0_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R1_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R2_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R3_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R4_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__VGT_R0_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__VGT_R1_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__TC_R_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__PA_W_CLNT_BEHAVIOR__SHIFT))
static const struct kgsl_functable z180_functable;
static struct z180_device device_2d0 = {
.dev = {
KGSL_DEVICE_COMMON_INIT(device_2d0.dev),
.name = DEVICE_2D0_NAME,
.id = KGSL_DEVICE_2D0,
.mh = {
.mharb = Z180_CFG_MHARB,
.mh_intf_cfg1 = 0x00032f07,
.mh_intf_cfg2 = 0x004b274f,
/* turn off memory protection unit by setting
acceptable physical address range to include
all pages. */
.mpu_base = 0x00000000,
.mpu_range = 0xFFFFF000,
},
.mmu = {
.config = Z180_MMU_CONFIG,
},
.pwrctrl = {
.irq_name = KGSL_2D0_IRQ,
},
.iomemname = KGSL_2D0_REG_MEMORY,
.ftbl = &z180_functable,
},
.cmdwin_lock = __SPIN_LOCK_INITIALIZER(device_2d1.cmdwin_lock),
};
static struct z180_device device_2d1 = {
.dev = {
KGSL_DEVICE_COMMON_INIT(device_2d1.dev),
.name = DEVICE_2D1_NAME,
.id = KGSL_DEVICE_2D1,
.mh = {
.mharb = Z180_CFG_MHARB,
.mh_intf_cfg1 = 0x00032f07,
.mh_intf_cfg2 = 0x004b274f,
/* turn off memory protection unit by setting
acceptable physical address range to include
all pages. */
.mpu_base = 0x00000000,
.mpu_range = 0xFFFFF000,
},
.mmu = {
.config = Z180_MMU_CONFIG,
},
.pwrctrl = {
.irq_name = KGSL_2D1_IRQ,
},
.iomemname = KGSL_2D1_REG_MEMORY,
.ftbl = &z180_functable,
},
.cmdwin_lock = __SPIN_LOCK_INITIALIZER(device_2d1.cmdwin_lock),
};
static irqreturn_t z180_irq_handler(struct kgsl_device *device)
{
irqreturn_t result = IRQ_NONE;
unsigned int status;
struct z180_device *z180_dev = Z180_DEVICE(device);
z180_regread(device, ADDR_VGC_IRQSTATUS >> 2, &status);
trace_kgsl_z180_irq_status(device, status);
if (status & GSL_VGC_INT_MASK) {
z180_regwrite(device,
ADDR_VGC_IRQSTATUS >> 2, status & GSL_VGC_INT_MASK);
result = IRQ_HANDLED;
if (status & REG_VGC_IRQSTATUS__FIFO_MASK)
KGSL_DRV_ERR(device, "z180 fifo interrupt\n");
if (status & REG_VGC_IRQSTATUS__MH_MASK)
kgsl_mh_intrcallback(device);
if (status & REG_VGC_IRQSTATUS__G2D_MASK) {
int count;
z180_regread(device,
ADDR_VGC_IRQ_ACTIVE_CNT >> 2,
&count);
count >>= 8;
count &= 255;
z180_dev->timestamp += count;
queue_work(device->work_queue, &device->ts_expired_ws);
wake_up_interruptible(&device->wait_queue);
}
}
if ((device->pwrctrl.nap_allowed == true) &&
(device->requested_state == KGSL_STATE_NONE)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NAP);
queue_work(device->work_queue, &device->idle_check_ws);
}
mod_timer_pending(&device->idle_timer,
jiffies + device->pwrctrl.interval_timeout);
return result;
}
static void z180_cleanup_pt(struct kgsl_device *device,
struct kgsl_pagetable *pagetable)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
kgsl_mmu_unmap(pagetable, &device->mmu.setstate_memory);
kgsl_mmu_unmap(pagetable, &device->memstore);
kgsl_mmu_unmap(pagetable, &z180_dev->ringbuffer.cmdbufdesc);
}
static int z180_setup_pt(struct kgsl_device *device,
struct kgsl_pagetable *pagetable)
{
int result = 0;
struct z180_device *z180_dev = Z180_DEVICE(device);
result = kgsl_mmu_map_global(pagetable, &device->mmu.setstate_memory);
if (result)
goto error;
result = kgsl_mmu_map_global(pagetable, &device->memstore);
if (result)
goto error_unmap_dummy;
result = kgsl_mmu_map_global(pagetable,
&z180_dev->ringbuffer.cmdbufdesc);
if (result)
goto error_unmap_memstore;
/*
* Set the mpu end to the last "normal" global memory we use.
* For the IOMMU, this will be used to restrict access to the
* mapped registers.
*/
device->mh.mpu_range = z180_dev->ringbuffer.cmdbufdesc.gpuaddr +
z180_dev->ringbuffer.cmdbufdesc.size;
return result;
error_unmap_dummy:
kgsl_mmu_unmap(pagetable, &device->mmu.setstate_memory);
error_unmap_memstore:
kgsl_mmu_unmap(pagetable, &device->memstore);
error:
return result;
}
static inline unsigned int rb_offset(unsigned int timestamp)
{
return (timestamp % Z180_PACKET_COUNT)
*sizeof(unsigned int)*(Z180_PACKET_SIZE);
}
static inline unsigned int rb_gpuaddr(struct z180_device *z180_dev,
unsigned int timestamp)
{
return z180_dev->ringbuffer.cmdbufdesc.gpuaddr + rb_offset(timestamp);
}
static void addmarker(struct z180_ringbuffer *rb, unsigned int timestamp)
{
char *ptr = (char *)(rb->cmdbufdesc.hostptr);
unsigned int *p = (unsigned int *)(ptr + rb_offset(timestamp));
*p++ = Z180_STREAM_PACKET;
*p++ = (Z180_MARKER_CMD | 5);
*p++ = ADDR_VGV3_LAST << 24;
*p++ = ADDR_VGV3_LAST << 24;
*p++ = ADDR_VGV3_LAST << 24;
*p++ = Z180_STREAM_PACKET;
*p++ = 5;
*p++ = ADDR_VGV3_LAST << 24;
*p++ = ADDR_VGV3_LAST << 24;
*p++ = ADDR_VGV3_LAST << 24;
}
static void addcmd(struct z180_ringbuffer *rb, unsigned int timestamp,
unsigned int cmd, unsigned int nextcnt)
{
char * ptr = (char *)(rb->cmdbufdesc.hostptr);
unsigned int *p = (unsigned int *)(ptr + (rb_offset(timestamp)
+ (Z180_MARKER_SIZE * sizeof(unsigned int))));
*p++ = Z180_STREAM_PACKET_CALL;
*p++ = cmd;
*p++ = Z180_CALL_CMD | nextcnt;
*p++ = ADDR_VGV3_LAST << 24;
*p++ = ADDR_VGV3_LAST << 24;
}
static void z180_cmdstream_start(struct kgsl_device *device)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
unsigned int cmd = VGV3_NEXTCMD_JUMP << VGV3_NEXTCMD_NEXTCMD_FSHIFT;
addmarker(&z180_dev->ringbuffer, 0);
z180_cmdwindow_write(device, ADDR_VGV3_MODE, 4);
z180_cmdwindow_write(device, ADDR_VGV3_NEXTADDR,
rb_gpuaddr(z180_dev, z180_dev->current_timestamp));
z180_cmdwindow_write(device, ADDR_VGV3_NEXTCMD, cmd | 5);
z180_cmdwindow_write(device, ADDR_VGV3_WRITEADDR,
device->memstore.gpuaddr);
cmd = (int)(((1) & VGV3_CONTROL_MARKADD_FMASK)
<< VGV3_CONTROL_MARKADD_FSHIFT);
z180_cmdwindow_write(device, ADDR_VGV3_CONTROL, cmd);
z180_cmdwindow_write(device, ADDR_VGV3_CONTROL, 0);
}
static int room_in_rb(struct z180_device *device)
{
int ts_diff;
ts_diff = device->current_timestamp - device->timestamp;
return ts_diff < Z180_PACKET_COUNT;
}
/**
* z180_idle() - Idle the 2D device
* @device: Pointer to the KGSL device struct for the Z180
*
* wait until the z180 submission queue is idle
*/
int z180_idle(struct kgsl_device *device)
{
int status = 0;
struct z180_device *z180_dev = Z180_DEVICE(device);
if (timestamp_cmp(z180_dev->current_timestamp,
z180_dev->timestamp) > 0)
status = z180_wait(device, NULL,
z180_dev->current_timestamp,
Z180_IDLE_TIMEOUT);
if (status)
KGSL_DRV_ERR(device, "z180_waittimestamp() timed out\n");
return status;
}
int
z180_cmdstream_issueibcmds(struct kgsl_device_private *dev_priv,
struct kgsl_context *context,
struct kgsl_cmdbatch *cmdbatch,
uint32_t *timestamp)
{
long result = 0;
unsigned int ofs = PACKETSIZE_STATESTREAM * sizeof(unsigned int);
unsigned int cnt = 5;
unsigned int old_timestamp = 0;
unsigned int nextcnt = Z180_STREAM_END_CMD | 5;
struct kgsl_mem_entry *entry = NULL;
unsigned int cmd;
struct kgsl_device *device = dev_priv->device;
struct kgsl_pagetable *pagetable = dev_priv->process_priv->pagetable;
struct z180_device *z180_dev = Z180_DEVICE(device);
unsigned int sizedwords;
unsigned int numibs;
struct kgsl_ibdesc *ibdesc;
mutex_lock(&device->mutex);
kgsl_active_count_get(device);
if (cmdbatch == NULL) {
result = EINVAL;
goto error;
}
ibdesc = cmdbatch->ibdesc;
numibs = cmdbatch->ibcount;
if (device->state & KGSL_STATE_HUNG) {
result = -EINVAL;
goto error;
}
if (numibs != 1) {
KGSL_DRV_ERR(device, "Invalid number of ibs: %d\n", numibs);
result = -EINVAL;
goto error;
}
cmd = ibdesc[0].gpuaddr;
sizedwords = ibdesc[0].sizedwords;
/*
* Get a kernel mapping to the IB for monkey patching.
* See the end of this function.
*/
entry = kgsl_sharedmem_find_region(dev_priv->process_priv, cmd,
sizedwords);
if (entry == NULL) {
KGSL_DRV_ERR(device, "Bad ibdesc: gpuaddr 0x%x size %d\n",
cmd, sizedwords);
result = -EINVAL;
goto error;
}
/*
* This will only map memory if it exists, otherwise it will reuse the
* mapping. And the 2d userspace reuses IBs so we likely won't create
* too many mappings.
*/
if (kgsl_gpuaddr_to_vaddr(&entry->memdesc, cmd) == NULL) {
KGSL_DRV_ERR(device,
"Cannot make kernel mapping for gpuaddr 0x%x\n",
cmd);
result = -EINVAL;
goto error;
}
KGSL_CMD_INFO(device, "ctxt %d ibaddr 0x%08x sizedwords %d\n",
context->id, cmd, sizedwords);
/* context switch */
if ((context->id != (int)z180_dev->ringbuffer.prevctx) ||
(cmdbatch->flags & KGSL_CONTEXT_CTX_SWITCH)) {
KGSL_CMD_INFO(device, "context switch %d -> %d\n",
context->id, z180_dev->ringbuffer.prevctx);
kgsl_mmu_setstate(&device->mmu, pagetable,
KGSL_MEMSTORE_GLOBAL);
cnt = PACKETSIZE_STATESTREAM;
ofs = 0;
}
result = kgsl_setstate(&device->mmu,
KGSL_MEMSTORE_GLOBAL,
kgsl_mmu_pt_get_flags(device->mmu.hwpagetable,
device->id));
if (result < 0)
goto error;
result = wait_event_interruptible_timeout(device->wait_queue,
room_in_rb(z180_dev),
msecs_to_jiffies(KGSL_TIMEOUT_DEFAULT));
if (result < 0) {
KGSL_CMD_ERR(device, "wait_event_interruptible_timeout "
"failed: %ld\n", result);
goto error;
}
result = 0;
old_timestamp = z180_dev->current_timestamp;
z180_dev->current_timestamp++;
*timestamp = z180_dev->current_timestamp;
z180_dev->ringbuffer.prevctx = context->id;
addcmd(&z180_dev->ringbuffer, old_timestamp, cmd + ofs, cnt);
kgsl_pwrscale_busy(device);
/* Make sure the next ringbuffer entry has a marker */
addmarker(&z180_dev->ringbuffer, z180_dev->current_timestamp);
/* monkey patch the IB so that it jumps back to the ringbuffer */
kgsl_sharedmem_writel(&entry->memdesc,
((sizedwords + 1) * sizeof(unsigned int)),
rb_gpuaddr(z180_dev, z180_dev->current_timestamp));
kgsl_sharedmem_writel(&entry->memdesc,
((sizedwords + 2) * sizeof(unsigned int)),
nextcnt);
/* sync memory before activating the hardware for the new command*/
mb();
cmd = (int)(((2) & VGV3_CONTROL_MARKADD_FMASK)
<< VGV3_CONTROL_MARKADD_FSHIFT);
z180_cmdwindow_write(device, ADDR_VGV3_CONTROL, cmd);
z180_cmdwindow_write(device, ADDR_VGV3_CONTROL, 0);
error:
kgsl_trace_issueibcmds(device, context->id, cmdbatch,
*timestamp, cmdbatch->flags, result, 0);
kgsl_active_count_put(device);
mutex_unlock(&device->mutex);
return (int)result;
}
static int z180_ringbuffer_init(struct kgsl_device *device)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
memset(&z180_dev->ringbuffer, 0, sizeof(struct z180_ringbuffer));
z180_dev->ringbuffer.prevctx = Z180_INVALID_CONTEXT;
z180_dev->ringbuffer.cmdbufdesc.flags = KGSL_MEMFLAGS_GPUREADONLY;
return kgsl_allocate_contiguous(&z180_dev->ringbuffer.cmdbufdesc,
Z180_RB_SIZE);
}
static void z180_ringbuffer_close(struct kgsl_device *device)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
kgsl_sharedmem_free(&z180_dev->ringbuffer.cmdbufdesc);
memset(&z180_dev->ringbuffer, 0, sizeof(struct z180_ringbuffer));
}
static int __devinit z180_probe(struct platform_device *pdev)
{
int status = -EINVAL;
struct kgsl_device *device = NULL;
struct z180_device *z180_dev;
device = (struct kgsl_device *)pdev->id_entry->driver_data;
device->parentdev = &pdev->dev;
z180_dev = Z180_DEVICE(device);
status = z180_ringbuffer_init(device);
if (status != 0)
goto error;
status = kgsl_device_platform_probe(device);
if (status)
goto error_close_ringbuffer;
kgsl_pwrscale_init(device);
kgsl_pwrscale_attach_policy(device, Z180_DEFAULT_PWRSCALE_POLICY);
return status;
error_close_ringbuffer:
z180_ringbuffer_close(device);
error:
device->parentdev = NULL;
return status;
}
static int __devexit z180_remove(struct platform_device *pdev)
{
struct kgsl_device *device = NULL;
device = (struct kgsl_device *)pdev->id_entry->driver_data;
kgsl_pwrscale_close(device);
kgsl_device_platform_remove(device);
z180_ringbuffer_close(device);
return 0;
}
static int z180_init(struct kgsl_device *device)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
z180_dev->timestamp = 0;
z180_dev->current_timestamp = 0;
return 0;
}
static int z180_start(struct kgsl_device *device)
{
int status = 0;
kgsl_pwrctrl_set_state(device, KGSL_STATE_INIT);
kgsl_pwrctrl_enable(device);
/* Set interrupts to 0 to ensure a good state */
z180_regwrite(device, (ADDR_VGC_IRQENABLE >> 2), 0x0);
kgsl_mh_start(device);
status = kgsl_mmu_start(device);
if (status)
goto error_clk_off;
z180_cmdstream_start(device);
mod_timer(&device->idle_timer, jiffies + FIRST_TIMEOUT);
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_ON);
device->ftbl->irqctrl(device, 1);
device->reset_counter++;
return 0;
error_clk_off:
z180_regwrite(device, (ADDR_VGC_IRQENABLE >> 2), 0);
kgsl_pwrctrl_disable(device);
return status;
}
static int z180_stop(struct kgsl_device *device)
{
device->ftbl->irqctrl(device, 0);
z180_idle(device);
del_timer_sync(&device->idle_timer);
kgsl_mmu_stop(&device->mmu);
/* Disable the clocks before the power rail. */
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_disable(device);
return 0;
}
static int z180_getproperty(struct kgsl_device *device,
enum kgsl_property_type type,
void *value,
unsigned int sizebytes)
{
int status = -EINVAL;
switch (type) {
case KGSL_PROP_DEVICE_INFO:
{
struct kgsl_devinfo devinfo;
if (sizebytes != sizeof(devinfo)) {
status = -EINVAL;
break;
}
memset(&devinfo, 0, sizeof(devinfo));
devinfo.device_id = device->id+1;
devinfo.chip_id = 0;
devinfo.mmu_enabled = kgsl_mmu_enabled();
if (copy_to_user(value, &devinfo, sizeof(devinfo)) !=
0) {
status = -EFAULT;
break;
}
status = 0;
}
break;
case KGSL_PROP_MMU_ENABLE:
{
int mmu_prop = kgsl_mmu_enabled();
if (sizebytes != sizeof(int)) {
status = -EINVAL;
break;
}
if (copy_to_user(value, &mmu_prop, sizeof(mmu_prop))) {
status = -EFAULT;
break;
}
status = 0;
}
break;
default:
KGSL_DRV_ERR(device, "invalid property: %d\n", type);
status = -EINVAL;
}
return status;
}
static bool z180_isidle(struct kgsl_device *device)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
return (timestamp_cmp(z180_dev->timestamp,
z180_dev->current_timestamp) == 0) ? true : false;
}
static int z180_suspend_context(struct kgsl_device *device)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
z180_dev->ringbuffer.prevctx = Z180_INVALID_CONTEXT;
return 0;
}
/* Not all Z180 registers are directly accessible.
* The _z180_(read|write)_simple functions below handle the ones that are.
*/
static void _z180_regread_simple(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int *value)
{
unsigned int *reg;
BUG_ON(offsetwords * sizeof(uint32_t) >= device->reg_len);
reg = (unsigned int *)(device->reg_virt + (offsetwords << 2));
/*ensure this read finishes before the next one.
* i.e. act like normal readl() */
*value = __raw_readl(reg);
rmb();
}
static void _z180_regwrite_simple(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int value)
{
unsigned int *reg;
BUG_ON(offsetwords*sizeof(uint32_t) >= device->reg_len);
reg = (unsigned int *)(device->reg_virt + (offsetwords << 2));
kgsl_cffdump_regwrite(device->id, offsetwords << 2, value);
/*ensure previous writes post before this one,
* i.e. act like normal writel() */
wmb();
__raw_writel(value, reg);
}
/* The MH registers must be accessed through via a 2 step write, (read|write)
* process. These registers may be accessed from interrupt context during
* the handling of MH or MMU error interrupts. Therefore a spin lock is used
* to ensure that the 2 step sequence is not interrupted.
*/
static void _z180_regread_mmu(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int *value)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
unsigned long flags;
spin_lock_irqsave(&z180_dev->cmdwin_lock, flags);
_z180_regwrite_simple(device, (ADDR_VGC_MH_READ_ADDR >> 2),
offsetwords);
_z180_regread_simple(device, (ADDR_VGC_MH_DATA_ADDR >> 2), value);
spin_unlock_irqrestore(&z180_dev->cmdwin_lock, flags);
}
static void _z180_regwrite_mmu(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int value)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
unsigned int cmdwinaddr;
unsigned long flags;
cmdwinaddr = ((Z180_CMDWINDOW_MMU << Z180_CMDWINDOW_TARGET_SHIFT) &
Z180_CMDWINDOW_TARGET_MASK);
cmdwinaddr |= ((offsetwords << Z180_CMDWINDOW_ADDR_SHIFT) &
Z180_CMDWINDOW_ADDR_MASK);
spin_lock_irqsave(&z180_dev->cmdwin_lock, flags);
_z180_regwrite_simple(device, ADDR_VGC_MMUCOMMANDSTREAM >> 2,
cmdwinaddr);
_z180_regwrite_simple(device, ADDR_VGC_MMUCOMMANDSTREAM >> 2, value);
spin_unlock_irqrestore(&z180_dev->cmdwin_lock, flags);
}
/* the rest of the code doesn't want to think about if it is writing mmu
* registers or normal registers so handle it here
*/
static void z180_regread(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int *value)
{
if (!in_interrupt())
kgsl_pre_hwaccess(device);
if ((offsetwords >= MH_ARBITER_CONFIG &&
offsetwords <= MH_AXI_HALT_CONTROL) ||
(offsetwords >= MH_MMU_CONFIG &&
offsetwords <= MH_MMU_MPU_END)) {
_z180_regread_mmu(device, offsetwords, value);
} else {
_z180_regread_simple(device, offsetwords, value);
}
}
static void z180_regwrite(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int value)
{
if (!in_interrupt())
kgsl_pre_hwaccess(device);
if ((offsetwords >= MH_ARBITER_CONFIG &&
offsetwords <= MH_CLNT_INTF_CTRL_CONFIG2) ||
(offsetwords >= MH_MMU_CONFIG &&
offsetwords <= MH_MMU_MPU_END)) {
_z180_regwrite_mmu(device, offsetwords, value);
} else {
_z180_regwrite_simple(device, offsetwords, value);
}
}
static void z180_cmdwindow_write(struct kgsl_device *device,
unsigned int addr, unsigned int data)
{
unsigned int cmdwinaddr;
cmdwinaddr = ((Z180_CMDWINDOW_2D << Z180_CMDWINDOW_TARGET_SHIFT) &
Z180_CMDWINDOW_TARGET_MASK);
cmdwinaddr |= ((addr << Z180_CMDWINDOW_ADDR_SHIFT) &
Z180_CMDWINDOW_ADDR_MASK);
z180_regwrite(device, ADDR_VGC_COMMANDSTREAM >> 2, cmdwinaddr);
z180_regwrite(device, ADDR_VGC_COMMANDSTREAM >> 2, data);
}
static unsigned int z180_readtimestamp(struct kgsl_device *device,
struct kgsl_context *context, enum kgsl_timestamp_type type)
{
struct z180_device *z180_dev = Z180_DEVICE(device);
(void)context;
/* get current EOP timestamp */
return z180_dev->timestamp;
}
static int z180_waittimestamp(struct kgsl_device *device,
struct kgsl_context *context,
unsigned int timestamp,
unsigned int msecs)
{
int status = -EINVAL;
/* Don't wait forever, set a max of Z180_IDLE_TIMEOUT */
if (msecs == -1)
msecs = Z180_IDLE_TIMEOUT;
mutex_unlock(&device->mutex);
status = z180_wait(device, context, timestamp, msecs);
mutex_lock(&device->mutex);
return status;
}
static int z180_wait(struct kgsl_device *device,
struct kgsl_context *context,
unsigned int timestamp,
unsigned int msecs)
{
int status = -EINVAL;
long timeout = 0;
timeout = wait_io_event_interruptible_timeout(
device->wait_queue,
kgsl_check_timestamp(device, context, timestamp),
msecs_to_jiffies(msecs));
if (timeout > 0)
status = 0;
else if (timeout == 0) {
status = -ETIMEDOUT;
kgsl_pwrctrl_set_state(device, KGSL_STATE_HUNG);
kgsl_postmortem_dump(device, 0);
} else
status = timeout;
return status;
}
struct kgsl_context *
z180_drawctxt_create(struct kgsl_device_private *dev_priv,
uint32_t *flags)
{
int ret;
struct kgsl_context *context = kzalloc(sizeof(*context), GFP_KERNEL);
if (context == NULL)
return ERR_PTR(-ENOMEM);
ret = kgsl_context_init(dev_priv, context);
if (ret != 0) {
kfree(context);
return ERR_PTR(ret);
}
return context;
}
static int
z180_drawctxt_detach(struct kgsl_context *context)
{
struct kgsl_device *device;
struct z180_device *z180_dev;
device = context->device;
z180_dev = Z180_DEVICE(device);
z180_idle(device);
if (z180_dev->ringbuffer.prevctx == context->id) {
z180_dev->ringbuffer.prevctx = Z180_INVALID_CONTEXT;
device->mmu.hwpagetable = device->mmu.defaultpagetable;
kgsl_setstate(&device->mmu, KGSL_MEMSTORE_GLOBAL,
KGSL_MMUFLAGS_PTUPDATE);
}
return 0;
}
static void
z180_drawctxt_destroy(struct kgsl_context *context)
{
kfree(context);
}
static void z180_power_stats(struct kgsl_device *device,
struct kgsl_power_stats *stats)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
s64 tmp = ktime_to_us(ktime_get());
if (pwr->time == 0) {
pwr->time = tmp;
stats->total_time = 0;
stats->busy_time = 0;
} else {
stats->total_time = tmp - pwr->time;
pwr->time = tmp;
stats->busy_time = tmp - device->on_time;
device->on_time = tmp;
}
}
static void z180_irqctrl(struct kgsl_device *device, int state)
{
/* Control interrupts for Z180 and the Z180 MMU */
if (state) {
z180_regwrite(device, (ADDR_VGC_IRQENABLE >> 2), 3);
z180_regwrite(device, MH_INTERRUPT_MASK,
kgsl_mmu_get_int_mask());
} else {
z180_regwrite(device, (ADDR_VGC_IRQENABLE >> 2), 0);
z180_regwrite(device, MH_INTERRUPT_MASK, 0);
}
}
static unsigned int z180_gpuid(struct kgsl_device *device, unsigned int *chipid)
{
if (chipid != NULL)
*chipid = 0;
/* Standard KGSL gpuid format:
* top word is 0x0002 for 2D or 0x0003 for 3D
* Bottom word is core specific identifer
*/
return (0x0002 << 16) | 180;
}
static const struct kgsl_functable z180_functable = {
/* Mandatory functions */
.regread = z180_regread,
.regwrite = z180_regwrite,
.idle = z180_idle,
.isidle = z180_isidle,
.suspend_context = z180_suspend_context,
.init = z180_init,
.start = z180_start,
.stop = z180_stop,
.getproperty = z180_getproperty,
.waittimestamp = z180_waittimestamp,
.readtimestamp = z180_readtimestamp,
.issueibcmds = z180_cmdstream_issueibcmds,
.setup_pt = z180_setup_pt,
.cleanup_pt = z180_cleanup_pt,
.power_stats = z180_power_stats,
.irqctrl = z180_irqctrl,
.gpuid = z180_gpuid,
.irq_handler = z180_irq_handler,
.drain = z180_idle, /* drain == idle for the z180 */
/* Optional functions */
.drawctxt_create = z180_drawctxt_create,
.drawctxt_detach = z180_drawctxt_detach,
.drawctxt_destroy = z180_drawctxt_destroy,
.ioctl = NULL,
.postmortem_dump = z180_dump,
};
static struct platform_device_id z180_id_table[] = {
{ DEVICE_2D0_NAME, (kernel_ulong_t)&device_2d0.dev, },
{ DEVICE_2D1_NAME, (kernel_ulong_t)&device_2d1.dev, },
{ },
};
MODULE_DEVICE_TABLE(platform, z180_id_table);
static struct platform_driver z180_platform_driver = {
.probe = z180_probe,
.remove = __devexit_p(z180_remove),
.suspend = kgsl_suspend_driver,
.resume = kgsl_resume_driver,
.id_table = z180_id_table,
.driver = {
.owner = THIS_MODULE,
.name = DEVICE_2D_NAME,
.pm = &kgsl_pm_ops,
}
};
static int __init kgsl_2d_init(void)
{
return platform_driver_register(&z180_platform_driver);
}
static void __exit kgsl_2d_exit(void)
{
platform_driver_unregister(&z180_platform_driver);
}
module_init(kgsl_2d_init);
module_exit(kgsl_2d_exit);
MODULE_DESCRIPTION("2D Graphics driver");
MODULE_VERSION("1.2");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:kgsl_2d");
| gpl-2.0 |
Mouseomics/R | src/appl/dsvdc.f | 43 | 15713 | c -- called from R's svd(x, ..., LINPACK = TRUE) , i.e, *NOT* by default --
c
c dsvdc is a subroutine to reduce a double precision nxp matrix x
c by orthogonal transformations u and v to diagonal form. the
c diagonal elements s(i) are the singular values of x. the
c columns of u are the corresponding left singular vectors,
c and the columns of v the right singular vectors.
c
c on entry
c
c x double precision(ldx,p), where ldx.ge.n.
c x contains the matrix whose singular value
c decomposition is to be computed. x is
c destroyed by dsvdc.
c
c ldx integer.
c ldx is the leading dimension of the array x.
c
c n integer.
c n is the number of rows of the matrix x.
c
c p integer.
c p is the number of columns of the matrix x.
c
c ldu integer.
c ldu is the leading dimension of the array u.
c (see below).
c
c ldv integer.
c ldv is the leading dimension of the array v.
c (see below).
c
c work double precision(n).
c work is a scratch array.
c
c job integer.
c job controls the computation of the singular
c vectors. it has the decimal expansion ab
c with the following meaning
c
c a.eq.0 do not compute the left singular
c vectors.
c a.eq.1 return the n left singular vectors
c in u.
c a.ge.2 return the first min(n,p) singular
c vectors in u.
c b.eq.0 do not compute the right singular
c vectors.
c b.eq.1 return the right singular vectors
c in v.
c
c on return
c
c s double precision(mm), where mm=min(n+1,p).
c the first min(n,p) entries of s contain the
c singular values of x arranged in descending
c order of magnitude.
c
c e double precision(p),
c e ordinarily contains zeros. however see the
c discussion of info for exceptions.
c
c u double precision(ldu,k), where ldu.ge.n. if
c joba.eq.1 then k.eq.n, if joba.ge.2
c then k.eq.min(n,p).
c u contains the matrix of left singular vectors.
c u is not referenced if joba.eq.0. if n.le.p
c or if joba.eq.2, then u may be identified with x
c in the subroutine call.
c
c v double precision(ldv,p), where ldv.ge.p.
c v contains the matrix of right singular vectors.
c v is not referenced if job.eq.0. if p.le.n,
c then v may be identified with x in the
c subroutine call.
c
c info integer.
c the singular values (and their corresponding
c singular vectors) s(info+1),s(info+2),...,s(m)
c are correct (here m=min(n,p)). thus if
c info.eq.0, all the singular values and their
c vectors are correct. in any event, the matrix
c b = trans(u)*x*v is the bidiagonal matrix
c with the elements of s on its diagonal and the
c elements of e on its super-diagonal (trans(u)
c is the transpose of u). thus the singular
c values of x and b are the same.
c
c linpack. this version dated 08/14/78 .
c correction made to shift 2/84.
c g.w. stewart, university of maryland, argonne national lab.
c
c Modified 2000-12-28 to use a relative convergence test,
c as this was infinite-looping on ix86.
c
c dsvdc uses the following functions and subprograms.
c
c external drot
c blas daxpy,ddot,dscal,dswap,dnrm2,drotg
c fortran dabs,dmax1,max0,min0,mod,dsqrt
c
subroutine dsvdc(x,ldx,n,p,s,e,u,ldu,v,ldv,work,job,info)
integer ldx,n,p,ldu,ldv,job,info
double precision x(ldx,*),s(*),e(*),u(ldu,*),v(ldv,*),work(*)
c
c internal variables
c
integer i,iter,j,jobu,k,kase,kk,l,ll,lls,lm1,lp1,ls,lu,m,maxit,
* mm,mm1,mp1,nct,nctp1,ncu,nrt,nrtp1
double precision ddot,t
double precision b,c,cs,el,emm1,f,g,dnrm2,scale,shift,sl,sm,sn,
* smm1,t1,test,ztest,acc
logical wantu,wantv
c
c unnecessary initializations of l and ls to keep g77 -Wall happy
c
l = 0
ls = 0
c
c
c set the maximum number of iterations.
c
maxit = 30
c
c determine what is to be computed.
c
wantu = .false.
wantv = .false.
jobu = mod(job,100)/10
ncu = n
if (jobu .gt. 1) ncu = min0(n,p)
if (jobu .ne. 0) wantu = .true.
if (mod(job,10) .ne. 0) wantv = .true.
c
c reduce x to bidiagonal form, storing the diagonal elements
c in s and the super-diagonal elements in e.
c
info = 0
nct = min0(n-1,p)
nrt = max0(0,min0(p-2,n))
lu = max0(nct,nrt)
if (lu .lt. 1) go to 170
do 160 l = 1, lu
lp1 = l + 1
if (l .gt. nct) go to 20
c
c compute the transformation for the l-th column and
c place the l-th diagonal in s(l).
c
s(l) = dnrm2(n-l+1,x(l,l),1)
if (s(l) .eq. 0.0d0) go to 10
if (x(l,l) .ne. 0.0d0) s(l) = dsign(s(l),x(l,l))
call dscal(n-l+1,1.0d0/s(l),x(l,l),1)
x(l,l) = 1.0d0 + x(l,l)
10 continue
s(l) = -s(l)
20 continue
if (p .lt. lp1) go to 50
do 40 j = lp1, p
if (l .gt. nct) go to 30
if (s(l) .eq. 0.0d0) go to 30
c
c apply the transformation.
c
t = -ddot(n-l+1,x(l,l),1,x(l,j),1)/x(l,l)
call daxpy(n-l+1,t,x(l,l),1,x(l,j),1)
30 continue
c
c place the l-th row of x into e for the
c subsequent calculation of the row transformation.
c
e(j) = x(l,j)
40 continue
50 continue
if (.not.wantu .or. l .gt. nct) go to 70
c
c place the transformation in u for subsequent back
c multiplication.
c
do 60 i = l, n
u(i,l) = x(i,l)
60 continue
70 continue
if (l .gt. nrt) go to 150
c
c compute the l-th row transformation and place the
c l-th super-diagonal in e(l).
c
e(l) = dnrm2(p-l,e(lp1),1)
if (e(l) .eq. 0.0d0) go to 80
if (e(lp1) .ne. 0.0d0) e(l) = dsign(e(l),e(lp1))
call dscal(p-l,1.0d0/e(l),e(lp1),1)
e(lp1) = 1.0d0 + e(lp1)
80 continue
e(l) = -e(l)
if (lp1 .gt. n .or. e(l) .eq. 0.0d0) go to 120
c
c apply the transformation.
c
do 90 i = lp1, n
work(i) = 0.0d0
90 continue
do 100 j = lp1, p
call daxpy(n-l,e(j),x(lp1,j),1,work(lp1),1)
100 continue
do 110 j = lp1, p
call daxpy(n-l,-e(j)/e(lp1),work(lp1),1,x(lp1,j),1)
110 continue
120 continue
if (.not.wantv) go to 140
c
c place the transformation in v for subsequent
c back multiplication.
c
do 130 i = lp1, p
v(i,l) = e(i)
130 continue
140 continue
150 continue
160 continue
170 continue
c
c set up the final bidiagonal matrix or order m.
c
m = min0(p,n+1)
nctp1 = nct + 1
nrtp1 = nrt + 1
if (nct .lt. p) s(nctp1) = x(nctp1,nctp1)
if (n .lt. m) s(m) = 0.0d0
if (nrtp1 .lt. m) e(nrtp1) = x(nrtp1,m)
e(m) = 0.0d0
c
c if required, generate u.
c
if (.not.wantu) go to 300
if (ncu .lt. nctp1) go to 200
do 190 j = nctp1, ncu
do 180 i = 1, n
u(i,j) = 0.0d0
180 continue
u(j,j) = 1.0d0
190 continue
200 continue
if (nct .lt. 1) go to 290
do 280 ll = 1, nct
l = nct - ll + 1
if (s(l) .eq. 0.0d0) go to 250
lp1 = l + 1
if (ncu .lt. lp1) go to 220
do 210 j = lp1, ncu
t = -ddot(n-l+1,u(l,l),1,u(l,j),1)/u(l,l)
call daxpy(n-l+1,t,u(l,l),1,u(l,j),1)
210 continue
220 continue
call dscal(n-l+1,-1.0d0,u(l,l),1)
u(l,l) = 1.0d0 + u(l,l)
lm1 = l - 1
if (lm1 .lt. 1) go to 240
do 230 i = 1, lm1
u(i,l) = 0.0d0
230 continue
240 continue
go to 270
250 continue
do 260 i = 1, n
u(i,l) = 0.0d0
260 continue
u(l,l) = 1.0d0
270 continue
280 continue
290 continue
300 continue
c
c if it is required, generate v.
c
if (.not.wantv) go to 350
do 340 ll = 1, p
l = p - ll + 1
lp1 = l + 1
if (l .gt. nrt) go to 320
if (e(l) .eq. 0.0d0) go to 320
do 310 j = lp1, p
t = -ddot(p-l,v(lp1,l),1,v(lp1,j),1)/v(lp1,l)
call daxpy(p-l,t,v(lp1,l),1,v(lp1,j),1)
310 continue
320 continue
do 330 i = 1, p
v(i,l) = 0.0d0
330 continue
v(l,l) = 1.0d0
340 continue
350 continue
c
c main iteration loop for the singular values.
c
mm = m
iter = 0
360 continue
c
c quit if all the singular values have been found.
c
c ...exit
if (m .eq. 0) go to 620
c
c if too many iterations have been performed, set
c flag and return.
c
if (iter .lt. maxit) go to 370
info = m
c ......exit
go to 620
370 continue
c
c this section of the program inspects for
c negligible elements in the s and e arrays. on
c completion the variables kase and l are set as follows.
c
c kase = 1 if s(m) and e(l-1) are negligible and l.lt.m
c kase = 2 if s(l) is negligible and l.lt.m
c kase = 3 if e(l-1) is negligible, l.lt.m, and
c s(l), ..., s(m) are not negligible (qr step).
c kase = 4 if e(m-1) is negligible (convergence).
c
do 390 ll = 1, m
l = m - ll
c ...exit
if (l .eq. 0) go to 400
test = dabs(s(l)) + dabs(s(l+1))
ztest = test + dabs(e(l))
acc = dabs(test - ztest)/(1.0d-100 + test)
if (acc .gt. 1.d-15) goto 380
c if (ztest .ne. test) go to 380
e(l) = 0.0d0
c ......exit
go to 400
380 continue
390 continue
400 continue
if (l .ne. m - 1) go to 410
kase = 4
go to 480
410 continue
lp1 = l + 1
mp1 = m + 1
do 430 lls = lp1, mp1
ls = m - lls + lp1
c ...exit
if (ls .eq. l) go to 440
test = 0.0d0
if (ls .ne. m) test = test + dabs(e(ls))
if (ls .ne. l + 1) test = test + dabs(e(ls-1))
ztest = test + dabs(s(ls))
c 1.0d-100 is to guard against a zero matrix, hence zero test
acc = dabs(test - ztest)/(1.0d-100 + test)
if (acc .gt. 1.d-15) goto 420
c if (ztest .ne. test) go to 420
s(ls) = 0.0d0
c ......exit
go to 440
420 continue
430 continue
440 continue
if (ls .ne. l) go to 450
kase = 3
go to 470
450 continue
if (ls .ne. m) go to 460
kase = 1
go to 470
460 continue
kase = 2
l = ls
470 continue
480 continue
l = l + 1
c
c perform the task indicated by kase.
c
go to (490,520,540,570), kase
c
c deflate negligible s(m).
c
490 continue
mm1 = m - 1
f = e(m-1)
e(m-1) = 0.0d0
do 510 kk = l, mm1
k = mm1 - kk + l
t1 = s(k)
call drotg(t1,f,cs,sn)
s(k) = t1
if (k .eq. l) go to 500
f = -sn*e(k-1)
e(k-1) = cs*e(k-1)
500 continue
if (wantv) call drot(p,v(1,k),1,v(1,m),1,cs,sn)
510 continue
go to 610
c
c split at negligible s(l).
c
520 continue
f = e(l-1)
e(l-1) = 0.0d0
do 530 k = l, m
t1 = s(k)
call drotg(t1,f,cs,sn)
s(k) = t1
f = -sn*e(k)
e(k) = cs*e(k)
if (wantu) call drot(n,u(1,k),1,u(1,l-1),1,cs,sn)
530 continue
go to 610
c
c perform one qr step.
c
540 continue
c
c calculate the shift.
c
scale = dmax1(dabs(s(m)),dabs(s(m-1)),dabs(e(m-1)),
* dabs(s(l)),dabs(e(l)))
sm = s(m)/scale
smm1 = s(m-1)/scale
emm1 = e(m-1)/scale
sl = s(l)/scale
el = e(l)/scale
b = ((smm1 + sm)*(smm1 - sm) + emm1**2)/2.0d0
c = (sm*emm1)**2
shift = 0.0d0
if (b .eq. 0.0d0 .and. c .eq. 0.0d0) go to 550
shift = dsqrt(b**2+c)
if (b .lt. 0.0d0) shift = -shift
shift = c/(b + shift)
550 continue
f = (sl + sm)*(sl - sm) + shift
g = sl*el
c
c chase zeros.
c
mm1 = m - 1
do 560 k = l, mm1
call drotg(f,g,cs,sn)
if (k .ne. l) e(k-1) = f
f = cs*s(k) + sn*e(k)
e(k) = cs*e(k) - sn*s(k)
g = sn*s(k+1)
s(k+1) = cs*s(k+1)
if (wantv) call drot(p,v(1,k),1,v(1,k+1),1,cs,sn)
call drotg(f,g,cs,sn)
s(k) = f
f = cs*e(k) + sn*s(k+1)
s(k+1) = -sn*e(k) + cs*s(k+1)
g = sn*e(k+1)
e(k+1) = cs*e(k+1)
if (wantu .and. k .lt. n)
* call drot(n,u(1,k),1,u(1,k+1),1,cs,sn)
560 continue
e(m-1) = f
iter = iter + 1
go to 610
c
c convergence.
c
570 continue
c
c make the singular value positive.
c
if (s(l) .ge. 0.0d0) go to 580
s(l) = -s(l)
if (wantv) call dscal(p,-1.0d0,v(1,l),1)
580 continue
c
c order the singular value.
c
590 if (l .eq. mm) go to 600
c ...exit
if (s(l) .ge. s(l+1)) go to 600
t = s(l)
s(l) = s(l+1)
s(l+1) = t
if (wantv .and. l .lt. p)
* call dswap(p,v(1,l),1,v(1,l+1),1)
if (wantu .and. l .lt. n)
* call dswap(n,u(1,l),1,u(1,l+1),1)
l = l + 1
go to 590
600 continue
iter = 0
m = m - 1
610 continue
go to 360
620 continue
return
end
| gpl-2.0 |
OptiPurity/kernel_lge_hammerhead | drivers/thermal/qpnp-temp-alarm.c | 299 | 17467 | /*
* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/string.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/spmi.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/thermal.h>
#include <linux/qpnp/qpnp-adc.h>
#define QPNP_TM_DRIVER_NAME "qcom,qpnp-temp-alarm"
enum qpnp_tm_registers {
QPNP_TM_REG_TYPE = 0x04,
QPNP_TM_REG_SUBTYPE = 0x05,
QPNP_TM_REG_STATUS = 0x08,
QPNP_TM_REG_SHUTDOWN_CTRL1 = 0x40,
QPNP_TM_REG_SHUTDOWN_CTRL2 = 0x42,
QPNP_TM_REG_ALARM_CTRL = 0x46,
};
#define QPNP_TM_TYPE 0x09
#define QPNP_TM_SUBTYPE 0x08
#define STATUS_STAGE_MASK 0x03
#define SHUTDOWN_CTRL1_OVERRIDE_STAGE3 0x80
#define SHUTDOWN_CTRL1_OVERRIDE_STAGE2 0x40
#define SHUTDOWN_CTRL1_THRESHOLD_MASK 0x03
#define SHUTDOWN_CTRL2_CLEAR_STAGE3 0x80
#define SHUTDOWN_CTRL2_CLEAR_STAGE2 0x40
#define ALARM_CTRL_FORCE_ENABLE 0x80
#define ALARM_CTRL_FOLLOW_HW_ENABLE 0x01
#define TEMP_STAGE_STEP 20000 /* Stage step: 20.000 C */
#define TEMP_STAGE_HYSTERESIS 2000
#define TEMP_THRESH_MIN 105000 /* Threshold Min: 105 C */
#define TEMP_THRESH_STEP 5000 /* Threshold step: 5 C */
#define THRESH_MIN 0
#define THRESH_MAX 3
/* Trip points from most critical to least critical */
#define TRIP_STAGE3 0
#define TRIP_STAGE2 1
#define TRIP_STAGE1 2
#define TRIP_NUM 3
enum qpnp_tm_adc_type {
QPNP_TM_ADC_NONE, /* Estimates temp based on overload level. */
QPNP_TM_ADC_QPNP_ADC,
};
/*
* Temperature in millicelcius reported during stage 0 if no ADC is present and
* no value has been specified via device tree.
*/
#define DEFAULT_NO_ADC_TEMP 37000
struct qpnp_tm_chip {
struct delayed_work irq_work;
struct spmi_device *spmi_dev;
struct thermal_zone_device *tz_dev;
const char *tm_name;
enum qpnp_tm_adc_type adc_type;
unsigned long temperature;
enum thermal_device_mode mode;
unsigned int thresh;
unsigned int stage;
unsigned int prev_stage;
int irq;
enum qpnp_vadc_channels adc_channel;
u16 base_addr;
bool allow_software_override;
};
/* Delay between TEMP_STAT IRQ going high and status value changing in ms. */
#define STATUS_REGISTER_DELAY_MS 40
enum pmic_thermal_override_mode {
SOFTWARE_OVERRIDE_DISABLED = 0,
SOFTWARE_OVERRIDE_ENABLED,
};
static inline int qpnp_tm_read(struct qpnp_tm_chip *chip, u16 addr, u8 *buf,
int len)
{
int rc;
rc = spmi_ext_register_readl(chip->spmi_dev->ctrl,
chip->spmi_dev->sid, chip->base_addr + addr, buf, len);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: spmi_ext_register_readl() failed. sid=%d, addr=%04X, len=%d, rc=%d\n",
__func__, chip->spmi_dev->sid, chip->base_addr + addr,
len, rc);
return rc;
}
static inline int qpnp_tm_write(struct qpnp_tm_chip *chip, u16 addr, u8 *buf,
int len)
{
int rc;
rc = spmi_ext_register_writel(chip->spmi_dev->ctrl,
chip->spmi_dev->sid, chip->base_addr + addr, buf, len);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: spmi_ext_register_writel() failed. sid=%d, addr=%04X, len=%d, rc=%d\n",
__func__, chip->spmi_dev->sid, chip->base_addr + addr,
len, rc);
return rc;
}
static inline int qpnp_tm_shutdown_override(struct qpnp_tm_chip *chip,
enum pmic_thermal_override_mode mode)
{
int rc = 0;
u8 reg;
if (chip->allow_software_override) {
reg = chip->thresh & SHUTDOWN_CTRL1_THRESHOLD_MASK;
if (mode == SOFTWARE_OVERRIDE_ENABLED)
reg |= SHUTDOWN_CTRL1_OVERRIDE_STAGE2
| SHUTDOWN_CTRL1_OVERRIDE_STAGE3;
rc = qpnp_tm_write(chip, QPNP_TM_REG_SHUTDOWN_CTRL1, ®, 1);
}
return rc;
}
static int qpnp_tm_update_temp(struct qpnp_tm_chip *chip)
{
struct qpnp_vadc_result adc_result;
int rc;
rc = qpnp_vadc_read(chip->adc_channel, &adc_result);
if (!rc)
chip->temperature = adc_result.physical;
else
dev_err(&chip->spmi_dev->dev, "%s: qpnp_vadc_read(%d) failed, rc=%d\n",
__func__, chip->adc_channel, rc);
return rc;
}
/*
* This function initializes the internal temperature value based on only the
* current thermal stage and threshold.
*/
static int qpnp_tm_init_temp_no_adc(struct qpnp_tm_chip *chip)
{
int rc;
u8 reg;
rc = qpnp_tm_read(chip, QPNP_TM_REG_STATUS, ®, 1);
if (rc < 0)
return rc;
chip->stage = reg & STATUS_STAGE_MASK;
if (chip->stage)
chip->temperature = chip->thresh * TEMP_THRESH_STEP +
(chip->stage - 1) * TEMP_STAGE_STEP +
TEMP_THRESH_MIN;
return 0;
}
/*
* This function updates the internal temperature value based on the
* current thermal stage and threshold as well as the previous stage
*/
static int qpnp_tm_update_temp_no_adc(struct qpnp_tm_chip *chip)
{
unsigned int stage;
int rc;
u8 reg;
rc = qpnp_tm_read(chip, QPNP_TM_REG_STATUS, ®, 1);
if (rc < 0)
return rc;
stage = reg & STATUS_STAGE_MASK;
if (stage > chip->stage) {
/* increasing stage, use lower bound */
chip->temperature = (stage - 1) * TEMP_STAGE_STEP
+ chip->thresh * TEMP_THRESH_STEP
+ TEMP_STAGE_HYSTERESIS + TEMP_THRESH_MIN;
} else if (stage < chip->stage) {
/* decreasing stage, use upper bound */
chip->temperature = stage * TEMP_STAGE_STEP
+ chip->thresh * TEMP_THRESH_STEP
- TEMP_STAGE_HYSTERESIS + TEMP_THRESH_MIN;
}
chip->stage = stage;
return 0;
}
static int qpnp_tz_get_temp_no_adc(struct thermal_zone_device *thermal,
unsigned long *temperature)
{
struct qpnp_tm_chip *chip = thermal->devdata;
int rc;
if (!temperature)
return -EINVAL;
rc = qpnp_tm_update_temp_no_adc(chip);
if (rc < 0)
return rc;
*temperature = chip->temperature;
return 0;
}
static int qpnp_tz_get_temp_qpnp_adc(struct thermal_zone_device *thermal,
unsigned long *temperature)
{
struct qpnp_tm_chip *chip = thermal->devdata;
int rc;
if (!temperature)
return -EINVAL;
rc = qpnp_tm_update_temp(chip);
if (rc < 0) {
dev_err(&chip->spmi_dev->dev, "%s: %s: adc read failed, rc = %d\n",
__func__, chip->tm_name, rc);
return rc;
}
*temperature = chip->temperature;
return 0;
}
static int qpnp_tz_get_mode(struct thermal_zone_device *thermal,
enum thermal_device_mode *mode)
{
struct qpnp_tm_chip *chip = thermal->devdata;
if (!mode)
return -EINVAL;
*mode = chip->mode;
return 0;
}
static int qpnp_tz_set_mode(struct thermal_zone_device *thermal,
enum thermal_device_mode mode)
{
struct qpnp_tm_chip *chip = thermal->devdata;
int rc = 0;
if (mode != chip->mode) {
if (mode == THERMAL_DEVICE_ENABLED)
rc = qpnp_tm_shutdown_override(chip,
SOFTWARE_OVERRIDE_ENABLED);
else
rc = qpnp_tm_shutdown_override(chip,
SOFTWARE_OVERRIDE_DISABLED);
chip->mode = mode;
}
return rc;
}
static int qpnp_tz_get_trip_type(struct thermal_zone_device *thermal,
int trip, enum thermal_trip_type *type)
{
if (trip < 0 || !type)
return -EINVAL;
switch (trip) {
case TRIP_STAGE3:
*type = THERMAL_TRIP_CRITICAL;
break;
case TRIP_STAGE2:
*type = THERMAL_TRIP_HOT;
break;
case TRIP_STAGE1:
*type = THERMAL_TRIP_HOT;
break;
default:
return -EINVAL;
}
return 0;
}
static int qpnp_tz_get_trip_temp(struct thermal_zone_device *thermal,
int trip, unsigned long *temperature)
{
struct qpnp_tm_chip *chip = thermal->devdata;
int thresh_temperature;
if (trip < 0 || !temperature)
return -EINVAL;
thresh_temperature = chip->thresh * TEMP_THRESH_STEP + TEMP_THRESH_MIN;
switch (trip) {
case TRIP_STAGE3:
thresh_temperature += 2 * TEMP_STAGE_STEP;
break;
case TRIP_STAGE2:
thresh_temperature += TEMP_STAGE_STEP;
break;
case TRIP_STAGE1:
break;
default:
return -EINVAL;
}
*temperature = thresh_temperature;
return 0;
}
static int qpnp_tz_get_crit_temp(struct thermal_zone_device *thermal,
unsigned long *temperature)
{
struct qpnp_tm_chip *chip = thermal->devdata;
if (!temperature)
return -EINVAL;
*temperature = chip->thresh * TEMP_THRESH_STEP + TEMP_THRESH_MIN +
2 * TEMP_STAGE_STEP;
return 0;
}
static struct thermal_zone_device_ops qpnp_thermal_zone_ops_no_adc = {
.get_temp = qpnp_tz_get_temp_no_adc,
.get_mode = qpnp_tz_get_mode,
.set_mode = qpnp_tz_set_mode,
.get_trip_type = qpnp_tz_get_trip_type,
.get_trip_temp = qpnp_tz_get_trip_temp,
.get_crit_temp = qpnp_tz_get_crit_temp,
};
static struct thermal_zone_device_ops qpnp_thermal_zone_ops_qpnp_adc = {
.get_temp = qpnp_tz_get_temp_qpnp_adc,
.get_mode = qpnp_tz_get_mode,
.set_mode = qpnp_tz_set_mode,
.get_trip_type = qpnp_tz_get_trip_type,
.get_trip_temp = qpnp_tz_get_trip_temp,
.get_crit_temp = qpnp_tz_get_crit_temp,
};
static void qpnp_tm_work(struct work_struct *work)
{
struct delayed_work *dwork
= container_of(work, struct delayed_work, work);
struct qpnp_tm_chip *chip
= container_of(dwork, struct qpnp_tm_chip, irq_work);
int rc;
u8 reg;
if (chip->adc_type == QPNP_TM_ADC_NONE) {
rc = qpnp_tm_update_temp_no_adc(chip);
if (rc < 0)
goto bail;
} else {
rc = qpnp_tm_read(chip, QPNP_TM_REG_STATUS, ®, 1);
if (rc < 0)
goto bail;
chip->stage = reg & STATUS_STAGE_MASK;
rc = qpnp_tm_update_temp(chip);
if (rc < 0)
goto bail;
}
if (chip->stage != chip->prev_stage) {
chip->prev_stage = chip->stage;
pr_crit("%s: PMIC Temp Alarm - stage=%u, threshold=%u, temperature=%lu mC\n",
chip->tm_name, chip->stage, chip->thresh,
chip->temperature);
thermal_zone_device_update(chip->tz_dev);
/* Notify user space */
sysfs_notify(&chip->tz_dev->device.kobj, NULL, "type");
}
bail:
return;
}
static irqreturn_t qpnp_tm_isr(int irq, void *data)
{
struct qpnp_tm_chip *chip = data;
schedule_delayed_work(&chip->irq_work,
msecs_to_jiffies(STATUS_REGISTER_DELAY_MS) + 1);
return IRQ_HANDLED;
}
static int qpnp_tm_init_reg(struct qpnp_tm_chip *chip)
{
int rc = 0;
u8 reg;
if (chip->thresh < THRESH_MIN || chip->thresh > THRESH_MAX) {
/* Read hardware threshold value if configuration is invalid. */
rc = qpnp_tm_read(chip, QPNP_TM_REG_SHUTDOWN_CTRL1, ®, 1);
if (rc < 0)
return rc;
chip->thresh = reg & SHUTDOWN_CTRL1_THRESHOLD_MASK;
}
/*
* Set threshold and disable software override of stage 2 and 3
* shutdowns.
*/
reg = chip->thresh & SHUTDOWN_CTRL1_THRESHOLD_MASK;
rc = qpnp_tm_write(chip, QPNP_TM_REG_SHUTDOWN_CTRL1, ®, 1);
if (rc < 0)
return rc;
/* Enable the thermal alarm PMIC module in always-on mode. */
reg = ALARM_CTRL_FORCE_ENABLE;
rc = qpnp_tm_write(chip, QPNP_TM_REG_ALARM_CTRL, ®, 1);
return rc;
}
static int __devinit qpnp_tm_probe(struct spmi_device *spmi)
{
struct device_node *node;
struct resource *res;
struct qpnp_tm_chip *chip;
struct thermal_zone_device_ops *tz_ops;
char *tm_name;
u32 default_temperature;
int rc = 0;
u8 raw_type[2], type, subtype;
if (!spmi || !(&spmi->dev) || !spmi->dev.of_node) {
dev_err(&spmi->dev, "%s: device tree node not found\n",
__func__);
return -EINVAL;
}
node = spmi->dev.of_node;
chip = kzalloc(sizeof(struct qpnp_tm_chip), GFP_KERNEL);
if (!chip) {
dev_err(&spmi->dev, "%s: Can't allocate qpnp_tm_chip\n",
__func__);
return -ENOMEM;
}
dev_set_drvdata(&spmi->dev, chip);
res = spmi_get_resource(spmi, NULL, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&spmi->dev, "%s: node is missing base address\n",
__func__);
rc = -EINVAL;
goto free_chip;
}
chip->base_addr = res->start;
chip->spmi_dev = spmi;
chip->irq = spmi_get_irq(spmi, NULL, 0);
if (chip->irq < 0) {
rc = chip->irq;
dev_err(&spmi->dev, "%s: node is missing irq, rc=%d\n",
__func__, rc);
goto free_chip;
}
chip->tm_name = of_get_property(node, "label", NULL);
if (chip->tm_name == NULL) {
dev_err(&spmi->dev, "%s: node is missing label\n",
__func__);
rc = -EINVAL;
goto free_chip;
}
tm_name = kstrdup(chip->tm_name, GFP_KERNEL);
if (tm_name == NULL) {
dev_err(&spmi->dev, "%s: could not allocate memory for label\n",
__func__);
rc = -ENOMEM;
goto free_chip;
}
chip->tm_name = tm_name;
INIT_DELAYED_WORK(&chip->irq_work, qpnp_tm_work);
/* These bindings are optional, so it is okay if they are not found. */
chip->thresh = THRESH_MAX + 1;
rc = of_property_read_u32(node, "qcom,threshold-set", &chip->thresh);
if (!rc && (chip->thresh < THRESH_MIN || chip->thresh > THRESH_MAX))
dev_err(&spmi->dev, "%s: invalid qcom,threshold-set=%u specified\n",
__func__, chip->thresh);
chip->adc_type = QPNP_TM_ADC_NONE;
rc = of_property_read_u32(node, "qcom,channel-num", &chip->adc_channel);
if (!rc) {
if (chip->adc_channel < 0 || chip->adc_channel >= ADC_MAX_NUM) {
dev_err(&spmi->dev, "%s: invalid qcom,channel-num=%d specified\n",
__func__, chip->adc_channel);
} else {
chip->adc_type = QPNP_TM_ADC_QPNP_ADC;
rc = qpnp_vadc_is_ready();
if (rc) {
/* Probe retry, do not print an error message */
goto err_cancel_work;
}
}
}
if (chip->adc_type == QPNP_TM_ADC_QPNP_ADC)
tz_ops = &qpnp_thermal_zone_ops_qpnp_adc;
else
tz_ops = &qpnp_thermal_zone_ops_no_adc;
chip->allow_software_override
= of_property_read_bool(node, "qcom,allow-override");
default_temperature = DEFAULT_NO_ADC_TEMP;
rc = of_property_read_u32(node, "qcom,default-temp",
&default_temperature);
chip->temperature = default_temperature;
rc = qpnp_tm_read(chip, QPNP_TM_REG_TYPE, raw_type, 2);
if (rc) {
dev_err(&spmi->dev, "%s: could not read type register, rc=%d\n",
__func__, rc);
goto err_cancel_work;
}
type = raw_type[0];
subtype = raw_type[1];
if (type != QPNP_TM_TYPE || subtype != QPNP_TM_SUBTYPE) {
dev_err(&spmi->dev, "%s: invalid type=%02X or subtype=%02X register value\n",
__func__, type, subtype);
rc = -ENODEV;
goto err_cancel_work;
}
rc = qpnp_tm_init_reg(chip);
if (rc) {
dev_err(&spmi->dev, "%s: qpnp_tm_init_reg() failed, rc=%d\n",
__func__, rc);
goto err_cancel_work;
}
if (chip->adc_type == QPNP_TM_ADC_NONE) {
rc = qpnp_tm_init_temp_no_adc(chip);
if (rc) {
dev_err(&spmi->dev, "%s: qpnp_tm_init_temp_no_adc() failed, rc=%d\n",
__func__, rc);
goto err_cancel_work;
}
}
/* Start in HW control; switch to SW control when user changes mode. */
chip->mode = THERMAL_DEVICE_DISABLED;
rc = qpnp_tm_shutdown_override(chip, SOFTWARE_OVERRIDE_DISABLED);
if (rc) {
dev_err(&spmi->dev, "%s: qpnp_tm_shutdown_override() failed, rc=%d\n",
__func__, rc);
goto err_cancel_work;
}
chip->tz_dev = thermal_zone_device_register(tm_name, TRIP_NUM, chip,
tz_ops, 0, 0, 0, 0);
if (chip->tz_dev == NULL) {
dev_err(&spmi->dev, "%s: thermal_zone_device_register() failed.\n",
__func__);
rc = -ENODEV;
goto err_cancel_work;
}
rc = request_irq(chip->irq, qpnp_tm_isr, IRQF_TRIGGER_RISING, tm_name,
chip);
if (rc < 0) {
dev_err(&spmi->dev, "%s: request_irq(%d) failed: %d\n",
__func__, chip->irq, rc);
goto err_free_tz;
}
return 0;
err_free_tz:
thermal_zone_device_unregister(chip->tz_dev);
err_cancel_work:
cancel_delayed_work_sync(&chip->irq_work);
kfree(chip->tm_name);
free_chip:
dev_set_drvdata(&spmi->dev, NULL);
kfree(chip);
return rc;
}
static int __devexit qpnp_tm_remove(struct spmi_device *spmi)
{
struct qpnp_tm_chip *chip = dev_get_drvdata(&spmi->dev);
dev_set_drvdata(&spmi->dev, NULL);
thermal_zone_device_unregister(chip->tz_dev);
kfree(chip->tm_name);
qpnp_tm_shutdown_override(chip, SOFTWARE_OVERRIDE_DISABLED);
free_irq(chip->irq, chip);
cancel_delayed_work_sync(&chip->irq_work);
kfree(chip);
return 0;
}
#ifdef CONFIG_PM
static int qpnp_tm_suspend(struct device *dev)
{
struct qpnp_tm_chip *chip = dev_get_drvdata(dev);
/* Clear override bits in suspend to allow hardware control */
qpnp_tm_shutdown_override(chip, SOFTWARE_OVERRIDE_DISABLED);
return 0;
}
static int qpnp_tm_resume(struct device *dev)
{
struct qpnp_tm_chip *chip = dev_get_drvdata(dev);
/* Override hardware actions so software can control */
if (chip->mode == THERMAL_DEVICE_ENABLED)
qpnp_tm_shutdown_override(chip, SOFTWARE_OVERRIDE_ENABLED);
return 0;
}
static const struct dev_pm_ops qpnp_tm_pm_ops = {
.suspend = qpnp_tm_suspend,
.resume = qpnp_tm_resume,
};
#define QPNP_TM_PM_OPS (&qpnp_tm_pm_ops)
#else
#define QPNP_TM_PM_OPS NULL
#endif
static struct of_device_id qpnp_tm_match_table[] = {
{ .compatible = QPNP_TM_DRIVER_NAME, },
{}
};
static const struct spmi_device_id qpnp_tm_id[] = {
{ QPNP_TM_DRIVER_NAME, 0 },
{}
};
static struct spmi_driver qpnp_tm_driver = {
.driver = {
.name = QPNP_TM_DRIVER_NAME,
.of_match_table = qpnp_tm_match_table,
.owner = THIS_MODULE,
.pm = QPNP_TM_PM_OPS,
},
.probe = qpnp_tm_probe,
.remove = __devexit_p(qpnp_tm_remove),
.id_table = qpnp_tm_id,
};
int __init qpnp_tm_init(void)
{
return spmi_driver_register(&qpnp_tm_driver);
}
static void __exit qpnp_tm_exit(void)
{
spmi_driver_unregister(&qpnp_tm_driver);
}
module_init(qpnp_tm_init);
module_exit(qpnp_tm_exit);
MODULE_DESCRIPTION("QPNP PMIC Temperature Alarm driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
varunchitre15/thunderzap_sprout | fs/f2fs/xattr.c | 299 | 15144 | /*
* fs/f2fs/xattr.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Portions of this code from linux/fs/ext2/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher <agruen@suse.de>
*
* Fix by Harrison Xing <harrison@mountainviewdata.com>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <luka.renko@hermes.si>.
* xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
* Red Hat Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/rwsem.h>
#include <linux/f2fs_fs.h>
#include <linux/security.h>
#include "f2fs.h"
#include "xattr.h"
static size_t f2fs_xattr_generic_list(struct dentry *dentry, char *list,
size_t list_size, const char *name, size_t len, int type)
{
struct f2fs_sb_info *sbi = F2FS_SB(dentry->d_sb);
int total_len, prefix_len = 0;
const char *prefix = NULL;
switch (type) {
case F2FS_XATTR_INDEX_USER:
if (!test_opt(sbi, XATTR_USER))
return -EOPNOTSUPP;
prefix = XATTR_USER_PREFIX;
prefix_len = XATTR_USER_PREFIX_LEN;
break;
case F2FS_XATTR_INDEX_TRUSTED:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
prefix = XATTR_TRUSTED_PREFIX;
prefix_len = XATTR_TRUSTED_PREFIX_LEN;
break;
case F2FS_XATTR_INDEX_SECURITY:
prefix = XATTR_SECURITY_PREFIX;
prefix_len = XATTR_SECURITY_PREFIX_LEN;
break;
default:
return -EINVAL;
}
total_len = prefix_len + len + 1;
if (list && total_len <= list_size) {
memcpy(list, prefix, prefix_len);
memcpy(list + prefix_len, name, len);
list[prefix_len + len] = '\0';
}
return total_len;
}
static int f2fs_xattr_generic_get(struct dentry *dentry, const char *name,
void *buffer, size_t size, int type)
{
struct f2fs_sb_info *sbi = F2FS_SB(dentry->d_sb);
switch (type) {
case F2FS_XATTR_INDEX_USER:
if (!test_opt(sbi, XATTR_USER))
return -EOPNOTSUPP;
break;
case F2FS_XATTR_INDEX_TRUSTED:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
break;
case F2FS_XATTR_INDEX_SECURITY:
break;
default:
return -EINVAL;
}
if (strcmp(name, "") == 0)
return -EINVAL;
return f2fs_getxattr(dentry->d_inode, type, name, buffer, size, NULL);
}
static int f2fs_xattr_generic_set(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags, int type)
{
struct f2fs_sb_info *sbi = F2FS_SB(dentry->d_sb);
switch (type) {
case F2FS_XATTR_INDEX_USER:
if (!test_opt(sbi, XATTR_USER))
return -EOPNOTSUPP;
break;
case F2FS_XATTR_INDEX_TRUSTED:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
break;
case F2FS_XATTR_INDEX_SECURITY:
break;
default:
return -EINVAL;
}
if (strcmp(name, "") == 0)
return -EINVAL;
return f2fs_setxattr(dentry->d_inode, type, name,
value, size, NULL, flags);
}
static size_t f2fs_xattr_advise_list(struct dentry *dentry, char *list,
size_t list_size, const char *name, size_t len, int type)
{
const char *xname = F2FS_SYSTEM_ADVISE_PREFIX;
size_t size;
if (type != F2FS_XATTR_INDEX_ADVISE)
return 0;
size = strlen(xname) + 1;
if (list && size <= list_size)
memcpy(list, xname, size);
return size;
}
static int f2fs_xattr_advise_get(struct dentry *dentry, const char *name,
void *buffer, size_t size, int type)
{
struct inode *inode = dentry->d_inode;
if (strcmp(name, "") != 0)
return -EINVAL;
if (buffer)
*((char *)buffer) = F2FS_I(inode)->i_advise;
return sizeof(char);
}
static int f2fs_xattr_advise_set(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags, int type)
{
struct inode *inode = dentry->d_inode;
if (strcmp(name, "") != 0)
return -EINVAL;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value == NULL)
return -EINVAL;
F2FS_I(inode)->i_advise |= *(char *)value;
mark_inode_dirty(inode);
return 0;
}
#ifdef CONFIG_F2FS_FS_SECURITY
static int f2fs_initxattrs(struct inode *inode, const struct xattr *xattr_array,
void *page)
{
const struct xattr *xattr;
int err = 0;
for (xattr = xattr_array; xattr->name != NULL; xattr++) {
err = f2fs_setxattr(inode, F2FS_XATTR_INDEX_SECURITY,
xattr->name, xattr->value,
xattr->value_len, (struct page *)page, 0);
if (err < 0)
break;
}
return err;
}
int f2fs_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr, struct page *ipage)
{
return security_inode_init_security(inode, dir, qstr,
&f2fs_initxattrs, ipage);
}
#endif
const struct xattr_handler f2fs_xattr_user_handler = {
.prefix = XATTR_USER_PREFIX,
.flags = F2FS_XATTR_INDEX_USER,
.list = f2fs_xattr_generic_list,
.get = f2fs_xattr_generic_get,
.set = f2fs_xattr_generic_set,
};
const struct xattr_handler f2fs_xattr_trusted_handler = {
.prefix = XATTR_TRUSTED_PREFIX,
.flags = F2FS_XATTR_INDEX_TRUSTED,
.list = f2fs_xattr_generic_list,
.get = f2fs_xattr_generic_get,
.set = f2fs_xattr_generic_set,
};
const struct xattr_handler f2fs_xattr_advise_handler = {
.prefix = F2FS_SYSTEM_ADVISE_PREFIX,
.flags = F2FS_XATTR_INDEX_ADVISE,
.list = f2fs_xattr_advise_list,
.get = f2fs_xattr_advise_get,
.set = f2fs_xattr_advise_set,
};
const struct xattr_handler f2fs_xattr_security_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.flags = F2FS_XATTR_INDEX_SECURITY,
.list = f2fs_xattr_generic_list,
.get = f2fs_xattr_generic_get,
.set = f2fs_xattr_generic_set,
};
static const struct xattr_handler *f2fs_xattr_handler_map[] = {
[F2FS_XATTR_INDEX_USER] = &f2fs_xattr_user_handler,
#ifdef CONFIG_F2FS_FS_POSIX_ACL
[F2FS_XATTR_INDEX_POSIX_ACL_ACCESS] = &f2fs_xattr_acl_access_handler,
[F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT] = &f2fs_xattr_acl_default_handler,
#endif
[F2FS_XATTR_INDEX_TRUSTED] = &f2fs_xattr_trusted_handler,
#ifdef CONFIG_F2FS_FS_SECURITY
[F2FS_XATTR_INDEX_SECURITY] = &f2fs_xattr_security_handler,
#endif
[F2FS_XATTR_INDEX_ADVISE] = &f2fs_xattr_advise_handler,
};
const struct xattr_handler *f2fs_xattr_handlers[] = {
&f2fs_xattr_user_handler,
#ifdef CONFIG_F2FS_FS_POSIX_ACL
&f2fs_xattr_acl_access_handler,
&f2fs_xattr_acl_default_handler,
#endif
&f2fs_xattr_trusted_handler,
#ifdef CONFIG_F2FS_FS_SECURITY
&f2fs_xattr_security_handler,
#endif
&f2fs_xattr_advise_handler,
NULL,
};
static inline const struct xattr_handler *f2fs_xattr_handler(int index)
{
const struct xattr_handler *handler = NULL;
if (index > 0 && index < ARRAY_SIZE(f2fs_xattr_handler_map))
handler = f2fs_xattr_handler_map[index];
return handler;
}
static struct f2fs_xattr_entry *__find_xattr(void *base_addr, int index,
size_t len, const char *name)
{
struct f2fs_xattr_entry *entry;
list_for_each_xattr(entry, base_addr) {
if (entry->e_name_index != index)
continue;
if (entry->e_name_len != len)
continue;
if (!memcmp(entry->e_name, name, len))
break;
}
return entry;
}
static void *read_all_xattrs(struct inode *inode, struct page *ipage)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct f2fs_xattr_header *header;
size_t size = PAGE_SIZE, inline_size = 0;
void *txattr_addr;
inline_size = inline_xattr_size(inode);
txattr_addr = kzalloc(inline_size + size, GFP_F2FS_ZERO);
if (!txattr_addr)
return NULL;
/* read from inline xattr */
if (inline_size) {
struct page *page = NULL;
void *inline_addr;
if (ipage) {
inline_addr = inline_xattr_addr(ipage);
} else {
page = get_node_page(sbi, inode->i_ino);
if (IS_ERR(page))
goto fail;
inline_addr = inline_xattr_addr(page);
}
memcpy(txattr_addr, inline_addr, inline_size);
f2fs_put_page(page, 1);
}
/* read from xattr node block */
if (F2FS_I(inode)->i_xattr_nid) {
struct page *xpage;
void *xattr_addr;
/* The inode already has an extended attribute block. */
xpage = get_node_page(sbi, F2FS_I(inode)->i_xattr_nid);
if (IS_ERR(xpage))
goto fail;
xattr_addr = page_address(xpage);
memcpy(txattr_addr + inline_size, xattr_addr, PAGE_SIZE);
f2fs_put_page(xpage, 1);
}
header = XATTR_HDR(txattr_addr);
/* never been allocated xattrs */
if (le32_to_cpu(header->h_magic) != F2FS_XATTR_MAGIC) {
header->h_magic = cpu_to_le32(F2FS_XATTR_MAGIC);
header->h_refcount = cpu_to_le32(1);
}
return txattr_addr;
fail:
kzfree(txattr_addr);
return NULL;
}
static inline int write_all_xattrs(struct inode *inode, __u32 hsize,
void *txattr_addr, struct page *ipage)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
size_t inline_size = 0;
void *xattr_addr;
struct page *xpage;
nid_t new_nid = 0;
int err;
inline_size = inline_xattr_size(inode);
if (hsize > inline_size && !F2FS_I(inode)->i_xattr_nid)
if (!alloc_nid(sbi, &new_nid))
return -ENOSPC;
/* write to inline xattr */
if (inline_size) {
struct page *page = NULL;
void *inline_addr;
if (ipage) {
inline_addr = inline_xattr_addr(ipage);
f2fs_wait_on_page_writeback(ipage, NODE);
} else {
page = get_node_page(sbi, inode->i_ino);
if (IS_ERR(page)) {
alloc_nid_failed(sbi, new_nid);
return PTR_ERR(page);
}
inline_addr = inline_xattr_addr(page);
f2fs_wait_on_page_writeback(page, NODE);
}
memcpy(inline_addr, txattr_addr, inline_size);
f2fs_put_page(page, 1);
/* no need to use xattr node block */
if (hsize <= inline_size) {
err = truncate_xattr_node(inode, ipage);
alloc_nid_failed(sbi, new_nid);
return err;
}
}
/* write to xattr node block */
if (F2FS_I(inode)->i_xattr_nid) {
xpage = get_node_page(sbi, F2FS_I(inode)->i_xattr_nid);
if (IS_ERR(xpage)) {
alloc_nid_failed(sbi, new_nid);
return PTR_ERR(xpage);
}
f2fs_bug_on(sbi, new_nid);
f2fs_wait_on_page_writeback(xpage, NODE);
} else {
struct dnode_of_data dn;
set_new_dnode(&dn, inode, NULL, NULL, new_nid);
xpage = new_node_page(&dn, XATTR_NODE_OFFSET, ipage);
if (IS_ERR(xpage)) {
alloc_nid_failed(sbi, new_nid);
return PTR_ERR(xpage);
}
alloc_nid_done(sbi, new_nid);
}
xattr_addr = page_address(xpage);
memcpy(xattr_addr, txattr_addr + inline_size, PAGE_SIZE -
sizeof(struct node_footer));
set_page_dirty(xpage);
f2fs_put_page(xpage, 1);
/* need to checkpoint during fsync */
F2FS_I(inode)->xattr_ver = cur_cp_version(F2FS_CKPT(sbi));
return 0;
}
int f2fs_getxattr(struct inode *inode, int index, const char *name,
void *buffer, size_t buffer_size, struct page *ipage)
{
struct f2fs_xattr_entry *entry;
void *base_addr;
int error = 0;
size_t size, len;
if (name == NULL)
return -EINVAL;
len = strlen(name);
if (len > F2FS_NAME_LEN)
return -ERANGE;
base_addr = read_all_xattrs(inode, ipage);
if (!base_addr)
return -ENOMEM;
entry = __find_xattr(base_addr, index, len, name);
if (IS_XATTR_LAST_ENTRY(entry)) {
error = -ENODATA;
goto cleanup;
}
size = le16_to_cpu(entry->e_value_size);
if (buffer && size > buffer_size) {
error = -ERANGE;
goto cleanup;
}
if (buffer) {
char *pval = entry->e_name + entry->e_name_len;
memcpy(buffer, pval, size);
}
error = size;
cleanup:
kzfree(base_addr);
return error;
}
ssize_t f2fs_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct f2fs_xattr_entry *entry;
void *base_addr;
int error = 0;
size_t rest = buffer_size;
base_addr = read_all_xattrs(inode, NULL);
if (!base_addr)
return -ENOMEM;
list_for_each_xattr(entry, base_addr) {
const struct xattr_handler *handler =
f2fs_xattr_handler(entry->e_name_index);
size_t size;
if (!handler)
continue;
size = handler->list(dentry, buffer, rest, entry->e_name,
entry->e_name_len, handler->flags);
if (buffer && size > rest) {
error = -ERANGE;
goto cleanup;
}
if (buffer)
buffer += size;
rest -= size;
}
error = buffer_size - rest;
cleanup:
kzfree(base_addr);
return error;
}
static int __f2fs_setxattr(struct inode *inode, int index,
const char *name, const void *value, size_t size,
struct page *ipage, int flags)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
struct f2fs_xattr_entry *here, *last;
void *base_addr;
int found, newsize;
size_t len;
__u32 new_hsize;
int error = -ENOMEM;
if (name == NULL)
return -EINVAL;
if (value == NULL)
size = 0;
len = strlen(name);
if (len > F2FS_NAME_LEN)
return -ERANGE;
if (size > MAX_VALUE_LEN(inode))
return -E2BIG;
base_addr = read_all_xattrs(inode, ipage);
if (!base_addr)
goto exit;
/* find entry with wanted name. */
here = __find_xattr(base_addr, index, len, name);
found = IS_XATTR_LAST_ENTRY(here) ? 0 : 1;
if ((flags & XATTR_REPLACE) && !found) {
error = -ENODATA;
goto exit;
} else if ((flags & XATTR_CREATE) && found) {
error = -EEXIST;
goto exit;
}
last = here;
while (!IS_XATTR_LAST_ENTRY(last))
last = XATTR_NEXT_ENTRY(last);
newsize = XATTR_ALIGN(sizeof(struct f2fs_xattr_entry) + len + size);
/* 1. Check space */
if (value) {
int free;
/*
* If value is NULL, it is remove operation.
* In case of update operation, we calculate free.
*/
free = MIN_OFFSET(inode) - ((char *)last - (char *)base_addr);
if (found)
free = free + ENTRY_SIZE(here);
if (unlikely(free < newsize)) {
error = -ENOSPC;
goto exit;
}
}
/* 2. Remove old entry */
if (found) {
/*
* If entry is found, remove old entry.
* If not found, remove operation is not needed.
*/
struct f2fs_xattr_entry *next = XATTR_NEXT_ENTRY(here);
int oldsize = ENTRY_SIZE(here);
memmove(here, next, (char *)last - (char *)next);
last = (struct f2fs_xattr_entry *)((char *)last - oldsize);
memset(last, 0, oldsize);
}
new_hsize = (char *)last - (char *)base_addr;
/* 3. Write new entry */
if (value) {
char *pval;
/*
* Before we come here, old entry is removed.
* We just write new entry.
*/
memset(last, 0, newsize);
last->e_name_index = index;
last->e_name_len = len;
memcpy(last->e_name, name, len);
pval = last->e_name + len;
memcpy(pval, value, size);
last->e_value_size = cpu_to_le16(size);
new_hsize += newsize;
}
error = write_all_xattrs(inode, new_hsize, base_addr, ipage);
if (error)
goto exit;
if (is_inode_flag_set(fi, FI_ACL_MODE)) {
inode->i_mode = fi->i_acl_mode;
inode->i_ctime = CURRENT_TIME;
clear_inode_flag(fi, FI_ACL_MODE);
}
if (index == F2FS_XATTR_INDEX_ENCRYPTION &&
!strcmp(name, F2FS_XATTR_NAME_ENCRYPTION_CONTEXT))
f2fs_set_encrypted_inode(inode);
if (ipage)
update_inode(inode, ipage);
else
update_inode_page(inode);
exit:
kzfree(base_addr);
return error;
}
int f2fs_setxattr(struct inode *inode, int index, const char *name,
const void *value, size_t size,
struct page *ipage, int flags)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
int err;
/* this case is only from init_inode_metadata */
if (ipage)
return __f2fs_setxattr(inode, index, name, value,
size, ipage, flags);
f2fs_balance_fs(sbi);
f2fs_lock_op(sbi);
/* protect xattr_ver */
down_write(&F2FS_I(inode)->i_sem);
err = __f2fs_setxattr(inode, index, name, value, size, ipage, flags);
up_write(&F2FS_I(inode)->i_sem);
f2fs_unlock_op(sbi);
return err;
}
| gpl-2.0 |
U8800Pro/kernel_huawei_u8800pro | arch/arm/mach-s3c64xx/mach-hmt.c | 811 | 6322 | /* mach-hmt.c - Platform code for Airgoo HMT
*
* Copyright 2009 Peter Korsgaard <jacmet@sunsite.dk>
*
* 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/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/fb.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/leds.h>
#include <linux/pwm_backlight.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <mach/regs-fb.h>
#include <mach/map.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <plat/iic.h>
#include <plat/fb.h>
#include <plat/nand.h>
#include <mach/s3c6410.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#define UCON S3C2410_UCON_DEFAULT
#define ULCON (S3C2410_LCON_CS8 | S3C2410_LCON_PNONE)
#define UFCON (S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE)
static struct s3c2410_uartcfg hmt_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
};
static int hmt_bl_init(struct device *dev)
{
int ret;
ret = gpio_request(S3C64XX_GPB(4), "lcd backlight enable");
if (!ret)
ret = gpio_direction_output(S3C64XX_GPB(4), 0);
return ret;
}
static int hmt_bl_notify(struct device *dev, int brightness)
{
/*
* translate from CIELUV/CIELAB L*->brightness, E.G. from
* perceived luminance to light output. Assumes range 0..25600
*/
if (brightness < 0x800) {
/* Y = Yn * L / 903.3 */
brightness = (100*256 * brightness + 231245/2) / 231245;
} else {
/* Y = Yn * ((L + 16) / 116 )^3 */
int t = (brightness*4 + 16*1024 + 58)/116;
brightness = 25 * ((t * t * t + 0x100000/2) / 0x100000);
}
gpio_set_value(S3C64XX_GPB(4), brightness);
return brightness;
}
static void hmt_bl_exit(struct device *dev)
{
gpio_free(S3C64XX_GPB(4));
}
static struct platform_pwm_backlight_data hmt_backlight_data = {
.pwm_id = 1,
.max_brightness = 100 * 256,
.dft_brightness = 40 * 256,
.pwm_period_ns = 1000000000 / (100 * 256 * 20),
.init = hmt_bl_init,
.notify = hmt_bl_notify,
.exit = hmt_bl_exit,
};
static struct platform_device hmt_backlight_device = {
.name = "pwm-backlight",
.dev = {
.parent = &s3c_device_timer[1].dev,
.platform_data = &hmt_backlight_data,
},
};
static struct s3c_fb_pd_win hmt_fb_win0 = {
.win_mode = {
.pixclock = 41094,
.left_margin = 8,
.right_margin = 13,
.upper_margin = 7,
.lower_margin = 5,
.hsync_len = 3,
.vsync_len = 1,
.xres = 800,
.yres = 480,
},
.max_bpp = 32,
.default_bpp = 16,
};
/* 405566 clocks per frame => 60Hz refresh requires 24333960Hz clock */
static struct s3c_fb_platdata hmt_lcd_pdata __initdata = {
.setup_gpio = s3c64xx_fb_gpio_setup_24bpp,
.win[0] = &hmt_fb_win0,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC,
};
static struct mtd_partition hmt_nand_part[] = {
[0] = {
.name = "uboot",
.size = SZ_512K,
.offset = 0,
},
[1] = {
.name = "uboot-env1",
.size = SZ_256K,
.offset = SZ_512K,
},
[2] = {
.name = "uboot-env2",
.size = SZ_256K,
.offset = SZ_512K + SZ_256K,
},
[3] = {
.name = "kernel",
.size = SZ_2M,
.offset = SZ_1M,
},
[4] = {
.name = "rootfs",
.size = MTDPART_SIZ_FULL,
.offset = SZ_1M + SZ_2M,
},
};
static struct s3c2410_nand_set hmt_nand_sets[] = {
[0] = {
.name = "nand",
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(hmt_nand_part),
.partitions = hmt_nand_part,
},
};
static struct s3c2410_platform_nand hmt_nand_info = {
.tacls = 25,
.twrph0 = 55,
.twrph1 = 40,
.nr_sets = ARRAY_SIZE(hmt_nand_sets),
.sets = hmt_nand_sets,
};
static struct gpio_led hmt_leds[] = {
{ /* left function keys */
.name = "left:blue",
.gpio = S3C64XX_GPO(12),
.default_trigger = "default-on",
},
{ /* right function keys - red */
.name = "right:red",
.gpio = S3C64XX_GPO(13),
},
{ /* right function keys - green */
.name = "right:green",
.gpio = S3C64XX_GPO(14),
},
{ /* right function keys - blue */
.name = "right:blue",
.gpio = S3C64XX_GPO(15),
.default_trigger = "default-on",
},
};
static struct gpio_led_platform_data hmt_led_data = {
.num_leds = ARRAY_SIZE(hmt_leds),
.leds = hmt_leds,
};
static struct platform_device hmt_leds_device = {
.name = "leds-gpio",
.id = -1,
.dev.platform_data = &hmt_led_data,
};
static struct map_desc hmt_iodesc[] = {};
static struct platform_device *hmt_devices[] __initdata = {
&s3c_device_i2c0,
&s3c_device_nand,
&s3c_device_fb,
&s3c_device_ohci,
&s3c_device_timer[1],
&hmt_backlight_device,
&hmt_leds_device,
};
static void __init hmt_map_io(void)
{
s3c64xx_init_io(hmt_iodesc, ARRAY_SIZE(hmt_iodesc));
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(hmt_uartcfgs, ARRAY_SIZE(hmt_uartcfgs));
}
static void __init hmt_machine_init(void)
{
s3c_i2c0_set_platdata(NULL);
s3c_fb_set_platdata(&hmt_lcd_pdata);
s3c_nand_set_platdata(&hmt_nand_info);
gpio_request(S3C64XX_GPC(7), "usb power");
gpio_direction_output(S3C64XX_GPC(7), 0);
gpio_request(S3C64XX_GPM(0), "usb power");
gpio_direction_output(S3C64XX_GPM(0), 1);
gpio_request(S3C64XX_GPK(7), "usb power");
gpio_direction_output(S3C64XX_GPK(7), 1);
gpio_request(S3C64XX_GPF(13), "usb power");
gpio_direction_output(S3C64XX_GPF(13), 1);
platform_add_devices(hmt_devices, ARRAY_SIZE(hmt_devices));
}
MACHINE_START(HMT, "Airgoo-HMT")
/* Maintainer: Peter Korsgaard <jacmet@sunsite.dk> */
.phys_io = S3C_PA_UART & 0xfff00000,
.io_pg_offst = (((u32)S3C_VA_UART) >> 18) & 0xfffc,
.boot_params = S3C64XX_PA_SDRAM + 0x100,
.init_irq = s3c6410_init_irq,
.map_io = hmt_map_io,
.init_machine = hmt_machine_init,
.timer = &s3c24xx_timer,
MACHINE_END
| gpl-2.0 |
daveti/prov-kernel | arch/arm/mm/mmap.c | 1323 | 3463 | /*
* linux/arch/arm/mm/mmap.c
*/
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/shm.h>
#include <linux/sched.h>
#include <linux/io.h>
#include <asm/cputype.h>
#include <asm/system.h>
#define COLOUR_ALIGN(addr,pgoff) \
((((addr)+SHMLBA-1)&~(SHMLBA-1)) + \
(((pgoff)<<PAGE_SHIFT) & (SHMLBA-1)))
/*
* We need to ensure that shared mappings are correctly aligned to
* avoid aliasing issues with VIPT caches. We need to ensure that
* a specific page of an object is always mapped at a multiple of
* SHMLBA bytes.
*
* We unconditionally provide this function for all cases, however
* in the VIVT case, we optimise out the alignment rules.
*/
unsigned long
arch_get_unmapped_area(struct file *filp, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long start_addr;
#ifdef CONFIG_CPU_V6
unsigned int cache_type;
int do_align = 0, aliasing = 0;
/*
* We only need to do colour alignment if either the I or D
* caches alias. This is indicated by bits 9 and 21 of the
* cache type register.
*/
cache_type = read_cpuid_cachetype();
if (cache_type != read_cpuid_id()) {
aliasing = (cache_type | cache_type >> 12) & (1 << 11);
if (aliasing)
do_align = filp || flags & MAP_SHARED;
}
#else
#define do_align 0
#define aliasing 0
#endif
/*
* We enforce the MAP_FIXED case.
*/
if (flags & MAP_FIXED) {
if (aliasing && flags & MAP_SHARED &&
(addr - (pgoff << PAGE_SHIFT)) & (SHMLBA - 1))
return -EINVAL;
return addr;
}
if (len > TASK_SIZE)
return -ENOMEM;
if (addr) {
if (do_align)
addr = COLOUR_ALIGN(addr, pgoff);
else
addr = PAGE_ALIGN(addr);
vma = find_vma(mm, addr);
if (TASK_SIZE - len >= addr &&
(!vma || addr + len <= vma->vm_start))
return addr;
}
if (len > mm->cached_hole_size) {
start_addr = addr = mm->free_area_cache;
} else {
start_addr = addr = TASK_UNMAPPED_BASE;
mm->cached_hole_size = 0;
}
full_search:
if (do_align)
addr = COLOUR_ALIGN(addr, pgoff);
else
addr = PAGE_ALIGN(addr);
for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
/* At this point: (!vma || addr < vma->vm_end). */
if (TASK_SIZE - len < addr) {
/*
* Start a new search - just in case we missed
* some holes.
*/
if (start_addr != TASK_UNMAPPED_BASE) {
start_addr = addr = TASK_UNMAPPED_BASE;
mm->cached_hole_size = 0;
goto full_search;
}
return -ENOMEM;
}
if (!vma || addr + len <= vma->vm_start) {
/*
* Remember the place where we stopped the search:
*/
mm->free_area_cache = addr + len;
return addr;
}
if (addr + mm->cached_hole_size < vma->vm_start)
mm->cached_hole_size = vma->vm_start - addr;
addr = vma->vm_end;
if (do_align)
addr = COLOUR_ALIGN(addr, pgoff);
}
}
/*
* You really shouldn't be using read() or write() on /dev/mem. This
* might go away in the future.
*/
int valid_phys_addr_range(unsigned long addr, size_t size)
{
if (addr < PHYS_OFFSET)
return 0;
if (addr + size > __pa(high_memory - 1) + 1)
return 0;
return 1;
}
/*
* We don't use supersection mappings for mmap() on /dev/mem, which
* means that we can't map the memory area above the 4G barrier into
* userspace.
*/
int valid_mmap_phys_addr_range(unsigned long pfn, size_t size)
{
return !(pfn + (size >> PAGE_SHIFT) > 0x00100000);
}
| gpl-2.0 |
martinbrook/tesco-hudl | drivers/md/dm-raid.c | 1579 | 17767 | /*
* Copyright (C) 2010-2011 Neil Brown
* Copyright (C) 2010-2011 Red Hat, Inc. All rights reserved.
*
* This file is released under the GPL.
*/
#include <linux/slab.h>
#include "md.h"
#include "raid5.h"
#include "dm.h"
#include "bitmap.h"
#define DM_MSG_PREFIX "raid"
/*
* If the MD doesn't support MD_SYNC_STATE_FORCED yet, then
* make it so the flag doesn't set anything.
*/
#ifndef MD_SYNC_STATE_FORCED
#define MD_SYNC_STATE_FORCED 0
#endif
struct raid_dev {
/*
* Two DM devices, one to hold metadata and one to hold the
* actual data/parity. The reason for this is to not confuse
* ti->len and give more flexibility in altering size and
* characteristics.
*
* While it is possible for this device to be associated
* with a different physical device than the data_dev, it
* is intended for it to be the same.
* |--------- Physical Device ---------|
* |- meta_dev -|------ data_dev ------|
*/
struct dm_dev *meta_dev;
struct dm_dev *data_dev;
struct mdk_rdev_s rdev;
};
/*
* Flags for rs->print_flags field.
*/
#define DMPF_DAEMON_SLEEP 0x1
#define DMPF_MAX_WRITE_BEHIND 0x2
#define DMPF_SYNC 0x4
#define DMPF_NOSYNC 0x8
#define DMPF_STRIPE_CACHE 0x10
#define DMPF_MIN_RECOVERY_RATE 0x20
#define DMPF_MAX_RECOVERY_RATE 0x40
struct raid_set {
struct dm_target *ti;
uint64_t print_flags;
struct mddev_s md;
struct raid_type *raid_type;
struct dm_target_callbacks callbacks;
struct raid_dev dev[0];
};
/* Supported raid types and properties. */
static struct raid_type {
const char *name; /* RAID algorithm. */
const char *descr; /* Descriptor text for logging. */
const unsigned parity_devs; /* # of parity devices. */
const unsigned minimal_devs; /* minimal # of devices in set. */
const unsigned level; /* RAID level. */
const unsigned algorithm; /* RAID algorithm. */
} raid_types[] = {
{"raid4", "RAID4 (dedicated parity disk)", 1, 2, 5, ALGORITHM_PARITY_0},
{"raid5_la", "RAID5 (left asymmetric)", 1, 2, 5, ALGORITHM_LEFT_ASYMMETRIC},
{"raid5_ra", "RAID5 (right asymmetric)", 1, 2, 5, ALGORITHM_RIGHT_ASYMMETRIC},
{"raid5_ls", "RAID5 (left symmetric)", 1, 2, 5, ALGORITHM_LEFT_SYMMETRIC},
{"raid5_rs", "RAID5 (right symmetric)", 1, 2, 5, ALGORITHM_RIGHT_SYMMETRIC},
{"raid6_zr", "RAID6 (zero restart)", 2, 4, 6, ALGORITHM_ROTATING_ZERO_RESTART},
{"raid6_nr", "RAID6 (N restart)", 2, 4, 6, ALGORITHM_ROTATING_N_RESTART},
{"raid6_nc", "RAID6 (N continue)", 2, 4, 6, ALGORITHM_ROTATING_N_CONTINUE}
};
static struct raid_type *get_raid_type(char *name)
{
int i;
for (i = 0; i < ARRAY_SIZE(raid_types); i++)
if (!strcmp(raid_types[i].name, name))
return &raid_types[i];
return NULL;
}
static struct raid_set *context_alloc(struct dm_target *ti, struct raid_type *raid_type, unsigned raid_devs)
{
unsigned i;
struct raid_set *rs;
sector_t sectors_per_dev;
if (raid_devs <= raid_type->parity_devs) {
ti->error = "Insufficient number of devices";
return ERR_PTR(-EINVAL);
}
sectors_per_dev = ti->len;
if (sector_div(sectors_per_dev, (raid_devs - raid_type->parity_devs))) {
ti->error = "Target length not divisible by number of data devices";
return ERR_PTR(-EINVAL);
}
rs = kzalloc(sizeof(*rs) + raid_devs * sizeof(rs->dev[0]), GFP_KERNEL);
if (!rs) {
ti->error = "Cannot allocate raid context";
return ERR_PTR(-ENOMEM);
}
mddev_init(&rs->md);
rs->ti = ti;
rs->raid_type = raid_type;
rs->md.raid_disks = raid_devs;
rs->md.level = raid_type->level;
rs->md.new_level = rs->md.level;
rs->md.dev_sectors = sectors_per_dev;
rs->md.layout = raid_type->algorithm;
rs->md.new_layout = rs->md.layout;
rs->md.delta_disks = 0;
rs->md.recovery_cp = 0;
for (i = 0; i < raid_devs; i++)
md_rdev_init(&rs->dev[i].rdev);
/*
* Remaining items to be initialized by further RAID params:
* rs->md.persistent
* rs->md.external
* rs->md.chunk_sectors
* rs->md.new_chunk_sectors
*/
return rs;
}
static void context_free(struct raid_set *rs)
{
int i;
for (i = 0; i < rs->md.raid_disks; i++)
if (rs->dev[i].data_dev)
dm_put_device(rs->ti, rs->dev[i].data_dev);
kfree(rs);
}
/*
* For every device we have two words
* <meta_dev>: meta device name or '-' if missing
* <data_dev>: data device name or '-' if missing
*
* This code parses those words.
*/
static int dev_parms(struct raid_set *rs, char **argv)
{
int i;
int rebuild = 0;
int metadata_available = 0;
int ret = 0;
for (i = 0; i < rs->md.raid_disks; i++, argv += 2) {
rs->dev[i].rdev.raid_disk = i;
rs->dev[i].meta_dev = NULL;
rs->dev[i].data_dev = NULL;
/*
* There are no offsets, since there is a separate device
* for data and metadata.
*/
rs->dev[i].rdev.data_offset = 0;
rs->dev[i].rdev.mddev = &rs->md;
if (strcmp(argv[0], "-")) {
rs->ti->error = "Metadata devices not supported";
return -EINVAL;
}
if (!strcmp(argv[1], "-")) {
if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
(!rs->dev[i].rdev.recovery_offset)) {
rs->ti->error = "Drive designated for rebuild not specified";
return -EINVAL;
}
continue;
}
ret = dm_get_device(rs->ti, argv[1],
dm_table_get_mode(rs->ti->table),
&rs->dev[i].data_dev);
if (ret) {
rs->ti->error = "RAID device lookup failure";
return ret;
}
rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
list_add(&rs->dev[i].rdev.same_set, &rs->md.disks);
if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
rebuild++;
}
if (metadata_available) {
rs->md.external = 0;
rs->md.persistent = 1;
rs->md.major_version = 2;
} else if (rebuild && !rs->md.recovery_cp) {
/*
* Without metadata, we will not be able to tell if the array
* is in-sync or not - we must assume it is not. Therefore,
* it is impossible to rebuild a drive.
*
* Even if there is metadata, the on-disk information may
* indicate that the array is not in-sync and it will then
* fail at that time.
*
* User could specify 'nosync' option if desperate.
*/
DMERR("Unable to rebuild drive while array is not in-sync");
rs->ti->error = "RAID device lookup failure";
return -EINVAL;
}
return 0;
}
/*
* Possible arguments are...
* RAID456:
* <chunk_size> [optional_args]
*
* Optional args:
* [[no]sync] Force or prevent recovery of the entire array
* [rebuild <idx>] Rebuild the drive indicated by the index
* [daemon_sleep <ms>] Time between bitmap daemon work to clear bits
* [min_recovery_rate <kB/sec/disk>] Throttle RAID initialization
* [max_recovery_rate <kB/sec/disk>] Throttle RAID initialization
* [max_write_behind <sectors>] See '-write-behind=' (man mdadm)
* [stripe_cache <sectors>] Stripe cache size for higher RAIDs
*/
static int parse_raid_params(struct raid_set *rs, char **argv,
unsigned num_raid_params)
{
unsigned i, rebuild_cnt = 0;
unsigned long value;
char *key;
/*
* First, parse the in-order required arguments
*/
if ((strict_strtoul(argv[0], 10, &value) < 0) ||
!is_power_of_2(value) || (value < 8)) {
rs->ti->error = "Bad chunk size";
return -EINVAL;
}
rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
argv++;
num_raid_params--;
/*
* Second, parse the unordered optional arguments
*/
for (i = 0; i < rs->md.raid_disks; i++)
set_bit(In_sync, &rs->dev[i].rdev.flags);
for (i = 0; i < num_raid_params; i++) {
if (!strcmp(argv[i], "nosync")) {
rs->md.recovery_cp = MaxSector;
rs->print_flags |= DMPF_NOSYNC;
rs->md.flags |= MD_SYNC_STATE_FORCED;
continue;
}
if (!strcmp(argv[i], "sync")) {
rs->md.recovery_cp = 0;
rs->print_flags |= DMPF_SYNC;
rs->md.flags |= MD_SYNC_STATE_FORCED;
continue;
}
/* The rest of the optional arguments come in key/value pairs */
if ((i + 1) >= num_raid_params) {
rs->ti->error = "Wrong number of raid parameters given";
return -EINVAL;
}
key = argv[i++];
if (strict_strtoul(argv[i], 10, &value) < 0) {
rs->ti->error = "Bad numerical argument given in raid params";
return -EINVAL;
}
if (!strcmp(key, "rebuild")) {
if (++rebuild_cnt > rs->raid_type->parity_devs) {
rs->ti->error = "Too many rebuild drives given";
return -EINVAL;
}
if (value > rs->md.raid_disks) {
rs->ti->error = "Invalid rebuild index given";
return -EINVAL;
}
clear_bit(In_sync, &rs->dev[value].rdev.flags);
rs->dev[value].rdev.recovery_offset = 0;
} else if (!strcmp(key, "max_write_behind")) {
rs->print_flags |= DMPF_MAX_WRITE_BEHIND;
/*
* In device-mapper, we specify things in sectors, but
* MD records this value in kB
*/
value /= 2;
if (value > COUNTER_MAX) {
rs->ti->error = "Max write-behind limit out of range";
return -EINVAL;
}
rs->md.bitmap_info.max_write_behind = value;
} else if (!strcmp(key, "daemon_sleep")) {
rs->print_flags |= DMPF_DAEMON_SLEEP;
if (!value || (value > MAX_SCHEDULE_TIMEOUT)) {
rs->ti->error = "daemon sleep period out of range";
return -EINVAL;
}
rs->md.bitmap_info.daemon_sleep = value;
} else if (!strcmp(key, "stripe_cache")) {
rs->print_flags |= DMPF_STRIPE_CACHE;
/*
* In device-mapper, we specify things in sectors, but
* MD records this value in kB
*/
value /= 2;
if (rs->raid_type->level < 5) {
rs->ti->error = "Inappropriate argument: stripe_cache";
return -EINVAL;
}
if (raid5_set_cache_size(&rs->md, (int)value)) {
rs->ti->error = "Bad stripe_cache size";
return -EINVAL;
}
} else if (!strcmp(key, "min_recovery_rate")) {
rs->print_flags |= DMPF_MIN_RECOVERY_RATE;
if (value > INT_MAX) {
rs->ti->error = "min_recovery_rate out of range";
return -EINVAL;
}
rs->md.sync_speed_min = (int)value;
} else if (!strcmp(key, "max_recovery_rate")) {
rs->print_flags |= DMPF_MAX_RECOVERY_RATE;
if (value > INT_MAX) {
rs->ti->error = "max_recovery_rate out of range";
return -EINVAL;
}
rs->md.sync_speed_max = (int)value;
} else {
DMERR("Unable to parse RAID parameter: %s", key);
rs->ti->error = "Unable to parse RAID parameters";
return -EINVAL;
}
}
/* Assume there are no metadata devices until the drives are parsed */
rs->md.persistent = 0;
rs->md.external = 1;
return 0;
}
static void do_table_event(struct work_struct *ws)
{
struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
dm_table_event(rs->ti->table);
}
static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
{
struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
return md_raid5_congested(&rs->md, bits);
}
/*
* Construct a RAID4/5/6 mapping:
* Args:
* <raid_type> <#raid_params> <raid_params> \
* <#raid_devs> { <meta_dev1> <dev1> .. <meta_devN> <devN> }
*
* ** metadata devices are not supported yet, use '-' instead **
*
* <raid_params> varies by <raid_type>. See 'parse_raid_params' for
* details on possible <raid_params>.
*/
static int raid_ctr(struct dm_target *ti, unsigned argc, char **argv)
{
int ret;
struct raid_type *rt;
unsigned long num_raid_params, num_raid_devs;
struct raid_set *rs = NULL;
/* Must have at least <raid_type> <#raid_params> */
if (argc < 2) {
ti->error = "Too few arguments";
return -EINVAL;
}
/* raid type */
rt = get_raid_type(argv[0]);
if (!rt) {
ti->error = "Unrecognised raid_type";
return -EINVAL;
}
argc--;
argv++;
/* number of RAID parameters */
if (strict_strtoul(argv[0], 10, &num_raid_params) < 0) {
ti->error = "Cannot understand number of RAID parameters";
return -EINVAL;
}
argc--;
argv++;
/* Skip over RAID params for now and find out # of devices */
if (num_raid_params + 1 > argc) {
ti->error = "Arguments do not agree with counts given";
return -EINVAL;
}
if ((strict_strtoul(argv[num_raid_params], 10, &num_raid_devs) < 0) ||
(num_raid_devs >= INT_MAX)) {
ti->error = "Cannot understand number of raid devices";
return -EINVAL;
}
rs = context_alloc(ti, rt, (unsigned)num_raid_devs);
if (IS_ERR(rs))
return PTR_ERR(rs);
ret = parse_raid_params(rs, argv, (unsigned)num_raid_params);
if (ret)
goto bad;
ret = -EINVAL;
argc -= num_raid_params + 1; /* +1: we already have num_raid_devs */
argv += num_raid_params + 1;
if (argc != (num_raid_devs * 2)) {
ti->error = "Supplied RAID devices does not match the count given";
goto bad;
}
ret = dev_parms(rs, argv);
if (ret)
goto bad;
INIT_WORK(&rs->md.event_work, do_table_event);
ti->split_io = rs->md.chunk_sectors;
ti->private = rs;
ti->num_flush_requests = 1;
mutex_lock(&rs->md.reconfig_mutex);
ret = md_run(&rs->md);
rs->md.in_sync = 0; /* Assume already marked dirty */
mutex_unlock(&rs->md.reconfig_mutex);
if (ret) {
ti->error = "Fail to run raid array";
goto bad;
}
rs->callbacks.congested_fn = raid_is_congested;
dm_table_add_target_callbacks(ti->table, &rs->callbacks);
return 0;
bad:
context_free(rs);
return ret;
}
static void raid_dtr(struct dm_target *ti)
{
struct raid_set *rs = ti->private;
list_del_init(&rs->callbacks.list);
md_stop(&rs->md);
context_free(rs);
}
static int raid_map(struct dm_target *ti, struct bio *bio, union map_info *map_context)
{
struct raid_set *rs = ti->private;
mddev_t *mddev = &rs->md;
mddev->pers->make_request(mddev, bio);
return DM_MAPIO_SUBMITTED;
}
static int raid_status(struct dm_target *ti, status_type_t type,
char *result, unsigned maxlen)
{
struct raid_set *rs = ti->private;
unsigned raid_param_cnt = 1; /* at least 1 for chunksize */
unsigned sz = 0;
int i;
sector_t sync;
switch (type) {
case STATUSTYPE_INFO:
DMEMIT("%s %d ", rs->raid_type->name, rs->md.raid_disks);
for (i = 0; i < rs->md.raid_disks; i++) {
if (test_bit(Faulty, &rs->dev[i].rdev.flags))
DMEMIT("D");
else if (test_bit(In_sync, &rs->dev[i].rdev.flags))
DMEMIT("A");
else
DMEMIT("a");
}
if (test_bit(MD_RECOVERY_RUNNING, &rs->md.recovery))
sync = rs->md.curr_resync_completed;
else
sync = rs->md.recovery_cp;
if (sync > rs->md.resync_max_sectors)
sync = rs->md.resync_max_sectors;
DMEMIT(" %llu/%llu",
(unsigned long long) sync,
(unsigned long long) rs->md.resync_max_sectors);
break;
case STATUSTYPE_TABLE:
/* The string you would use to construct this array */
for (i = 0; i < rs->md.raid_disks; i++)
if (rs->dev[i].data_dev &&
!test_bit(In_sync, &rs->dev[i].rdev.flags))
raid_param_cnt++; /* for rebuilds */
raid_param_cnt += (hweight64(rs->print_flags) * 2);
if (rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC))
raid_param_cnt--;
DMEMIT("%s %u %u", rs->raid_type->name,
raid_param_cnt, rs->md.chunk_sectors);
if ((rs->print_flags & DMPF_SYNC) &&
(rs->md.recovery_cp == MaxSector))
DMEMIT(" sync");
if (rs->print_flags & DMPF_NOSYNC)
DMEMIT(" nosync");
for (i = 0; i < rs->md.raid_disks; i++)
if (rs->dev[i].data_dev &&
!test_bit(In_sync, &rs->dev[i].rdev.flags))
DMEMIT(" rebuild %u", i);
if (rs->print_flags & DMPF_DAEMON_SLEEP)
DMEMIT(" daemon_sleep %lu",
rs->md.bitmap_info.daemon_sleep);
if (rs->print_flags & DMPF_MIN_RECOVERY_RATE)
DMEMIT(" min_recovery_rate %d", rs->md.sync_speed_min);
if (rs->print_flags & DMPF_MAX_RECOVERY_RATE)
DMEMIT(" max_recovery_rate %d", rs->md.sync_speed_max);
if (rs->print_flags & DMPF_MAX_WRITE_BEHIND)
DMEMIT(" max_write_behind %lu",
rs->md.bitmap_info.max_write_behind);
if (rs->print_flags & DMPF_STRIPE_CACHE) {
raid5_conf_t *conf = rs->md.private;
/* convert from kiB to sectors */
DMEMIT(" stripe_cache %d",
conf ? conf->max_nr_stripes * 2 : 0);
}
DMEMIT(" %d", rs->md.raid_disks);
for (i = 0; i < rs->md.raid_disks; i++) {
DMEMIT(" -"); /* metadata device */
if (rs->dev[i].data_dev)
DMEMIT(" %s", rs->dev[i].data_dev->name);
else
DMEMIT(" -");
}
}
return 0;
}
static int raid_iterate_devices(struct dm_target *ti, iterate_devices_callout_fn fn, void *data)
{
struct raid_set *rs = ti->private;
unsigned i;
int ret = 0;
for (i = 0; !ret && i < rs->md.raid_disks; i++)
if (rs->dev[i].data_dev)
ret = fn(ti,
rs->dev[i].data_dev,
0, /* No offset on data devs */
rs->md.dev_sectors,
data);
return ret;
}
static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
{
struct raid_set *rs = ti->private;
unsigned chunk_size = rs->md.chunk_sectors << 9;
raid5_conf_t *conf = rs->md.private;
blk_limits_io_min(limits, chunk_size);
blk_limits_io_opt(limits, chunk_size * (conf->raid_disks - conf->max_degraded));
}
static void raid_presuspend(struct dm_target *ti)
{
struct raid_set *rs = ti->private;
md_stop_writes(&rs->md);
}
static void raid_postsuspend(struct dm_target *ti)
{
struct raid_set *rs = ti->private;
mddev_suspend(&rs->md);
}
static void raid_resume(struct dm_target *ti)
{
struct raid_set *rs = ti->private;
mddev_resume(&rs->md);
}
static struct target_type raid_target = {
.name = "raid",
.version = {1, 0, 0},
.module = THIS_MODULE,
.ctr = raid_ctr,
.dtr = raid_dtr,
.map = raid_map,
.status = raid_status,
.iterate_devices = raid_iterate_devices,
.io_hints = raid_io_hints,
.presuspend = raid_presuspend,
.postsuspend = raid_postsuspend,
.resume = raid_resume,
};
static int __init dm_raid_init(void)
{
return dm_register_target(&raid_target);
}
static void __exit dm_raid_exit(void)
{
dm_unregister_target(&raid_target);
}
module_init(dm_raid_init);
module_exit(dm_raid_exit);
MODULE_DESCRIPTION(DM_NAME " raid4/5/6 target");
MODULE_ALIAS("dm-raid4");
MODULE_ALIAS("dm-raid5");
MODULE_ALIAS("dm-raid6");
MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
instantinfrastructure/linux-yocto-3.10 | drivers/char/msm_smd_pkt.c | 3115 | 10883 | /* Copyright (c) 2008-2010, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.
*
*/
/*
* SMD Packet Driver -- Provides userspace interface to SMD packet ports.
*/
#include <linux/slab.h>
#include <linux/cdev.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include <linux/workqueue.h>
#include <linux/poll.h>
#include <mach/msm_smd.h>
#define NUM_SMD_PKT_PORTS 9
#define DEVICE_NAME "smdpkt"
#define MAX_BUF_SIZE 2048
struct smd_pkt_dev {
struct cdev cdev;
struct device *devicep;
struct smd_channel *ch;
int open_count;
struct mutex ch_lock;
struct mutex rx_lock;
struct mutex tx_lock;
wait_queue_head_t ch_read_wait_queue;
wait_queue_head_t ch_opened_wait_queue;
int i;
unsigned char tx_buf[MAX_BUF_SIZE];
unsigned char rx_buf[MAX_BUF_SIZE];
int remote_open;
} *smd_pkt_devp[NUM_SMD_PKT_PORTS];
struct class *smd_pkt_classp;
static dev_t smd_pkt_number;
static int msm_smd_pkt_debug_enable;
module_param_named(debug_enable, msm_smd_pkt_debug_enable,
int, S_IRUGO | S_IWUSR | S_IWGRP);
#ifdef DEBUG
#define D_DUMP_BUFFER(prestr, cnt, buf) do { \
int i; \
if (msm_smd_pkt_debug_enable) { \
pr_debug("%s", prestr); \
for (i = 0; i < cnt; i++) \
pr_debug("%.2x", buf[i]); \
pr_debug("\n"); \
} \
} while (0)
#else
#define D_DUMP_BUFFER(prestr, cnt, buf) do {} while (0)
#endif
#ifdef DEBUG
#define DBG(x...) do { \
if (msm_smd_pkt_debug_enable) \
pr_debug(x); \
} while (0)
#else
#define DBG(x...) do {} while (0)
#endif
static void check_and_wakeup_reader(struct smd_pkt_dev *smd_pkt_devp)
{
int sz;
if (!smd_pkt_devp || !smd_pkt_devp->ch)
return;
sz = smd_cur_packet_size(smd_pkt_devp->ch);
if (sz == 0) {
DBG("no packet\n");
return;
}
if (sz > smd_read_avail(smd_pkt_devp->ch)) {
DBG("incomplete packet\n");
return;
}
DBG("waking up reader\n");
wake_up_interruptible(&smd_pkt_devp->ch_read_wait_queue);
}
static int smd_pkt_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int r, bytes_read;
struct smd_pkt_dev *smd_pkt_devp;
struct smd_channel *chl;
DBG("read %d bytes\n", count);
if (count > MAX_BUF_SIZE)
return -EINVAL;
smd_pkt_devp = file->private_data;
if (!smd_pkt_devp || !smd_pkt_devp->ch)
return -EINVAL;
chl = smd_pkt_devp->ch;
wait_for_packet:
r = wait_event_interruptible(smd_pkt_devp->ch_read_wait_queue,
(smd_cur_packet_size(chl) > 0 &&
smd_read_avail(chl) >=
smd_cur_packet_size(chl)));
if (r < 0) {
if (r != -ERESTARTSYS)
pr_err("wait returned %d\n", r);
return r;
}
mutex_lock(&smd_pkt_devp->rx_lock);
bytes_read = smd_cur_packet_size(smd_pkt_devp->ch);
if (bytes_read == 0 ||
bytes_read < smd_read_avail(smd_pkt_devp->ch)) {
mutex_unlock(&smd_pkt_devp->rx_lock);
DBG("Nothing to read\n");
goto wait_for_packet;
}
if (bytes_read > count) {
mutex_unlock(&smd_pkt_devp->rx_lock);
pr_info("packet size %d > buffer size %d", bytes_read, count);
return -EINVAL;
}
r = smd_read(smd_pkt_devp->ch, smd_pkt_devp->rx_buf, bytes_read);
if (r != bytes_read) {
mutex_unlock(&smd_pkt_devp->rx_lock);
pr_err("smd_read failed to read %d bytes: %d\n", bytes_read, r);
return -EIO;
}
D_DUMP_BUFFER("read: ", bytes_read, smd_pkt_devp->rx_buf);
r = copy_to_user(buf, smd_pkt_devp->rx_buf, bytes_read);
mutex_unlock(&smd_pkt_devp->rx_lock);
if (r) {
pr_err("copy_to_user failed %d\n", r);
return -EFAULT;
}
DBG("read complete %d bytes\n", bytes_read);
check_and_wakeup_reader(smd_pkt_devp);
return bytes_read;
}
static int smd_pkt_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int r;
struct smd_pkt_dev *smd_pkt_devp;
if (count > MAX_BUF_SIZE)
return -EINVAL;
DBG("writting %d bytes\n", count);
smd_pkt_devp = file->private_data;
if (!smd_pkt_devp || !smd_pkt_devp->ch)
return -EINVAL;
mutex_lock(&smd_pkt_devp->tx_lock);
if (smd_write_avail(smd_pkt_devp->ch) < count) {
mutex_unlock(&smd_pkt_devp->tx_lock);
DBG("Not enough space to write\n");
return -ENOMEM;
}
D_DUMP_BUFFER("write: ", count, buf);
r = copy_from_user(smd_pkt_devp->tx_buf, buf, count);
if (r) {
mutex_unlock(&smd_pkt_devp->tx_lock);
pr_err("copy_from_user failed %d\n", r);
return -EFAULT;
}
r = smd_write(smd_pkt_devp->ch, smd_pkt_devp->tx_buf, count);
if (r != count) {
mutex_unlock(&smd_pkt_devp->tx_lock);
pr_err("smd_write failed to write %d bytes: %d.\n", count, r);
return -EIO;
}
mutex_unlock(&smd_pkt_devp->tx_lock);
DBG("wrote %d bytes\n", count);
return count;
}
static unsigned int smd_pkt_poll(struct file *file, poll_table *wait)
{
struct smd_pkt_dev *smd_pkt_devp;
unsigned int mask = 0;
smd_pkt_devp = file->private_data;
if (!smd_pkt_devp)
return POLLERR;
DBG("poll waiting\n");
poll_wait(file, &smd_pkt_devp->ch_read_wait_queue, wait);
if (smd_read_avail(smd_pkt_devp->ch))
mask |= POLLIN | POLLRDNORM;
DBG("poll return\n");
return mask;
}
static void smd_pkt_ch_notify(void *priv, unsigned event)
{
struct smd_pkt_dev *smd_pkt_devp = priv;
if (smd_pkt_devp->ch == 0)
return;
switch (event) {
case SMD_EVENT_DATA:
DBG("data\n");
check_and_wakeup_reader(smd_pkt_devp);
break;
case SMD_EVENT_OPEN:
DBG("remote open\n");
smd_pkt_devp->remote_open = 1;
wake_up_interruptible(&smd_pkt_devp->ch_opened_wait_queue);
break;
case SMD_EVENT_CLOSE:
smd_pkt_devp->remote_open = 0;
pr_info("remote closed\n");
break;
default:
pr_err("unknown event %d\n", event);
break;
}
}
static char *smd_pkt_dev_name[] = {
"smdcntl0",
"smdcntl1",
"smdcntl2",
"smdcntl3",
"smdcntl4",
"smdcntl5",
"smdcntl6",
"smdcntl7",
"smd22",
};
static char *smd_ch_name[] = {
"DATA5_CNTL",
"DATA6_CNTL",
"DATA7_CNTL",
"DATA8_CNTL",
"DATA9_CNTL",
"DATA12_CNTL",
"DATA13_CNTL",
"DATA14_CNTL",
"DATA22",
};
static int smd_pkt_open(struct inode *inode, struct file *file)
{
int r = 0;
struct smd_pkt_dev *smd_pkt_devp;
smd_pkt_devp = container_of(inode->i_cdev, struct smd_pkt_dev, cdev);
if (!smd_pkt_devp)
return -EINVAL;
file->private_data = smd_pkt_devp;
mutex_lock(&smd_pkt_devp->ch_lock);
if (smd_pkt_devp->open_count == 0) {
r = smd_open(smd_ch_name[smd_pkt_devp->i],
&smd_pkt_devp->ch, smd_pkt_devp,
smd_pkt_ch_notify);
if (r < 0) {
pr_err("smd_open failed for %s, %d\n",
smd_ch_name[smd_pkt_devp->i], r);
goto out;
}
r = wait_event_interruptible_timeout(
smd_pkt_devp->ch_opened_wait_queue,
smd_pkt_devp->remote_open,
msecs_to_jiffies(2 * HZ));
if (r == 0)
r = -ETIMEDOUT;
if (r < 0) {
pr_err("wait returned %d\n", r);
smd_close(smd_pkt_devp->ch);
smd_pkt_devp->ch = 0;
} else {
smd_pkt_devp->open_count++;
r = 0;
}
}
out:
mutex_unlock(&smd_pkt_devp->ch_lock);
return r;
}
static int smd_pkt_release(struct inode *inode, struct file *file)
{
int r = 0;
struct smd_pkt_dev *smd_pkt_devp = file->private_data;
if (!smd_pkt_devp)
return -EINVAL;
mutex_lock(&smd_pkt_devp->ch_lock);
if (--smd_pkt_devp->open_count == 0) {
r = smd_close(smd_pkt_devp->ch);
smd_pkt_devp->ch = 0;
}
mutex_unlock(&smd_pkt_devp->ch_lock);
return r;
}
static const struct file_operations smd_pkt_fops = {
.owner = THIS_MODULE,
.open = smd_pkt_open,
.release = smd_pkt_release,
.read = smd_pkt_read,
.write = smd_pkt_write,
.poll = smd_pkt_poll,
};
static int __init smd_pkt_init(void)
{
int i;
int r;
r = alloc_chrdev_region(&smd_pkt_number, 0,
NUM_SMD_PKT_PORTS, DEVICE_NAME);
if (r) {
pr_err("alloc_chrdev_region() failed %d\n", r);
return r;
}
smd_pkt_classp = class_create(THIS_MODULE, DEVICE_NAME);
if (IS_ERR(smd_pkt_classp)) {
r = PTR_ERR(smd_pkt_classp);
pr_err("class_create() failed %d\n", r);
goto unreg_chardev;
}
for (i = 0; i < NUM_SMD_PKT_PORTS; ++i) {
smd_pkt_devp[i] = kzalloc(sizeof(struct smd_pkt_dev),
GFP_KERNEL);
if (!smd_pkt_devp[i]) {
pr_err("kmalloc() failed\n");
goto clean_cdevs;
}
smd_pkt_devp[i]->i = i;
init_waitqueue_head(&smd_pkt_devp[i]->ch_read_wait_queue);
smd_pkt_devp[i]->remote_open = 0;
init_waitqueue_head(&smd_pkt_devp[i]->ch_opened_wait_queue);
mutex_init(&smd_pkt_devp[i]->ch_lock);
mutex_init(&smd_pkt_devp[i]->rx_lock);
mutex_init(&smd_pkt_devp[i]->tx_lock);
cdev_init(&smd_pkt_devp[i]->cdev, &smd_pkt_fops);
smd_pkt_devp[i]->cdev.owner = THIS_MODULE;
r = cdev_add(&smd_pkt_devp[i]->cdev,
(smd_pkt_number + i), 1);
if (r) {
pr_err("cdev_add() failed %d\n", r);
kfree(smd_pkt_devp[i]);
goto clean_cdevs;
}
smd_pkt_devp[i]->devicep =
device_create(smd_pkt_classp, NULL,
(smd_pkt_number + i), NULL,
smd_pkt_dev_name[i]);
if (IS_ERR(smd_pkt_devp[i]->devicep)) {
r = PTR_ERR(smd_pkt_devp[i]->devicep);
pr_err("device_create() failed %d\n", r);
cdev_del(&smd_pkt_devp[i]->cdev);
kfree(smd_pkt_devp[i]);
goto clean_cdevs;
}
}
pr_info("SMD Packet Port Driver Initialized.\n");
return 0;
clean_cdevs:
if (i > 0) {
while (--i >= 0) {
mutex_destroy(&smd_pkt_devp[i]->ch_lock);
mutex_destroy(&smd_pkt_devp[i]->rx_lock);
mutex_destroy(&smd_pkt_devp[i]->tx_lock);
cdev_del(&smd_pkt_devp[i]->cdev);
kfree(smd_pkt_devp[i]);
device_destroy(smd_pkt_classp,
MKDEV(MAJOR(smd_pkt_number), i));
}
}
class_destroy(smd_pkt_classp);
unreg_chardev:
unregister_chrdev_region(MAJOR(smd_pkt_number), NUM_SMD_PKT_PORTS);
return r;
}
module_init(smd_pkt_init);
static void __exit smd_pkt_cleanup(void)
{
int i;
for (i = 0; i < NUM_SMD_PKT_PORTS; ++i) {
mutex_destroy(&smd_pkt_devp[i]->ch_lock);
mutex_destroy(&smd_pkt_devp[i]->rx_lock);
mutex_destroy(&smd_pkt_devp[i]->tx_lock);
cdev_del(&smd_pkt_devp[i]->cdev);
kfree(smd_pkt_devp[i]);
device_destroy(smd_pkt_classp,
MKDEV(MAJOR(smd_pkt_number), i));
}
class_destroy(smd_pkt_classp);
unregister_chrdev_region(MAJOR(smd_pkt_number), NUM_SMD_PKT_PORTS);
}
module_exit(smd_pkt_cleanup);
MODULE_DESCRIPTION("MSM Shared Memory Packet Port");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Team-Hydra/sultan-kernel-pyramid-pure-3.4 | arch/microblaze/pci/pci-common.c | 4395 | 47129 | /*
* Contains common pci routines for ALL ppc platform
* (based on pci_32.c and pci_64.c)
*
* Port for PPC64 David Engebretsen, IBM Corp.
* Contains common pci routines for ppc64 platform, pSeries and iSeries brands.
*
* Copyright (C) 2003 Anton Blanchard <anton@au.ibm.com>, IBM
* Rework, based on alpha PCI code.
*
* Common pmac/prep/chrp pci routines. -- Cort
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <linux/syscalls.h>
#include <linux/irq.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_pci.h>
#include <linux/export.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/pci-bridge.h>
#include <asm/byteorder.h>
static DEFINE_SPINLOCK(hose_spinlock);
LIST_HEAD(hose_list);
/* XXX kill that some day ... */
static int global_phb_number; /* Global phb counter */
/* ISA Memory physical address */
resource_size_t isa_mem_base;
static struct dma_map_ops *pci_dma_ops = &dma_direct_ops;
unsigned long isa_io_base;
unsigned long pci_dram_offset;
static int pci_bus_count;
void set_pci_dma_ops(struct dma_map_ops *dma_ops)
{
pci_dma_ops = dma_ops;
}
struct dma_map_ops *get_pci_dma_ops(void)
{
return pci_dma_ops;
}
EXPORT_SYMBOL(get_pci_dma_ops);
struct pci_controller *pcibios_alloc_controller(struct device_node *dev)
{
struct pci_controller *phb;
phb = zalloc_maybe_bootmem(sizeof(struct pci_controller), GFP_KERNEL);
if (!phb)
return NULL;
spin_lock(&hose_spinlock);
phb->global_number = global_phb_number++;
list_add_tail(&phb->list_node, &hose_list);
spin_unlock(&hose_spinlock);
phb->dn = dev;
phb->is_dynamic = mem_init_done;
return phb;
}
void pcibios_free_controller(struct pci_controller *phb)
{
spin_lock(&hose_spinlock);
list_del(&phb->list_node);
spin_unlock(&hose_spinlock);
if (phb->is_dynamic)
kfree(phb);
}
static resource_size_t pcibios_io_size(const struct pci_controller *hose)
{
return resource_size(&hose->io_resource);
}
int pcibios_vaddr_is_ioport(void __iomem *address)
{
int ret = 0;
struct pci_controller *hose;
resource_size_t size;
spin_lock(&hose_spinlock);
list_for_each_entry(hose, &hose_list, list_node) {
size = pcibios_io_size(hose);
if (address >= hose->io_base_virt &&
address < (hose->io_base_virt + size)) {
ret = 1;
break;
}
}
spin_unlock(&hose_spinlock);
return ret;
}
unsigned long pci_address_to_pio(phys_addr_t address)
{
struct pci_controller *hose;
resource_size_t size;
unsigned long ret = ~0;
spin_lock(&hose_spinlock);
list_for_each_entry(hose, &hose_list, list_node) {
size = pcibios_io_size(hose);
if (address >= hose->io_base_phys &&
address < (hose->io_base_phys + size)) {
unsigned long base =
(unsigned long)hose->io_base_virt - _IO_BASE;
ret = base + (address - hose->io_base_phys);
break;
}
}
spin_unlock(&hose_spinlock);
return ret;
}
EXPORT_SYMBOL_GPL(pci_address_to_pio);
/*
* Return the domain number for this bus.
*/
int pci_domain_nr(struct pci_bus *bus)
{
struct pci_controller *hose = pci_bus_to_host(bus);
return hose->global_number;
}
EXPORT_SYMBOL(pci_domain_nr);
/* This routine is meant to be used early during boot, when the
* PCI bus numbers have not yet been assigned, and you need to
* issue PCI config cycles to an OF device.
* It could also be used to "fix" RTAS config cycles if you want
* to set pci_assign_all_buses to 1 and still use RTAS for PCI
* config cycles.
*/
struct pci_controller *pci_find_hose_for_OF_device(struct device_node *node)
{
while (node) {
struct pci_controller *hose, *tmp;
list_for_each_entry_safe(hose, tmp, &hose_list, list_node)
if (hose->dn == node)
return hose;
node = node->parent;
}
return NULL;
}
static ssize_t pci_show_devspec(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pci_dev *pdev;
struct device_node *np;
pdev = to_pci_dev(dev);
np = pci_device_to_OF_node(pdev);
if (np == NULL || np->full_name == NULL)
return 0;
return sprintf(buf, "%s", np->full_name);
}
static DEVICE_ATTR(devspec, S_IRUGO, pci_show_devspec, NULL);
/* Add sysfs properties */
int pcibios_add_platform_entries(struct pci_dev *pdev)
{
return device_create_file(&pdev->dev, &dev_attr_devspec);
}
void pcibios_set_master(struct pci_dev *dev)
{
/* No special bus mastering setup handling */
}
char __devinit *pcibios_setup(char *str)
{
return str;
}
/*
* Reads the interrupt pin to determine if interrupt is use by card.
* If the interrupt is used, then gets the interrupt line from the
* openfirmware and sets it in the pci_dev and pci_config line.
*/
int pci_read_irq_line(struct pci_dev *pci_dev)
{
struct of_irq oirq;
unsigned int virq;
/* The current device-tree that iSeries generates from the HV
* PCI informations doesn't contain proper interrupt routing,
* and all the fallback would do is print out crap, so we
* don't attempt to resolve the interrupts here at all, some
* iSeries specific fixup does it.
*
* In the long run, we will hopefully fix the generated device-tree
* instead.
*/
pr_debug("PCI: Try to map irq for %s...\n", pci_name(pci_dev));
#ifdef DEBUG
memset(&oirq, 0xff, sizeof(oirq));
#endif
/* Try to get a mapping from the device-tree */
if (of_irq_map_pci(pci_dev, &oirq)) {
u8 line, pin;
/* If that fails, lets fallback to what is in the config
* space and map that through the default controller. We
* also set the type to level low since that's what PCI
* interrupts are. If your platform does differently, then
* either provide a proper interrupt tree or don't use this
* function.
*/
if (pci_read_config_byte(pci_dev, PCI_INTERRUPT_PIN, &pin))
return -1;
if (pin == 0)
return -1;
if (pci_read_config_byte(pci_dev, PCI_INTERRUPT_LINE, &line) ||
line == 0xff || line == 0) {
return -1;
}
pr_debug(" No map ! Using line %d (pin %d) from PCI config\n",
line, pin);
virq = irq_create_mapping(NULL, line);
if (virq)
irq_set_irq_type(virq, IRQ_TYPE_LEVEL_LOW);
} else {
pr_debug(" Got one, spec %d cells (0x%08x 0x%08x...) on %s\n",
oirq.size, oirq.specifier[0], oirq.specifier[1],
oirq.controller ? oirq.controller->full_name :
"<default>");
virq = irq_create_of_mapping(oirq.controller, oirq.specifier,
oirq.size);
}
if (!virq) {
pr_debug(" Failed to map !\n");
return -1;
}
pr_debug(" Mapped to linux irq %d\n", virq);
pci_dev->irq = virq;
return 0;
}
EXPORT_SYMBOL(pci_read_irq_line);
/*
* Platform support for /proc/bus/pci/X/Y mmap()s,
* modelled on the sparc64 implementation by Dave Miller.
* -- paulus.
*/
/*
* Adjust vm_pgoff of VMA such that it is the physical page offset
* corresponding to the 32-bit pci bus offset for DEV requested by the user.
*
* Basically, the user finds the base address for his device which he wishes
* to mmap. They read the 32-bit value from the config space base register,
* add whatever PAGE_SIZE multiple offset they wish, and feed this into the
* offset parameter of mmap on /proc/bus/pci/XXX for that device.
*
* Returns negative error code on failure, zero on success.
*/
static struct resource *__pci_mmap_make_offset(struct pci_dev *dev,
resource_size_t *offset,
enum pci_mmap_state mmap_state)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
unsigned long io_offset = 0;
int i, res_bit;
if (hose == 0)
return NULL; /* should never happen */
/* If memory, add on the PCI bridge address offset */
if (mmap_state == pci_mmap_mem) {
#if 0 /* See comment in pci_resource_to_user() for why this is disabled */
*offset += hose->pci_mem_offset;
#endif
res_bit = IORESOURCE_MEM;
} else {
io_offset = (unsigned long)hose->io_base_virt - _IO_BASE;
*offset += io_offset;
res_bit = IORESOURCE_IO;
}
/*
* Check that the offset requested corresponds to one of the
* resources of the device.
*/
for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
struct resource *rp = &dev->resource[i];
int flags = rp->flags;
/* treat ROM as memory (should be already) */
if (i == PCI_ROM_RESOURCE)
flags |= IORESOURCE_MEM;
/* Active and same type? */
if ((flags & res_bit) == 0)
continue;
/* In the range of this resource? */
if (*offset < (rp->start & PAGE_MASK) || *offset > rp->end)
continue;
/* found it! construct the final physical address */
if (mmap_state == pci_mmap_io)
*offset += hose->io_base_phys - io_offset;
return rp;
}
return NULL;
}
/*
* Set vm_page_prot of VMA, as appropriate for this architecture, for a pci
* device mapping.
*/
static pgprot_t __pci_mmap_set_pgprot(struct pci_dev *dev, struct resource *rp,
pgprot_t protection,
enum pci_mmap_state mmap_state,
int write_combine)
{
pgprot_t prot = protection;
/* Write combine is always 0 on non-memory space mappings. On
* memory space, if the user didn't pass 1, we check for a
* "prefetchable" resource. This is a bit hackish, but we use
* this to workaround the inability of /sysfs to provide a write
* combine bit
*/
if (mmap_state != pci_mmap_mem)
write_combine = 0;
else if (write_combine == 0) {
if (rp->flags & IORESOURCE_PREFETCH)
write_combine = 1;
}
return pgprot_noncached(prot);
}
/*
* This one is used by /dev/mem and fbdev who have no clue about the
* PCI device, it tries to find the PCI device first and calls the
* above routine
*/
pgprot_t pci_phys_mem_access_prot(struct file *file,
unsigned long pfn,
unsigned long size,
pgprot_t prot)
{
struct pci_dev *pdev = NULL;
struct resource *found = NULL;
resource_size_t offset = ((resource_size_t)pfn) << PAGE_SHIFT;
int i;
if (page_is_ram(pfn))
return prot;
prot = pgprot_noncached(prot);
for_each_pci_dev(pdev) {
for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
struct resource *rp = &pdev->resource[i];
int flags = rp->flags;
/* Active and same type? */
if ((flags & IORESOURCE_MEM) == 0)
continue;
/* In the range of this resource? */
if (offset < (rp->start & PAGE_MASK) ||
offset > rp->end)
continue;
found = rp;
break;
}
if (found)
break;
}
if (found) {
if (found->flags & IORESOURCE_PREFETCH)
prot = pgprot_noncached_wc(prot);
pci_dev_put(pdev);
}
pr_debug("PCI: Non-PCI map for %llx, prot: %lx\n",
(unsigned long long)offset, pgprot_val(prot));
return prot;
}
/*
* Perform the actual remap of the pages for a PCI device mapping, as
* appropriate for this architecture. The region in the process to map
* is described by vm_start and vm_end members of VMA, the base physical
* address is found in vm_pgoff.
* The pci device structure is provided so that architectures may make mapping
* decisions on a per-device or per-bus basis.
*
* Returns a negative error code on failure, zero on success.
*/
int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
enum pci_mmap_state mmap_state, int write_combine)
{
resource_size_t offset =
((resource_size_t)vma->vm_pgoff) << PAGE_SHIFT;
struct resource *rp;
int ret;
rp = __pci_mmap_make_offset(dev, &offset, mmap_state);
if (rp == NULL)
return -EINVAL;
vma->vm_pgoff = offset >> PAGE_SHIFT;
vma->vm_page_prot = __pci_mmap_set_pgprot(dev, rp,
vma->vm_page_prot,
mmap_state, write_combine);
ret = remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start, vma->vm_page_prot);
return ret;
}
/* This provides legacy IO read access on a bus */
int pci_legacy_read(struct pci_bus *bus, loff_t port, u32 *val, size_t size)
{
unsigned long offset;
struct pci_controller *hose = pci_bus_to_host(bus);
struct resource *rp = &hose->io_resource;
void __iomem *addr;
/* Check if port can be supported by that bus. We only check
* the ranges of the PHB though, not the bus itself as the rules
* for forwarding legacy cycles down bridges are not our problem
* here. So if the host bridge supports it, we do it.
*/
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
offset += port;
if (!(rp->flags & IORESOURCE_IO))
return -ENXIO;
if (offset < rp->start || (offset + size) > rp->end)
return -ENXIO;
addr = hose->io_base_virt + port;
switch (size) {
case 1:
*((u8 *)val) = in_8(addr);
return 1;
case 2:
if (port & 1)
return -EINVAL;
*((u16 *)val) = in_le16(addr);
return 2;
case 4:
if (port & 3)
return -EINVAL;
*((u32 *)val) = in_le32(addr);
return 4;
}
return -EINVAL;
}
/* This provides legacy IO write access on a bus */
int pci_legacy_write(struct pci_bus *bus, loff_t port, u32 val, size_t size)
{
unsigned long offset;
struct pci_controller *hose = pci_bus_to_host(bus);
struct resource *rp = &hose->io_resource;
void __iomem *addr;
/* Check if port can be supported by that bus. We only check
* the ranges of the PHB though, not the bus itself as the rules
* for forwarding legacy cycles down bridges are not our problem
* here. So if the host bridge supports it, we do it.
*/
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
offset += port;
if (!(rp->flags & IORESOURCE_IO))
return -ENXIO;
if (offset < rp->start || (offset + size) > rp->end)
return -ENXIO;
addr = hose->io_base_virt + port;
/* WARNING: The generic code is idiotic. It gets passed a pointer
* to what can be a 1, 2 or 4 byte quantity and always reads that
* as a u32, which means that we have to correct the location of
* the data read within those 32 bits for size 1 and 2
*/
switch (size) {
case 1:
out_8(addr, val >> 24);
return 1;
case 2:
if (port & 1)
return -EINVAL;
out_le16(addr, val >> 16);
return 2;
case 4:
if (port & 3)
return -EINVAL;
out_le32(addr, val);
return 4;
}
return -EINVAL;
}
/* This provides legacy IO or memory mmap access on a bus */
int pci_mmap_legacy_page_range(struct pci_bus *bus,
struct vm_area_struct *vma,
enum pci_mmap_state mmap_state)
{
struct pci_controller *hose = pci_bus_to_host(bus);
resource_size_t offset =
((resource_size_t)vma->vm_pgoff) << PAGE_SHIFT;
resource_size_t size = vma->vm_end - vma->vm_start;
struct resource *rp;
pr_debug("pci_mmap_legacy_page_range(%04x:%02x, %s @%llx..%llx)\n",
pci_domain_nr(bus), bus->number,
mmap_state == pci_mmap_mem ? "MEM" : "IO",
(unsigned long long)offset,
(unsigned long long)(offset + size - 1));
if (mmap_state == pci_mmap_mem) {
/* Hack alert !
*
* Because X is lame and can fail starting if it gets an error
* trying to mmap legacy_mem (instead of just moving on without
* legacy memory access) we fake it here by giving it anonymous
* memory, effectively behaving just like /dev/zero
*/
if ((offset + size) > hose->isa_mem_size) {
#ifdef CONFIG_MMU
printk(KERN_DEBUG
"Process %s (pid:%d) mapped non-existing PCI"
"legacy memory for 0%04x:%02x\n",
current->comm, current->pid, pci_domain_nr(bus),
bus->number);
#endif
if (vma->vm_flags & VM_SHARED)
return shmem_zero_setup(vma);
return 0;
}
offset += hose->isa_mem_phys;
} else {
unsigned long io_offset = (unsigned long)hose->io_base_virt - \
_IO_BASE;
unsigned long roffset = offset + io_offset;
rp = &hose->io_resource;
if (!(rp->flags & IORESOURCE_IO))
return -ENXIO;
if (roffset < rp->start || (roffset + size) > rp->end)
return -ENXIO;
offset += hose->io_base_phys;
}
pr_debug(" -> mapping phys %llx\n", (unsigned long long)offset);
vma->vm_pgoff = offset >> PAGE_SHIFT;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
void pci_resource_to_user(const struct pci_dev *dev, int bar,
const struct resource *rsrc,
resource_size_t *start, resource_size_t *end)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
resource_size_t offset = 0;
if (hose == NULL)
return;
if (rsrc->flags & IORESOURCE_IO)
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
/* We pass a fully fixed up address to userland for MMIO instead of
* a BAR value because X is lame and expects to be able to use that
* to pass to /dev/mem !
*
* That means that we'll have potentially 64 bits values where some
* userland apps only expect 32 (like X itself since it thinks only
* Sparc has 64 bits MMIO) but if we don't do that, we break it on
* 32 bits CHRPs :-(
*
* Hopefully, the sysfs insterface is immune to that gunk. Once X
* has been fixed (and the fix spread enough), we can re-enable the
* 2 lines below and pass down a BAR value to userland. In that case
* we'll also have to re-enable the matching code in
* __pci_mmap_make_offset().
*
* BenH.
*/
#if 0
else if (rsrc->flags & IORESOURCE_MEM)
offset = hose->pci_mem_offset;
#endif
*start = rsrc->start - offset;
*end = rsrc->end - offset;
}
/**
* pci_process_bridge_OF_ranges - Parse PCI bridge resources from device tree
* @hose: newly allocated pci_controller to be setup
* @dev: device node of the host bridge
* @primary: set if primary bus (32 bits only, soon to be deprecated)
*
* This function will parse the "ranges" property of a PCI host bridge device
* node and setup the resource mapping of a pci controller based on its
* content.
*
* Life would be boring if it wasn't for a few issues that we have to deal
* with here:
*
* - We can only cope with one IO space range and up to 3 Memory space
* ranges. However, some machines (thanks Apple !) tend to split their
* space into lots of small contiguous ranges. So we have to coalesce.
*
* - We can only cope with all memory ranges having the same offset
* between CPU addresses and PCI addresses. Unfortunately, some bridges
* are setup for a large 1:1 mapping along with a small "window" which
* maps PCI address 0 to some arbitrary high address of the CPU space in
* order to give access to the ISA memory hole.
* The way out of here that I've chosen for now is to always set the
* offset based on the first resource found, then override it if we
* have a different offset and the previous was set by an ISA hole.
*
* - Some busses have IO space not starting at 0, which causes trouble with
* the way we do our IO resource renumbering. The code somewhat deals with
* it for 64 bits but I would expect problems on 32 bits.
*
* - Some 32 bits platforms such as 4xx can have physical space larger than
* 32 bits so we need to use 64 bits values for the parsing
*/
void __devinit pci_process_bridge_OF_ranges(struct pci_controller *hose,
struct device_node *dev,
int primary)
{
const u32 *ranges;
int rlen;
int pna = of_n_addr_cells(dev);
int np = pna + 5;
int memno = 0, isa_hole = -1;
u32 pci_space;
unsigned long long pci_addr, cpu_addr, pci_next, cpu_next, size;
unsigned long long isa_mb = 0;
struct resource *res;
printk(KERN_INFO "PCI host bridge %s %s ranges:\n",
dev->full_name, primary ? "(primary)" : "");
/* Get ranges property */
ranges = of_get_property(dev, "ranges", &rlen);
if (ranges == NULL)
return;
/* Parse it */
pr_debug("Parsing ranges property...\n");
while ((rlen -= np * 4) >= 0) {
/* Read next ranges element */
pci_space = ranges[0];
pci_addr = of_read_number(ranges + 1, 2);
cpu_addr = of_translate_address(dev, ranges + 3);
size = of_read_number(ranges + pna + 3, 2);
pr_debug("pci_space: 0x%08x pci_addr:0x%016llx "
"cpu_addr:0x%016llx size:0x%016llx\n",
pci_space, pci_addr, cpu_addr, size);
ranges += np;
/* If we failed translation or got a zero-sized region
* (some FW try to feed us with non sensical zero sized regions
* such as power3 which look like some kind of attempt
* at exposing the VGA memory hole)
*/
if (cpu_addr == OF_BAD_ADDR || size == 0)
continue;
/* Now consume following elements while they are contiguous */
for (; rlen >= np * sizeof(u32);
ranges += np, rlen -= np * 4) {
if (ranges[0] != pci_space)
break;
pci_next = of_read_number(ranges + 1, 2);
cpu_next = of_translate_address(dev, ranges + 3);
if (pci_next != pci_addr + size ||
cpu_next != cpu_addr + size)
break;
size += of_read_number(ranges + pna + 3, 2);
}
/* Act based on address space type */
res = NULL;
switch ((pci_space >> 24) & 0x3) {
case 1: /* PCI IO space */
printk(KERN_INFO
" IO 0x%016llx..0x%016llx -> 0x%016llx\n",
cpu_addr, cpu_addr + size - 1, pci_addr);
/* We support only one IO range */
if (hose->pci_io_size) {
printk(KERN_INFO
" \\--> Skipped (too many) !\n");
continue;
}
/* On 32 bits, limit I/O space to 16MB */
if (size > 0x01000000)
size = 0x01000000;
/* 32 bits needs to map IOs here */
hose->io_base_virt = ioremap(cpu_addr, size);
/* Expect trouble if pci_addr is not 0 */
if (primary)
isa_io_base =
(unsigned long)hose->io_base_virt;
/* pci_io_size and io_base_phys always represent IO
* space starting at 0 so we factor in pci_addr
*/
hose->pci_io_size = pci_addr + size;
hose->io_base_phys = cpu_addr - pci_addr;
/* Build resource */
res = &hose->io_resource;
res->flags = IORESOURCE_IO;
res->start = pci_addr;
break;
case 2: /* PCI Memory space */
case 3: /* PCI 64 bits Memory space */
printk(KERN_INFO
" MEM 0x%016llx..0x%016llx -> 0x%016llx %s\n",
cpu_addr, cpu_addr + size - 1, pci_addr,
(pci_space & 0x40000000) ? "Prefetch" : "");
/* We support only 3 memory ranges */
if (memno >= 3) {
printk(KERN_INFO
" \\--> Skipped (too many) !\n");
continue;
}
/* Handles ISA memory hole space here */
if (pci_addr == 0) {
isa_mb = cpu_addr;
isa_hole = memno;
if (primary || isa_mem_base == 0)
isa_mem_base = cpu_addr;
hose->isa_mem_phys = cpu_addr;
hose->isa_mem_size = size;
}
/* We get the PCI/Mem offset from the first range or
* the, current one if the offset came from an ISA
* hole. If they don't match, bugger.
*/
if (memno == 0 ||
(isa_hole >= 0 && pci_addr != 0 &&
hose->pci_mem_offset == isa_mb))
hose->pci_mem_offset = cpu_addr - pci_addr;
else if (pci_addr != 0 &&
hose->pci_mem_offset != cpu_addr - pci_addr) {
printk(KERN_INFO
" \\--> Skipped (offset mismatch) !\n");
continue;
}
/* Build resource */
res = &hose->mem_resources[memno++];
res->flags = IORESOURCE_MEM;
if (pci_space & 0x40000000)
res->flags |= IORESOURCE_PREFETCH;
res->start = cpu_addr;
break;
}
if (res != NULL) {
res->name = dev->full_name;
res->end = res->start + size - 1;
res->parent = NULL;
res->sibling = NULL;
res->child = NULL;
}
}
/* If there's an ISA hole and the pci_mem_offset is -not- matching
* the ISA hole offset, then we need to remove the ISA hole from
* the resource list for that brige
*/
if (isa_hole >= 0 && hose->pci_mem_offset != isa_mb) {
unsigned int next = isa_hole + 1;
printk(KERN_INFO " Removing ISA hole at 0x%016llx\n", isa_mb);
if (next < memno)
memmove(&hose->mem_resources[isa_hole],
&hose->mem_resources[next],
sizeof(struct resource) * (memno - next));
hose->mem_resources[--memno].flags = 0;
}
}
/* Decide whether to display the domain number in /proc */
int pci_proc_domain(struct pci_bus *bus)
{
struct pci_controller *hose = pci_bus_to_host(bus);
return 0;
}
/* This header fixup will do the resource fixup for all devices as they are
* probed, but not for bridge ranges
*/
static void __devinit pcibios_fixup_resources(struct pci_dev *dev)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
int i;
if (!hose) {
printk(KERN_ERR "No host bridge for PCI dev %s !\n",
pci_name(dev));
return;
}
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
struct resource *res = dev->resource + i;
if (!res->flags)
continue;
if (res->start == 0) {
pr_debug("PCI:%s Resource %d %016llx-%016llx [%x]" \
"is unassigned\n",
pci_name(dev), i,
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned int)res->flags);
res->end -= res->start;
res->start = 0;
res->flags |= IORESOURCE_UNSET;
continue;
}
pr_debug("PCI:%s Resource %d %016llx-%016llx [%x]\n",
pci_name(dev), i,
(unsigned long long)res->start,\
(unsigned long long)res->end,
(unsigned int)res->flags);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, pcibios_fixup_resources);
/* This function tries to figure out if a bridge resource has been initialized
* by the firmware or not. It doesn't have to be absolutely bullet proof, but
* things go more smoothly when it gets it right. It should covers cases such
* as Apple "closed" bridge resources and bare-metal pSeries unassigned bridges
*/
static int __devinit pcibios_uninitialized_bridge_resource(struct pci_bus *bus,
struct resource *res)
{
struct pci_controller *hose = pci_bus_to_host(bus);
struct pci_dev *dev = bus->self;
resource_size_t offset;
u16 command;
int i;
/* Job is a bit different between memory and IO */
if (res->flags & IORESOURCE_MEM) {
/* If the BAR is non-0 (res != pci_mem_offset) then it's
* probably been initialized by somebody
*/
if (res->start != hose->pci_mem_offset)
return 0;
/* The BAR is 0, let's check if memory decoding is enabled on
* the bridge. If not, we consider it unassigned
*/
pci_read_config_word(dev, PCI_COMMAND, &command);
if ((command & PCI_COMMAND_MEMORY) == 0)
return 1;
/* Memory decoding is enabled and the BAR is 0. If any of
* the bridge resources covers that starting address (0 then
* it's good enough for us for memory
*/
for (i = 0; i < 3; i++) {
if ((hose->mem_resources[i].flags & IORESOURCE_MEM) &&
hose->mem_resources[i].start == hose->pci_mem_offset)
return 0;
}
/* Well, it starts at 0 and we know it will collide so we may as
* well consider it as unassigned. That covers the Apple case.
*/
return 1;
} else {
/* If the BAR is non-0, then we consider it assigned */
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
if (((res->start - offset) & 0xfffffffful) != 0)
return 0;
/* Here, we are a bit different than memory as typically IO
* space starting at low addresses -is- valid. What we do
* instead if that we consider as unassigned anything that
* doesn't have IO enabled in the PCI command register,
* and that's it.
*/
pci_read_config_word(dev, PCI_COMMAND, &command);
if (command & PCI_COMMAND_IO)
return 0;
/* It's starting at 0 and IO is disabled in the bridge, consider
* it unassigned
*/
return 1;
}
}
/* Fixup resources of a PCI<->PCI bridge */
static void __devinit pcibios_fixup_bridge(struct pci_bus *bus)
{
struct resource *res;
int i;
struct pci_dev *dev = bus->self;
pci_bus_for_each_resource(bus, res, i) {
if (!res)
continue;
if (!res->flags)
continue;
if (i >= 3 && bus->self->transparent)
continue;
pr_debug("PCI:%s Bus rsrc %d %016llx-%016llx [%x] fixup...\n",
pci_name(dev), i,
(unsigned long long)res->start,\
(unsigned long long)res->end,
(unsigned int)res->flags);
/* Try to detect uninitialized P2P bridge resources,
* and clear them out so they get re-assigned later
*/
if (pcibios_uninitialized_bridge_resource(bus, res)) {
res->flags = 0;
pr_debug("PCI:%s (unassigned)\n",
pci_name(dev));
} else {
pr_debug("PCI:%s %016llx-%016llx\n",
pci_name(dev),
(unsigned long long)res->start,
(unsigned long long)res->end);
}
}
}
void __devinit pcibios_setup_bus_self(struct pci_bus *bus)
{
/* Fix up the bus resources for P2P bridges */
if (bus->self != NULL)
pcibios_fixup_bridge(bus);
}
void __devinit pcibios_setup_bus_devices(struct pci_bus *bus)
{
struct pci_dev *dev;
pr_debug("PCI: Fixup bus devices %d (%s)\n",
bus->number, bus->self ? pci_name(bus->self) : "PHB");
list_for_each_entry(dev, &bus->devices, bus_list) {
/* Setup OF node pointer in archdata */
dev->dev.of_node = pci_device_to_OF_node(dev);
/* Fixup NUMA node as it may not be setup yet by the generic
* code and is needed by the DMA init
*/
set_dev_node(&dev->dev, pcibus_to_node(dev->bus));
/* Hook up default DMA ops */
set_dma_ops(&dev->dev, pci_dma_ops);
dev->dev.archdata.dma_data = (void *)PCI_DRAM_OFFSET;
/* Read default IRQs and fixup if necessary */
pci_read_irq_line(dev);
}
}
void __devinit pcibios_fixup_bus(struct pci_bus *bus)
{
/* When called from the generic PCI probe, read PCI<->PCI bridge
* bases. This is -not- called when generating the PCI tree from
* the OF device-tree.
*/
if (bus->self != NULL)
pci_read_bridge_bases(bus);
/* Now fixup the bus bus */
pcibios_setup_bus_self(bus);
/* Now fixup devices on that bus */
pcibios_setup_bus_devices(bus);
}
EXPORT_SYMBOL(pcibios_fixup_bus);
static int skip_isa_ioresource_align(struct pci_dev *dev)
{
return 0;
}
/*
* We need to avoid collisions with `mirrored' VGA ports
* and other strange ISA hardware, so we always want the
* addresses to be allocated in the 0x000-0x0ff region
* modulo 0x400.
*
* Why? Because some silly external IO cards only decode
* the low 10 bits of the IO address. The 0x00-0xff region
* is reserved for motherboard devices that decode all 16
* bits, so it's ok to allocate at, say, 0x2800-0x28ff,
* but we want to try to avoid allocating at 0x2900-0x2bff
* which might have be mirrored at 0x0100-0x03ff..
*/
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
struct pci_dev *dev = data;
resource_size_t start = res->start;
if (res->flags & IORESOURCE_IO) {
if (skip_isa_ioresource_align(dev))
return start;
if (start & 0x300)
start = (start + 0x3ff) & ~0x3ff;
}
return start;
}
EXPORT_SYMBOL(pcibios_align_resource);
/*
* Reparent resource children of pr that conflict with res
* under res, and make res replace those children.
*/
static int __init reparent_resources(struct resource *parent,
struct resource *res)
{
struct resource *p, **pp;
struct resource **firstpp = NULL;
for (pp = &parent->child; (p = *pp) != NULL; pp = &p->sibling) {
if (p->end < res->start)
continue;
if (res->end < p->start)
break;
if (p->start < res->start || p->end > res->end)
return -1; /* not completely contained */
if (firstpp == NULL)
firstpp = pp;
}
if (firstpp == NULL)
return -1; /* didn't find any conflicting entries? */
res->parent = parent;
res->child = *firstpp;
res->sibling = *pp;
*firstpp = res;
*pp = NULL;
for (p = res->child; p != NULL; p = p->sibling) {
p->parent = res;
pr_debug("PCI: Reparented %s [%llx..%llx] under %s\n",
p->name,
(unsigned long long)p->start,
(unsigned long long)p->end, res->name);
}
return 0;
}
/*
* Handle resources of PCI devices. If the world were perfect, we could
* just allocate all the resource regions and do nothing more. It isn't.
* On the other hand, we cannot just re-allocate all devices, as it would
* require us to know lots of host bridge internals. So we attempt to
* keep as much of the original configuration as possible, but tweak it
* when it's found to be wrong.
*
* Known BIOS problems we have to work around:
* - I/O or memory regions not configured
* - regions configured, but not enabled in the command register
* - bogus I/O addresses above 64K used
* - expansion ROMs left enabled (this may sound harmless, but given
* the fact the PCI specs explicitly allow address decoders to be
* shared between expansion ROMs and other resource regions, it's
* at least dangerous)
*
* Our solution:
* (1) Allocate resources for all buses behind PCI-to-PCI bridges.
* This gives us fixed barriers on where we can allocate.
* (2) Allocate resources for all enabled devices. If there is
* a collision, just mark the resource as unallocated. Also
* disable expansion ROMs during this step.
* (3) Try to allocate resources for disabled devices. If the
* resources were assigned correctly, everything goes well,
* if they weren't, they won't disturb allocation of other
* resources.
* (4) Assign new addresses to resources which were either
* not configured at all or misconfigured. If explicitly
* requested by the user, configure expansion ROM address
* as well.
*/
void pcibios_allocate_bus_resources(struct pci_bus *bus)
{
struct pci_bus *b;
int i;
struct resource *res, *pr;
pr_debug("PCI: Allocating bus resources for %04x:%02x...\n",
pci_domain_nr(bus), bus->number);
pci_bus_for_each_resource(bus, res, i) {
if (!res || !res->flags
|| res->start > res->end || res->parent)
continue;
if (bus->parent == NULL)
pr = (res->flags & IORESOURCE_IO) ?
&ioport_resource : &iomem_resource;
else {
/* Don't bother with non-root busses when
* re-assigning all resources. We clear the
* resource flags as if they were colliding
* and as such ensure proper re-allocation
* later.
*/
pr = pci_find_parent_resource(bus->self, res);
if (pr == res) {
/* this happens when the generic PCI
* code (wrongly) decides that this
* bridge is transparent -- paulus
*/
continue;
}
}
pr_debug("PCI: %s (bus %d) bridge rsrc %d: %016llx-%016llx "
"[0x%x], parent %p (%s)\n",
bus->self ? pci_name(bus->self) : "PHB",
bus->number, i,
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned int)res->flags,
pr, (pr && pr->name) ? pr->name : "nil");
if (pr && !(pr->flags & IORESOURCE_UNSET)) {
if (request_resource(pr, res) == 0)
continue;
/*
* Must be a conflict with an existing entry.
* Move that entry (or entries) under the
* bridge resource and try again.
*/
if (reparent_resources(pr, res) == 0)
continue;
}
printk(KERN_WARNING "PCI: Cannot allocate resource region "
"%d of PCI bridge %d, will remap\n", i, bus->number);
clear_resource:
res->start = res->end = 0;
res->flags = 0;
}
list_for_each_entry(b, &bus->children, node)
pcibios_allocate_bus_resources(b);
}
static inline void __devinit alloc_resource(struct pci_dev *dev, int idx)
{
struct resource *pr, *r = &dev->resource[idx];
pr_debug("PCI: Allocating %s: Resource %d: %016llx..%016llx [%x]\n",
pci_name(dev), idx,
(unsigned long long)r->start,
(unsigned long long)r->end,
(unsigned int)r->flags);
pr = pci_find_parent_resource(dev, r);
if (!pr || (pr->flags & IORESOURCE_UNSET) ||
request_resource(pr, r) < 0) {
printk(KERN_WARNING "PCI: Cannot allocate resource region %d"
" of device %s, will remap\n", idx, pci_name(dev));
if (pr)
pr_debug("PCI: parent is %p: %016llx-%016llx [%x]\n",
pr,
(unsigned long long)pr->start,
(unsigned long long)pr->end,
(unsigned int)pr->flags);
/* We'll assign a new address later */
r->flags |= IORESOURCE_UNSET;
r->end -= r->start;
r->start = 0;
}
}
static void __init pcibios_allocate_resources(int pass)
{
struct pci_dev *dev = NULL;
int idx, disabled;
u16 command;
struct resource *r;
for_each_pci_dev(dev) {
pci_read_config_word(dev, PCI_COMMAND, &command);
for (idx = 0; idx <= PCI_ROM_RESOURCE; idx++) {
r = &dev->resource[idx];
if (r->parent) /* Already allocated */
continue;
if (!r->flags || (r->flags & IORESOURCE_UNSET))
continue; /* Not assigned at all */
/* We only allocate ROMs on pass 1 just in case they
* have been screwed up by firmware
*/
if (idx == PCI_ROM_RESOURCE)
disabled = 1;
if (r->flags & IORESOURCE_IO)
disabled = !(command & PCI_COMMAND_IO);
else
disabled = !(command & PCI_COMMAND_MEMORY);
if (pass == disabled)
alloc_resource(dev, idx);
}
if (pass)
continue;
r = &dev->resource[PCI_ROM_RESOURCE];
if (r->flags) {
/* Turn the ROM off, leave the resource region,
* but keep it unregistered.
*/
u32 reg;
pci_read_config_dword(dev, dev->rom_base_reg, ®);
if (reg & PCI_ROM_ADDRESS_ENABLE) {
pr_debug("PCI: Switching off ROM of %s\n",
pci_name(dev));
r->flags &= ~IORESOURCE_ROM_ENABLE;
pci_write_config_dword(dev, dev->rom_base_reg,
reg & ~PCI_ROM_ADDRESS_ENABLE);
}
}
}
}
static void __init pcibios_reserve_legacy_regions(struct pci_bus *bus)
{
struct pci_controller *hose = pci_bus_to_host(bus);
resource_size_t offset;
struct resource *res, *pres;
int i;
pr_debug("Reserving legacy ranges for domain %04x\n",
pci_domain_nr(bus));
/* Check for IO */
if (!(hose->io_resource.flags & IORESOURCE_IO))
goto no_io;
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
res = kzalloc(sizeof(struct resource), GFP_KERNEL);
BUG_ON(res == NULL);
res->name = "Legacy IO";
res->flags = IORESOURCE_IO;
res->start = offset;
res->end = (offset + 0xfff) & 0xfffffffful;
pr_debug("Candidate legacy IO: %pR\n", res);
if (request_resource(&hose->io_resource, res)) {
printk(KERN_DEBUG
"PCI %04x:%02x Cannot reserve Legacy IO %pR\n",
pci_domain_nr(bus), bus->number, res);
kfree(res);
}
no_io:
/* Check for memory */
offset = hose->pci_mem_offset;
pr_debug("hose mem offset: %016llx\n", (unsigned long long)offset);
for (i = 0; i < 3; i++) {
pres = &hose->mem_resources[i];
if (!(pres->flags & IORESOURCE_MEM))
continue;
pr_debug("hose mem res: %pR\n", pres);
if ((pres->start - offset) <= 0xa0000 &&
(pres->end - offset) >= 0xbffff)
break;
}
if (i >= 3)
return;
res = kzalloc(sizeof(struct resource), GFP_KERNEL);
BUG_ON(res == NULL);
res->name = "Legacy VGA memory";
res->flags = IORESOURCE_MEM;
res->start = 0xa0000 + offset;
res->end = 0xbffff + offset;
pr_debug("Candidate VGA memory: %pR\n", res);
if (request_resource(pres, res)) {
printk(KERN_DEBUG
"PCI %04x:%02x Cannot reserve VGA memory %pR\n",
pci_domain_nr(bus), bus->number, res);
kfree(res);
}
}
void __init pcibios_resource_survey(void)
{
struct pci_bus *b;
/* Allocate and assign resources. If we re-assign everything, then
* we skip the allocate phase
*/
list_for_each_entry(b, &pci_root_buses, node)
pcibios_allocate_bus_resources(b);
pcibios_allocate_resources(0);
pcibios_allocate_resources(1);
/* Before we start assigning unassigned resource, we try to reserve
* the low IO area and the VGA memory area if they intersect the
* bus available resources to avoid allocating things on top of them
*/
list_for_each_entry(b, &pci_root_buses, node)
pcibios_reserve_legacy_regions(b);
/* Now proceed to assigning things that were left unassigned */
pr_debug("PCI: Assigning unassigned resources...\n");
pci_assign_unassigned_resources();
}
#ifdef CONFIG_HOTPLUG
/* This is used by the PCI hotplug driver to allocate resource
* of newly plugged busses. We can try to consolidate with the
* rest of the code later, for now, keep it as-is as our main
* resource allocation function doesn't deal with sub-trees yet.
*/
void __devinit pcibios_claim_one_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
struct pci_bus *child_bus;
list_for_each_entry(dev, &bus->devices, bus_list) {
int i;
for (i = 0; i < PCI_NUM_RESOURCES; i++) {
struct resource *r = &dev->resource[i];
if (r->parent || !r->start || !r->flags)
continue;
pr_debug("PCI: Claiming %s: "
"Resource %d: %016llx..%016llx [%x]\n",
pci_name(dev), i,
(unsigned long long)r->start,
(unsigned long long)r->end,
(unsigned int)r->flags);
pci_claim_resource(dev, i);
}
}
list_for_each_entry(child_bus, &bus->children, node)
pcibios_claim_one_bus(child_bus);
}
EXPORT_SYMBOL_GPL(pcibios_claim_one_bus);
/* pcibios_finish_adding_to_bus
*
* This is to be called by the hotplug code after devices have been
* added to a bus, this include calling it for a PHB that is just
* being added
*/
void pcibios_finish_adding_to_bus(struct pci_bus *bus)
{
pr_debug("PCI: Finishing adding to hotplug bus %04x:%02x\n",
pci_domain_nr(bus), bus->number);
/* Allocate bus and devices resources */
pcibios_allocate_bus_resources(bus);
pcibios_claim_one_bus(bus);
/* Add new devices to global lists. Register in proc, sysfs. */
pci_bus_add_devices(bus);
/* Fixup EEH */
/* eeh_add_device_tree_late(bus); */
}
EXPORT_SYMBOL_GPL(pcibios_finish_adding_to_bus);
#endif /* CONFIG_HOTPLUG */
int pcibios_enable_device(struct pci_dev *dev, int mask)
{
return pci_enable_resources(dev, mask);
}
static void __devinit pcibios_setup_phb_resources(struct pci_controller *hose, struct list_head *resources)
{
struct resource *res;
int i;
/* Hookup PHB IO resource */
res = &hose->io_resource;
/* Fixup IO space offset */
io_offset = (unsigned long)hose->io_base_virt - isa_io_base;
res->start = (res->start + io_offset) & 0xffffffffu;
res->end = (res->end + io_offset) & 0xffffffffu;
if (!res->flags) {
printk(KERN_WARNING "PCI: I/O resource not set for host"
" bridge %s (domain %d)\n",
hose->dn->full_name, hose->global_number);
/* Workaround for lack of IO resource only on 32-bit */
res->start = (unsigned long)hose->io_base_virt - isa_io_base;
res->end = res->start + IO_SPACE_LIMIT;
res->flags = IORESOURCE_IO;
}
pci_add_resource_offset(resources, res, hose->io_base_virt - _IO_BASE);
pr_debug("PCI: PHB IO resource = %016llx-%016llx [%lx]\n",
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned long)res->flags);
/* Hookup PHB Memory resources */
for (i = 0; i < 3; ++i) {
res = &hose->mem_resources[i];
if (!res->flags) {
if (i > 0)
continue;
printk(KERN_ERR "PCI: Memory resource 0 not set for "
"host bridge %s (domain %d)\n",
hose->dn->full_name, hose->global_number);
/* Workaround for lack of MEM resource only on 32-bit */
res->start = hose->pci_mem_offset;
res->end = (resource_size_t)-1LL;
res->flags = IORESOURCE_MEM;
}
pci_add_resource_offset(resources, res, hose->pci_mem_offset);
pr_debug("PCI: PHB MEM resource %d = %016llx-%016llx [%lx]\n",
i, (unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned long)res->flags);
}
pr_debug("PCI: PHB MEM offset = %016llx\n",
(unsigned long long)hose->pci_mem_offset);
pr_debug("PCI: PHB IO offset = %08lx\n",
(unsigned long)hose->io_base_virt - _IO_BASE);
}
struct device_node *pcibios_get_phb_of_node(struct pci_bus *bus)
{
struct pci_controller *hose = bus->sysdata;
return of_node_get(hose->dn);
}
static void __devinit pcibios_scan_phb(struct pci_controller *hose)
{
LIST_HEAD(resources);
struct pci_bus *bus;
struct device_node *node = hose->dn;
pr_debug("PCI: Scanning PHB %s\n",
node ? node->full_name : "<NO NAME>");
pcibios_setup_phb_resources(hose, &resources);
bus = pci_scan_root_bus(hose->parent, hose->first_busno,
hose->ops, hose, &resources);
if (bus == NULL) {
printk(KERN_ERR "Failed to create bus for PCI domain %04x\n",
hose->global_number);
pci_free_resource_list(&resources);
return;
}
bus->secondary = hose->first_busno;
hose->bus = bus;
hose->last_busno = bus->subordinate;
}
static int __init pcibios_init(void)
{
struct pci_controller *hose, *tmp;
int next_busno = 0;
printk(KERN_INFO "PCI: Probing PCI hardware\n");
/* Scan all of the recorded PCI controllers. */
list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
hose->last_busno = 0xff;
pcibios_scan_phb(hose);
if (next_busno <= hose->last_busno)
next_busno = hose->last_busno + 1;
}
pci_bus_count = next_busno;
/* Call common code to handle resource allocation */
pcibios_resource_survey();
return 0;
}
subsys_initcall(pcibios_init);
static struct pci_controller *pci_bus_to_hose(int bus)
{
struct pci_controller *hose, *tmp;
list_for_each_entry_safe(hose, tmp, &hose_list, list_node)
if (bus >= hose->first_busno && bus <= hose->last_busno)
return hose;
return NULL;
}
/* Provide information on locations of various I/O regions in physical
* memory. Do this on a per-card basis so that we choose the right
* root bridge.
* Note that the returned IO or memory base is a physical address
*/
long sys_pciconfig_iobase(long which, unsigned long bus, unsigned long devfn)
{
struct pci_controller *hose;
long result = -EOPNOTSUPP;
hose = pci_bus_to_hose(bus);
if (!hose)
return -ENODEV;
switch (which) {
case IOBASE_BRIDGE_NUMBER:
return (long)hose->first_busno;
case IOBASE_MEMORY:
return (long)hose->pci_mem_offset;
case IOBASE_IO:
return (long)hose->io_base_phys;
case IOBASE_ISA_IO:
return (long)isa_io_base;
case IOBASE_ISA_MEM:
return (long)isa_mem_base;
}
return result;
}
/*
* Null PCI config access functions, for the case when we can't
* find a hose.
*/
#define NULL_PCI_OP(rw, size, type) \
static int \
null_##rw##_config_##size(struct pci_dev *dev, int offset, type val) \
{ \
return PCIBIOS_DEVICE_NOT_FOUND; \
}
static int
null_read_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 *val)
{
return PCIBIOS_DEVICE_NOT_FOUND;
}
static int
null_write_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 val)
{
return PCIBIOS_DEVICE_NOT_FOUND;
}
static struct pci_ops null_pci_ops = {
.read = null_read_config,
.write = null_write_config,
};
/*
* These functions are used early on before PCI scanning is done
* and all of the pci_dev and pci_bus structures have been created.
*/
static struct pci_bus *
fake_pci_bus(struct pci_controller *hose, int busnr)
{
static struct pci_bus bus;
if (!hose)
printk(KERN_ERR "Can't find hose for PCI bus %d!\n", busnr);
bus.number = busnr;
bus.sysdata = hose;
bus.ops = hose ? hose->ops : &null_pci_ops;
return &bus;
}
#define EARLY_PCI_OP(rw, size, type) \
int early_##rw##_config_##size(struct pci_controller *hose, int bus, \
int devfn, int offset, type value) \
{ \
return pci_bus_##rw##_config_##size(fake_pci_bus(hose, bus), \
devfn, offset, value); \
}
EARLY_PCI_OP(read, byte, u8 *)
EARLY_PCI_OP(read, word, u16 *)
EARLY_PCI_OP(read, dword, u32 *)
EARLY_PCI_OP(write, byte, u8)
EARLY_PCI_OP(write, word, u16)
EARLY_PCI_OP(write, dword, u32)
int early_find_capability(struct pci_controller *hose, int bus, int devfn,
int cap)
{
return pci_bus_find_capability(fake_pci_bus(hose, bus), devfn, cap);
}
| gpl-2.0 |
AntaresOne/AntaresCore-Kernel-h815 | drivers/isdn/hisax/elsa_cs.c | 4651 | 5929 | /*======================================================================
An elsa_cs PCMCIA client driver
This driver is for the Elsa PCM ISDN Cards, i.e. the MicroLink
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Modifications from dummy_cs.c are Copyright (C) 1999-2001 Klaus
Lichtenwalder <Lichtenwalder@ACM.org>. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in
which case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/ioport.h>
#include <asm/io.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#include "hisax_cfg.h"
MODULE_DESCRIPTION("ISDN4Linux: PCMCIA client driver for Elsa PCM cards");
MODULE_AUTHOR("Klaus Lichtenwalder");
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
static int protocol = 2; /* EURO-ISDN Default */
module_param(protocol, int, 0);
static int elsa_cs_config(struct pcmcia_device *link);
static void elsa_cs_release(struct pcmcia_device *link);
static void elsa_cs_detach(struct pcmcia_device *p_dev);
typedef struct local_info_t {
struct pcmcia_device *p_dev;
int busy;
int cardnr;
} local_info_t;
static int elsa_cs_probe(struct pcmcia_device *link)
{
local_info_t *local;
dev_dbg(&link->dev, "elsa_cs_attach()\n");
/* Allocate space for private device-specific data */
local = kzalloc(sizeof(local_info_t), GFP_KERNEL);
if (!local) return -ENOMEM;
local->p_dev = link;
link->priv = local;
local->cardnr = -1;
return elsa_cs_config(link);
} /* elsa_cs_attach */
static void elsa_cs_detach(struct pcmcia_device *link)
{
local_info_t *info = link->priv;
dev_dbg(&link->dev, "elsa_cs_detach(0x%p)\n", link);
info->busy = 1;
elsa_cs_release(link);
kfree(info);
} /* elsa_cs_detach */
static int elsa_cs_configcheck(struct pcmcia_device *p_dev, void *priv_data)
{
int j;
p_dev->io_lines = 3;
p_dev->resource[0]->end = 8;
p_dev->resource[0]->flags &= IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
if ((p_dev->resource[0]->end) && p_dev->resource[0]->start) {
printk(KERN_INFO "(elsa_cs: looks like the 96 model)\n");
if (!pcmcia_request_io(p_dev))
return 0;
} else {
printk(KERN_INFO "(elsa_cs: looks like the 97 model)\n");
for (j = 0x2f0; j > 0x100; j -= 0x10) {
p_dev->resource[0]->start = j;
if (!pcmcia_request_io(p_dev))
return 0;
}
}
return -ENODEV;
}
static int elsa_cs_config(struct pcmcia_device *link)
{
int i;
IsdnCard_t icard;
dev_dbg(&link->dev, "elsa_config(0x%p)\n", link);
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
i = pcmcia_loop_config(link, elsa_cs_configcheck, NULL);
if (i != 0)
goto failed;
if (!link->irq)
goto failed;
i = pcmcia_enable_device(link);
if (i != 0)
goto failed;
icard.para[0] = link->irq;
icard.para[1] = link->resource[0]->start;
icard.protocol = protocol;
icard.typ = ISDN_CTYPE_ELSA_PCMCIA;
i = hisax_init_pcmcia(link, &(((local_info_t *)link->priv)->busy), &icard);
if (i < 0) {
printk(KERN_ERR "elsa_cs: failed to initialize Elsa "
"PCMCIA %d with %pR\n", i, link->resource[0]);
elsa_cs_release(link);
} else
((local_info_t *)link->priv)->cardnr = i;
return 0;
failed:
elsa_cs_release(link);
return -ENODEV;
} /* elsa_cs_config */
static void elsa_cs_release(struct pcmcia_device *link)
{
local_info_t *local = link->priv;
dev_dbg(&link->dev, "elsa_cs_release(0x%p)\n", link);
if (local) {
if (local->cardnr >= 0) {
/* no unregister function with hisax */
HiSax_closecard(local->cardnr);
}
}
pcmcia_disable_device(link);
} /* elsa_cs_release */
static int elsa_suspend(struct pcmcia_device *link)
{
local_info_t *dev = link->priv;
dev->busy = 1;
return 0;
}
static int elsa_resume(struct pcmcia_device *link)
{
local_info_t *dev = link->priv;
dev->busy = 0;
return 0;
}
static const struct pcmcia_device_id elsa_ids[] = {
PCMCIA_DEVICE_PROD_ID12("ELSA AG (Aachen, Germany)", "MicroLink ISDN/MC ", 0x983de2c4, 0x333ba257),
PCMCIA_DEVICE_PROD_ID12("ELSA GmbH, Aachen", "MicroLink ISDN/MC ", 0x639e5718, 0x333ba257),
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, elsa_ids);
static struct pcmcia_driver elsa_cs_driver = {
.owner = THIS_MODULE,
.name = "elsa_cs",
.probe = elsa_cs_probe,
.remove = elsa_cs_detach,
.id_table = elsa_ids,
.suspend = elsa_suspend,
.resume = elsa_resume,
};
module_pcmcia_driver(elsa_cs_driver);
| gpl-2.0 |
uberlaggydarwin/306shcaf | arch/mips/lantiq/xway/devices.c | 4651 | 2864 | /*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Copyright (C) 2010 John Crispin <blogic@openwrt.org>
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/mtd/physmap.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/etherdevice.h>
#include <linux/time.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <asm/bootinfo.h>
#include <asm/irq.h>
#include <lantiq_soc.h>
#include <lantiq_irq.h>
#include <lantiq_platform.h>
#include "devices.h"
/* gpio */
static struct resource ltq_gpio_resource[] = {
{
.name = "gpio0",
.start = LTQ_GPIO0_BASE_ADDR,
.end = LTQ_GPIO0_BASE_ADDR + LTQ_GPIO_SIZE - 1,
.flags = IORESOURCE_MEM,
}, {
.name = "gpio1",
.start = LTQ_GPIO1_BASE_ADDR,
.end = LTQ_GPIO1_BASE_ADDR + LTQ_GPIO_SIZE - 1,
.flags = IORESOURCE_MEM,
}, {
.name = "gpio2",
.start = LTQ_GPIO2_BASE_ADDR,
.end = LTQ_GPIO2_BASE_ADDR + LTQ_GPIO_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
void __init ltq_register_gpio(void)
{
platform_device_register_simple("ltq_gpio", 0,
<q_gpio_resource[0], 1);
platform_device_register_simple("ltq_gpio", 1,
<q_gpio_resource[1], 1);
/* AR9 and VR9 have an extra gpio block */
if (ltq_is_ar9() || ltq_is_vr9()) {
platform_device_register_simple("ltq_gpio", 2,
<q_gpio_resource[2], 1);
}
}
/* serial to parallel conversion */
static struct resource ltq_stp_resource = {
.name = "stp",
.start = LTQ_STP_BASE_ADDR,
.end = LTQ_STP_BASE_ADDR + LTQ_STP_SIZE - 1,
.flags = IORESOURCE_MEM,
};
void __init ltq_register_gpio_stp(void)
{
platform_device_register_simple("ltq_stp", 0, <q_stp_resource, 1);
}
/* asc ports - amazon se has its own serial mapping */
static struct resource ltq_ase_asc_resources[] = {
{
.name = "asc0",
.start = LTQ_ASC1_BASE_ADDR,
.end = LTQ_ASC1_BASE_ADDR + LTQ_ASC_SIZE - 1,
.flags = IORESOURCE_MEM,
},
IRQ_RES(tx, LTQ_ASC_ASE_TIR),
IRQ_RES(rx, LTQ_ASC_ASE_RIR),
IRQ_RES(err, LTQ_ASC_ASE_EIR),
};
void __init ltq_register_ase_asc(void)
{
platform_device_register_simple("ltq_asc", 0,
ltq_ase_asc_resources, ARRAY_SIZE(ltq_ase_asc_resources));
}
/* ethernet */
static struct resource ltq_etop_resources = {
.name = "etop",
.start = LTQ_ETOP_BASE_ADDR,
.end = LTQ_ETOP_BASE_ADDR + LTQ_ETOP_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device ltq_etop = {
.name = "ltq_etop",
.resource = <q_etop_resources,
.num_resources = 1,
};
void __init
ltq_register_etop(struct ltq_eth_data *eth)
{
if (eth) {
ltq_etop.dev.platform_data = eth;
platform_device_register(<q_etop);
}
}
| gpl-2.0 |
houzhenggang/linux-rlx-upstream | arch/arm/mach-shmobile/intc-sh7377.c | 4907 | 21533 | /*
* sh7377 processor support - INTC hardware block
*
* Copyright (C) 2010 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/sh_intc.h>
#include <mach/intc.h>
#include <mach/irqs.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
enum {
UNUSED_INTCA = 0,
ENABLED,
DISABLED,
/* interrupt sources INTCA */
DIRC,
_2DG,
CRYPT_STD,
IIC1_ALI1, IIC1_TACKI1, IIC1_WAITI1, IIC1_DTEI1,
AP_ARM_IRQPMU, AP_ARM_COMMTX, AP_ARM_COMMRX,
MFI_MFIM, MFI_MFIS,
BBIF1, BBIF2,
USBDMAC_USHDMI,
USBHS_USHI0, USBHS_USHI1,
_3DG_SGX540,
CMT1_CMT10, CMT1_CMT11, CMT1_CMT12, CMT1_CMT13, CMT2, CMT3,
KEYSC_KEY,
SCIFA0, SCIFA1, SCIFA2, SCIFA3,
MSIOF2, MSIOF1,
SCIFA4, SCIFA5, SCIFB,
FLCTL_FLSTEI, FLCTL_FLTENDI, FLCTL_FLTREQ0I, FLCTL_FLTREQ1I,
SDHI0,
SDHI1,
MSU_MSU, MSU_MSU2,
IRREM,
MSUG,
IRDA,
TPU0, TPU1, TPU2, TPU3, TPU4,
LCRC,
PINTCA_PINT1, PINTCA_PINT2,
TTI20,
MISTY,
DDM,
RWDT0, RWDT1,
DMAC_1_DEI0, DMAC_1_DEI1, DMAC_1_DEI2, DMAC_1_DEI3,
DMAC_2_DEI4, DMAC_2_DEI5, DMAC_2_DADERR,
DMAC2_1_DEI0, DMAC2_1_DEI1, DMAC2_1_DEI2, DMAC2_1_DEI3,
DMAC2_2_DEI4, DMAC2_2_DEI5, DMAC2_2_DADERR,
DMAC3_1_DEI0, DMAC3_1_DEI1, DMAC3_1_DEI2, DMAC3_1_DEI3,
DMAC3_2_DEI4, DMAC3_2_DEI5, DMAC3_2_DADERR,
SHWYSTAT_RT, SHWYSTAT_HS, SHWYSTAT_COM,
ICUSB_ICUSB0, ICUSB_ICUSB1,
ICUDMC_ICUDMC1, ICUDMC_ICUDMC2,
SPU2_SPU0, SPU2_SPU1,
FSI,
FMSI,
SCUV,
IPMMU_IPMMUB,
AP_ARM_CTIIRQ, AP_ARM_DMAEXTERRIRQ, AP_ARM_DMAIRQ, AP_ARM_DMASIRQ,
MFIS2,
CPORTR2S,
CMT14, CMT15,
SCIFA6,
/* interrupt groups INTCA */
DMAC_1, DMAC_2, DMAC2_1, DMAC2_2, DMAC3_1, DMAC3_2, SHWYSTAT,
AP_ARM1, AP_ARM2, USBHS, SPU2, FLCTL, IIC1,
ICUSB, ICUDMC
};
static struct intc_vect intca_vectors[] __initdata = {
INTC_VECT(DIRC, 0x0560),
INTC_VECT(_2DG, 0x05e0),
INTC_VECT(CRYPT_STD, 0x0700),
INTC_VECT(IIC1_ALI1, 0x0780), INTC_VECT(IIC1_TACKI1, 0x07a0),
INTC_VECT(IIC1_WAITI1, 0x07c0), INTC_VECT(IIC1_DTEI1, 0x07e0),
INTC_VECT(AP_ARM_IRQPMU, 0x0800), INTC_VECT(AP_ARM_COMMTX, 0x0840),
INTC_VECT(AP_ARM_COMMRX, 0x0860),
INTC_VECT(MFI_MFIM, 0x0900), INTC_VECT(MFI_MFIS, 0x0920),
INTC_VECT(BBIF1, 0x0940), INTC_VECT(BBIF2, 0x0960),
INTC_VECT(USBDMAC_USHDMI, 0x0a00),
INTC_VECT(USBHS_USHI0, 0x0a20), INTC_VECT(USBHS_USHI1, 0x0a40),
INTC_VECT(_3DG_SGX540, 0x0a60),
INTC_VECT(CMT1_CMT10, 0x0b00), INTC_VECT(CMT1_CMT11, 0x0b20),
INTC_VECT(CMT1_CMT12, 0x0b40), INTC_VECT(CMT1_CMT13, 0x0b60),
INTC_VECT(CMT2, 0x0b80), INTC_VECT(CMT3, 0x0ba0),
INTC_VECT(KEYSC_KEY, 0x0be0),
INTC_VECT(SCIFA0, 0x0c00), INTC_VECT(SCIFA1, 0x0c20),
INTC_VECT(SCIFA2, 0x0c40), INTC_VECT(SCIFA3, 0x0c60),
INTC_VECT(MSIOF2, 0x0c80), INTC_VECT(MSIOF1, 0x0d00),
INTC_VECT(SCIFA4, 0x0d20), INTC_VECT(SCIFA5, 0x0d40),
INTC_VECT(SCIFB, 0x0d60),
INTC_VECT(FLCTL_FLSTEI, 0x0d80), INTC_VECT(FLCTL_FLTENDI, 0x0da0),
INTC_VECT(FLCTL_FLTREQ0I, 0x0dc0), INTC_VECT(FLCTL_FLTREQ1I, 0x0de0),
INTC_VECT(SDHI0, 0x0e00), INTC_VECT(SDHI0, 0x0e20),
INTC_VECT(SDHI0, 0x0e40), INTC_VECT(SDHI0, 0x0e60),
INTC_VECT(SDHI1, 0x0e80), INTC_VECT(SDHI1, 0x0ea0),
INTC_VECT(SDHI1, 0x0ec0), INTC_VECT(SDHI1, 0x0ee0),
INTC_VECT(MSU_MSU, 0x0f20), INTC_VECT(MSU_MSU2, 0x0f40),
INTC_VECT(IRREM, 0x0f60),
INTC_VECT(MSUG, 0x0fa0),
INTC_VECT(IRDA, 0x0480),
INTC_VECT(TPU0, 0x04a0), INTC_VECT(TPU1, 0x04c0),
INTC_VECT(TPU2, 0x04e0), INTC_VECT(TPU3, 0x0500),
INTC_VECT(TPU4, 0x0520),
INTC_VECT(LCRC, 0x0540),
INTC_VECT(PINTCA_PINT1, 0x1000), INTC_VECT(PINTCA_PINT2, 0x1020),
INTC_VECT(TTI20, 0x1100),
INTC_VECT(MISTY, 0x1120),
INTC_VECT(DDM, 0x1140),
INTC_VECT(RWDT0, 0x1280), INTC_VECT(RWDT1, 0x12a0),
INTC_VECT(DMAC_1_DEI0, 0x2000), INTC_VECT(DMAC_1_DEI1, 0x2020),
INTC_VECT(DMAC_1_DEI2, 0x2040), INTC_VECT(DMAC_1_DEI3, 0x2060),
INTC_VECT(DMAC_2_DEI4, 0x2080), INTC_VECT(DMAC_2_DEI5, 0x20a0),
INTC_VECT(DMAC_2_DADERR, 0x20c0),
INTC_VECT(DMAC2_1_DEI0, 0x2100), INTC_VECT(DMAC2_1_DEI1, 0x2120),
INTC_VECT(DMAC2_1_DEI2, 0x2140), INTC_VECT(DMAC2_1_DEI3, 0x2160),
INTC_VECT(DMAC2_2_DEI4, 0x2180), INTC_VECT(DMAC2_2_DEI5, 0x21a0),
INTC_VECT(DMAC2_2_DADERR, 0x21c0),
INTC_VECT(DMAC3_1_DEI0, 0x2200), INTC_VECT(DMAC3_1_DEI1, 0x2220),
INTC_VECT(DMAC3_1_DEI2, 0x2240), INTC_VECT(DMAC3_1_DEI3, 0x2260),
INTC_VECT(DMAC3_2_DEI4, 0x2280), INTC_VECT(DMAC3_2_DEI5, 0x22a0),
INTC_VECT(DMAC3_2_DADERR, 0x22c0),
INTC_VECT(SHWYSTAT_RT, 0x1300), INTC_VECT(SHWYSTAT_HS, 0x1d20),
INTC_VECT(SHWYSTAT_COM, 0x1340),
INTC_VECT(ICUSB_ICUSB0, 0x1700), INTC_VECT(ICUSB_ICUSB1, 0x1720),
INTC_VECT(ICUDMC_ICUDMC1, 0x1780), INTC_VECT(ICUDMC_ICUDMC2, 0x17a0),
INTC_VECT(SPU2_SPU0, 0x1800), INTC_VECT(SPU2_SPU1, 0x1820),
INTC_VECT(FSI, 0x1840),
INTC_VECT(FMSI, 0x1860),
INTC_VECT(SCUV, 0x1880),
INTC_VECT(IPMMU_IPMMUB, 0x1900),
INTC_VECT(AP_ARM_CTIIRQ, 0x1980),
INTC_VECT(AP_ARM_DMAEXTERRIRQ, 0x19a0),
INTC_VECT(AP_ARM_DMAIRQ, 0x19c0),
INTC_VECT(AP_ARM_DMASIRQ, 0x19e0),
INTC_VECT(MFIS2, 0x1a00),
INTC_VECT(CPORTR2S, 0x1a20),
INTC_VECT(CMT14, 0x1a40), INTC_VECT(CMT15, 0x1a60),
INTC_VECT(SCIFA6, 0x1a80),
};
static struct intc_group intca_groups[] __initdata = {
INTC_GROUP(DMAC_1, DMAC_1_DEI0,
DMAC_1_DEI1, DMAC_1_DEI2, DMAC_1_DEI3),
INTC_GROUP(DMAC_2, DMAC_2_DEI4,
DMAC_2_DEI5, DMAC_2_DADERR),
INTC_GROUP(DMAC2_1, DMAC2_1_DEI0,
DMAC2_1_DEI1, DMAC2_1_DEI2, DMAC2_1_DEI3),
INTC_GROUP(DMAC2_2, DMAC2_2_DEI4,
DMAC2_2_DEI5, DMAC2_2_DADERR),
INTC_GROUP(DMAC3_1, DMAC3_1_DEI0,
DMAC3_1_DEI1, DMAC3_1_DEI2, DMAC3_1_DEI3),
INTC_GROUP(DMAC3_2, DMAC3_2_DEI4,
DMAC3_2_DEI5, DMAC3_2_DADERR),
INTC_GROUP(AP_ARM1, AP_ARM_IRQPMU, AP_ARM_COMMTX, AP_ARM_COMMTX),
INTC_GROUP(USBHS, USBHS_USHI0, USBHS_USHI1),
INTC_GROUP(SPU2, SPU2_SPU0, SPU2_SPU1),
INTC_GROUP(FLCTL, FLCTL_FLSTEI, FLCTL_FLTENDI,
FLCTL_FLTREQ0I, FLCTL_FLTREQ1I),
INTC_GROUP(IIC1, IIC1_ALI1, IIC1_TACKI1, IIC1_WAITI1, IIC1_DTEI1),
INTC_GROUP(SHWYSTAT, SHWYSTAT_RT, SHWYSTAT_HS, SHWYSTAT_COM),
INTC_GROUP(ICUSB, ICUSB_ICUSB0, ICUSB_ICUSB1),
INTC_GROUP(ICUDMC, ICUDMC_ICUDMC1, ICUDMC_ICUDMC2),
};
static struct intc_mask_reg intca_mask_registers[] __initdata = {
{ 0xe6940080, 0xe69400c0, 8, /* IMR0A / IMCR0A */
{ DMAC2_1_DEI3, DMAC2_1_DEI2, DMAC2_1_DEI1, DMAC2_1_DEI0,
AP_ARM_IRQPMU, 0, AP_ARM_COMMTX, AP_ARM_COMMRX } },
{ 0xe6940084, 0xe69400c4, 8, /* IMR1A / IMCR1A */
{ _2DG, CRYPT_STD, DIRC, 0,
DMAC_1_DEI3, DMAC_1_DEI2, DMAC_1_DEI1, DMAC_1_DEI0 } },
{ 0xe6940088, 0xe69400c8, 8, /* IMR2A / IMCR2A */
{ PINTCA_PINT1, PINTCA_PINT2, 0, 0,
BBIF1, BBIF2, MFI_MFIS, MFI_MFIM } },
{ 0xe694008c, 0xe69400cc, 8, /* IMR3A / IMCR3A */
{ DMAC3_1_DEI3, DMAC3_1_DEI2, DMAC3_1_DEI1, DMAC3_1_DEI0,
DMAC3_2_DADERR, DMAC3_2_DEI5, DMAC3_2_DEI4, IRDA } },
{ 0xe6940090, 0xe69400d0, 8, /* IMR4A / IMCR4A */
{ DDM, 0, 0, 0,
0, 0, 0, 0 } },
{ 0xe6940094, 0xe69400d4, 8, /* IMR5A / IMCR5A */
{ KEYSC_KEY, DMAC_2_DADERR, DMAC_2_DEI5, DMAC_2_DEI4,
SCIFA3, SCIFA2, SCIFA1, SCIFA0 } },
{ 0xe6940098, 0xe69400d8, 8, /* IMR6A / IMCR6A */
{ SCIFB, SCIFA5, SCIFA4, MSIOF1,
0, 0, MSIOF2, 0 } },
{ 0xe694009c, 0xe69400dc, 8, /* IMR7A / IMCR7A */
{ DISABLED, ENABLED, ENABLED, ENABLED,
FLCTL_FLTREQ1I, FLCTL_FLTREQ0I, FLCTL_FLTENDI, FLCTL_FLSTEI } },
{ 0xe69400a0, 0xe69400e0, 8, /* IMR8A / IMCR8A */
{ DISABLED, ENABLED, ENABLED, ENABLED,
TTI20, USBDMAC_USHDMI, 0, MSUG } },
{ 0xe69400a4, 0xe69400e4, 8, /* IMR9A / IMCR9A */
{ CMT1_CMT13, CMT1_CMT12, CMT1_CMT11, CMT1_CMT10,
CMT2, USBHS_USHI1, USBHS_USHI0, _3DG_SGX540 } },
{ 0xe69400a8, 0xe69400e8, 8, /* IMR10A / IMCR10A */
{ 0, DMAC2_2_DADERR, DMAC2_2_DEI5, DMAC2_2_DEI4,
0, 0, 0, 0 } },
{ 0xe69400ac, 0xe69400ec, 8, /* IMR11A / IMCR11A */
{ IIC1_DTEI1, IIC1_WAITI1, IIC1_TACKI1, IIC1_ALI1,
LCRC, MSU_MSU2, IRREM, MSU_MSU } },
{ 0xe69400b0, 0xe69400f0, 8, /* IMR12A / IMCR12A */
{ 0, 0, TPU0, TPU1,
TPU2, TPU3, TPU4, 0 } },
{ 0xe69400b4, 0xe69400f4, 8, /* IMR13A / IMCR13A */
{ 0, 0, 0, 0,
MISTY, CMT3, RWDT1, RWDT0 } },
{ 0xe6950080, 0xe69500c0, 8, /* IMR0A3 / IMCR0A3 */
{ SHWYSTAT_RT, SHWYSTAT_HS, SHWYSTAT_COM, 0,
0, 0, 0, 0 } },
{ 0xe6950090, 0xe69500d0, 8, /* IMR4A3 / IMCR4A3 */
{ ICUSB_ICUSB0, ICUSB_ICUSB1, 0, 0,
ICUDMC_ICUDMC1, ICUDMC_ICUDMC2, 0, 0 } },
{ 0xe6950094, 0xe69500d4, 8, /* IMR5A3 / IMCR5A3 */
{ SPU2_SPU0, SPU2_SPU1, FSI, FMSI,
SCUV, 0, 0, 0 } },
{ 0xe6950098, 0xe69500d8, 8, /* IMR6A3 / IMCR6A3 */
{ IPMMU_IPMMUB, 0, 0, 0,
AP_ARM_CTIIRQ, AP_ARM_DMAEXTERRIRQ,
AP_ARM_DMAIRQ, AP_ARM_DMASIRQ } },
{ 0xe695009c, 0xe69500dc, 8, /* IMR7A3 / IMCR7A3 */
{ MFIS2, CPORTR2S, CMT14, CMT15,
SCIFA6, 0, 0, 0 } },
};
static struct intc_prio_reg intca_prio_registers[] __initdata = {
{ 0xe6940000, 0, 16, 4, /* IPRAA */ { DMAC3_1, DMAC3_2, CMT2, LCRC } },
{ 0xe6940004, 0, 16, 4, /* IPRBA */ { IRDA, 0, BBIF1, BBIF2 } },
{ 0xe6940008, 0, 16, 4, /* IPRCA */ { _2DG, CRYPT_STD,
CMT1_CMT11, AP_ARM1 } },
{ 0xe694000c, 0, 16, 4, /* IPRDA */ { PINTCA_PINT1, PINTCA_PINT2,
CMT1_CMT12, TPU4 } },
{ 0xe6940010, 0, 16, 4, /* IPREA */ { DMAC_1, MFI_MFIS,
MFI_MFIM, USBHS } },
{ 0xe6940014, 0, 16, 4, /* IPRFA */ { KEYSC_KEY, DMAC_2,
_3DG_SGX540, CMT1_CMT10 } },
{ 0xe6940018, 0, 16, 4, /* IPRGA */ { SCIFA0, SCIFA1,
SCIFA2, SCIFA3 } },
{ 0xe694001c, 0, 16, 4, /* IPRGH */ { MSIOF2, USBDMAC_USHDMI,
FLCTL, SDHI0 } },
{ 0xe6940020, 0, 16, 4, /* IPRIA */ { MSIOF1, SCIFA4, MSU_MSU, IIC1 } },
{ 0xe6940024, 0, 16, 4, /* IPRJA */ { DMAC2_1, DMAC2_2, MSUG, TTI20 } },
{ 0xe6940028, 0, 16, 4, /* IPRKA */ { 0, CMT1_CMT13, IRREM, SDHI1 } },
{ 0xe694002c, 0, 16, 4, /* IPRLA */ { TPU0, TPU1, TPU2, TPU3 } },
{ 0xe6940030, 0, 16, 4, /* IPRMA */ { MISTY, CMT3, RWDT1, RWDT0 } },
{ 0xe6940034, 0, 16, 4, /* IPRNA */ { SCIFB, SCIFA5, 0, DDM } },
{ 0xe6940038, 0, 16, 4, /* IPROA */ { 0, 0, DIRC, 0 } },
{ 0xe6950000, 0, 16, 4, /* IPRAA3 */ { SHWYSTAT, 0, 0, 0 } },
{ 0xe6950020, 0, 16, 4, /* IPRIA3 */ { ICUSB, 0, 0, 0 } },
{ 0xe6950024, 0, 16, 4, /* IPRJA3 */ { ICUDMC, 0, 0, 0 } },
{ 0xe6950028, 0, 16, 4, /* IPRKA3 */ { SPU2, 0, FSI, FMSI } },
{ 0xe695002c, 0, 16, 4, /* IPRLA3 */ { SCUV, 0, 0, 0 } },
{ 0xe6950030, 0, 16, 4, /* IPRMA3 */ { IPMMU_IPMMUB, 0, 0, 0 } },
{ 0xe6950034, 0, 16, 4, /* IPRNA3 */ { AP_ARM2, 0, 0, 0 } },
{ 0xe6950038, 0, 16, 4, /* IPROA3 */ { MFIS2, CPORTR2S,
CMT14, CMT15 } },
{ 0xe694003c, 0, 16, 4, /* IPRPA3 */ { SCIFA6, 0, 0, 0 } },
};
static struct intc_desc intca_desc __initdata = {
.name = "sh7377-intca",
.force_enable = ENABLED,
.force_disable = DISABLED,
.hw = INTC_HW_DESC(intca_vectors, intca_groups,
intca_mask_registers, intca_prio_registers,
NULL, NULL),
};
INTC_IRQ_PINS_32(intca_irq_pins, 0xe6900000,
INTC_VECT, "sh7377-intca-irq-pins");
/* this macro ignore entry which is also in INTCA */
#define __IGNORE(a...)
#define __IGNORE0(a...) 0
enum {
UNUSED_INTCS = 0,
INTCS,
/* interrupt sources INTCS */
VEU_VEU0, VEU_VEU1, VEU_VEU2, VEU_VEU3,
RTDMAC1_1_DEI0, RTDMAC1_1_DEI1, RTDMAC1_1_DEI2, RTDMAC1_1_DEI3,
CEU,
BEU_BEU0, BEU_BEU1, BEU_BEU2,
__IGNORE(MFI)
__IGNORE(BBIF2)
VPU,
TSIF1,
__IGNORE(SGX540)
_2DDMAC,
IIC2_ALI2, IIC2_TACKI2, IIC2_WAITI2, IIC2_DTEI2,
IPMMU_IPMMUR, IPMMU_IPMMUR2,
RTDMAC1_2_DEI4, RTDMAC1_2_DEI5, RTDMAC1_2_DADERR,
__IGNORE(KEYSC)
__IGNORE(TTI20)
__IGNORE(MSIOF)
IIC0_ALI0, IIC0_TACKI0, IIC0_WAITI0, IIC0_DTEI0,
TMU_TUNI0, TMU_TUNI1, TMU_TUNI2,
CMT0,
TSIF0,
__IGNORE(CMT2)
LMB,
__IGNORE(MSUG)
__IGNORE(MSU_MSU, MSU_MSU2)
__IGNORE(CTI)
MVI3,
__IGNORE(RWDT0)
__IGNORE(RWDT1)
ICB,
PEP,
ASA,
__IGNORE(_2DG)
HQE,
JPU,
LCDC0,
__IGNORE(LCRC)
RTDMAC2_1_DEI0, RTDMAC2_1_DEI1, RTDMAC2_1_DEI2, RTDMAC2_1_DEI3,
RTDMAC2_2_DEI4, RTDMAC2_2_DEI5, RTDMAC2_2_DADERR,
FRC,
LCDC1,
CSIRX,
DSITX_DSITX0, DSITX_DSITX1,
__IGNORE(SPU2_SPU0, SPU2_SPU1)
__IGNORE(FSI)
__IGNORE(FMSI)
__IGNORE(SCUV)
TMU1_TUNI10, TMU1_TUNI11, TMU1_TUNI12,
TSIF2,
CMT4,
__IGNORE(MFIS2)
CPORTS2R,
/* interrupt groups INTCS */
RTDMAC1_1, RTDMAC1_2, VEU, BEU, IIC0, __IGNORE(MSU) IPMMU,
IIC2, RTDMAC2_1, RTDMAC2_2, DSITX, __IGNORE(SPU2) TMU1,
};
#define INTCS_INTVECT 0x0F80
static struct intc_vect intcs_vectors[] __initdata = {
INTCS_VECT(VEU_VEU0, 0x0700), INTCS_VECT(VEU_VEU1, 0x0720),
INTCS_VECT(VEU_VEU2, 0x0740), INTCS_VECT(VEU_VEU3, 0x0760),
INTCS_VECT(RTDMAC1_1_DEI0, 0x0800), INTCS_VECT(RTDMAC1_1_DEI1, 0x0820),
INTCS_VECT(RTDMAC1_1_DEI2, 0x0840), INTCS_VECT(RTDMAC1_1_DEI3, 0x0860),
INTCS_VECT(CEU, 0x0880),
INTCS_VECT(BEU_BEU0, 0x08A0),
INTCS_VECT(BEU_BEU1, 0x08C0),
INTCS_VECT(BEU_BEU2, 0x08E0),
__IGNORE(INTCS_VECT(MFI, 0x0900))
__IGNORE(INTCS_VECT(BBIF2, 0x0960))
INTCS_VECT(VPU, 0x0980),
INTCS_VECT(TSIF1, 0x09A0),
__IGNORE(INTCS_VECT(SGX540, 0x09E0))
INTCS_VECT(_2DDMAC, 0x0A00),
INTCS_VECT(IIC2_ALI2, 0x0A80), INTCS_VECT(IIC2_TACKI2, 0x0AA0),
INTCS_VECT(IIC2_WAITI2, 0x0AC0), INTCS_VECT(IIC2_DTEI2, 0x0AE0),
INTCS_VECT(IPMMU_IPMMUR, 0x0B00), INTCS_VECT(IPMMU_IPMMUR2, 0x0B20),
INTCS_VECT(RTDMAC1_2_DEI4, 0x0B80),
INTCS_VECT(RTDMAC1_2_DEI5, 0x0BA0),
INTCS_VECT(RTDMAC1_2_DADERR, 0x0BC0),
__IGNORE(INTCS_VECT(KEYSC 0x0BE0))
__IGNORE(INTCS_VECT(TTI20, 0x0C80))
__IGNORE(INTCS_VECT(MSIOF, 0x0D20))
INTCS_VECT(IIC0_ALI0, 0x0E00), INTCS_VECT(IIC0_TACKI0, 0x0E20),
INTCS_VECT(IIC0_WAITI0, 0x0E40), INTCS_VECT(IIC0_DTEI0, 0x0E60),
INTCS_VECT(TMU_TUNI0, 0x0E80),
INTCS_VECT(TMU_TUNI1, 0x0EA0),
INTCS_VECT(TMU_TUNI2, 0x0EC0),
INTCS_VECT(CMT0, 0x0F00),
INTCS_VECT(TSIF0, 0x0F20),
__IGNORE(INTCS_VECT(CMT2, 0x0F40))
INTCS_VECT(LMB, 0x0F60),
__IGNORE(INTCS_VECT(MSUG, 0x0F80))
__IGNORE(INTCS_VECT(MSU_MSU, 0x0FA0))
__IGNORE(INTCS_VECT(MSU_MSU2, 0x0FC0))
__IGNORE(INTCS_VECT(CTI, 0x0400))
INTCS_VECT(MVI3, 0x0420),
__IGNORE(INTCS_VECT(RWDT0, 0x0440))
__IGNORE(INTCS_VECT(RWDT1, 0x0460))
INTCS_VECT(ICB, 0x0480),
INTCS_VECT(PEP, 0x04A0),
INTCS_VECT(ASA, 0x04C0),
__IGNORE(INTCS_VECT(_2DG, 0x04E0))
INTCS_VECT(HQE, 0x0540),
INTCS_VECT(JPU, 0x0560),
INTCS_VECT(LCDC0, 0x0580),
__IGNORE(INTCS_VECT(LCRC, 0x05A0))
INTCS_VECT(RTDMAC2_1_DEI0, 0x1300), INTCS_VECT(RTDMAC2_1_DEI1, 0x1320),
INTCS_VECT(RTDMAC2_1_DEI2, 0x1340), INTCS_VECT(RTDMAC2_1_DEI3, 0x1360),
INTCS_VECT(RTDMAC2_2_DEI4, 0x1380), INTCS_VECT(RTDMAC2_2_DEI5, 0x13A0),
INTCS_VECT(RTDMAC2_2_DADERR, 0x13C0),
INTCS_VECT(FRC, 0x1700),
INTCS_VECT(LCDC1, 0x1780),
INTCS_VECT(CSIRX, 0x17A0),
INTCS_VECT(DSITX_DSITX0, 0x17C0), INTCS_VECT(DSITX_DSITX1, 0x17E0),
__IGNORE(INTCS_VECT(SPU2_SPU0, 0x1800))
__IGNORE(INTCS_VECT(SPU2_SPU1, 0x1820))
__IGNORE(INTCS_VECT(FSI, 0x1840))
__IGNORE(INTCS_VECT(FMSI, 0x1860))
__IGNORE(INTCS_VECT(SCUV, 0x1880))
INTCS_VECT(TMU1_TUNI10, 0x1900), INTCS_VECT(TMU1_TUNI11, 0x1920),
INTCS_VECT(TMU1_TUNI12, 0x1940),
INTCS_VECT(TSIF2, 0x1960),
INTCS_VECT(CMT4, 0x1980),
__IGNORE(INTCS_VECT(MFIS2, 0x1A00))
INTCS_VECT(CPORTS2R, 0x1A20),
INTC_VECT(INTCS, INTCS_INTVECT),
};
static struct intc_group intcs_groups[] __initdata = {
INTC_GROUP(RTDMAC1_1,
RTDMAC1_1_DEI0, RTDMAC1_1_DEI1,
RTDMAC1_1_DEI2, RTDMAC1_1_DEI3),
INTC_GROUP(RTDMAC1_2,
RTDMAC1_2_DEI4, RTDMAC1_2_DEI5, RTDMAC1_2_DADERR),
INTC_GROUP(VEU, VEU_VEU0, VEU_VEU1, VEU_VEU2, VEU_VEU3),
INTC_GROUP(BEU, BEU_BEU0, BEU_BEU1, BEU_BEU2),
INTC_GROUP(IIC0, IIC0_ALI0, IIC0_TACKI0, IIC0_WAITI0, IIC0_DTEI0),
__IGNORE(INTC_GROUP(MSU, MSU_MSU, MSU_MSU2))
INTC_GROUP(IPMMU, IPMMU_IPMMUR, IPMMU_IPMMUR2),
INTC_GROUP(IIC2, IIC2_ALI2, IIC2_TACKI2, IIC2_WAITI2, IIC2_DTEI2),
INTC_GROUP(RTDMAC2_1,
RTDMAC2_1_DEI0, RTDMAC2_1_DEI1,
RTDMAC2_1_DEI2, RTDMAC2_1_DEI3),
INTC_GROUP(RTDMAC2_2, RTDMAC2_2_DEI4, RTDMAC2_2_DEI5, RTDMAC2_2_DADERR),
INTC_GROUP(DSITX, DSITX_DSITX0, DSITX_DSITX1),
__IGNORE(INTC_GROUP(SPU2, SPU2_SPU0, SPU2_SPU1))
INTC_GROUP(TMU1, TMU1_TUNI10, TMU1_TUNI11, TMU1_TUNI12),
};
static struct intc_mask_reg intcs_mask_registers[] __initdata = {
{ 0xE6940184, 0xE69401C4, 8, /* IMR1AS / IMCR1AS */
{ BEU_BEU2, BEU_BEU1, BEU_BEU0, CEU,
VEU_VEU3, VEU_VEU2, VEU_VEU1, VEU_VEU0 } },
{ 0xE6940188, 0xE69401C8, 8, /* IMR2AS / IMCR2AS */
{ 0, 0, 0, VPU,
__IGNORE0(BBIF2), 0, 0, __IGNORE0(MFI) } },
{ 0xE694018C, 0xE69401CC, 8, /* IMR3AS / IMCR3AS */
{ 0, 0, 0, _2DDMAC,
__IGNORE0(_2DG), ASA, PEP, ICB } },
{ 0xE6940190, 0xE69401D0, 8, /* IMR4AS / IMCR4AS */
{ 0, 0, MVI3, __IGNORE0(CTI),
JPU, HQE, __IGNORE0(LCRC), LCDC0 } },
{ 0xE6940194, 0xE69401D4, 8, /* IMR5AS / IMCR5AS */
{ __IGNORE0(KEYSC), RTDMAC1_2_DADERR, RTDMAC1_2_DEI5, RTDMAC1_2_DEI4,
RTDMAC1_1_DEI3, RTDMAC1_1_DEI2, RTDMAC1_1_DEI1, RTDMAC1_1_DEI0 } },
__IGNORE({ 0xE6940198, 0xE69401D8, 8, /* IMR6AS / IMCR6AS */
{ 0, 0, MSIOF, 0,
SGX540, 0, TTI20, 0 } })
{ 0xE694019C, 0xE69401DC, 8, /* IMR7AS / IMCR7AS */
{ 0, TMU_TUNI2, TMU_TUNI1, TMU_TUNI0,
0, 0, 0, 0 } },
__IGNORE({ 0xE69401A0, 0xE69401E0, 8, /* IMR8AS / IMCR8AS */
{ 0, 0, 0, 0,
0, MSU_MSU, MSU_MSU2, MSUG } })
{ 0xE69401A4, 0xE69401E4, 8, /* IMR9AS / IMCR9AS */
{ __IGNORE0(RWDT1), __IGNORE0(RWDT0), __IGNORE0(CMT2), CMT0,
IIC2_DTEI2, IIC2_WAITI2, IIC2_TACKI2, IIC2_ALI2 } },
{ 0xE69401A8, 0xE69401E8, 8, /* IMR10AS / IMCR10AS */
{ 0, 0, IPMMU_IPMMUR, IPMMU_IPMMUR2,
0, 0, 0, 0 } },
{ 0xE69401AC, 0xE69401EC, 8, /* IMR11AS / IMCR11AS */
{ IIC0_DTEI0, IIC0_WAITI0, IIC0_TACKI0, IIC0_ALI0,
0, TSIF1, LMB, TSIF0 } },
{ 0xE6950180, 0xE69501C0, 8, /* IMR0AS3 / IMCR0AS3 */
{ RTDMAC2_1_DEI0, RTDMAC2_1_DEI1, RTDMAC2_1_DEI2, RTDMAC2_1_DEI3,
RTDMAC2_2_DEI4, RTDMAC2_2_DEI5, RTDMAC2_2_DADERR, 0 } },
{ 0xE6950190, 0xE69501D0, 8, /* IMR4AS3 / IMCR4AS3 */
{ FRC, 0, 0, 0,
LCDC1, CSIRX, DSITX_DSITX0, DSITX_DSITX1 } },
__IGNORE({ 0xE6950194, 0xE69501D4, 8, /* IMR5AS3 / IMCR5AS3 */
{SPU2_SPU0, SPU2_SPU1, FSI, FMSI,
SCUV, 0, 0, 0 } })
{ 0xE6950198, 0xE69501D8, 8, /* IMR6AS3 / IMCR6AS3 */
{ TMU1_TUNI10, TMU1_TUNI11, TMU1_TUNI12, TSIF2,
CMT4, 0, 0, 0 } },
{ 0xE695019C, 0xE69501DC, 8, /* IMR7AS3 / IMCR7AS3 */
{ __IGNORE0(MFIS2), CPORTS2R, 0, 0,
0, 0, 0, 0 } },
{ 0xFFD20104, 0, 16, /* INTAMASK */
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, INTCS } }
};
static struct intc_prio_reg intcs_prio_registers[] __initdata = {
/* IPRAS */
{ 0xFFD20000, 0, 16, 4, { __IGNORE0(CTI), MVI3, _2DDMAC, ICB } },
/* IPRBS */
{ 0xFFD20004, 0, 16, 4, { JPU, LCDC0, 0, __IGNORE0(LCRC) } },
/* IPRCS */
__IGNORE({ 0xFFD20008, 0, 16, 4, { BBIF2, 0, 0, 0 } })
/* IPRES */
{ 0xFFD20010, 0, 16, 4, { RTDMAC1_1, CEU, __IGNORE0(MFI), VPU } },
/* IPRFS */
{ 0xFFD20014, 0, 16, 4,
{ __IGNORE0(KEYSC), RTDMAC1_2, __IGNORE0(CMT2), CMT0 } },
/* IPRGS */
{ 0xFFD20018, 0, 16, 4, { TMU_TUNI0, TMU_TUNI1, TMU_TUNI2, TSIF1 } },
/* IPRHS */
{ 0xFFD2001C, 0, 16, 4, { __IGNORE0(TTI20), 0, VEU, BEU } },
/* IPRIS */
{ 0xFFD20020, 0, 16, 4, { 0, __IGNORE0(MSIOF), TSIF0, IIC0 } },
/* IPRJS */
__IGNORE({ 0xFFD20024, 0, 16, 4, { 0, SGX540, MSUG, MSU } })
/* IPRKS */
{ 0xFFD20028, 0, 16, 4, { __IGNORE0(_2DG), ASA, LMB, PEP } },
/* IPRLS */
{ 0xFFD2002C, 0, 16, 4, { IPMMU, 0, 0, HQE } },
/* IPRMS */
{ 0xFFD20030, 0, 16, 4,
{ IIC2, 0, __IGNORE0(RWDT1), __IGNORE0(RWDT0) } },
/* IPRAS3 */
{ 0xFFD50000, 0, 16, 4, { RTDMAC2_1, 0, 0, 0 } },
/* IPRBS3 */
{ 0xFFD50004, 0, 16, 4, { RTDMAC2_2, 0, 0, 0 } },
/* IPRIS3 */
{ 0xFFD50020, 0, 16, 4, { FRC, 0, 0, 0 } },
/* IPRJS3 */
{ 0xFFD50024, 0, 16, 4, { LCDC1, CSIRX, DSITX, 0 } },
/* IPRKS3 */
__IGNORE({ 0xFFD50028, 0, 16, 4, { SPU2, 0, FSI, FMSI } })
/* IPRLS3 */
__IGNORE({ 0xFFD5002C, 0, 16, 4, { SCUV, 0, 0, 0 } })
/* IPRMS3 */
{ 0xFFD50030, 0, 16, 4, { TMU1, 0, 0, TSIF2 } },
/* IPRNS3 */
{ 0xFFD50034, 0, 16, 4, { CMT4, 0, 0, 0 } },
/* IPROS3 */
{ 0xFFD50038, 0, 16, 4, { __IGNORE0(MFIS2), CPORTS2R, 0, 0 } },
};
static struct resource intcs_resources[] __initdata = {
[0] = {
.start = 0xffd20000,
.end = 0xffd500ff,
.flags = IORESOURCE_MEM,
}
};
static struct intc_desc intcs_desc __initdata = {
.name = "sh7377-intcs",
.resource = intcs_resources,
.num_resources = ARRAY_SIZE(intcs_resources),
.hw = INTC_HW_DESC(intcs_vectors, intcs_groups,
intcs_mask_registers, intcs_prio_registers,
NULL, NULL),
};
static void intcs_demux(unsigned int irq, struct irq_desc *desc)
{
void __iomem *reg = (void *)irq_get_handler_data(irq);
unsigned int evtcodeas = ioread32(reg);
generic_handle_irq(intcs_evt2irq(evtcodeas));
}
#define INTEVTSA 0xFFD20100
void __init sh7377_init_irq(void)
{
void __iomem *intevtsa = ioremap_nocache(INTEVTSA, PAGE_SIZE);
register_intc_controller(&intca_desc);
register_intc_controller(&intca_irq_pins_desc);
register_intc_controller(&intcs_desc);
/* demux using INTEVTSA */
irq_set_handler_data(evt2irq(INTCS_INTVECT), (void *)intevtsa);
irq_set_chained_handler(evt2irq(INTCS_INTVECT), intcs_demux);
}
| gpl-2.0 |
TeamRegular/android_kernel_zara | arch/arm/mach-imx/cpu-imx27.c | 5163 | 1919 | /*
* Copyright 2007 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Juergen Beisert, kernel@pengutronix.de
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/*
* i.MX27 specific CPU detection code
*/
#include <linux/io.h>
#include <linux/module.h>
#include <mach/hardware.h>
static int mx27_cpu_rev = -1;
static int mx27_cpu_partnumber;
#define SYS_CHIP_ID 0x00 /* The offset of CHIP ID register */
static int mx27_read_cpu_rev(void)
{
u32 val;
/*
* now we have access to the IO registers. As we need
* the silicon revision very early we read it here to
* avoid any further hooks
*/
val = __raw_readl(MX27_IO_ADDRESS(MX27_SYSCTRL_BASE_ADDR
+ SYS_CHIP_ID));
mx27_cpu_partnumber = (int)((val >> 12) & 0xFFFF);
switch (val >> 28) {
case 0:
return IMX_CHIP_REVISION_1_0;
case 1:
return IMX_CHIP_REVISION_2_0;
case 2:
return IMX_CHIP_REVISION_2_1;
default:
return IMX_CHIP_REVISION_UNKNOWN;
}
}
/*
* Returns:
* the silicon revision of the cpu
* -EINVAL - not a mx27
*/
int mx27_revision(void)
{
if (mx27_cpu_rev == -1)
mx27_cpu_rev = mx27_read_cpu_rev();
if (mx27_cpu_partnumber != 0x8821)
return -EINVAL;
return mx27_cpu_rev;
}
EXPORT_SYMBOL(mx27_revision);
| gpl-2.0 |
rbheromax/raybst-kernel | drivers/video/geode/suspend_gx.c | 14123 | 6242 | /*
* Copyright (C) 2007 Advanced Micro Devices, Inc.
* Copyright (C) 2008 Andres Salomon <dilinger@debian.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/fb.h>
#include <asm/io.h>
#include <asm/msr.h>
#include <linux/cs5535.h>
#include <asm/delay.h>
#include "gxfb.h"
#ifdef CONFIG_PM
static void gx_save_regs(struct gxfb_par *par)
{
int i;
/* wait for the BLT engine to stop being busy */
do {
i = read_gp(par, GP_BLT_STATUS);
} while (i & (GP_BLT_STATUS_BLT_PENDING | GP_BLT_STATUS_BLT_BUSY));
/* save MSRs */
rdmsrl(MSR_GX_MSR_PADSEL, par->msr.padsel);
rdmsrl(MSR_GLCP_DOTPLL, par->msr.dotpll);
write_dc(par, DC_UNLOCK, DC_UNLOCK_UNLOCK);
/* save registers */
memcpy(par->gp, par->gp_regs, sizeof(par->gp));
memcpy(par->dc, par->dc_regs, sizeof(par->dc));
memcpy(par->vp, par->vid_regs, sizeof(par->vp));
memcpy(par->fp, par->vid_regs + VP_FP_START, sizeof(par->fp));
/* save the palette */
write_dc(par, DC_PAL_ADDRESS, 0);
for (i = 0; i < ARRAY_SIZE(par->pal); i++)
par->pal[i] = read_dc(par, DC_PAL_DATA);
}
static void gx_set_dotpll(uint32_t dotpll_hi)
{
uint32_t dotpll_lo;
int i;
rdmsrl(MSR_GLCP_DOTPLL, dotpll_lo);
dotpll_lo |= MSR_GLCP_DOTPLL_DOTRESET;
dotpll_lo &= ~MSR_GLCP_DOTPLL_BYPASS;
wrmsr(MSR_GLCP_DOTPLL, dotpll_lo, dotpll_hi);
/* wait for the PLL to lock */
for (i = 0; i < 200; i++) {
rdmsrl(MSR_GLCP_DOTPLL, dotpll_lo);
if (dotpll_lo & MSR_GLCP_DOTPLL_LOCK)
break;
udelay(1);
}
/* PLL set, unlock */
dotpll_lo &= ~MSR_GLCP_DOTPLL_DOTRESET;
wrmsr(MSR_GLCP_DOTPLL, dotpll_lo, dotpll_hi);
}
static void gx_restore_gfx_proc(struct gxfb_par *par)
{
int i;
for (i = 0; i < ARRAY_SIZE(par->gp); i++) {
switch (i) {
case GP_VECTOR_MODE:
case GP_BLT_MODE:
case GP_BLT_STATUS:
case GP_HST_SRC:
/* don't restore these registers */
break;
default:
write_gp(par, i, par->gp[i]);
}
}
}
static void gx_restore_display_ctlr(struct gxfb_par *par)
{
int i;
for (i = 0; i < ARRAY_SIZE(par->dc); i++) {
switch (i) {
case DC_UNLOCK:
/* unlock the DC; runs first */
write_dc(par, DC_UNLOCK, DC_UNLOCK_UNLOCK);
break;
case DC_GENERAL_CFG:
/* write without the enables */
write_dc(par, i, par->dc[i] & ~(DC_GENERAL_CFG_VIDE |
DC_GENERAL_CFG_ICNE |
DC_GENERAL_CFG_CURE |
DC_GENERAL_CFG_DFLE));
break;
case DC_DISPLAY_CFG:
/* write without the enables */
write_dc(par, i, par->dc[i] & ~(DC_DISPLAY_CFG_VDEN |
DC_DISPLAY_CFG_GDEN |
DC_DISPLAY_CFG_TGEN));
break;
case DC_RSVD_0:
case DC_RSVD_1:
case DC_RSVD_2:
case DC_RSVD_3:
case DC_RSVD_4:
case DC_LINE_CNT:
case DC_PAL_ADDRESS:
case DC_PAL_DATA:
case DC_DFIFO_DIAG:
case DC_CFIFO_DIAG:
case DC_RSVD_5:
/* don't restore these registers */
break;
default:
write_dc(par, i, par->dc[i]);
}
}
/* restore the palette */
write_dc(par, DC_PAL_ADDRESS, 0);
for (i = 0; i < ARRAY_SIZE(par->pal); i++)
write_dc(par, DC_PAL_DATA, par->pal[i]);
}
static void gx_restore_video_proc(struct gxfb_par *par)
{
int i;
wrmsrl(MSR_GX_MSR_PADSEL, par->msr.padsel);
for (i = 0; i < ARRAY_SIZE(par->vp); i++) {
switch (i) {
case VP_VCFG:
/* don't enable video yet */
write_vp(par, i, par->vp[i] & ~VP_VCFG_VID_EN);
break;
case VP_DCFG:
/* don't enable CRT yet */
write_vp(par, i, par->vp[i] &
~(VP_DCFG_DAC_BL_EN | VP_DCFG_VSYNC_EN |
VP_DCFG_HSYNC_EN | VP_DCFG_CRT_EN));
break;
case VP_GAR:
case VP_GDR:
case VP_RSVD_0:
case VP_RSVD_1:
case VP_RSVD_2:
case VP_RSVD_3:
case VP_CRC32:
case VP_AWT:
case VP_VTM:
/* don't restore these registers */
break;
default:
write_vp(par, i, par->vp[i]);
}
}
}
static void gx_restore_regs(struct gxfb_par *par)
{
int i;
gx_set_dotpll((uint32_t) (par->msr.dotpll >> 32));
gx_restore_gfx_proc(par);
gx_restore_display_ctlr(par);
gx_restore_video_proc(par);
/* Flat Panel */
for (i = 0; i < ARRAY_SIZE(par->fp); i++) {
if (i != FP_PM && i != FP_RSVD_0)
write_fp(par, i, par->fp[i]);
}
}
static void gx_disable_graphics(struct gxfb_par *par)
{
/* shut down the engine */
write_vp(par, VP_VCFG, par->vp[VP_VCFG] & ~VP_VCFG_VID_EN);
write_vp(par, VP_DCFG, par->vp[VP_DCFG] & ~(VP_DCFG_DAC_BL_EN |
VP_DCFG_VSYNC_EN | VP_DCFG_HSYNC_EN | VP_DCFG_CRT_EN));
/* turn off the flat panel */
write_fp(par, FP_PM, par->fp[FP_PM] & ~FP_PM_P);
/* turn off display */
write_dc(par, DC_UNLOCK, DC_UNLOCK_UNLOCK);
write_dc(par, DC_GENERAL_CFG, par->dc[DC_GENERAL_CFG] &
~(DC_GENERAL_CFG_VIDE | DC_GENERAL_CFG_ICNE |
DC_GENERAL_CFG_CURE | DC_GENERAL_CFG_DFLE));
write_dc(par, DC_DISPLAY_CFG, par->dc[DC_DISPLAY_CFG] &
~(DC_DISPLAY_CFG_VDEN | DC_DISPLAY_CFG_GDEN |
DC_DISPLAY_CFG_TGEN));
write_dc(par, DC_UNLOCK, DC_UNLOCK_LOCK);
}
static void gx_enable_graphics(struct gxfb_par *par)
{
uint32_t fp;
fp = read_fp(par, FP_PM);
if (par->fp[FP_PM] & FP_PM_P) {
/* power on the panel if not already power{ed,ing} on */
if (!(fp & (FP_PM_PANEL_ON|FP_PM_PANEL_PWR_UP)))
write_fp(par, FP_PM, par->fp[FP_PM]);
} else {
/* power down the panel if not already power{ed,ing} down */
if (!(fp & (FP_PM_PANEL_OFF|FP_PM_PANEL_PWR_DOWN)))
write_fp(par, FP_PM, par->fp[FP_PM]);
}
/* turn everything on */
write_vp(par, VP_VCFG, par->vp[VP_VCFG]);
write_vp(par, VP_DCFG, par->vp[VP_DCFG]);
write_dc(par, DC_DISPLAY_CFG, par->dc[DC_DISPLAY_CFG]);
/* do this last; it will enable the FIFO load */
write_dc(par, DC_GENERAL_CFG, par->dc[DC_GENERAL_CFG]);
/* lock the door behind us */
write_dc(par, DC_UNLOCK, DC_UNLOCK_LOCK);
}
int gx_powerdown(struct fb_info *info)
{
struct gxfb_par *par = info->par;
if (par->powered_down)
return 0;
gx_save_regs(par);
gx_disable_graphics(par);
par->powered_down = 1;
return 0;
}
int gx_powerup(struct fb_info *info)
{
struct gxfb_par *par = info->par;
if (!par->powered_down)
return 0;
gx_restore_regs(par);
gx_enable_graphics(par);
par->powered_down = 0;
return 0;
}
#endif
| gpl-2.0 |
tmatsuya/milkymist-linux | drivers/scsi/aic7xxx/aic79xx_core.c | 44 | 278804 | /*
* Core routines and tables shareable across OS platforms.
*
* Copyright (c) 1994-2002 Justin T. Gibbs.
* Copyright (c) 2000-2003 Adaptec Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* $Id: //depot/aic7xxx/aic7xxx/aic79xx.c#250 $
*/
#ifdef __linux__
#include "aic79xx_osm.h"
#include "aic79xx_inline.h"
#include "aicasm/aicasm_insformat.h"
#else
#include <dev/aic7xxx/aic79xx_osm.h>
#include <dev/aic7xxx/aic79xx_inline.h>
#include <dev/aic7xxx/aicasm/aicasm_insformat.h>
#endif
/***************************** Lookup Tables **********************************/
static char *ahd_chip_names[] =
{
"NONE",
"aic7901",
"aic7902",
"aic7901A"
};
static const u_int num_chip_names = ARRAY_SIZE(ahd_chip_names);
/*
* Hardware error codes.
*/
struct ahd_hard_error_entry {
uint8_t errno;
char *errmesg;
};
static struct ahd_hard_error_entry ahd_hard_errors[] = {
{ DSCTMOUT, "Discard Timer has timed out" },
{ ILLOPCODE, "Illegal Opcode in sequencer program" },
{ SQPARERR, "Sequencer Parity Error" },
{ DPARERR, "Data-path Parity Error" },
{ MPARERR, "Scratch or SCB Memory Parity Error" },
{ CIOPARERR, "CIOBUS Parity Error" },
};
static const u_int num_errors = ARRAY_SIZE(ahd_hard_errors);
static struct ahd_phase_table_entry ahd_phase_table[] =
{
{ P_DATAOUT, MSG_NOOP, "in Data-out phase" },
{ P_DATAIN, MSG_INITIATOR_DET_ERR, "in Data-in phase" },
{ P_DATAOUT_DT, MSG_NOOP, "in DT Data-out phase" },
{ P_DATAIN_DT, MSG_INITIATOR_DET_ERR, "in DT Data-in phase" },
{ P_COMMAND, MSG_NOOP, "in Command phase" },
{ P_MESGOUT, MSG_NOOP, "in Message-out phase" },
{ P_STATUS, MSG_INITIATOR_DET_ERR, "in Status phase" },
{ P_MESGIN, MSG_PARITY_ERROR, "in Message-in phase" },
{ P_BUSFREE, MSG_NOOP, "while idle" },
{ 0, MSG_NOOP, "in unknown phase" }
};
/*
* In most cases we only wish to itterate over real phases, so
* exclude the last element from the count.
*/
static const u_int num_phases = ARRAY_SIZE(ahd_phase_table) - 1;
/* Our Sequencer Program */
#include "aic79xx_seq.h"
/**************************** Function Declarations ***************************/
static void ahd_handle_transmission_error(struct ahd_softc *ahd);
static void ahd_handle_lqiphase_error(struct ahd_softc *ahd,
u_int lqistat1);
static int ahd_handle_pkt_busfree(struct ahd_softc *ahd,
u_int busfreetime);
static int ahd_handle_nonpkt_busfree(struct ahd_softc *ahd);
static void ahd_handle_proto_violation(struct ahd_softc *ahd);
static void ahd_force_renegotiation(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo);
static struct ahd_tmode_tstate*
ahd_alloc_tstate(struct ahd_softc *ahd,
u_int scsi_id, char channel);
#ifdef AHD_TARGET_MODE
static void ahd_free_tstate(struct ahd_softc *ahd,
u_int scsi_id, char channel, int force);
#endif
static void ahd_devlimited_syncrate(struct ahd_softc *ahd,
struct ahd_initiator_tinfo *,
u_int *period,
u_int *ppr_options,
role_t role);
static void ahd_update_neg_table(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
struct ahd_transinfo *tinfo);
static void ahd_update_pending_scbs(struct ahd_softc *ahd);
static void ahd_fetch_devinfo(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo);
static void ahd_scb_devinfo(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
struct scb *scb);
static void ahd_setup_initiator_msgout(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
struct scb *scb);
static void ahd_build_transfer_msg(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo);
static void ahd_construct_sdtr(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
u_int period, u_int offset);
static void ahd_construct_wdtr(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
u_int bus_width);
static void ahd_construct_ppr(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
u_int period, u_int offset,
u_int bus_width, u_int ppr_options);
static void ahd_clear_msg_state(struct ahd_softc *ahd);
static void ahd_handle_message_phase(struct ahd_softc *ahd);
typedef enum {
AHDMSG_1B,
AHDMSG_2B,
AHDMSG_EXT
} ahd_msgtype;
static int ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type,
u_int msgval, int full);
static int ahd_parse_msg(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo);
static int ahd_handle_msg_reject(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo);
static void ahd_handle_ign_wide_residue(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo);
static void ahd_reinitialize_dataptrs(struct ahd_softc *ahd);
static void ahd_handle_devreset(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
u_int lun, cam_status status,
char *message, int verbose_level);
#ifdef AHD_TARGET_MODE
static void ahd_setup_target_msgin(struct ahd_softc *ahd,
struct ahd_devinfo *devinfo,
struct scb *scb);
#endif
static u_int ahd_sglist_size(struct ahd_softc *ahd);
static u_int ahd_sglist_allocsize(struct ahd_softc *ahd);
static bus_dmamap_callback_t
ahd_dmamap_cb;
static void ahd_initialize_hscbs(struct ahd_softc *ahd);
static int ahd_init_scbdata(struct ahd_softc *ahd);
static void ahd_fini_scbdata(struct ahd_softc *ahd);
static void ahd_setup_iocell_workaround(struct ahd_softc *ahd);
static void ahd_iocell_first_selection(struct ahd_softc *ahd);
static void ahd_add_col_list(struct ahd_softc *ahd,
struct scb *scb, u_int col_idx);
static void ahd_rem_col_list(struct ahd_softc *ahd,
struct scb *scb);
static void ahd_chip_init(struct ahd_softc *ahd);
static void ahd_qinfifo_requeue(struct ahd_softc *ahd,
struct scb *prev_scb,
struct scb *scb);
static int ahd_qinfifo_count(struct ahd_softc *ahd);
static int ahd_search_scb_list(struct ahd_softc *ahd, int target,
char channel, int lun, u_int tag,
role_t role, uint32_t status,
ahd_search_action action,
u_int *list_head, u_int *list_tail,
u_int tid);
static void ahd_stitch_tid_list(struct ahd_softc *ahd,
u_int tid_prev, u_int tid_cur,
u_int tid_next);
static void ahd_add_scb_to_free_list(struct ahd_softc *ahd,
u_int scbid);
static u_int ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
u_int prev, u_int next, u_int tid);
static void ahd_reset_current_bus(struct ahd_softc *ahd);
static ahd_callback_t ahd_stat_timer;
#ifdef AHD_DUMP_SEQ
static void ahd_dumpseq(struct ahd_softc *ahd);
#endif
static void ahd_loadseq(struct ahd_softc *ahd);
static int ahd_check_patch(struct ahd_softc *ahd,
struct patch **start_patch,
u_int start_instr, u_int *skip_addr);
static u_int ahd_resolve_seqaddr(struct ahd_softc *ahd,
u_int address);
static void ahd_download_instr(struct ahd_softc *ahd,
u_int instrptr, uint8_t *dconsts);
static int ahd_probe_stack_size(struct ahd_softc *ahd);
static int ahd_scb_active_in_fifo(struct ahd_softc *ahd,
struct scb *scb);
static void ahd_run_data_fifo(struct ahd_softc *ahd,
struct scb *scb);
#ifdef AHD_TARGET_MODE
static void ahd_queue_lstate_event(struct ahd_softc *ahd,
struct ahd_tmode_lstate *lstate,
u_int initiator_id,
u_int event_type,
u_int event_arg);
static void ahd_update_scsiid(struct ahd_softc *ahd,
u_int targid_mask);
static int ahd_handle_target_cmd(struct ahd_softc *ahd,
struct target_cmd *cmd);
#endif
static int ahd_abort_scbs(struct ahd_softc *ahd, int target,
char channel, int lun, u_int tag,
role_t role, uint32_t status);
static void ahd_alloc_scbs(struct ahd_softc *ahd);
static void ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl,
u_int scbid);
static void ahd_calc_residual(struct ahd_softc *ahd,
struct scb *scb);
static void ahd_clear_critical_section(struct ahd_softc *ahd);
static void ahd_clear_intstat(struct ahd_softc *ahd);
static void ahd_enable_coalescing(struct ahd_softc *ahd,
int enable);
static u_int ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl);
static void ahd_freeze_devq(struct ahd_softc *ahd,
struct scb *scb);
static void ahd_handle_scb_status(struct ahd_softc *ahd,
struct scb *scb);
static struct ahd_phase_table_entry* ahd_lookup_phase_entry(int phase);
static void ahd_shutdown(void *arg);
static void ahd_update_coalescing_values(struct ahd_softc *ahd,
u_int timer,
u_int maxcmds,
u_int mincmds);
static int ahd_verify_vpd_cksum(struct vpd_config *vpd);
static int ahd_wait_seeprom(struct ahd_softc *ahd);
static int ahd_match_scb(struct ahd_softc *ahd, struct scb *scb,
int target, char channel, int lun,
u_int tag, role_t role);
/******************************** Private Inlines *****************************/
static __inline void
ahd_assert_atn(struct ahd_softc *ahd)
{
ahd_outb(ahd, SCSISIGO, ATNO);
}
/*
* Determine if the current connection has a packetized
* agreement. This does not necessarily mean that we
* are currently in a packetized transfer. We could
* just as easily be sending or receiving a message.
*/
static __inline int
ahd_currently_packetized(struct ahd_softc *ahd)
{
ahd_mode_state saved_modes;
int packetized;
saved_modes = ahd_save_modes(ahd);
if ((ahd->bugs & AHD_PKTIZED_STATUS_BUG) != 0) {
/*
* The packetized bit refers to the last
* connection, not the current one. Check
* for non-zero LQISTATE instead.
*/
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
packetized = ahd_inb(ahd, LQISTATE) != 0;
} else {
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
packetized = ahd_inb(ahd, LQISTAT2) & PACKETIZED;
}
ahd_restore_modes(ahd, saved_modes);
return (packetized);
}
static __inline int
ahd_set_active_fifo(struct ahd_softc *ahd)
{
u_int active_fifo;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
active_fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
switch (active_fifo) {
case 0:
case 1:
ahd_set_modes(ahd, active_fifo, active_fifo);
return (1);
default:
return (0);
}
}
static __inline void
ahd_unbusy_tcl(struct ahd_softc *ahd, u_int tcl)
{
ahd_busy_tcl(ahd, tcl, SCB_LIST_NULL);
}
/*
* Determine whether the sequencer reported a residual
* for this SCB/transaction.
*/
static __inline void
ahd_update_residual(struct ahd_softc *ahd, struct scb *scb)
{
uint32_t sgptr;
sgptr = ahd_le32toh(scb->hscb->sgptr);
if ((sgptr & SG_STATUS_VALID) != 0)
ahd_calc_residual(ahd, scb);
}
static __inline void
ahd_complete_scb(struct ahd_softc *ahd, struct scb *scb)
{
uint32_t sgptr;
sgptr = ahd_le32toh(scb->hscb->sgptr);
if ((sgptr & SG_STATUS_VALID) != 0)
ahd_handle_scb_status(ahd, scb);
else
ahd_done(ahd, scb);
}
/************************* Sequencer Execution Control ************************/
/*
* Restart the sequencer program from address zero
*/
static void
ahd_restart(struct ahd_softc *ahd)
{
ahd_pause(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
/* No more pending messages */
ahd_clear_msg_state(ahd);
ahd_outb(ahd, SCSISIGO, 0); /* De-assert BSY */
ahd_outb(ahd, MSG_OUT, MSG_NOOP); /* No message to send */
ahd_outb(ahd, SXFRCTL1, ahd_inb(ahd, SXFRCTL1) & ~BITBUCKET);
ahd_outb(ahd, SEQINTCTL, 0);
ahd_outb(ahd, LASTPHASE, P_BUSFREE);
ahd_outb(ahd, SEQ_FLAGS, 0);
ahd_outb(ahd, SAVED_SCSIID, 0xFF);
ahd_outb(ahd, SAVED_LUN, 0xFF);
/*
* Ensure that the sequencer's idea of TQINPOS
* matches our own. The sequencer increments TQINPOS
* only after it sees a DMA complete and a reset could
* occur before the increment leaving the kernel to believe
* the command arrived but the sequencer to not.
*/
ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
/* Always allow reselection */
ahd_outb(ahd, SCSISEQ1,
ahd_inb(ahd, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
/*
* Clear any pending sequencer interrupt. It is no
* longer relevant since we're resetting the Program
* Counter.
*/
ahd_outb(ahd, CLRINT, CLRSEQINT);
ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
ahd_unpause(ahd);
}
static void
ahd_clear_fifo(struct ahd_softc *ahd, u_int fifo)
{
ahd_mode_state saved_modes;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_FIFOS) != 0)
printf("%s: Clearing FIFO %d\n", ahd_name(ahd), fifo);
#endif
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, fifo, fifo);
ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
ahd_outb(ahd, CCSGCTL, CCSGRESET);
ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
ahd_outb(ahd, SG_STATE, 0);
ahd_restore_modes(ahd, saved_modes);
}
/************************* Input/Output Queues ********************************/
/*
* Flush and completed commands that are sitting in the command
* complete queues down on the chip but have yet to be dma'ed back up.
*/
static void
ahd_flush_qoutfifo(struct ahd_softc *ahd)
{
struct scb *scb;
ahd_mode_state saved_modes;
u_int saved_scbptr;
u_int ccscbctl;
u_int scbid;
u_int next_scbid;
saved_modes = ahd_save_modes(ahd);
/*
* Flush the good status FIFO for completed packetized commands.
*/
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
saved_scbptr = ahd_get_scbptr(ahd);
while ((ahd_inb(ahd, LQISTAT2) & LQIGSAVAIL) != 0) {
u_int fifo_mode;
u_int i;
scbid = ahd_inw(ahd, GSFIFO);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: Warning - GSFIFO SCB %d invalid\n",
ahd_name(ahd), scbid);
continue;
}
/*
* Determine if this transaction is still active in
* any FIFO. If it is, we must flush that FIFO to
* the host before completing the command.
*/
fifo_mode = 0;
rescan_fifos:
for (i = 0; i < 2; i++) {
/* Toggle to the other mode. */
fifo_mode ^= 1;
ahd_set_modes(ahd, fifo_mode, fifo_mode);
if (ahd_scb_active_in_fifo(ahd, scb) == 0)
continue;
ahd_run_data_fifo(ahd, scb);
/*
* Running this FIFO may cause a CFG4DATA for
* this same transaction to assert in the other
* FIFO or a new snapshot SAVEPTRS interrupt
* in this FIFO. Even running a FIFO may not
* clear the transaction if we are still waiting
* for data to drain to the host. We must loop
* until the transaction is not active in either
* FIFO just to be sure. Reset our loop counter
* so we will visit both FIFOs again before
* declaring this transaction finished. We
* also delay a bit so that status has a chance
* to change before we look at this FIFO again.
*/
ahd_delay(200);
goto rescan_fifos;
}
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_set_scbptr(ahd, scbid);
if ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_LIST_NULL) == 0
&& ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_FULL_RESID) != 0
|| (ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR)
& SG_LIST_NULL) != 0)) {
u_int comp_head;
/*
* The transfer completed with a residual.
* Place this SCB on the complete DMA list
* so that we update our in-core copy of the
* SCB before completing the command.
*/
ahd_outb(ahd, SCB_SCSI_STATUS, 0);
ahd_outb(ahd, SCB_SGPTR,
ahd_inb_scbram(ahd, SCB_SGPTR)
| SG_STATUS_VALID);
ahd_outw(ahd, SCB_TAG, scbid);
ahd_outw(ahd, SCB_NEXT_COMPLETE, SCB_LIST_NULL);
comp_head = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
if (SCBID_IS_NULL(comp_head)) {
ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, scbid);
ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
} else {
u_int tail;
tail = ahd_inw(ahd, COMPLETE_DMA_SCB_TAIL);
ahd_set_scbptr(ahd, tail);
ahd_outw(ahd, SCB_NEXT_COMPLETE, scbid);
ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
ahd_set_scbptr(ahd, scbid);
}
} else
ahd_complete_scb(ahd, scb);
}
ahd_set_scbptr(ahd, saved_scbptr);
/*
* Setup for command channel portion of flush.
*/
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
/*
* Wait for any inprogress DMA to complete and clear DMA state
* if this if for an SCB in the qinfifo.
*/
while (((ccscbctl = ahd_inb(ahd, CCSCBCTL)) & (CCARREN|CCSCBEN)) != 0) {
if ((ccscbctl & (CCSCBDIR|CCARREN)) == (CCSCBDIR|CCARREN)) {
if ((ccscbctl & ARRDONE) != 0)
break;
} else if ((ccscbctl & CCSCBDONE) != 0)
break;
ahd_delay(200);
}
/*
* We leave the sequencer to cleanup in the case of DMA's to
* update the qoutfifo. In all other cases (DMA's to the
* chip or a push of an SCB from the COMPLETE_DMA_SCB list),
* we disable the DMA engine so that the sequencer will not
* attempt to handle the DMA completion.
*/
if ((ccscbctl & CCSCBDIR) != 0 || (ccscbctl & ARRDONE) != 0)
ahd_outb(ahd, CCSCBCTL, ccscbctl & ~(CCARREN|CCSCBEN));
/*
* Complete any SCBs that just finished
* being DMA'ed into the qoutfifo.
*/
ahd_run_qoutfifo(ahd);
saved_scbptr = ahd_get_scbptr(ahd);
/*
* Manually update/complete any completed SCBs that are waiting to be
* DMA'ed back up to the host.
*/
scbid = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
while (!SCBID_IS_NULL(scbid)) {
uint8_t *hscb_ptr;
u_int i;
ahd_set_scbptr(ahd, scbid);
next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: Warning - DMA-up and complete "
"SCB %d invalid\n", ahd_name(ahd), scbid);
continue;
}
hscb_ptr = (uint8_t *)scb->hscb;
for (i = 0; i < sizeof(struct hardware_scb); i++)
*hscb_ptr++ = ahd_inb_scbram(ahd, SCB_BASE + i);
ahd_complete_scb(ahd, scb);
scbid = next_scbid;
}
ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
scbid = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
while (!SCBID_IS_NULL(scbid)) {
ahd_set_scbptr(ahd, scbid);
next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: Warning - Complete Qfrz SCB %d invalid\n",
ahd_name(ahd), scbid);
continue;
}
ahd_complete_scb(ahd, scb);
scbid = next_scbid;
}
ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
scbid = ahd_inw(ahd, COMPLETE_SCB_HEAD);
while (!SCBID_IS_NULL(scbid)) {
ahd_set_scbptr(ahd, scbid);
next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: Warning - Complete SCB %d invalid\n",
ahd_name(ahd), scbid);
continue;
}
ahd_complete_scb(ahd, scb);
scbid = next_scbid;
}
ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
/*
* Restore state.
*/
ahd_set_scbptr(ahd, saved_scbptr);
ahd_restore_modes(ahd, saved_modes);
ahd->flags |= AHD_UPDATE_PEND_CMDS;
}
/*
* Determine if an SCB for a packetized transaction
* is active in a FIFO.
*/
static int
ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb)
{
/*
* The FIFO is only active for our transaction if
* the SCBPTR matches the SCB's ID and the firmware
* has installed a handler for the FIFO or we have
* a pending SAVEPTRS or CFG4DATA interrupt.
*/
if (ahd_get_scbptr(ahd) != SCB_GET_TAG(scb)
|| ((ahd_inb(ahd, LONGJMP_ADDR+1) & INVALID_ADDR) != 0
&& (ahd_inb(ahd, SEQINTSRC) & (CFG4DATA|SAVEPTRS)) == 0))
return (0);
return (1);
}
/*
* Run a data fifo to completion for a transaction we know
* has completed across the SCSI bus (good status has been
* received). We are already set to the correct FIFO mode
* on entry to this routine.
*
* This function attempts to operate exactly as the firmware
* would when running this FIFO. Care must be taken to update
* this routine any time the firmware's FIFO algorithm is
* changed.
*/
static void
ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb)
{
u_int seqintsrc;
seqintsrc = ahd_inb(ahd, SEQINTSRC);
if ((seqintsrc & CFG4DATA) != 0) {
uint32_t datacnt;
uint32_t sgptr;
/*
* Clear full residual flag.
*/
sgptr = ahd_inl_scbram(ahd, SCB_SGPTR) & ~SG_FULL_RESID;
ahd_outb(ahd, SCB_SGPTR, sgptr);
/*
* Load datacnt and address.
*/
datacnt = ahd_inl_scbram(ahd, SCB_DATACNT);
if ((datacnt & AHD_DMA_LAST_SEG) != 0) {
sgptr |= LAST_SEG;
ahd_outb(ahd, SG_STATE, 0);
} else
ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
ahd_outq(ahd, HADDR, ahd_inq_scbram(ahd, SCB_DATAPTR));
ahd_outl(ahd, HCNT, datacnt & AHD_SG_LEN_MASK);
ahd_outb(ahd, SG_CACHE_PRE, sgptr);
ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
/*
* Initialize Residual Fields.
*/
ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, datacnt >> 24);
ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr & SG_PTR_MASK);
/*
* Mark the SCB as having a FIFO in use.
*/
ahd_outb(ahd, SCB_FIFO_USE_COUNT,
ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) + 1);
/*
* Install a "fake" handler for this FIFO.
*/
ahd_outw(ahd, LONGJMP_ADDR, 0);
/*
* Notify the hardware that we have satisfied
* this sequencer interrupt.
*/
ahd_outb(ahd, CLRSEQINTSRC, CLRCFG4DATA);
} else if ((seqintsrc & SAVEPTRS) != 0) {
uint32_t sgptr;
uint32_t resid;
if ((ahd_inb(ahd, LONGJMP_ADDR+1)&INVALID_ADDR) != 0) {
/*
* Snapshot Save Pointers. All that
* is necessary to clear the snapshot
* is a CLRCHN.
*/
goto clrchn;
}
/*
* Disable S/G fetch so the DMA engine
* is available to future users.
*/
if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
ahd_outb(ahd, CCSGCTL, 0);
ahd_outb(ahd, SG_STATE, 0);
/*
* Flush the data FIFO. Strickly only
* necessary for Rev A parts.
*/
ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) | FIFOFLUSH);
/*
* Calculate residual.
*/
sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
resid = ahd_inl(ahd, SHCNT);
resid |= ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT+3) << 24;
ahd_outl(ahd, SCB_RESIDUAL_DATACNT, resid);
if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG) == 0) {
/*
* Must back up to the correct S/G element.
* Typically this just means resetting our
* low byte to the offset in the SG_CACHE,
* but if we wrapped, we have to correct
* the other bytes of the sgptr too.
*/
if ((ahd_inb(ahd, SG_CACHE_SHADOW) & 0x80) != 0
&& (sgptr & 0x80) == 0)
sgptr -= 0x100;
sgptr &= ~0xFF;
sgptr |= ahd_inb(ahd, SG_CACHE_SHADOW)
& SG_ADDR_MASK;
ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
ahd_outb(ahd, SCB_RESIDUAL_DATACNT + 3, 0);
} else if ((resid & AHD_SG_LEN_MASK) == 0) {
ahd_outb(ahd, SCB_RESIDUAL_SGPTR,
sgptr | SG_LIST_NULL);
}
/*
* Save Pointers.
*/
ahd_outq(ahd, SCB_DATAPTR, ahd_inq(ahd, SHADDR));
ahd_outl(ahd, SCB_DATACNT, resid);
ahd_outl(ahd, SCB_SGPTR, sgptr);
ahd_outb(ahd, CLRSEQINTSRC, CLRSAVEPTRS);
ahd_outb(ahd, SEQIMODE,
ahd_inb(ahd, SEQIMODE) | ENSAVEPTRS);
/*
* If the data is to the SCSI bus, we are
* done, otherwise wait for FIFOEMP.
*/
if ((ahd_inb(ahd, DFCNTRL) & DIRECTION) != 0)
goto clrchn;
} else if ((ahd_inb(ahd, SG_STATE) & LOADING_NEEDED) != 0) {
uint32_t sgptr;
uint64_t data_addr;
uint32_t data_len;
u_int dfcntrl;
/*
* Disable S/G fetch so the DMA engine
* is available to future users. We won't
* be using the DMA engine to load segments.
*/
if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) {
ahd_outb(ahd, CCSGCTL, 0);
ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
}
/*
* Wait for the DMA engine to notice that the
* host transfer is enabled and that there is
* space in the S/G FIFO for new segments before
* loading more segments.
*/
if ((ahd_inb(ahd, DFSTATUS) & PRELOAD_AVAIL) != 0
&& (ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) {
/*
* Determine the offset of the next S/G
* element to load.
*/
sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
sgptr &= SG_PTR_MASK;
if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
struct ahd_dma64_seg *sg;
sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
data_addr = sg->addr;
data_len = sg->len;
sgptr += sizeof(*sg);
} else {
struct ahd_dma_seg *sg;
sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
data_addr = sg->len & AHD_SG_HIGH_ADDR_MASK;
data_addr <<= 8;
data_addr |= sg->addr;
data_len = sg->len;
sgptr += sizeof(*sg);
}
/*
* Update residual information.
*/
ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, data_len >> 24);
ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
/*
* Load the S/G.
*/
if (data_len & AHD_DMA_LAST_SEG) {
sgptr |= LAST_SEG;
ahd_outb(ahd, SG_STATE, 0);
}
ahd_outq(ahd, HADDR, data_addr);
ahd_outl(ahd, HCNT, data_len & AHD_SG_LEN_MASK);
ahd_outb(ahd, SG_CACHE_PRE, sgptr & 0xFF);
/*
* Advertise the segment to the hardware.
*/
dfcntrl = ahd_inb(ahd, DFCNTRL)|PRELOADEN|HDMAEN;
if ((ahd->features & AHD_NEW_DFCNTRL_OPTS) != 0) {
/*
* Use SCSIENWRDIS so that SCSIEN
* is never modified by this
* operation.
*/
dfcntrl |= SCSIENWRDIS;
}
ahd_outb(ahd, DFCNTRL, dfcntrl);
}
} else if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG_DONE) != 0) {
/*
* Transfer completed to the end of SG list
* and has flushed to the host.
*/
ahd_outb(ahd, SCB_SGPTR,
ahd_inb_scbram(ahd, SCB_SGPTR) | SG_LIST_NULL);
goto clrchn;
} else if ((ahd_inb(ahd, DFSTATUS) & FIFOEMP) != 0) {
clrchn:
/*
* Clear any handler for this FIFO, decrement
* the FIFO use count for the SCB, and release
* the FIFO.
*/
ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
ahd_outb(ahd, SCB_FIFO_USE_COUNT,
ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) - 1);
ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
}
}
/*
* Look for entries in the QoutFIFO that have completed.
* The valid_tag completion field indicates the validity
* of the entry - the valid value toggles each time through
* the queue. We use the sg_status field in the completion
* entry to avoid referencing the hscb if the completion
* occurred with no errors and no residual. sg_status is
* a copy of the first byte (little endian) of the sgptr
* hscb field.
*/
void
ahd_run_qoutfifo(struct ahd_softc *ahd)
{
struct ahd_completion *completion;
struct scb *scb;
u_int scb_index;
if ((ahd->flags & AHD_RUNNING_QOUTFIFO) != 0)
panic("ahd_run_qoutfifo recursion");
ahd->flags |= AHD_RUNNING_QOUTFIFO;
ahd_sync_qoutfifo(ahd, BUS_DMASYNC_POSTREAD);
for (;;) {
completion = &ahd->qoutfifo[ahd->qoutfifonext];
if (completion->valid_tag != ahd->qoutfifonext_valid_tag)
break;
scb_index = ahd_le16toh(completion->tag);
scb = ahd_lookup_scb(ahd, scb_index);
if (scb == NULL) {
printf("%s: WARNING no command for scb %d "
"(cmdcmplt)\nQOUTPOS = %d\n",
ahd_name(ahd), scb_index,
ahd->qoutfifonext);
ahd_dump_card_state(ahd);
} else if ((completion->sg_status & SG_STATUS_VALID) != 0) {
ahd_handle_scb_status(ahd, scb);
} else {
ahd_done(ahd, scb);
}
ahd->qoutfifonext = (ahd->qoutfifonext+1) & (AHD_QOUT_SIZE-1);
if (ahd->qoutfifonext == 0)
ahd->qoutfifonext_valid_tag ^= QOUTFIFO_ENTRY_VALID;
}
ahd->flags &= ~AHD_RUNNING_QOUTFIFO;
}
/************************* Interrupt Handling *********************************/
void
ahd_handle_hwerrint(struct ahd_softc *ahd)
{
/*
* Some catastrophic hardware error has occurred.
* Print it for the user and disable the controller.
*/
int i;
int error;
error = ahd_inb(ahd, ERROR);
for (i = 0; i < num_errors; i++) {
if ((error & ahd_hard_errors[i].errno) != 0)
printf("%s: hwerrint, %s\n",
ahd_name(ahd), ahd_hard_errors[i].errmesg);
}
ahd_dump_card_state(ahd);
panic("BRKADRINT");
/* Tell everyone that this HBA is no longer available */
ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
CAM_NO_HBA);
/* Tell the system that this controller has gone away. */
ahd_free(ahd);
}
#ifdef AHD_DEBUG
static void
ahd_dump_sglist(struct scb *scb)
{
int i;
if (scb->sg_count > 0) {
if ((scb->ahd_softc->flags & AHD_64BIT_ADDRESSING) != 0) {
struct ahd_dma64_seg *sg_list;
sg_list = (struct ahd_dma64_seg*)scb->sg_list;
for (i = 0; i < scb->sg_count; i++) {
uint64_t addr;
uint32_t len;
addr = ahd_le64toh(sg_list[i].addr);
len = ahd_le32toh(sg_list[i].len);
printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
i,
(uint32_t)((addr >> 32) & 0xFFFFFFFF),
(uint32_t)(addr & 0xFFFFFFFF),
sg_list[i].len & AHD_SG_LEN_MASK,
(sg_list[i].len & AHD_DMA_LAST_SEG)
? " Last" : "");
}
} else {
struct ahd_dma_seg *sg_list;
sg_list = (struct ahd_dma_seg*)scb->sg_list;
for (i = 0; i < scb->sg_count; i++) {
uint32_t len;
len = ahd_le32toh(sg_list[i].len);
printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
i,
(len & AHD_SG_HIGH_ADDR_MASK) >> 24,
ahd_le32toh(sg_list[i].addr),
len & AHD_SG_LEN_MASK,
len & AHD_DMA_LAST_SEG ? " Last" : "");
}
}
}
}
#endif /* AHD_DEBUG */
void
ahd_handle_seqint(struct ahd_softc *ahd, u_int intstat)
{
u_int seqintcode;
/*
* Save the sequencer interrupt code and clear the SEQINT
* bit. We will unpause the sequencer, if appropriate,
* after servicing the request.
*/
seqintcode = ahd_inb(ahd, SEQINTCODE);
ahd_outb(ahd, CLRINT, CLRSEQINT);
if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
/*
* Unpause the sequencer and let it clear
* SEQINT by writing NO_SEQINT to it. This
* will cause the sequencer to be paused again,
* which is the expected state of this routine.
*/
ahd_unpause(ahd);
while (!ahd_is_paused(ahd))
;
ahd_outb(ahd, CLRINT, CLRSEQINT);
}
ahd_update_modes(ahd);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("%s: Handle Seqint Called for code %d\n",
ahd_name(ahd), seqintcode);
#endif
switch (seqintcode) {
case ENTERING_NONPACK:
{
struct scb *scb;
u_int scbid;
AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
/*
* Somehow need to know if this
* is from a selection or reselection.
* From that, we can determine target
* ID so we at least have an I_T nexus.
*/
} else {
ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
ahd_outb(ahd, SAVED_LUN, scb->hscb->lun);
ahd_outb(ahd, SEQ_FLAGS, 0x0);
}
if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0
&& (ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
/*
* Phase change after read stream with
* CRC error with P0 asserted on last
* packet.
*/
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
printf("%s: Assuming LQIPHASE_NLQ with "
"P0 assertion\n", ahd_name(ahd));
#endif
}
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
printf("%s: Entering NONPACK\n", ahd_name(ahd));
#endif
break;
}
case INVALID_SEQINT:
printf("%s: Invalid Sequencer interrupt occurred, "
"resetting channel.\n",
ahd_name(ahd));
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
ahd_dump_card_state(ahd);
#endif
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
break;
case STATUS_OVERRUN:
{
struct scb *scb;
u_int scbid;
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL)
ahd_print_path(ahd, scb);
else
printf("%s: ", ahd_name(ahd));
printf("SCB %d Packetized Status Overrun", scbid);
ahd_dump_card_state(ahd);
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
break;
}
case CFG4ISTAT_INTR:
{
struct scb *scb;
u_int scbid;
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
ahd_dump_card_state(ahd);
printf("CFG4ISTAT: Free SCB %d referenced", scbid);
panic("For safety");
}
ahd_outq(ahd, HADDR, scb->sense_busaddr);
ahd_outw(ahd, HCNT, AHD_SENSE_BUFSIZE);
ahd_outb(ahd, HCNT + 2, 0);
ahd_outb(ahd, SG_CACHE_PRE, SG_LAST_SEG);
ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
break;
}
case ILLEGAL_PHASE:
{
u_int bus_phase;
bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
printf("%s: ILLEGAL_PHASE 0x%x\n",
ahd_name(ahd), bus_phase);
switch (bus_phase) {
case P_DATAOUT:
case P_DATAIN:
case P_DATAOUT_DT:
case P_DATAIN_DT:
case P_MESGOUT:
case P_STATUS:
case P_MESGIN:
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
printf("%s: Issued Bus Reset.\n", ahd_name(ahd));
break;
case P_COMMAND:
{
struct ahd_devinfo devinfo;
struct scb *scb;
struct ahd_initiator_tinfo *targ_info;
struct ahd_tmode_tstate *tstate;
struct ahd_transinfo *tinfo;
u_int scbid;
/*
* If a target takes us into the command phase
* assume that it has been externally reset and
* has thus lost our previous packetized negotiation
* agreement. Since we have not sent an identify
* message and may not have fully qualified the
* connection, we change our command to TUR, assert
* ATN and ABORT the task when we go to message in
* phase. The OSM will see the REQUEUE_REQUEST
* status and retry the command.
*/
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("Invalid phase with no valid SCB. "
"Resetting bus.\n");
ahd_reset_channel(ahd, 'A',
/*Initiate Reset*/TRUE);
break;
}
ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
SCB_GET_TARGET(ahd, scb),
SCB_GET_LUN(scb),
SCB_GET_CHANNEL(ahd, scb),
ROLE_INITIATOR);
targ_info = ahd_fetch_transinfo(ahd,
devinfo.channel,
devinfo.our_scsiid,
devinfo.target,
&tstate);
tinfo = &targ_info->curr;
ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_ACTIVE, /*paused*/TRUE);
ahd_set_syncrate(ahd, &devinfo, /*period*/0,
/*offset*/0, /*ppr_options*/0,
AHD_TRANS_ACTIVE, /*paused*/TRUE);
/* Hand-craft TUR command */
ahd_outb(ahd, SCB_CDB_STORE, 0);
ahd_outb(ahd, SCB_CDB_STORE+1, 0);
ahd_outb(ahd, SCB_CDB_STORE+2, 0);
ahd_outb(ahd, SCB_CDB_STORE+3, 0);
ahd_outb(ahd, SCB_CDB_STORE+4, 0);
ahd_outb(ahd, SCB_CDB_STORE+5, 0);
ahd_outb(ahd, SCB_CDB_LEN, 6);
scb->hscb->control &= ~(TAG_ENB|SCB_TAG_TYPE);
scb->hscb->control |= MK_MESSAGE;
ahd_outb(ahd, SCB_CONTROL, scb->hscb->control);
ahd_outb(ahd, MSG_OUT, HOST_MSG);
ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
/*
* The lun is 0, regardless of the SCB's lun
* as we have not sent an identify message.
*/
ahd_outb(ahd, SAVED_LUN, 0);
ahd_outb(ahd, SEQ_FLAGS, 0);
ahd_assert_atn(ahd);
scb->flags &= ~SCB_PACKETIZED;
scb->flags |= SCB_ABORT|SCB_EXTERNAL_RESET;
ahd_freeze_devq(ahd, scb);
ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
ahd_freeze_scb(scb);
/* Notify XPT */
ahd_send_async(ahd, devinfo.channel, devinfo.target,
CAM_LUN_WILDCARD, AC_SENT_BDR);
/*
* Allow the sequencer to continue with
* non-pack processing.
*/
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, CLRLQOINT1, CLRLQOPHACHGINPKT);
if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
ahd_outb(ahd, CLRLQOINT1, 0);
}
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
ahd_print_path(ahd, scb);
printf("Unexpected command phase from "
"packetized target\n");
}
#endif
break;
}
}
break;
}
case CFG4OVERRUN:
{
struct scb *scb;
u_int scb_index;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
printf("%s: CFG4OVERRUN mode = %x\n", ahd_name(ahd),
ahd_inb(ahd, MODE_PTR));
}
#endif
scb_index = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scb_index);
if (scb == NULL) {
/*
* Attempt to transfer to an SCB that is
* not outstanding.
*/
ahd_assert_atn(ahd);
ahd_outb(ahd, MSG_OUT, HOST_MSG);
ahd->msgout_buf[0] = MSG_ABORT_TASK;
ahd->msgout_len = 1;
ahd->msgout_index = 0;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
/*
* Clear status received flag to prevent any
* attempt to complete this bogus SCB.
*/
ahd_outb(ahd, SCB_CONTROL,
ahd_inb_scbram(ahd, SCB_CONTROL)
& ~STATUS_RCVD);
}
break;
}
case DUMP_CARD_STATE:
{
ahd_dump_card_state(ahd);
break;
}
case PDATA_REINIT:
{
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
printf("%s: PDATA_REINIT - DFCNTRL = 0x%x "
"SG_CACHE_SHADOW = 0x%x\n",
ahd_name(ahd), ahd_inb(ahd, DFCNTRL),
ahd_inb(ahd, SG_CACHE_SHADOW));
}
#endif
ahd_reinitialize_dataptrs(ahd);
break;
}
case HOST_MSG_LOOP:
{
struct ahd_devinfo devinfo;
/*
* The sequencer has encountered a message phase
* that requires host assistance for completion.
* While handling the message phase(s), we will be
* notified by the sequencer after each byte is
* transfered so we can track bus phase changes.
*
* If this is the first time we've seen a HOST_MSG_LOOP
* interrupt, initialize the state of the host message
* loop.
*/
ahd_fetch_devinfo(ahd, &devinfo);
if (ahd->msg_type == MSG_TYPE_NONE) {
struct scb *scb;
u_int scb_index;
u_int bus_phase;
bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
if (bus_phase != P_MESGIN
&& bus_phase != P_MESGOUT) {
printf("ahd_intr: HOST_MSG_LOOP bad "
"phase 0x%x\n", bus_phase);
/*
* Probably transitioned to bus free before
* we got here. Just punt the message.
*/
ahd_dump_card_state(ahd);
ahd_clear_intstat(ahd);
ahd_restart(ahd);
return;
}
scb_index = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scb_index);
if (devinfo.role == ROLE_INITIATOR) {
if (bus_phase == P_MESGOUT)
ahd_setup_initiator_msgout(ahd,
&devinfo,
scb);
else {
ahd->msg_type =
MSG_TYPE_INITIATOR_MSGIN;
ahd->msgin_index = 0;
}
}
#ifdef AHD_TARGET_MODE
else {
if (bus_phase == P_MESGOUT) {
ahd->msg_type =
MSG_TYPE_TARGET_MSGOUT;
ahd->msgin_index = 0;
}
else
ahd_setup_target_msgin(ahd,
&devinfo,
scb);
}
#endif
}
ahd_handle_message_phase(ahd);
break;
}
case NO_MATCH:
{
/* Ensure we don't leave the selection hardware on */
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
printf("%s:%c:%d: no active SCB for reconnecting "
"target - issuing BUS DEVICE RESET\n",
ahd_name(ahd), 'A', ahd_inb(ahd, SELID) >> 4);
printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
"REG0 == 0x%x ACCUM = 0x%x\n",
ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN),
ahd_inw(ahd, REG0), ahd_inb(ahd, ACCUM));
printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
"SINDEX == 0x%x\n",
ahd_inb(ahd, SEQ_FLAGS), ahd_get_scbptr(ahd),
ahd_find_busy_tcl(ahd,
BUILD_TCL(ahd_inb(ahd, SAVED_SCSIID),
ahd_inb(ahd, SAVED_LUN))),
ahd_inw(ahd, SINDEX));
printf("SELID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
"SCB_CONTROL == 0x%x\n",
ahd_inb(ahd, SELID), ahd_inb_scbram(ahd, SCB_SCSIID),
ahd_inb_scbram(ahd, SCB_LUN),
ahd_inb_scbram(ahd, SCB_CONTROL));
printf("SCSIBUS[0] == 0x%x, SCSISIGI == 0x%x\n",
ahd_inb(ahd, SCSIBUS), ahd_inb(ahd, SCSISIGI));
printf("SXFRCTL0 == 0x%x\n", ahd_inb(ahd, SXFRCTL0));
printf("SEQCTL0 == 0x%x\n", ahd_inb(ahd, SEQCTL0));
ahd_dump_card_state(ahd);
ahd->msgout_buf[0] = MSG_BUS_DEV_RESET;
ahd->msgout_len = 1;
ahd->msgout_index = 0;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
ahd_outb(ahd, MSG_OUT, HOST_MSG);
ahd_assert_atn(ahd);
break;
}
case PROTO_VIOLATION:
{
ahd_handle_proto_violation(ahd);
break;
}
case IGN_WIDE_RES:
{
struct ahd_devinfo devinfo;
ahd_fetch_devinfo(ahd, &devinfo);
ahd_handle_ign_wide_residue(ahd, &devinfo);
break;
}
case BAD_PHASE:
{
u_int lastphase;
lastphase = ahd_inb(ahd, LASTPHASE);
printf("%s:%c:%d: unknown scsi bus phase %x, "
"lastphase = 0x%x. Attempting to continue\n",
ahd_name(ahd), 'A',
SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
lastphase, ahd_inb(ahd, SCSISIGI));
break;
}
case MISSED_BUSFREE:
{
u_int lastphase;
lastphase = ahd_inb(ahd, LASTPHASE);
printf("%s:%c:%d: Missed busfree. "
"Lastphase = 0x%x, Curphase = 0x%x\n",
ahd_name(ahd), 'A',
SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
lastphase, ahd_inb(ahd, SCSISIGI));
ahd_restart(ahd);
return;
}
case DATA_OVERRUN:
{
/*
* When the sequencer detects an overrun, it
* places the controller in "BITBUCKET" mode
* and allows the target to complete its transfer.
* Unfortunately, none of the counters get updated
* when the controller is in this mode, so we have
* no way of knowing how large the overrun was.
*/
struct scb *scb;
u_int scbindex;
#ifdef AHD_DEBUG
u_int lastphase;
#endif
scbindex = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbindex);
#ifdef AHD_DEBUG
lastphase = ahd_inb(ahd, LASTPHASE);
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
ahd_print_path(ahd, scb);
printf("data overrun detected %s. Tag == 0x%x.\n",
ahd_lookup_phase_entry(lastphase)->phasemsg,
SCB_GET_TAG(scb));
ahd_print_path(ahd, scb);
printf("%s seen Data Phase. Length = %ld. "
"NumSGs = %d.\n",
ahd_inb(ahd, SEQ_FLAGS) & DPHASE
? "Have" : "Haven't",
ahd_get_transfer_length(scb), scb->sg_count);
ahd_dump_sglist(scb);
}
#endif
/*
* Set this and it will take effect when the
* target does a command complete.
*/
ahd_freeze_devq(ahd, scb);
ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
ahd_freeze_scb(scb);
break;
}
case MKMSG_FAILED:
{
struct ahd_devinfo devinfo;
struct scb *scb;
u_int scbid;
ahd_fetch_devinfo(ahd, &devinfo);
printf("%s:%c:%d:%d: Attempt to issue message failed\n",
ahd_name(ahd), devinfo.channel, devinfo.target,
devinfo.lun);
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL
&& (scb->flags & SCB_RECOVERY_SCB) != 0)
/*
* Ensure that we didn't put a second instance of this
* SCB into the QINFIFO.
*/
ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
SCB_GET_CHANNEL(ahd, scb),
SCB_GET_LUN(scb), SCB_GET_TAG(scb),
ROLE_INITIATOR, /*status*/0,
SEARCH_REMOVE);
ahd_outb(ahd, SCB_CONTROL,
ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
break;
}
case TASKMGMT_FUNC_COMPLETE:
{
u_int scbid;
struct scb *scb;
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL) {
u_int lun;
u_int tag;
cam_status error;
ahd_print_path(ahd, scb);
printf("Task Management Func 0x%x Complete\n",
scb->hscb->task_management);
lun = CAM_LUN_WILDCARD;
tag = SCB_LIST_NULL;
switch (scb->hscb->task_management) {
case SIU_TASKMGMT_ABORT_TASK:
tag = SCB_GET_TAG(scb);
case SIU_TASKMGMT_ABORT_TASK_SET:
case SIU_TASKMGMT_CLEAR_TASK_SET:
lun = scb->hscb->lun;
error = CAM_REQ_ABORTED;
ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
'A', lun, tag, ROLE_INITIATOR,
error);
break;
case SIU_TASKMGMT_LUN_RESET:
lun = scb->hscb->lun;
case SIU_TASKMGMT_TARGET_RESET:
{
struct ahd_devinfo devinfo;
ahd_scb_devinfo(ahd, &devinfo, scb);
error = CAM_BDR_SENT;
ahd_handle_devreset(ahd, &devinfo, lun,
CAM_BDR_SENT,
lun != CAM_LUN_WILDCARD
? "Lun Reset"
: "Target Reset",
/*verbose_level*/0);
break;
}
default:
panic("Unexpected TaskMgmt Func\n");
break;
}
}
break;
}
case TASKMGMT_CMD_CMPLT_OKAY:
{
u_int scbid;
struct scb *scb;
/*
* An ABORT TASK TMF failed to be delivered before
* the targeted command completed normally.
*/
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL) {
/*
* Remove the second instance of this SCB from
* the QINFIFO if it is still there.
*/
ahd_print_path(ahd, scb);
printf("SCB completes before TMF\n");
/*
* Handle losing the race. Wait until any
* current selection completes. We will then
* set the TMF back to zero in this SCB so that
* the sequencer doesn't bother to issue another
* sequencer interrupt for its completion.
*/
while ((ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
&& (ahd_inb(ahd, SSTAT0) & SELDO) == 0
&& (ahd_inb(ahd, SSTAT1) & SELTO) == 0)
;
ahd_outb(ahd, SCB_TASK_MANAGEMENT, 0);
ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
SCB_GET_CHANNEL(ahd, scb),
SCB_GET_LUN(scb), SCB_GET_TAG(scb),
ROLE_INITIATOR, /*status*/0,
SEARCH_REMOVE);
}
break;
}
case TRACEPOINT0:
case TRACEPOINT1:
case TRACEPOINT2:
case TRACEPOINT3:
printf("%s: Tracepoint %d\n", ahd_name(ahd),
seqintcode - TRACEPOINT0);
break;
case NO_SEQINT:
break;
case SAW_HWERR:
ahd_handle_hwerrint(ahd);
break;
default:
printf("%s: Unexpected SEQINTCODE %d\n", ahd_name(ahd),
seqintcode);
break;
}
/*
* The sequencer is paused immediately on
* a SEQINT, so we should restart it when
* we're done.
*/
ahd_unpause(ahd);
}
void
ahd_handle_scsiint(struct ahd_softc *ahd, u_int intstat)
{
struct scb *scb;
u_int status0;
u_int status3;
u_int status;
u_int lqistat1;
u_int lqostat0;
u_int scbid;
u_int busfreetime;
ahd_update_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
status3 = ahd_inb(ahd, SSTAT3) & (NTRAMPERR|OSRAMPERR);
status0 = ahd_inb(ahd, SSTAT0) & (IOERR|OVERRUN|SELDI|SELDO);
status = ahd_inb(ahd, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
lqistat1 = ahd_inb(ahd, LQISTAT1);
lqostat0 = ahd_inb(ahd, LQOSTAT0);
busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
/*
* Ignore external resets after a bus reset.
*/
if (((status & SCSIRSTI) != 0) && (ahd->flags & AHD_BUS_RESET_ACTIVE)) {
ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
return;
}
/*
* Clear bus reset flag
*/
ahd->flags &= ~AHD_BUS_RESET_ACTIVE;
if ((status0 & (SELDI|SELDO)) != 0) {
u_int simode0;
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
simode0 = ahd_inb(ahd, SIMODE0);
status0 &= simode0 & (IOERR|OVERRUN|SELDI|SELDO);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
}
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL
&& (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
scb = NULL;
if ((status0 & IOERR) != 0) {
u_int now_lvd;
now_lvd = ahd_inb(ahd, SBLKCTL) & ENAB40;
printf("%s: Transceiver State Has Changed to %s mode\n",
ahd_name(ahd), now_lvd ? "LVD" : "SE");
ahd_outb(ahd, CLRSINT0, CLRIOERR);
/*
* A change in I/O mode is equivalent to a bus reset.
*/
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
ahd_pause(ahd);
ahd_setup_iocell_workaround(ahd);
ahd_unpause(ahd);
} else if ((status0 & OVERRUN) != 0) {
printf("%s: SCSI offset overrun detected. Resetting bus.\n",
ahd_name(ahd));
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
} else if ((status & SCSIRSTI) != 0) {
printf("%s: Someone reset channel A\n", ahd_name(ahd));
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/FALSE);
} else if ((status & SCSIPERR) != 0) {
/* Make sure the sequencer is in a safe location. */
ahd_clear_critical_section(ahd);
ahd_handle_transmission_error(ahd);
} else if (lqostat0 != 0) {
printf("%s: lqostat0 == 0x%x!\n", ahd_name(ahd), lqostat0);
ahd_outb(ahd, CLRLQOINT0, lqostat0);
if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
ahd_outb(ahd, CLRLQOINT1, 0);
} else if ((status & SELTO) != 0) {
u_int scbid;
/* Stop the selection */
ahd_outb(ahd, SCSISEQ0, 0);
/* Make sure the sequencer is in a safe location. */
ahd_clear_critical_section(ahd);
/* No more pending messages */
ahd_clear_msg_state(ahd);
/* Clear interrupt state */
ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
/*
* Although the driver does not care about the
* 'Selection in Progress' status bit, the busy
* LED does. SELINGO is only cleared by a sucessfull
* selection, so we must manually clear it to insure
* the LED turns off just incase no future successful
* selections occur (e.g. no devices on the bus).
*/
ahd_outb(ahd, CLRSINT0, CLRSELINGO);
scbid = ahd_inw(ahd, WAITING_TID_HEAD);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: ahd_intr - referenced scb not "
"valid during SELTO scb(0x%x)\n",
ahd_name(ahd), scbid);
ahd_dump_card_state(ahd);
} else {
struct ahd_devinfo devinfo;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_SELTO) != 0) {
ahd_print_path(ahd, scb);
printf("Saw Selection Timeout for SCB 0x%x\n",
scbid);
}
#endif
ahd_scb_devinfo(ahd, &devinfo, scb);
ahd_set_transaction_status(scb, CAM_SEL_TIMEOUT);
ahd_freeze_devq(ahd, scb);
/*
* Cancel any pending transactions on the device
* now that it seems to be missing. This will
* also revert us to async/narrow transfers until
* we can renegotiate with the device.
*/
ahd_handle_devreset(ahd, &devinfo,
CAM_LUN_WILDCARD,
CAM_SEL_TIMEOUT,
"Selection Timeout",
/*verbose_level*/1);
}
ahd_outb(ahd, CLRINT, CLRSCSIINT);
ahd_iocell_first_selection(ahd);
ahd_unpause(ahd);
} else if ((status0 & (SELDI|SELDO)) != 0) {
ahd_iocell_first_selection(ahd);
ahd_unpause(ahd);
} else if (status3 != 0) {
printf("%s: SCSI Cell parity error SSTAT3 == 0x%x\n",
ahd_name(ahd), status3);
ahd_outb(ahd, CLRSINT3, status3);
} else if ((lqistat1 & (LQIPHASE_LQ|LQIPHASE_NLQ)) != 0) {
/* Make sure the sequencer is in a safe location. */
ahd_clear_critical_section(ahd);
ahd_handle_lqiphase_error(ahd, lqistat1);
} else if ((lqistat1 & LQICRCI_NLQ) != 0) {
/*
* This status can be delayed during some
* streaming operations. The SCSIPHASE
* handler has already dealt with this case
* so just clear the error.
*/
ahd_outb(ahd, CLRLQIINT1, CLRLQICRCI_NLQ);
} else if ((status & BUSFREE) != 0
|| (lqistat1 & LQOBUSFREE) != 0) {
u_int lqostat1;
int restart;
int clear_fifo;
int packetized;
u_int mode;
/*
* Clear our selection hardware as soon as possible.
* We may have an entry in the waiting Q for this target,
* that is affected by this busfree and we don't want to
* go about selecting the target while we handle the event.
*/
ahd_outb(ahd, SCSISEQ0, 0);
/* Make sure the sequencer is in a safe location. */
ahd_clear_critical_section(ahd);
/*
* Determine what we were up to at the time of
* the busfree.
*/
mode = AHD_MODE_SCSI;
busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
lqostat1 = ahd_inb(ahd, LQOSTAT1);
switch (busfreetime) {
case BUSFREE_DFF0:
case BUSFREE_DFF1:
{
u_int scbid;
struct scb *scb;
mode = busfreetime == BUSFREE_DFF0
? AHD_MODE_DFF0 : AHD_MODE_DFF1;
ahd_set_modes(ahd, mode, mode);
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: Invalid SCB %d in DFF%d "
"during unexpected busfree\n",
ahd_name(ahd), scbid, mode);
packetized = 0;
} else
packetized = (scb->flags & SCB_PACKETIZED) != 0;
clear_fifo = 1;
break;
}
case BUSFREE_LQO:
clear_fifo = 0;
packetized = 1;
break;
default:
clear_fifo = 0;
packetized = (lqostat1 & LQOBUSFREE) != 0;
if (!packetized
&& ahd_inb(ahd, LASTPHASE) == P_BUSFREE
&& (ahd_inb(ahd, SSTAT0) & SELDI) == 0
&& ((ahd_inb(ahd, SSTAT0) & SELDO) == 0
|| (ahd_inb(ahd, SCSISEQ0) & ENSELO) == 0))
/*
* Assume packetized if we are not
* on the bus in a non-packetized
* capacity and any pending selection
* was a packetized selection.
*/
packetized = 1;
break;
}
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("Saw Busfree. Busfreetime = 0x%x.\n",
busfreetime);
#endif
/*
* Busfrees that occur in non-packetized phases are
* handled by the nonpkt_busfree handler.
*/
if (packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE) {
restart = ahd_handle_pkt_busfree(ahd, busfreetime);
} else {
packetized = 0;
restart = ahd_handle_nonpkt_busfree(ahd);
}
/*
* Clear the busfree interrupt status. The setting of
* the interrupt is a pulse, so in a perfect world, we
* would not need to muck with the ENBUSFREE logic. This
* would ensure that if the bus moves on to another
* connection, busfree protection is still in force. If
* BUSFREEREV is broken, however, we must manually clear
* the ENBUSFREE if the busfree occurred during a non-pack
* connection so that we don't get false positives during
* future, packetized, connections.
*/
ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
if (packetized == 0
&& (ahd->bugs & AHD_BUSFREEREV_BUG) != 0)
ahd_outb(ahd, SIMODE1,
ahd_inb(ahd, SIMODE1) & ~ENBUSFREE);
if (clear_fifo)
ahd_clear_fifo(ahd, mode);
ahd_clear_msg_state(ahd);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
if (restart) {
ahd_restart(ahd);
} else {
ahd_unpause(ahd);
}
} else {
printf("%s: Missing case in ahd_handle_scsiint. status = %x\n",
ahd_name(ahd), status);
ahd_dump_card_state(ahd);
ahd_clear_intstat(ahd);
ahd_unpause(ahd);
}
}
static void
ahd_handle_transmission_error(struct ahd_softc *ahd)
{
struct scb *scb;
u_int scbid;
u_int lqistat1;
u_int lqistat2;
u_int msg_out;
u_int curphase;
u_int lastphase;
u_int perrdiag;
u_int cur_col;
int silent;
scb = NULL;
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
lqistat1 = ahd_inb(ahd, LQISTAT1) & ~(LQIPHASE_LQ|LQIPHASE_NLQ);
lqistat2 = ahd_inb(ahd, LQISTAT2);
if ((lqistat1 & (LQICRCI_NLQ|LQICRCI_LQ)) == 0
&& (ahd->bugs & AHD_NLQICRC_DELAYED_BUG) != 0) {
u_int lqistate;
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
lqistate = ahd_inb(ahd, LQISTATE);
if ((lqistate >= 0x1E && lqistate <= 0x24)
|| (lqistate == 0x29)) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
printf("%s: NLQCRC found via LQISTATE\n",
ahd_name(ahd));
}
#endif
lqistat1 |= LQICRCI_NLQ;
}
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
}
ahd_outb(ahd, CLRLQIINT1, lqistat1);
lastphase = ahd_inb(ahd, LASTPHASE);
curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
perrdiag = ahd_inb(ahd, PERRDIAG);
msg_out = MSG_INITIATOR_DET_ERR;
ahd_outb(ahd, CLRSINT1, CLRSCSIPERR);
/*
* Try to find the SCB associated with this error.
*/
silent = FALSE;
if (lqistat1 == 0
|| (lqistat1 & LQICRCI_NLQ) != 0) {
if ((lqistat1 & (LQICRCI_NLQ|LQIOVERI_NLQ)) != 0)
ahd_set_active_fifo(ahd);
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL && SCB_IS_SILENT(scb))
silent = TRUE;
}
cur_col = 0;
if (silent == FALSE) {
printf("%s: Transmission error detected\n", ahd_name(ahd));
ahd_lqistat1_print(lqistat1, &cur_col, 50);
ahd_lastphase_print(lastphase, &cur_col, 50);
ahd_scsisigi_print(curphase, &cur_col, 50);
ahd_perrdiag_print(perrdiag, &cur_col, 50);
printf("\n");
ahd_dump_card_state(ahd);
}
if ((lqistat1 & (LQIOVERI_LQ|LQIOVERI_NLQ)) != 0) {
if (silent == FALSE) {
printf("%s: Gross protocol error during incoming "
"packet. lqistat1 == 0x%x. Resetting bus.\n",
ahd_name(ahd), lqistat1);
}
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
return;
} else if ((lqistat1 & LQICRCI_LQ) != 0) {
/*
* A CRC error has been detected on an incoming LQ.
* The bus is currently hung on the last ACK.
* Hit LQIRETRY to release the last ack, and
* wait for the sequencer to determine that ATNO
* is asserted while in message out to take us
* to our host message loop. No NONPACKREQ or
* LQIPHASE type errors will occur in this
* scenario. After this first LQIRETRY, the LQI
* manager will be in ISELO where it will
* happily sit until another packet phase begins.
* Unexpected bus free detection is enabled
* through any phases that occur after we release
* this last ack until the LQI manager sees a
* packet phase. This implies we may have to
* ignore a perfectly valid "unexected busfree"
* after our "initiator detected error" message is
* sent. A busfree is the expected response after
* we tell the target that it's L_Q was corrupted.
* (SPI4R09 10.7.3.3.3)
*/
ahd_outb(ahd, LQCTL2, LQIRETRY);
printf("LQIRetry for LQICRCI_LQ to release ACK\n");
} else if ((lqistat1 & LQICRCI_NLQ) != 0) {
/*
* We detected a CRC error in a NON-LQ packet.
* The hardware has varying behavior in this situation
* depending on whether this packet was part of a
* stream or not.
*
* PKT by PKT mode:
* The hardware has already acked the complete packet.
* If the target honors our outstanding ATN condition,
* we should be (or soon will be) in MSGOUT phase.
* This will trigger the LQIPHASE_LQ status bit as the
* hardware was expecting another LQ. Unexpected
* busfree detection is enabled. Once LQIPHASE_LQ is
* true (first entry into host message loop is much
* the same), we must clear LQIPHASE_LQ and hit
* LQIRETRY so the hardware is ready to handle
* a future LQ. NONPACKREQ will not be asserted again
* once we hit LQIRETRY until another packet is
* processed. The target may either go busfree
* or start another packet in response to our message.
*
* Read Streaming P0 asserted:
* If we raise ATN and the target completes the entire
* stream (P0 asserted during the last packet), the
* hardware will ack all data and return to the ISTART
* state. When the target reponds to our ATN condition,
* LQIPHASE_LQ will be asserted. We should respond to
* this with an LQIRETRY to prepare for any future
* packets. NONPACKREQ will not be asserted again
* once we hit LQIRETRY until another packet is
* processed. The target may either go busfree or
* start another packet in response to our message.
* Busfree detection is enabled.
*
* Read Streaming P0 not asserted:
* If we raise ATN and the target transitions to
* MSGOUT in or after a packet where P0 is not
* asserted, the hardware will assert LQIPHASE_NLQ.
* We should respond to the LQIPHASE_NLQ with an
* LQIRETRY. Should the target stay in a non-pkt
* phase after we send our message, the hardware
* will assert LQIPHASE_LQ. Recovery is then just as
* listed above for the read streaming with P0 asserted.
* Busfree detection is enabled.
*/
if (silent == FALSE)
printf("LQICRC_NLQ\n");
if (scb == NULL) {
printf("%s: No SCB valid for LQICRC_NLQ. "
"Resetting bus\n", ahd_name(ahd));
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
return;
}
} else if ((lqistat1 & LQIBADLQI) != 0) {
printf("Need to handle BADLQI!\n");
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
return;
} else if ((perrdiag & (PARITYERR|PREVPHASE)) == PARITYERR) {
if ((curphase & ~P_DATAIN_DT) != 0) {
/* Ack the byte. So we can continue. */
if (silent == FALSE)
printf("Acking %s to clear perror\n",
ahd_lookup_phase_entry(curphase)->phasemsg);
ahd_inb(ahd, SCSIDAT);
}
if (curphase == P_MESGIN)
msg_out = MSG_PARITY_ERROR;
}
/*
* We've set the hardware to assert ATN if we
* get a parity error on "in" phases, so all we
* need to do is stuff the message buffer with
* the appropriate message. "In" phases have set
* mesg_out to something other than MSG_NOP.
*/
ahd->send_msg_perror = msg_out;
if (scb != NULL && msg_out == MSG_INITIATOR_DET_ERR)
scb->flags |= SCB_TRANSMISSION_ERROR;
ahd_outb(ahd, MSG_OUT, HOST_MSG);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
ahd_unpause(ahd);
}
static void
ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1)
{
/*
* Clear the sources of the interrupts.
*/
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, CLRLQIINT1, lqistat1);
/*
* If the "illegal" phase changes were in response
* to our ATN to flag a CRC error, AND we ended up
* on packet boundaries, clear the error, restart the
* LQI manager as appropriate, and go on our merry
* way toward sending the message. Otherwise, reset
* the bus to clear the error.
*/
ahd_set_active_fifo(ahd);
if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0
&& (ahd_inb(ahd, MDFFSTAT) & DLZERO) != 0) {
if ((lqistat1 & LQIPHASE_LQ) != 0) {
printf("LQIRETRY for LQIPHASE_LQ\n");
ahd_outb(ahd, LQCTL2, LQIRETRY);
} else if ((lqistat1 & LQIPHASE_NLQ) != 0) {
printf("LQIRETRY for LQIPHASE_NLQ\n");
ahd_outb(ahd, LQCTL2, LQIRETRY);
} else
panic("ahd_handle_lqiphase_error: No phase errors\n");
ahd_dump_card_state(ahd);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
ahd_unpause(ahd);
} else {
printf("Reseting Channel for LQI Phase error\n");
ahd_dump_card_state(ahd);
ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
}
}
/*
* Packetized unexpected or expected busfree.
* Entered in mode based on busfreetime.
*/
static int
ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime)
{
u_int lqostat1;
AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
lqostat1 = ahd_inb(ahd, LQOSTAT1);
if ((lqostat1 & LQOBUSFREE) != 0) {
struct scb *scb;
u_int scbid;
u_int saved_scbptr;
u_int waiting_h;
u_int waiting_t;
u_int next;
/*
* The LQO manager detected an unexpected busfree
* either:
*
* 1) During an outgoing LQ.
* 2) After an outgoing LQ but before the first
* REQ of the command packet.
* 3) During an outgoing command packet.
*
* In all cases, CURRSCB is pointing to the
* SCB that encountered the failure. Clean
* up the queue, clear SELDO and LQOBUSFREE,
* and allow the sequencer to restart the select
* out at its lesure.
*/
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
scbid = ahd_inw(ahd, CURRSCB);
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL)
panic("SCB not valid during LQOBUSFREE");
/*
* Clear the status.
*/
ahd_outb(ahd, CLRLQOINT1, CLRLQOBUSFREE);
if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
ahd_outb(ahd, CLRLQOINT1, 0);
ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
ahd_flush_device_writes(ahd);
ahd_outb(ahd, CLRSINT0, CLRSELDO);
/*
* Return the LQO manager to its idle loop. It will
* not do this automatically if the busfree occurs
* after the first REQ of either the LQ or command
* packet or between the LQ and command packet.
*/
ahd_outb(ahd, LQCTL2, ahd_inb(ahd, LQCTL2) | LQOTOIDLE);
/*
* Update the waiting for selection queue so
* we restart on the correct SCB.
*/
waiting_h = ahd_inw(ahd, WAITING_TID_HEAD);
saved_scbptr = ahd_get_scbptr(ahd);
if (waiting_h != scbid) {
ahd_outw(ahd, WAITING_TID_HEAD, scbid);
waiting_t = ahd_inw(ahd, WAITING_TID_TAIL);
if (waiting_t == waiting_h) {
ahd_outw(ahd, WAITING_TID_TAIL, scbid);
next = SCB_LIST_NULL;
} else {
ahd_set_scbptr(ahd, waiting_h);
next = ahd_inw_scbram(ahd, SCB_NEXT2);
}
ahd_set_scbptr(ahd, scbid);
ahd_outw(ahd, SCB_NEXT2, next);
}
ahd_set_scbptr(ahd, saved_scbptr);
if (scb->crc_retry_count < AHD_MAX_LQ_CRC_ERRORS) {
if (SCB_IS_SILENT(scb) == FALSE) {
ahd_print_path(ahd, scb);
printf("Probable outgoing LQ CRC error. "
"Retrying command\n");
}
scb->crc_retry_count++;
} else {
ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
ahd_freeze_scb(scb);
ahd_freeze_devq(ahd, scb);
}
/* Return unpausing the sequencer. */
return (0);
} else if ((ahd_inb(ahd, PERRDIAG) & PARITYERR) != 0) {
/*
* Ignore what are really parity errors that
* occur on the last REQ of a free running
* clock prior to going busfree. Some drives
* do not properly active negate just before
* going busfree resulting in a parity glitch.
*/
ahd_outb(ahd, CLRSINT1, CLRSCSIPERR|CLRBUSFREE);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MASKED_ERRORS) != 0)
printf("%s: Parity on last REQ detected "
"during busfree phase.\n",
ahd_name(ahd));
#endif
/* Return unpausing the sequencer. */
return (0);
}
if (ahd->src_mode != AHD_MODE_SCSI) {
u_int scbid;
struct scb *scb;
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
ahd_print_path(ahd, scb);
printf("Unexpected PKT busfree condition\n");
ahd_dump_card_state(ahd);
ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A',
SCB_GET_LUN(scb), SCB_GET_TAG(scb),
ROLE_INITIATOR, CAM_UNEXP_BUSFREE);
/* Return restarting the sequencer. */
return (1);
}
printf("%s: Unexpected PKT busfree condition\n", ahd_name(ahd));
ahd_dump_card_state(ahd);
/* Restart the sequencer. */
return (1);
}
/*
* Non-packetized unexpected or expected busfree.
*/
static int
ahd_handle_nonpkt_busfree(struct ahd_softc *ahd)
{
struct ahd_devinfo devinfo;
struct scb *scb;
u_int lastphase;
u_int saved_scsiid;
u_int saved_lun;
u_int target;
u_int initiator_role_id;
u_int scbid;
u_int ppr_busfree;
int printerror;
/*
* Look at what phase we were last in. If its message out,
* chances are pretty good that the busfree was in response
* to one of our abort requests.
*/
lastphase = ahd_inb(ahd, LASTPHASE);
saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
saved_lun = ahd_inb(ahd, SAVED_LUN);
target = SCSIID_TARGET(ahd, saved_scsiid);
initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
ahd_compile_devinfo(&devinfo, initiator_role_id,
target, saved_lun, 'A', ROLE_INITIATOR);
printerror = 1;
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
if (scb != NULL
&& (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
scb = NULL;
ppr_busfree = (ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0;
if (lastphase == P_MESGOUT) {
u_int tag;
tag = SCB_LIST_NULL;
if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT_TAG, TRUE)
|| ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT, TRUE)) {
int found;
int sent_msg;
if (scb == NULL) {
ahd_print_devinfo(ahd, &devinfo);
printf("Abort for unidentified "
"connection completed.\n");
/* restart the sequencer. */
return (1);
}
sent_msg = ahd->msgout_buf[ahd->msgout_index - 1];
ahd_print_path(ahd, scb);
printf("SCB %d - Abort%s Completed.\n",
SCB_GET_TAG(scb),
sent_msg == MSG_ABORT_TAG ? "" : " Tag");
if (sent_msg == MSG_ABORT_TAG)
tag = SCB_GET_TAG(scb);
if ((scb->flags & SCB_EXTERNAL_RESET) != 0) {
/*
* This abort is in response to an
* unexpected switch to command phase
* for a packetized connection. Since
* the identify message was never sent,
* "saved lun" is 0. We really want to
* abort only the SCB that encountered
* this error, which could have a different
* lun. The SCB will be retried so the OS
* will see the UA after renegotiating to
* packetized.
*/
tag = SCB_GET_TAG(scb);
saved_lun = scb->hscb->lun;
}
found = ahd_abort_scbs(ahd, target, 'A', saved_lun,
tag, ROLE_INITIATOR,
CAM_REQ_ABORTED);
printf("found == 0x%x\n", found);
printerror = 0;
} else if (ahd_sent_msg(ahd, AHDMSG_1B,
MSG_BUS_DEV_RESET, TRUE)) {
#ifdef __FreeBSD__
/*
* Don't mark the user's request for this BDR
* as completing with CAM_BDR_SENT. CAM3
* specifies CAM_REQ_CMP.
*/
if (scb != NULL
&& scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
&& ahd_match_scb(ahd, scb, target, 'A',
CAM_LUN_WILDCARD, SCB_LIST_NULL,
ROLE_INITIATOR))
ahd_set_transaction_status(scb, CAM_REQ_CMP);
#endif
ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD,
CAM_BDR_SENT, "Bus Device Reset",
/*verbose_level*/0);
printerror = 0;
} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, FALSE)
&& ppr_busfree == 0) {
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
/*
* PPR Rejected.
*
* If the previous negotiation was packetized,
* this could be because the device has been
* reset without our knowledge. Force our
* current negotiation to async and retry the
* negotiation. Otherwise retry the command
* with non-ppr negotiation.
*/
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("PPR negotiation rejected busfree.\n");
#endif
tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
devinfo.our_scsiid,
devinfo.target, &tstate);
if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)!=0) {
ahd_set_width(ahd, &devinfo,
MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_CUR,
/*paused*/TRUE);
ahd_set_syncrate(ahd, &devinfo,
/*period*/0, /*offset*/0,
/*ppr_options*/0,
AHD_TRANS_CUR,
/*paused*/TRUE);
/*
* The expect PPR busfree handler below
* will effect the retry and necessary
* abort.
*/
} else {
tinfo->curr.transport_version = 2;
tinfo->goal.transport_version = 2;
tinfo->goal.ppr_options = 0;
/*
* Remove any SCBs in the waiting for selection
* queue that may also be for this target so
* that command ordering is preserved.
*/
ahd_freeze_devq(ahd, scb);
ahd_qinfifo_requeue_tail(ahd, scb);
printerror = 0;
}
} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, FALSE)
&& ppr_busfree == 0) {
/*
* Negotiation Rejected. Go-narrow and
* retry command.
*/
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("WDTR negotiation rejected busfree.\n");
#endif
ahd_set_width(ahd, &devinfo,
MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_CUR|AHD_TRANS_GOAL,
/*paused*/TRUE);
/*
* Remove any SCBs in the waiting for selection
* queue that may also be for this target so that
* command ordering is preserved.
*/
ahd_freeze_devq(ahd, scb);
ahd_qinfifo_requeue_tail(ahd, scb);
printerror = 0;
} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, FALSE)
&& ppr_busfree == 0) {
/*
* Negotiation Rejected. Go-async and
* retry command.
*/
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("SDTR negotiation rejected busfree.\n");
#endif
ahd_set_syncrate(ahd, &devinfo,
/*period*/0, /*offset*/0,
/*ppr_options*/0,
AHD_TRANS_CUR|AHD_TRANS_GOAL,
/*paused*/TRUE);
/*
* Remove any SCBs in the waiting for selection
* queue that may also be for this target so that
* command ordering is preserved.
*/
ahd_freeze_devq(ahd, scb);
ahd_qinfifo_requeue_tail(ahd, scb);
printerror = 0;
} else if ((ahd->msg_flags & MSG_FLAG_EXPECT_IDE_BUSFREE) != 0
&& ahd_sent_msg(ahd, AHDMSG_1B,
MSG_INITIATOR_DET_ERR, TRUE)) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("Expected IDE Busfree\n");
#endif
printerror = 0;
} else if ((ahd->msg_flags & MSG_FLAG_EXPECT_QASREJ_BUSFREE)
&& ahd_sent_msg(ahd, AHDMSG_1B,
MSG_MESSAGE_REJECT, TRUE)) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("Expected QAS Reject Busfree\n");
#endif
printerror = 0;
}
}
/*
* The busfree required flag is honored at the end of
* the message phases. We check it last in case we
* had to send some other message that caused a busfree.
*/
if (printerror != 0
&& (lastphase == P_MESGIN || lastphase == P_MESGOUT)
&& ((ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0)) {
ahd_freeze_devq(ahd, scb);
ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
ahd_freeze_scb(scb);
if ((ahd->msg_flags & MSG_FLAG_IU_REQ_CHANGED) != 0) {
ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
SCB_GET_CHANNEL(ahd, scb),
SCB_GET_LUN(scb), SCB_LIST_NULL,
ROLE_INITIATOR, CAM_REQ_ABORTED);
} else {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("PPR Negotiation Busfree.\n");
#endif
ahd_done(ahd, scb);
}
printerror = 0;
}
if (printerror != 0) {
int aborted;
aborted = 0;
if (scb != NULL) {
u_int tag;
if ((scb->hscb->control & TAG_ENB) != 0)
tag = SCB_GET_TAG(scb);
else
tag = SCB_LIST_NULL;
ahd_print_path(ahd, scb);
aborted = ahd_abort_scbs(ahd, target, 'A',
SCB_GET_LUN(scb), tag,
ROLE_INITIATOR,
CAM_UNEXP_BUSFREE);
} else {
/*
* We had not fully identified this connection,
* so we cannot abort anything.
*/
printf("%s: ", ahd_name(ahd));
}
printf("Unexpected busfree %s, %d SCBs aborted, "
"PRGMCNT == 0x%x\n",
ahd_lookup_phase_entry(lastphase)->phasemsg,
aborted,
ahd_inw(ahd, PRGMCNT));
ahd_dump_card_state(ahd);
if (lastphase != P_BUSFREE)
ahd_force_renegotiation(ahd, &devinfo);
}
/* Always restart the sequencer. */
return (1);
}
static void
ahd_handle_proto_violation(struct ahd_softc *ahd)
{
struct ahd_devinfo devinfo;
struct scb *scb;
u_int scbid;
u_int seq_flags;
u_int curphase;
u_int lastphase;
int found;
ahd_fetch_devinfo(ahd, &devinfo);
scbid = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scbid);
seq_flags = ahd_inb(ahd, SEQ_FLAGS);
curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
lastphase = ahd_inb(ahd, LASTPHASE);
if ((seq_flags & NOT_IDENTIFIED) != 0) {
/*
* The reconnecting target either did not send an
* identify message, or did, but we didn't find an SCB
* to match.
*/
ahd_print_devinfo(ahd, &devinfo);
printf("Target did not send an IDENTIFY message. "
"LASTPHASE = 0x%x.\n", lastphase);
scb = NULL;
} else if (scb == NULL) {
/*
* We don't seem to have an SCB active for this
* transaction. Print an error and reset the bus.
*/
ahd_print_devinfo(ahd, &devinfo);
printf("No SCB found during protocol violation\n");
goto proto_violation_reset;
} else {
ahd_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
if ((seq_flags & NO_CDB_SENT) != 0) {
ahd_print_path(ahd, scb);
printf("No or incomplete CDB sent to device.\n");
} else if ((ahd_inb_scbram(ahd, SCB_CONTROL)
& STATUS_RCVD) == 0) {
/*
* The target never bothered to provide status to
* us prior to completing the command. Since we don't
* know the disposition of this command, we must attempt
* to abort it. Assert ATN and prepare to send an abort
* message.
*/
ahd_print_path(ahd, scb);
printf("Completed command without status.\n");
} else {
ahd_print_path(ahd, scb);
printf("Unknown protocol violation.\n");
ahd_dump_card_state(ahd);
}
}
if ((lastphase & ~P_DATAIN_DT) == 0
|| lastphase == P_COMMAND) {
proto_violation_reset:
/*
* Target either went directly to data
* phase or didn't respond to our ATN.
* The only safe thing to do is to blow
* it away with a bus reset.
*/
found = ahd_reset_channel(ahd, 'A', TRUE);
printf("%s: Issued Channel %c Bus Reset. "
"%d SCBs aborted\n", ahd_name(ahd), 'A', found);
} else {
/*
* Leave the selection hardware off in case
* this abort attempt will affect yet to
* be sent commands.
*/
ahd_outb(ahd, SCSISEQ0,
ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
ahd_assert_atn(ahd);
ahd_outb(ahd, MSG_OUT, HOST_MSG);
if (scb == NULL) {
ahd_print_devinfo(ahd, &devinfo);
ahd->msgout_buf[0] = MSG_ABORT_TASK;
ahd->msgout_len = 1;
ahd->msgout_index = 0;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
} else {
ahd_print_path(ahd, scb);
scb->flags |= SCB_ABORT;
}
printf("Protocol violation %s. Attempting to abort.\n",
ahd_lookup_phase_entry(curphase)->phasemsg);
}
}
/*
* Force renegotiation to occur the next time we initiate
* a command to the current device.
*/
static void
ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
struct ahd_initiator_tinfo *targ_info;
struct ahd_tmode_tstate *tstate;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
ahd_print_devinfo(ahd, devinfo);
printf("Forcing renegotiation\n");
}
#endif
targ_info = ahd_fetch_transinfo(ahd,
devinfo->channel,
devinfo->our_scsiid,
devinfo->target,
&tstate);
ahd_update_neg_request(ahd, devinfo, tstate,
targ_info, AHD_NEG_IF_NON_ASYNC);
}
#define AHD_MAX_STEPS 2000
static void
ahd_clear_critical_section(struct ahd_softc *ahd)
{
ahd_mode_state saved_modes;
int stepping;
int steps;
int first_instr;
u_int simode0;
u_int simode1;
u_int simode3;
u_int lqimode0;
u_int lqimode1;
u_int lqomode0;
u_int lqomode1;
if (ahd->num_critical_sections == 0)
return;
stepping = FALSE;
steps = 0;
first_instr = 0;
simode0 = 0;
simode1 = 0;
simode3 = 0;
lqimode0 = 0;
lqimode1 = 0;
lqomode0 = 0;
lqomode1 = 0;
saved_modes = ahd_save_modes(ahd);
for (;;) {
struct cs *cs;
u_int seqaddr;
u_int i;
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
seqaddr = ahd_inw(ahd, CURADDR);
cs = ahd->critical_sections;
for (i = 0; i < ahd->num_critical_sections; i++, cs++) {
if (cs->begin < seqaddr && cs->end >= seqaddr)
break;
}
if (i == ahd->num_critical_sections)
break;
if (steps > AHD_MAX_STEPS) {
printf("%s: Infinite loop in critical section\n"
"%s: First Instruction 0x%x now 0x%x\n",
ahd_name(ahd), ahd_name(ahd), first_instr,
seqaddr);
ahd_dump_card_state(ahd);
panic("critical section loop");
}
steps++;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("%s: Single stepping at 0x%x\n", ahd_name(ahd),
seqaddr);
#endif
if (stepping == FALSE) {
first_instr = seqaddr;
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
simode0 = ahd_inb(ahd, SIMODE0);
simode3 = ahd_inb(ahd, SIMODE3);
lqimode0 = ahd_inb(ahd, LQIMODE0);
lqimode1 = ahd_inb(ahd, LQIMODE1);
lqomode0 = ahd_inb(ahd, LQOMODE0);
lqomode1 = ahd_inb(ahd, LQOMODE1);
ahd_outb(ahd, SIMODE0, 0);
ahd_outb(ahd, SIMODE3, 0);
ahd_outb(ahd, LQIMODE0, 0);
ahd_outb(ahd, LQIMODE1, 0);
ahd_outb(ahd, LQOMODE0, 0);
ahd_outb(ahd, LQOMODE1, 0);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
simode1 = ahd_inb(ahd, SIMODE1);
/*
* We don't clear ENBUSFREE. Unfortunately
* we cannot re-enable busfree detection within
* the current connection, so we must leave it
* on while single stepping.
*/
ahd_outb(ahd, SIMODE1, simode1 & ENBUSFREE);
ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) | STEP);
stepping = TRUE;
}
ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
ahd_outb(ahd, HCNTRL, ahd->unpause);
while (!ahd_is_paused(ahd))
ahd_delay(200);
ahd_update_modes(ahd);
}
if (stepping) {
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
ahd_outb(ahd, SIMODE0, simode0);
ahd_outb(ahd, SIMODE3, simode3);
ahd_outb(ahd, LQIMODE0, lqimode0);
ahd_outb(ahd, LQIMODE1, lqimode1);
ahd_outb(ahd, LQOMODE0, lqomode0);
ahd_outb(ahd, LQOMODE1, lqomode1);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) & ~STEP);
ahd_outb(ahd, SIMODE1, simode1);
/*
* SCSIINT seems to glitch occassionally when
* the interrupt masks are restored. Clear SCSIINT
* one more time so that only persistent errors
* are seen as a real interrupt.
*/
ahd_outb(ahd, CLRINT, CLRSCSIINT);
}
ahd_restore_modes(ahd, saved_modes);
}
/*
* Clear any pending interrupt status.
*/
static void
ahd_clear_intstat(struct ahd_softc *ahd)
{
AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
/* Clear any interrupt conditions this may have caused */
ahd_outb(ahd, CLRLQIINT0, CLRLQIATNQAS|CLRLQICRCT1|CLRLQICRCT2
|CLRLQIBADLQT|CLRLQIATNLQ|CLRLQIATNCMD);
ahd_outb(ahd, CLRLQIINT1, CLRLQIPHASE_LQ|CLRLQIPHASE_NLQ|CLRLIQABORT
|CLRLQICRCI_LQ|CLRLQICRCI_NLQ|CLRLQIBADLQI
|CLRLQIOVERI_LQ|CLRLQIOVERI_NLQ|CLRNONPACKREQ);
ahd_outb(ahd, CLRLQOINT0, CLRLQOTARGSCBPERR|CLRLQOSTOPT2|CLRLQOATNLQ
|CLRLQOATNPKT|CLRLQOTCRC);
ahd_outb(ahd, CLRLQOINT1, CLRLQOINITSCBPERR|CLRLQOSTOPI2|CLRLQOBADQAS
|CLRLQOBUSFREE|CLRLQOPHACHGINPKT);
if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
ahd_outb(ahd, CLRLQOINT0, 0);
ahd_outb(ahd, CLRLQOINT1, 0);
}
ahd_outb(ahd, CLRSINT3, CLRNTRAMPERR|CLROSRAMPERR);
ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
|CLRBUSFREE|CLRSCSIPERR|CLRREQINIT);
ahd_outb(ahd, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO
|CLRIOERR|CLROVERRUN);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
}
/**************************** Debugging Routines ******************************/
#ifdef AHD_DEBUG
uint32_t ahd_debug = AHD_DEBUG_OPTS;
#endif
#if 0
void
ahd_print_scb(struct scb *scb)
{
struct hardware_scb *hscb;
int i;
hscb = scb->hscb;
printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
(void *)scb,
hscb->control,
hscb->scsiid,
hscb->lun,
hscb->cdb_len);
printf("Shared Data: ");
for (i = 0; i < sizeof(hscb->shared_data.idata.cdb); i++)
printf("%#02x", hscb->shared_data.idata.cdb[i]);
printf(" dataptr:%#x%x datacnt:%#x sgptr:%#x tag:%#x\n",
(uint32_t)((ahd_le64toh(hscb->dataptr) >> 32) & 0xFFFFFFFF),
(uint32_t)(ahd_le64toh(hscb->dataptr) & 0xFFFFFFFF),
ahd_le32toh(hscb->datacnt),
ahd_le32toh(hscb->sgptr),
SCB_GET_TAG(scb));
ahd_dump_sglist(scb);
}
#endif /* 0 */
/************************* Transfer Negotiation *******************************/
/*
* Allocate per target mode instance (ID we respond to as a target)
* transfer negotiation data structures.
*/
static struct ahd_tmode_tstate *
ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel)
{
struct ahd_tmode_tstate *master_tstate;
struct ahd_tmode_tstate *tstate;
int i;
master_tstate = ahd->enabled_targets[ahd->our_id];
if (ahd->enabled_targets[scsi_id] != NULL
&& ahd->enabled_targets[scsi_id] != master_tstate)
panic("%s: ahd_alloc_tstate - Target already allocated",
ahd_name(ahd));
tstate = malloc(sizeof(*tstate), M_DEVBUF, M_NOWAIT);
if (tstate == NULL)
return (NULL);
/*
* If we have allocated a master tstate, copy user settings from
* the master tstate (taken from SRAM or the EEPROM) for this
* channel, but reset our current and goal settings to async/narrow
* until an initiator talks to us.
*/
if (master_tstate != NULL) {
memcpy(tstate, master_tstate, sizeof(*tstate));
memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
for (i = 0; i < 16; i++) {
memset(&tstate->transinfo[i].curr, 0,
sizeof(tstate->transinfo[i].curr));
memset(&tstate->transinfo[i].goal, 0,
sizeof(tstate->transinfo[i].goal));
}
} else
memset(tstate, 0, sizeof(*tstate));
ahd->enabled_targets[scsi_id] = tstate;
return (tstate);
}
#ifdef AHD_TARGET_MODE
/*
* Free per target mode instance (ID we respond to as a target)
* transfer negotiation data structures.
*/
static void
ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force)
{
struct ahd_tmode_tstate *tstate;
/*
* Don't clean up our "master" tstate.
* It has our default user settings.
*/
if (scsi_id == ahd->our_id
&& force == FALSE)
return;
tstate = ahd->enabled_targets[scsi_id];
if (tstate != NULL)
free(tstate, M_DEVBUF);
ahd->enabled_targets[scsi_id] = NULL;
}
#endif
/*
* Called when we have an active connection to a target on the bus,
* this function finds the nearest period to the input period limited
* by the capabilities of the bus connectivity of and sync settings for
* the target.
*/
void
ahd_devlimited_syncrate(struct ahd_softc *ahd,
struct ahd_initiator_tinfo *tinfo,
u_int *period, u_int *ppr_options, role_t role)
{
struct ahd_transinfo *transinfo;
u_int maxsync;
if ((ahd_inb(ahd, SBLKCTL) & ENAB40) != 0
&& (ahd_inb(ahd, SSTAT2) & EXP_ACTIVE) == 0) {
maxsync = AHD_SYNCRATE_PACED;
} else {
maxsync = AHD_SYNCRATE_ULTRA;
/* Can't do DT related options on an SE bus */
*ppr_options &= MSG_EXT_PPR_QAS_REQ;
}
/*
* Never allow a value higher than our current goal
* period otherwise we may allow a target initiated
* negotiation to go above the limit as set by the
* user. In the case of an initiator initiated
* sync negotiation, we limit based on the user
* setting. This allows the system to still accept
* incoming negotiations even if target initiated
* negotiation is not performed.
*/
if (role == ROLE_TARGET)
transinfo = &tinfo->user;
else
transinfo = &tinfo->goal;
*ppr_options &= (transinfo->ppr_options|MSG_EXT_PPR_PCOMP_EN);
if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
maxsync = max(maxsync, (u_int)AHD_SYNCRATE_ULTRA2);
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
}
if (transinfo->period == 0) {
*period = 0;
*ppr_options = 0;
} else {
*period = max(*period, (u_int)transinfo->period);
ahd_find_syncrate(ahd, period, ppr_options, maxsync);
}
}
/*
* Look up the valid period to SCSIRATE conversion in our table.
* Return the period and offset that should be sent to the target
* if this was the beginning of an SDTR.
*/
void
ahd_find_syncrate(struct ahd_softc *ahd, u_int *period,
u_int *ppr_options, u_int maxsync)
{
if (*period < maxsync)
*period = maxsync;
if ((*ppr_options & MSG_EXT_PPR_DT_REQ) != 0
&& *period > AHD_SYNCRATE_MIN_DT)
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
if (*period > AHD_SYNCRATE_MIN)
*period = 0;
/* Honor PPR option conformance rules. */
if (*period > AHD_SYNCRATE_PACED)
*ppr_options &= ~MSG_EXT_PPR_RTI;
if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
*ppr_options &= (MSG_EXT_PPR_DT_REQ|MSG_EXT_PPR_QAS_REQ);
if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0)
*ppr_options &= MSG_EXT_PPR_QAS_REQ;
/* Skip all PACED only entries if IU is not available */
if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0
&& *period < AHD_SYNCRATE_DT)
*period = AHD_SYNCRATE_DT;
/* Skip all DT only entries if DT is not available */
if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
&& *period < AHD_SYNCRATE_ULTRA2)
*period = AHD_SYNCRATE_ULTRA2;
}
/*
* Truncate the given synchronous offset to a value the
* current adapter type and syncrate are capable of.
*/
static void
ahd_validate_offset(struct ahd_softc *ahd,
struct ahd_initiator_tinfo *tinfo,
u_int period, u_int *offset, int wide,
role_t role)
{
u_int maxoffset;
/* Limit offset to what we can do */
if (period == 0)
maxoffset = 0;
else if (period <= AHD_SYNCRATE_PACED) {
if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0)
maxoffset = MAX_OFFSET_PACED_BUG;
else
maxoffset = MAX_OFFSET_PACED;
} else
maxoffset = MAX_OFFSET_NON_PACED;
*offset = min(*offset, maxoffset);
if (tinfo != NULL) {
if (role == ROLE_TARGET)
*offset = min(*offset, (u_int)tinfo->user.offset);
else
*offset = min(*offset, (u_int)tinfo->goal.offset);
}
}
/*
* Truncate the given transfer width parameter to a value the
* current adapter type is capable of.
*/
static void
ahd_validate_width(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo,
u_int *bus_width, role_t role)
{
switch (*bus_width) {
default:
if (ahd->features & AHD_WIDE) {
/* Respond Wide */
*bus_width = MSG_EXT_WDTR_BUS_16_BIT;
break;
}
/* FALLTHROUGH */
case MSG_EXT_WDTR_BUS_8_BIT:
*bus_width = MSG_EXT_WDTR_BUS_8_BIT;
break;
}
if (tinfo != NULL) {
if (role == ROLE_TARGET)
*bus_width = min((u_int)tinfo->user.width, *bus_width);
else
*bus_width = min((u_int)tinfo->goal.width, *bus_width);
}
}
/*
* Update the bitmask of targets for which the controller should
* negotiate with at the next convenient oportunity. This currently
* means the next time we send the initial identify messages for
* a new transaction.
*/
int
ahd_update_neg_request(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
struct ahd_tmode_tstate *tstate,
struct ahd_initiator_tinfo *tinfo, ahd_neg_type neg_type)
{
u_int auto_negotiate_orig;
auto_negotiate_orig = tstate->auto_negotiate;
if (neg_type == AHD_NEG_ALWAYS) {
/*
* Force our "current" settings to be
* unknown so that unless a bus reset
* occurs the need to renegotiate is
* recorded persistently.
*/
if ((ahd->features & AHD_WIDE) != 0)
tinfo->curr.width = AHD_WIDTH_UNKNOWN;
tinfo->curr.period = AHD_PERIOD_UNKNOWN;
tinfo->curr.offset = AHD_OFFSET_UNKNOWN;
}
if (tinfo->curr.period != tinfo->goal.period
|| tinfo->curr.width != tinfo->goal.width
|| tinfo->curr.offset != tinfo->goal.offset
|| tinfo->curr.ppr_options != tinfo->goal.ppr_options
|| (neg_type == AHD_NEG_IF_NON_ASYNC
&& (tinfo->goal.offset != 0
|| tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
|| tinfo->goal.ppr_options != 0)))
tstate->auto_negotiate |= devinfo->target_mask;
else
tstate->auto_negotiate &= ~devinfo->target_mask;
return (auto_negotiate_orig != tstate->auto_negotiate);
}
/*
* Update the user/goal/curr tables of synchronous negotiation
* parameters as well as, in the case of a current or active update,
* any data structures on the host controller. In the case of an
* active update, the specified target is currently talking to us on
* the bus, so the transfer parameter update must take effect
* immediately.
*/
void
ahd_set_syncrate(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
u_int period, u_int offset, u_int ppr_options,
u_int type, int paused)
{
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
u_int old_period;
u_int old_offset;
u_int old_ppr;
int active;
int update_needed;
active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
update_needed = 0;
if (period == 0 || offset == 0) {
period = 0;
offset = 0;
}
tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
if ((type & AHD_TRANS_USER) != 0) {
tinfo->user.period = period;
tinfo->user.offset = offset;
tinfo->user.ppr_options = ppr_options;
}
if ((type & AHD_TRANS_GOAL) != 0) {
tinfo->goal.period = period;
tinfo->goal.offset = offset;
tinfo->goal.ppr_options = ppr_options;
}
old_period = tinfo->curr.period;
old_offset = tinfo->curr.offset;
old_ppr = tinfo->curr.ppr_options;
if ((type & AHD_TRANS_CUR) != 0
&& (old_period != period
|| old_offset != offset
|| old_ppr != ppr_options)) {
update_needed++;
tinfo->curr.period = period;
tinfo->curr.offset = offset;
tinfo->curr.ppr_options = ppr_options;
ahd_send_async(ahd, devinfo->channel, devinfo->target,
CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
if (bootverbose) {
if (offset != 0) {
int options;
printf("%s: target %d synchronous with "
"period = 0x%x, offset = 0x%x",
ahd_name(ahd), devinfo->target,
period, offset);
options = 0;
if ((ppr_options & MSG_EXT_PPR_RD_STRM) != 0) {
printf("(RDSTRM");
options++;
}
if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) {
printf("%s", options ? "|DT" : "(DT");
options++;
}
if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
printf("%s", options ? "|IU" : "(IU");
options++;
}
if ((ppr_options & MSG_EXT_PPR_RTI) != 0) {
printf("%s", options ? "|RTI" : "(RTI");
options++;
}
if ((ppr_options & MSG_EXT_PPR_QAS_REQ) != 0) {
printf("%s", options ? "|QAS" : "(QAS");
options++;
}
if (options != 0)
printf(")\n");
else
printf("\n");
} else {
printf("%s: target %d using "
"asynchronous transfers%s\n",
ahd_name(ahd), devinfo->target,
(ppr_options & MSG_EXT_PPR_QAS_REQ) != 0
? "(QAS)" : "");
}
}
}
/*
* Always refresh the neg-table to handle the case of the
* sequencer setting the ENATNO bit for a MK_MESSAGE request.
* We will always renegotiate in that case if this is a
* packetized request. Also manage the busfree expected flag
* from this common routine so that we catch changes due to
* WDTR or SDTR messages.
*/
if ((type & AHD_TRANS_CUR) != 0) {
if (!paused)
ahd_pause(ahd);
ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
if (!paused)
ahd_unpause(ahd);
if (ahd->msg_type != MSG_TYPE_NONE) {
if ((old_ppr & MSG_EXT_PPR_IU_REQ)
!= (ppr_options & MSG_EXT_PPR_IU_REQ)) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
ahd_print_devinfo(ahd, devinfo);
printf("Expecting IU Change busfree\n");
}
#endif
ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
| MSG_FLAG_IU_REQ_CHANGED;
}
if ((old_ppr & MSG_EXT_PPR_IU_REQ) != 0) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("PPR with IU_REQ outstanding\n");
#endif
ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE;
}
}
}
update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
tinfo, AHD_NEG_TO_GOAL);
if (update_needed && active)
ahd_update_pending_scbs(ahd);
}
/*
* Update the user/goal/curr tables of wide negotiation
* parameters as well as, in the case of a current or active update,
* any data structures on the host controller. In the case of an
* active update, the specified target is currently talking to us on
* the bus, so the transfer parameter update must take effect
* immediately.
*/
void
ahd_set_width(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
u_int width, u_int type, int paused)
{
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
u_int oldwidth;
int active;
int update_needed;
active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
update_needed = 0;
tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
if ((type & AHD_TRANS_USER) != 0)
tinfo->user.width = width;
if ((type & AHD_TRANS_GOAL) != 0)
tinfo->goal.width = width;
oldwidth = tinfo->curr.width;
if ((type & AHD_TRANS_CUR) != 0 && oldwidth != width) {
update_needed++;
tinfo->curr.width = width;
ahd_send_async(ahd, devinfo->channel, devinfo->target,
CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
if (bootverbose) {
printf("%s: target %d using %dbit transfers\n",
ahd_name(ahd), devinfo->target,
8 * (0x01 << width));
}
}
if ((type & AHD_TRANS_CUR) != 0) {
if (!paused)
ahd_pause(ahd);
ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
if (!paused)
ahd_unpause(ahd);
}
update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
tinfo, AHD_NEG_TO_GOAL);
if (update_needed && active)
ahd_update_pending_scbs(ahd);
}
/*
* Update the current state of tagged queuing for a given target.
*/
static void
ahd_set_tags(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
struct ahd_devinfo *devinfo, ahd_queue_alg alg)
{
struct scsi_device *sdev = cmd->device;
ahd_platform_set_tags(ahd, sdev, devinfo, alg);
ahd_send_async(ahd, devinfo->channel, devinfo->target,
devinfo->lun, AC_TRANSFER_NEG);
}
static void
ahd_update_neg_table(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
struct ahd_transinfo *tinfo)
{
ahd_mode_state saved_modes;
u_int period;
u_int ppr_opts;
u_int con_opts;
u_int offset;
u_int saved_negoaddr;
uint8_t iocell_opts[sizeof(ahd->iocell_opts)];
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
saved_negoaddr = ahd_inb(ahd, NEGOADDR);
ahd_outb(ahd, NEGOADDR, devinfo->target);
period = tinfo->period;
offset = tinfo->offset;
memcpy(iocell_opts, ahd->iocell_opts, sizeof(ahd->iocell_opts));
ppr_opts = tinfo->ppr_options & (MSG_EXT_PPR_QAS_REQ|MSG_EXT_PPR_DT_REQ
|MSG_EXT_PPR_IU_REQ|MSG_EXT_PPR_RTI);
con_opts = 0;
if (period == 0)
period = AHD_SYNCRATE_ASYNC;
if (period == AHD_SYNCRATE_160) {
if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
/*
* When the SPI4 spec was finalized, PACE transfers
* was not made a configurable option in the PPR
* message. Instead it is assumed to be enabled for
* any syncrate faster than 80MHz. Nevertheless,
* Harpoon2A4 allows this to be configurable.
*
* Harpoon2A4 also assumes at most 2 data bytes per
* negotiated REQ/ACK offset. Paced transfers take
* 4, so we must adjust our offset.
*/
ppr_opts |= PPROPT_PACE;
offset *= 2;
/*
* Harpoon2A assumed that there would be a
* fallback rate between 160MHz and 80Mhz,
* so 7 is used as the period factor rather
* than 8 for 160MHz.
*/
period = AHD_SYNCRATE_REVA_160;
}
if ((tinfo->ppr_options & MSG_EXT_PPR_PCOMP_EN) == 0)
iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
~AHD_PRECOMP_MASK;
} else {
/*
* Precomp should be disabled for non-paced transfers.
*/
iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_PRECOMP_MASK;
if ((ahd->features & AHD_NEW_IOCELL_OPTS) != 0
&& (ppr_opts & MSG_EXT_PPR_DT_REQ) != 0
&& (ppr_opts & MSG_EXT_PPR_IU_REQ) == 0) {
/*
* Slow down our CRC interval to be
* compatible with non-packetized
* U160 devices that can't handle a
* CRC at full speed.
*/
con_opts |= ENSLOWCRC;
}
if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
/*
* On H2A4, revert to a slower slewrate
* on non-paced transfers.
*/
iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
~AHD_SLEWRATE_MASK;
}
}
ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PRECOMP_SLEW);
ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_PRECOMP_SLEW_INDEX]);
ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_AMPLITUDE);
ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_AMPLITUDE_INDEX]);
ahd_outb(ahd, NEGPERIOD, period);
ahd_outb(ahd, NEGPPROPTS, ppr_opts);
ahd_outb(ahd, NEGOFFSET, offset);
if (tinfo->width == MSG_EXT_WDTR_BUS_16_BIT)
con_opts |= WIDEXFER;
/*
* Slow down our CRC interval to be
* compatible with packetized U320 devices
* that can't handle a CRC at full speed
*/
if (ahd->features & AHD_AIC79XXB_SLOWCRC) {
con_opts |= ENSLOWCRC;
}
/*
* During packetized transfers, the target will
* give us the oportunity to send command packets
* without us asserting attention.
*/
if ((tinfo->ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
con_opts |= ENAUTOATNO;
ahd_outb(ahd, NEGCONOPTS, con_opts);
ahd_outb(ahd, NEGOADDR, saved_negoaddr);
ahd_restore_modes(ahd, saved_modes);
}
/*
* When the transfer settings for a connection change, setup for
* negotiation in pending SCBs to effect the change as quickly as
* possible. We also cancel any negotiations that are scheduled
* for inflight SCBs that have not been started yet.
*/
static void
ahd_update_pending_scbs(struct ahd_softc *ahd)
{
struct scb *pending_scb;
int pending_scb_count;
int paused;
u_int saved_scbptr;
ahd_mode_state saved_modes;
/*
* Traverse the pending SCB list and ensure that all of the
* SCBs there have the proper settings. We can only safely
* clear the negotiation required flag (setting requires the
* execution queue to be modified) and this is only possible
* if we are not already attempting to select out for this
* SCB. For this reason, all callers only call this routine
* if we are changing the negotiation settings for the currently
* active transaction on the bus.
*/
pending_scb_count = 0;
LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
struct ahd_devinfo devinfo;
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
ahd_scb_devinfo(ahd, &devinfo, pending_scb);
tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
devinfo.our_scsiid,
devinfo.target, &tstate);
if ((tstate->auto_negotiate & devinfo.target_mask) == 0
&& (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
pending_scb->hscb->control &= ~MK_MESSAGE;
}
ahd_sync_scb(ahd, pending_scb,
BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
pending_scb_count++;
}
if (pending_scb_count == 0)
return;
if (ahd_is_paused(ahd)) {
paused = 1;
} else {
paused = 0;
ahd_pause(ahd);
}
/*
* Force the sequencer to reinitialize the selection for
* the command at the head of the execution queue if it
* has already been setup. The negotiation changes may
* effect whether we select-out with ATN. It is only
* safe to clear ENSELO when the bus is not free and no
* selection is in progres or completed.
*/
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
if ((ahd_inb(ahd, SCSISIGI) & BSYI) != 0
&& (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) == 0)
ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
saved_scbptr = ahd_get_scbptr(ahd);
/* Ensure that the hscbs down on the card match the new information */
LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
u_int scb_tag;
u_int control;
scb_tag = SCB_GET_TAG(pending_scb);
ahd_set_scbptr(ahd, scb_tag);
control = ahd_inb_scbram(ahd, SCB_CONTROL);
control &= ~MK_MESSAGE;
control |= pending_scb->hscb->control & MK_MESSAGE;
ahd_outb(ahd, SCB_CONTROL, control);
}
ahd_set_scbptr(ahd, saved_scbptr);
ahd_restore_modes(ahd, saved_modes);
if (paused == 0)
ahd_unpause(ahd);
}
/**************************** Pathing Information *****************************/
static void
ahd_fetch_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
ahd_mode_state saved_modes;
u_int saved_scsiid;
role_t role;
int our_id;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
if (ahd_inb(ahd, SSTAT0) & TARGET)
role = ROLE_TARGET;
else
role = ROLE_INITIATOR;
if (role == ROLE_TARGET
&& (ahd_inb(ahd, SEQ_FLAGS) & CMDPHASE_PENDING) != 0) {
/* We were selected, so pull our id from TARGIDIN */
our_id = ahd_inb(ahd, TARGIDIN) & OID;
} else if (role == ROLE_TARGET)
our_id = ahd_inb(ahd, TOWNID);
else
our_id = ahd_inb(ahd, IOWNID);
saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
ahd_compile_devinfo(devinfo,
our_id,
SCSIID_TARGET(ahd, saved_scsiid),
ahd_inb(ahd, SAVED_LUN),
SCSIID_CHANNEL(ahd, saved_scsiid),
role);
ahd_restore_modes(ahd, saved_modes);
}
void
ahd_print_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
printf("%s:%c:%d:%d: ", ahd_name(ahd), 'A',
devinfo->target, devinfo->lun);
}
static struct ahd_phase_table_entry*
ahd_lookup_phase_entry(int phase)
{
struct ahd_phase_table_entry *entry;
struct ahd_phase_table_entry *last_entry;
/*
* num_phases doesn't include the default entry which
* will be returned if the phase doesn't match.
*/
last_entry = &ahd_phase_table[num_phases];
for (entry = ahd_phase_table; entry < last_entry; entry++) {
if (phase == entry->phase)
break;
}
return (entry);
}
void
ahd_compile_devinfo(struct ahd_devinfo *devinfo, u_int our_id, u_int target,
u_int lun, char channel, role_t role)
{
devinfo->our_scsiid = our_id;
devinfo->target = target;
devinfo->lun = lun;
devinfo->target_offset = target;
devinfo->channel = channel;
devinfo->role = role;
if (channel == 'B')
devinfo->target_offset += 8;
devinfo->target_mask = (0x01 << devinfo->target_offset);
}
static void
ahd_scb_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
struct scb *scb)
{
role_t role;
int our_id;
our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
role = ROLE_INITIATOR;
if ((scb->hscb->control & TARGET_SCB) != 0)
role = ROLE_TARGET;
ahd_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahd, scb),
SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), role);
}
/************************ Message Phase Processing ****************************/
/*
* When an initiator transaction with the MK_MESSAGE flag either reconnects
* or enters the initial message out phase, we are interrupted. Fill our
* outgoing message buffer with the appropriate message and beging handing
* the message phase(s) manually.
*/
static void
ahd_setup_initiator_msgout(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
struct scb *scb)
{
/*
* To facilitate adding multiple messages together,
* each routine should increment the index and len
* variables instead of setting them explicitly.
*/
ahd->msgout_index = 0;
ahd->msgout_len = 0;
if (ahd_currently_packetized(ahd))
ahd->msg_flags |= MSG_FLAG_PACKETIZED;
if (ahd->send_msg_perror
&& ahd_inb(ahd, MSG_OUT) == HOST_MSG) {
ahd->msgout_buf[ahd->msgout_index++] = ahd->send_msg_perror;
ahd->msgout_len++;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("Setting up for Parity Error delivery\n");
#endif
return;
} else if (scb == NULL) {
printf("%s: WARNING. No pending message for "
"I_T msgin. Issuing NO-OP\n", ahd_name(ahd));
ahd->msgout_buf[ahd->msgout_index++] = MSG_NOOP;
ahd->msgout_len++;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
return;
}
if ((scb->flags & SCB_DEVICE_RESET) == 0
&& (scb->flags & SCB_PACKETIZED) == 0
&& ahd_inb(ahd, MSG_OUT) == MSG_IDENTIFYFLAG) {
u_int identify_msg;
identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
if ((scb->hscb->control & DISCENB) != 0)
identify_msg |= MSG_IDENTIFY_DISCFLAG;
ahd->msgout_buf[ahd->msgout_index++] = identify_msg;
ahd->msgout_len++;
if ((scb->hscb->control & TAG_ENB) != 0) {
ahd->msgout_buf[ahd->msgout_index++] =
scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
ahd->msgout_buf[ahd->msgout_index++] = SCB_GET_TAG(scb);
ahd->msgout_len += 2;
}
}
if (scb->flags & SCB_DEVICE_RESET) {
ahd->msgout_buf[ahd->msgout_index++] = MSG_BUS_DEV_RESET;
ahd->msgout_len++;
ahd_print_path(ahd, scb);
printf("Bus Device Reset Message Sent\n");
/*
* Clear our selection hardware in advance of
* the busfree. We may have an entry in the waiting
* Q for this target, and we don't want to go about
* selecting while we handle the busfree and blow it
* away.
*/
ahd_outb(ahd, SCSISEQ0, 0);
} else if ((scb->flags & SCB_ABORT) != 0) {
if ((scb->hscb->control & TAG_ENB) != 0) {
ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT_TAG;
} else {
ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT;
}
ahd->msgout_len++;
ahd_print_path(ahd, scb);
printf("Abort%s Message Sent\n",
(scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
/*
* Clear our selection hardware in advance of
* the busfree. We may have an entry in the waiting
* Q for this target, and we don't want to go about
* selecting while we handle the busfree and blow it
* away.
*/
ahd_outb(ahd, SCSISEQ0, 0);
} else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
ahd_build_transfer_msg(ahd, devinfo);
/*
* Clear our selection hardware in advance of potential
* PPR IU status change busfree. We may have an entry in
* the waiting Q for this target, and we don't want to go
* about selecting while we handle the busfree and blow
* it away.
*/
ahd_outb(ahd, SCSISEQ0, 0);
} else {
printf("ahd_intr: AWAITING_MSG for an SCB that "
"does not have a waiting message\n");
printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
devinfo->target_mask);
panic("SCB = %d, SCB Control = %x:%x, MSG_OUT = %x "
"SCB flags = %x", SCB_GET_TAG(scb), scb->hscb->control,
ahd_inb_scbram(ahd, SCB_CONTROL), ahd_inb(ahd, MSG_OUT),
scb->flags);
}
/*
* Clear the MK_MESSAGE flag from the SCB so we aren't
* asked to send this message again.
*/
ahd_outb(ahd, SCB_CONTROL,
ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
scb->hscb->control &= ~MK_MESSAGE;
ahd->msgout_index = 0;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
}
/*
* Build an appropriate transfer negotiation message for the
* currently active target.
*/
static void
ahd_build_transfer_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
/*
* We need to initiate transfer negotiations.
* If our current and goal settings are identical,
* we want to renegotiate due to a check condition.
*/
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
int dowide;
int dosync;
int doppr;
u_int period;
u_int ppr_options;
u_int offset;
tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
/*
* Filter our period based on the current connection.
* If we can't perform DT transfers on this segment (not in LVD
* mode for instance), then our decision to issue a PPR message
* may change.
*/
period = tinfo->goal.period;
offset = tinfo->goal.offset;
ppr_options = tinfo->goal.ppr_options;
/* Target initiated PPR is not allowed in the SCSI spec */
if (devinfo->role == ROLE_TARGET)
ppr_options = 0;
ahd_devlimited_syncrate(ahd, tinfo, &period,
&ppr_options, devinfo->role);
dowide = tinfo->curr.width != tinfo->goal.width;
dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
/*
* Only use PPR if we have options that need it, even if the device
* claims to support it. There might be an expander in the way
* that doesn't.
*/
doppr = ppr_options != 0;
if (!dowide && !dosync && !doppr) {
dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
dosync = tinfo->goal.offset != 0;
}
if (!dowide && !dosync && !doppr) {
/*
* Force async with a WDTR message if we have a wide bus,
* or just issue an SDTR with a 0 offset.
*/
if ((ahd->features & AHD_WIDE) != 0)
dowide = 1;
else
dosync = 1;
if (bootverbose) {
ahd_print_devinfo(ahd, devinfo);
printf("Ensuring async\n");
}
}
/* Target initiated PPR is not allowed in the SCSI spec */
if (devinfo->role == ROLE_TARGET)
doppr = 0;
/*
* Both the PPR message and SDTR message require the
* goal syncrate to be limited to what the target device
* is capable of handling (based on whether an LVD->SE
* expander is on the bus), so combine these two cases.
* Regardless, guarantee that if we are using WDTR and SDTR
* messages that WDTR comes first.
*/
if (doppr || (dosync && !dowide)) {
offset = tinfo->goal.offset;
ahd_validate_offset(ahd, tinfo, period, &offset,
doppr ? tinfo->goal.width
: tinfo->curr.width,
devinfo->role);
if (doppr) {
ahd_construct_ppr(ahd, devinfo, period, offset,
tinfo->goal.width, ppr_options);
} else {
ahd_construct_sdtr(ahd, devinfo, period, offset);
}
} else {
ahd_construct_wdtr(ahd, devinfo, tinfo->goal.width);
}
}
/*
* Build a synchronous negotiation message in our message
* buffer based on the input parameters.
*/
static void
ahd_construct_sdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
u_int period, u_int offset)
{
if (offset == 0)
period = AHD_ASYNC_XFER_PERIOD;
ahd->msgout_index += spi_populate_sync_msg(
ahd->msgout_buf + ahd->msgout_index, period, offset);
ahd->msgout_len += 5;
if (bootverbose) {
printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
ahd_name(ahd), devinfo->channel, devinfo->target,
devinfo->lun, period, offset);
}
}
/*
* Build a wide negotiateion message in our message
* buffer based on the input parameters.
*/
static void
ahd_construct_wdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
u_int bus_width)
{
ahd->msgout_index += spi_populate_width_msg(
ahd->msgout_buf + ahd->msgout_index, bus_width);
ahd->msgout_len += 4;
if (bootverbose) {
printf("(%s:%c:%d:%d): Sending WDTR %x\n",
ahd_name(ahd), devinfo->channel, devinfo->target,
devinfo->lun, bus_width);
}
}
/*
* Build a parallel protocol request message in our message
* buffer based on the input parameters.
*/
static void
ahd_construct_ppr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
u_int period, u_int offset, u_int bus_width,
u_int ppr_options)
{
/*
* Always request precompensation from
* the other target if we are running
* at paced syncrates.
*/
if (period <= AHD_SYNCRATE_PACED)
ppr_options |= MSG_EXT_PPR_PCOMP_EN;
if (offset == 0)
period = AHD_ASYNC_XFER_PERIOD;
ahd->msgout_index += spi_populate_ppr_msg(
ahd->msgout_buf + ahd->msgout_index, period, offset,
bus_width, ppr_options);
ahd->msgout_len += 8;
if (bootverbose) {
printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
"offset %x, ppr_options %x\n", ahd_name(ahd),
devinfo->channel, devinfo->target, devinfo->lun,
bus_width, period, offset, ppr_options);
}
}
/*
* Clear any active message state.
*/
static void
ahd_clear_msg_state(struct ahd_softc *ahd)
{
ahd_mode_state saved_modes;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd->send_msg_perror = 0;
ahd->msg_flags = MSG_FLAG_NONE;
ahd->msgout_len = 0;
ahd->msgin_index = 0;
ahd->msg_type = MSG_TYPE_NONE;
if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
/*
* The target didn't care to respond to our
* message request, so clear ATN.
*/
ahd_outb(ahd, CLRSINT1, CLRATNO);
}
ahd_outb(ahd, MSG_OUT, MSG_NOOP);
ahd_outb(ahd, SEQ_FLAGS2,
ahd_inb(ahd, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
ahd_restore_modes(ahd, saved_modes);
}
/*
* Manual message loop handler.
*/
static void
ahd_handle_message_phase(struct ahd_softc *ahd)
{
struct ahd_devinfo devinfo;
u_int bus_phase;
int end_session;
ahd_fetch_devinfo(ahd, &devinfo);
end_session = FALSE;
bus_phase = ahd_inb(ahd, LASTPHASE);
if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0) {
printf("LQIRETRY for LQIPHASE_OUTPKT\n");
ahd_outb(ahd, LQCTL2, LQIRETRY);
}
reswitch:
switch (ahd->msg_type) {
case MSG_TYPE_INITIATOR_MSGOUT:
{
int lastbyte;
int phasemis;
int msgdone;
if (ahd->msgout_len == 0 && ahd->send_msg_perror == 0)
panic("HOST_MSG_LOOP interrupt with no active message");
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
ahd_print_devinfo(ahd, &devinfo);
printf("INITIATOR_MSG_OUT");
}
#endif
phasemis = bus_phase != P_MESGOUT;
if (phasemis) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
printf(" PHASEMIS %s\n",
ahd_lookup_phase_entry(bus_phase)
->phasemsg);
}
#endif
if (bus_phase == P_MESGIN) {
/*
* Change gears and see if
* this messages is of interest to
* us or should be passed back to
* the sequencer.
*/
ahd_outb(ahd, CLRSINT1, CLRATNO);
ahd->send_msg_perror = 0;
ahd->msg_type = MSG_TYPE_INITIATOR_MSGIN;
ahd->msgin_index = 0;
goto reswitch;
}
end_session = TRUE;
break;
}
if (ahd->send_msg_perror) {
ahd_outb(ahd, CLRSINT1, CLRATNO);
ahd_outb(ahd, CLRSINT1, CLRREQINIT);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf(" byte 0x%x\n", ahd->send_msg_perror);
#endif
/*
* If we are notifying the target of a CRC error
* during packetized operations, the target is
* within its rights to acknowledge our message
* with a busfree.
*/
if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0
&& ahd->send_msg_perror == MSG_INITIATOR_DET_ERR)
ahd->msg_flags |= MSG_FLAG_EXPECT_IDE_BUSFREE;
ahd_outb(ahd, RETURN_2, ahd->send_msg_perror);
ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
break;
}
msgdone = ahd->msgout_index == ahd->msgout_len;
if (msgdone) {
/*
* The target has requested a retry.
* Re-assert ATN, reset our message index to
* 0, and try again.
*/
ahd->msgout_index = 0;
ahd_assert_atn(ahd);
}
lastbyte = ahd->msgout_index == (ahd->msgout_len - 1);
if (lastbyte) {
/* Last byte is signified by dropping ATN */
ahd_outb(ahd, CLRSINT1, CLRATNO);
}
/*
* Clear our interrupt status and present
* the next byte on the bus.
*/
ahd_outb(ahd, CLRSINT1, CLRREQINIT);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf(" byte 0x%x\n",
ahd->msgout_buf[ahd->msgout_index]);
#endif
ahd_outb(ahd, RETURN_2, ahd->msgout_buf[ahd->msgout_index++]);
ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
break;
}
case MSG_TYPE_INITIATOR_MSGIN:
{
int phasemis;
int message_done;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
ahd_print_devinfo(ahd, &devinfo);
printf("INITIATOR_MSG_IN");
}
#endif
phasemis = bus_phase != P_MESGIN;
if (phasemis) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
printf(" PHASEMIS %s\n",
ahd_lookup_phase_entry(bus_phase)
->phasemsg);
}
#endif
ahd->msgin_index = 0;
if (bus_phase == P_MESGOUT
&& (ahd->send_msg_perror != 0
|| (ahd->msgout_len != 0
&& ahd->msgout_index == 0))) {
ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
goto reswitch;
}
end_session = TRUE;
break;
}
/* Pull the byte in without acking it */
ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIBUS);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf(" byte 0x%x\n",
ahd->msgin_buf[ahd->msgin_index]);
#endif
message_done = ahd_parse_msg(ahd, &devinfo);
if (message_done) {
/*
* Clear our incoming message buffer in case there
* is another message following this one.
*/
ahd->msgin_index = 0;
/*
* If this message illicited a response,
* assert ATN so the target takes us to the
* message out phase.
*/
if (ahd->msgout_len != 0) {
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
ahd_print_devinfo(ahd, &devinfo);
printf("Asserting ATN for response\n");
}
#endif
ahd_assert_atn(ahd);
}
} else
ahd->msgin_index++;
if (message_done == MSGLOOP_TERMINATED) {
end_session = TRUE;
} else {
/* Ack the byte */
ahd_outb(ahd, CLRSINT1, CLRREQINIT);
ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_READ);
}
break;
}
case MSG_TYPE_TARGET_MSGIN:
{
int msgdone;
int msgout_request;
/*
* By default, the message loop will continue.
*/
ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
if (ahd->msgout_len == 0)
panic("Target MSGIN with no active message");
/*
* If we interrupted a mesgout session, the initiator
* will not know this until our first REQ. So, we
* only honor mesgout requests after we've sent our
* first byte.
*/
if ((ahd_inb(ahd, SCSISIGI) & ATNI) != 0
&& ahd->msgout_index > 0)
msgout_request = TRUE;
else
msgout_request = FALSE;
if (msgout_request) {
/*
* Change gears and see if
* this messages is of interest to
* us or should be passed back to
* the sequencer.
*/
ahd->msg_type = MSG_TYPE_TARGET_MSGOUT;
ahd_outb(ahd, SCSISIGO, P_MESGOUT | BSYO);
ahd->msgin_index = 0;
/* Dummy read to REQ for first byte */
ahd_inb(ahd, SCSIDAT);
ahd_outb(ahd, SXFRCTL0,
ahd_inb(ahd, SXFRCTL0) | SPIOEN);
break;
}
msgdone = ahd->msgout_index == ahd->msgout_len;
if (msgdone) {
ahd_outb(ahd, SXFRCTL0,
ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
end_session = TRUE;
break;
}
/*
* Present the next byte on the bus.
*/
ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN);
ahd_outb(ahd, SCSIDAT, ahd->msgout_buf[ahd->msgout_index++]);
break;
}
case MSG_TYPE_TARGET_MSGOUT:
{
int lastbyte;
int msgdone;
/*
* By default, the message loop will continue.
*/
ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
/*
* The initiator signals that this is
* the last byte by dropping ATN.
*/
lastbyte = (ahd_inb(ahd, SCSISIGI) & ATNI) == 0;
/*
* Read the latched byte, but turn off SPIOEN first
* so that we don't inadvertently cause a REQ for the
* next byte.
*/
ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIDAT);
msgdone = ahd_parse_msg(ahd, &devinfo);
if (msgdone == MSGLOOP_TERMINATED) {
/*
* The message is *really* done in that it caused
* us to go to bus free. The sequencer has already
* been reset at this point, so pull the ejection
* handle.
*/
return;
}
ahd->msgin_index++;
/*
* XXX Read spec about initiator dropping ATN too soon
* and use msgdone to detect it.
*/
if (msgdone == MSGLOOP_MSGCOMPLETE) {
ahd->msgin_index = 0;
/*
* If this message illicited a response, transition
* to the Message in phase and send it.
*/
if (ahd->msgout_len != 0) {
ahd_outb(ahd, SCSISIGO, P_MESGIN | BSYO);
ahd_outb(ahd, SXFRCTL0,
ahd_inb(ahd, SXFRCTL0) | SPIOEN);
ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
ahd->msgin_index = 0;
break;
}
}
if (lastbyte)
end_session = TRUE;
else {
/* Ask for the next byte. */
ahd_outb(ahd, SXFRCTL0,
ahd_inb(ahd, SXFRCTL0) | SPIOEN);
}
break;
}
default:
panic("Unknown REQINIT message type");
}
if (end_session) {
if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0) {
printf("%s: Returning to Idle Loop\n",
ahd_name(ahd));
ahd_clear_msg_state(ahd);
/*
* Perform the equivalent of a clear_target_state.
*/
ahd_outb(ahd, LASTPHASE, P_BUSFREE);
ahd_outb(ahd, SEQ_FLAGS, NOT_IDENTIFIED|NO_CDB_SENT);
ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
} else {
ahd_clear_msg_state(ahd);
ahd_outb(ahd, RETURN_1, EXIT_MSG_LOOP);
}
}
}
/*
* See if we sent a particular extended message to the target.
* If "full" is true, return true only if the target saw the full
* message. If "full" is false, return true if the target saw at
* least the first byte of the message.
*/
static int
ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type, u_int msgval, int full)
{
int found;
u_int index;
found = FALSE;
index = 0;
while (index < ahd->msgout_len) {
if (ahd->msgout_buf[index] == MSG_EXTENDED) {
u_int end_index;
end_index = index + 1 + ahd->msgout_buf[index + 1];
if (ahd->msgout_buf[index+2] == msgval
&& type == AHDMSG_EXT) {
if (full) {
if (ahd->msgout_index > end_index)
found = TRUE;
} else if (ahd->msgout_index > index)
found = TRUE;
}
index = end_index;
} else if (ahd->msgout_buf[index] >= MSG_SIMPLE_TASK
&& ahd->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
/* Skip tag type and tag id or residue param*/
index += 2;
} else {
/* Single byte message */
if (type == AHDMSG_1B
&& ahd->msgout_index > index
&& (ahd->msgout_buf[index] == msgval
|| ((ahd->msgout_buf[index] & MSG_IDENTIFYFLAG) != 0
&& msgval == MSG_IDENTIFYFLAG)))
found = TRUE;
index++;
}
if (found)
break;
}
return (found);
}
/*
* Wait for a complete incoming message, parse it, and respond accordingly.
*/
static int
ahd_parse_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
int reject;
int done;
int response;
done = MSGLOOP_IN_PROG;
response = FALSE;
reject = FALSE;
tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
/*
* Parse as much of the message as is available,
* rejecting it if we don't support it. When
* the entire message is available and has been
* handled, return MSGLOOP_MSGCOMPLETE, indicating
* that we have parsed an entire message.
*
* In the case of extended messages, we accept the length
* byte outright and perform more checking once we know the
* extended message type.
*/
switch (ahd->msgin_buf[0]) {
case MSG_DISCONNECT:
case MSG_SAVEDATAPOINTER:
case MSG_CMDCOMPLETE:
case MSG_RESTOREPOINTERS:
case MSG_IGN_WIDE_RESIDUE:
/*
* End our message loop as these are messages
* the sequencer handles on its own.
*/
done = MSGLOOP_TERMINATED;
break;
case MSG_MESSAGE_REJECT:
response = ahd_handle_msg_reject(ahd, devinfo);
/* FALLTHROUGH */
case MSG_NOOP:
done = MSGLOOP_MSGCOMPLETE;
break;
case MSG_EXTENDED:
{
/* Wait for enough of the message to begin validation */
if (ahd->msgin_index < 2)
break;
switch (ahd->msgin_buf[2]) {
case MSG_EXT_SDTR:
{
u_int period;
u_int ppr_options;
u_int offset;
u_int saved_offset;
if (ahd->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
reject = TRUE;
break;
}
/*
* Wait until we have both args before validating
* and acting on this message.
*
* Add one to MSG_EXT_SDTR_LEN to account for
* the extended message preamble.
*/
if (ahd->msgin_index < (MSG_EXT_SDTR_LEN + 1))
break;
period = ahd->msgin_buf[3];
ppr_options = 0;
saved_offset = offset = ahd->msgin_buf[4];
ahd_devlimited_syncrate(ahd, tinfo, &period,
&ppr_options, devinfo->role);
ahd_validate_offset(ahd, tinfo, period, &offset,
tinfo->curr.width, devinfo->role);
if (bootverbose) {
printf("(%s:%c:%d:%d): Received "
"SDTR period %x, offset %x\n\t"
"Filtered to period %x, offset %x\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun,
ahd->msgin_buf[3], saved_offset,
period, offset);
}
ahd_set_syncrate(ahd, devinfo, period,
offset, ppr_options,
AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
/*paused*/TRUE);
/*
* See if we initiated Sync Negotiation
* and didn't have to fall down to async
* transfers.
*/
if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, TRUE)) {
/* We started it */
if (saved_offset != offset) {
/* Went too low - force async */
reject = TRUE;
}
} else {
/*
* Send our own SDTR in reply
*/
if (bootverbose
&& devinfo->role == ROLE_INITIATOR) {
printf("(%s:%c:%d:%d): Target "
"Initiated SDTR\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
}
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_construct_sdtr(ahd, devinfo,
period, offset);
ahd->msgout_index = 0;
response = TRUE;
}
done = MSGLOOP_MSGCOMPLETE;
break;
}
case MSG_EXT_WDTR:
{
u_int bus_width;
u_int saved_width;
u_int sending_reply;
sending_reply = FALSE;
if (ahd->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
reject = TRUE;
break;
}
/*
* Wait until we have our arg before validating
* and acting on this message.
*
* Add one to MSG_EXT_WDTR_LEN to account for
* the extended message preamble.
*/
if (ahd->msgin_index < (MSG_EXT_WDTR_LEN + 1))
break;
bus_width = ahd->msgin_buf[3];
saved_width = bus_width;
ahd_validate_width(ahd, tinfo, &bus_width,
devinfo->role);
if (bootverbose) {
printf("(%s:%c:%d:%d): Received WDTR "
"%x filtered to %x\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun,
saved_width, bus_width);
}
if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, TRUE)) {
/*
* Don't send a WDTR back to the
* target, since we asked first.
* If the width went higher than our
* request, reject it.
*/
if (saved_width > bus_width) {
reject = TRUE;
printf("(%s:%c:%d:%d): requested %dBit "
"transfers. Rejecting...\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun,
8 * (0x01 << bus_width));
bus_width = 0;
}
} else {
/*
* Send our own WDTR in reply
*/
if (bootverbose
&& devinfo->role == ROLE_INITIATOR) {
printf("(%s:%c:%d:%d): Target "
"Initiated WDTR\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
}
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_construct_wdtr(ahd, devinfo, bus_width);
ahd->msgout_index = 0;
response = TRUE;
sending_reply = TRUE;
}
/*
* After a wide message, we are async, but
* some devices don't seem to honor this portion
* of the spec. Force a renegotiation of the
* sync component of our transfer agreement even
* if our goal is async. By updating our width
* after forcing the negotiation, we avoid
* renegotiating for width.
*/
ahd_update_neg_request(ahd, devinfo, tstate,
tinfo, AHD_NEG_ALWAYS);
ahd_set_width(ahd, devinfo, bus_width,
AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
/*paused*/TRUE);
if (sending_reply == FALSE && reject == FALSE) {
/*
* We will always have an SDTR to send.
*/
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_build_transfer_msg(ahd, devinfo);
ahd->msgout_index = 0;
response = TRUE;
}
done = MSGLOOP_MSGCOMPLETE;
break;
}
case MSG_EXT_PPR:
{
u_int period;
u_int offset;
u_int bus_width;
u_int ppr_options;
u_int saved_width;
u_int saved_offset;
u_int saved_ppr_options;
if (ahd->msgin_buf[1] != MSG_EXT_PPR_LEN) {
reject = TRUE;
break;
}
/*
* Wait until we have all args before validating
* and acting on this message.
*
* Add one to MSG_EXT_PPR_LEN to account for
* the extended message preamble.
*/
if (ahd->msgin_index < (MSG_EXT_PPR_LEN + 1))
break;
period = ahd->msgin_buf[3];
offset = ahd->msgin_buf[5];
bus_width = ahd->msgin_buf[6];
saved_width = bus_width;
ppr_options = ahd->msgin_buf[7];
/*
* According to the spec, a DT only
* period factor with no DT option
* set implies async.
*/
if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
&& period <= 9)
offset = 0;
saved_ppr_options = ppr_options;
saved_offset = offset;
/*
* Transfer options are only available if we
* are negotiating wide.
*/
if (bus_width == 0)
ppr_options &= MSG_EXT_PPR_QAS_REQ;
ahd_validate_width(ahd, tinfo, &bus_width,
devinfo->role);
ahd_devlimited_syncrate(ahd, tinfo, &period,
&ppr_options, devinfo->role);
ahd_validate_offset(ahd, tinfo, period, &offset,
bus_width, devinfo->role);
if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, TRUE)) {
/*
* If we are unable to do any of the
* requested options (we went too low),
* then we'll have to reject the message.
*/
if (saved_width > bus_width
|| saved_offset != offset
|| saved_ppr_options != ppr_options) {
reject = TRUE;
period = 0;
offset = 0;
bus_width = 0;
ppr_options = 0;
}
} else {
if (devinfo->role != ROLE_TARGET)
printf("(%s:%c:%d:%d): Target "
"Initiated PPR\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
else
printf("(%s:%c:%d:%d): Initiator "
"Initiated PPR\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_construct_ppr(ahd, devinfo, period, offset,
bus_width, ppr_options);
ahd->msgout_index = 0;
response = TRUE;
}
if (bootverbose) {
printf("(%s:%c:%d:%d): Received PPR width %x, "
"period %x, offset %x,options %x\n"
"\tFiltered to width %x, period %x, "
"offset %x, options %x\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun,
saved_width, ahd->msgin_buf[3],
saved_offset, saved_ppr_options,
bus_width, period, offset, ppr_options);
}
ahd_set_width(ahd, devinfo, bus_width,
AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
/*paused*/TRUE);
ahd_set_syncrate(ahd, devinfo, period,
offset, ppr_options,
AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
/*paused*/TRUE);
done = MSGLOOP_MSGCOMPLETE;
break;
}
default:
/* Unknown extended message. Reject it. */
reject = TRUE;
break;
}
break;
}
#ifdef AHD_TARGET_MODE
case MSG_BUS_DEV_RESET:
ahd_handle_devreset(ahd, devinfo, CAM_LUN_WILDCARD,
CAM_BDR_SENT,
"Bus Device Reset Received",
/*verbose_level*/0);
ahd_restart(ahd);
done = MSGLOOP_TERMINATED;
break;
case MSG_ABORT_TAG:
case MSG_ABORT:
case MSG_CLEAR_QUEUE:
{
int tag;
/* Target mode messages */
if (devinfo->role != ROLE_TARGET) {
reject = TRUE;
break;
}
tag = SCB_LIST_NULL;
if (ahd->msgin_buf[0] == MSG_ABORT_TAG)
tag = ahd_inb(ahd, INITIATOR_TAG);
ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
devinfo->lun, tag, ROLE_TARGET,
CAM_REQ_ABORTED);
tstate = ahd->enabled_targets[devinfo->our_scsiid];
if (tstate != NULL) {
struct ahd_tmode_lstate* lstate;
lstate = tstate->enabled_luns[devinfo->lun];
if (lstate != NULL) {
ahd_queue_lstate_event(ahd, lstate,
devinfo->our_scsiid,
ahd->msgin_buf[0],
/*arg*/tag);
ahd_send_lstate_events(ahd, lstate);
}
}
ahd_restart(ahd);
done = MSGLOOP_TERMINATED;
break;
}
#endif
case MSG_QAS_REQUEST:
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
printf("%s: QAS request. SCSISIGI == 0x%x\n",
ahd_name(ahd), ahd_inb(ahd, SCSISIGI));
#endif
ahd->msg_flags |= MSG_FLAG_EXPECT_QASREJ_BUSFREE;
/* FALLTHROUGH */
case MSG_TERM_IO_PROC:
default:
reject = TRUE;
break;
}
if (reject) {
/*
* Setup to reject the message.
*/
ahd->msgout_index = 0;
ahd->msgout_len = 1;
ahd->msgout_buf[0] = MSG_MESSAGE_REJECT;
done = MSGLOOP_MSGCOMPLETE;
response = TRUE;
}
if (done != MSGLOOP_IN_PROG && !response)
/* Clear the outgoing message buffer */
ahd->msgout_len = 0;
return (done);
}
/*
* Process a message reject message.
*/
static int
ahd_handle_msg_reject(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
/*
* What we care about here is if we had an
* outstanding SDTR or WDTR message for this
* target. If we did, this is a signal that
* the target is refusing negotiation.
*/
struct scb *scb;
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
u_int scb_index;
u_int last_msg;
int response = 0;
scb_index = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scb_index);
tinfo = ahd_fetch_transinfo(ahd, devinfo->channel,
devinfo->our_scsiid,
devinfo->target, &tstate);
/* Might be necessary */
last_msg = ahd_inb(ahd, LAST_MSG);
if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/TRUE)
&& tinfo->goal.period <= AHD_SYNCRATE_PACED) {
/*
* Target may not like our SPI-4 PPR Options.
* Attempt to negotiate 80MHz which will turn
* off these options.
*/
if (bootverbose) {
printf("(%s:%c:%d:%d): PPR Rejected. "
"Trying simple U160 PPR\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
}
tinfo->goal.period = AHD_SYNCRATE_DT;
tinfo->goal.ppr_options &= MSG_EXT_PPR_IU_REQ
| MSG_EXT_PPR_QAS_REQ
| MSG_EXT_PPR_DT_REQ;
} else {
/*
* Target does not support the PPR message.
* Attempt to negotiate SPI-2 style.
*/
if (bootverbose) {
printf("(%s:%c:%d:%d): PPR Rejected. "
"Trying WDTR/SDTR\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
}
tinfo->goal.ppr_options = 0;
tinfo->curr.transport_version = 2;
tinfo->goal.transport_version = 2;
}
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_build_transfer_msg(ahd, devinfo);
ahd->msgout_index = 0;
response = 1;
} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
/* note 8bit xfers */
printf("(%s:%c:%d:%d): refuses WIDE negotiation. Using "
"8bit transfers\n", ahd_name(ahd),
devinfo->channel, devinfo->target, devinfo->lun);
ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
/*paused*/TRUE);
/*
* No need to clear the sync rate. If the target
* did not accept the command, our syncrate is
* unaffected. If the target started the negotiation,
* but rejected our response, we already cleared the
* sync rate before sending our WDTR.
*/
if (tinfo->goal.offset != tinfo->curr.offset) {
/* Start the sync negotiation */
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_build_transfer_msg(ahd, devinfo);
ahd->msgout_index = 0;
response = 1;
}
} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
/* note asynch xfers and clear flag */
ahd_set_syncrate(ahd, devinfo, /*period*/0,
/*offset*/0, /*ppr_options*/0,
AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
/*paused*/TRUE);
printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
"Using asynchronous transfers\n",
ahd_name(ahd), devinfo->channel,
devinfo->target, devinfo->lun);
} else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
int tag_type;
int mask;
tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
if (tag_type == MSG_SIMPLE_TASK) {
printf("(%s:%c:%d:%d): refuses tagged commands. "
"Performing non-tagged I/O\n", ahd_name(ahd),
devinfo->channel, devinfo->target, devinfo->lun);
ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_NONE);
mask = ~0x23;
} else {
printf("(%s:%c:%d:%d): refuses %s tagged commands. "
"Performing simple queue tagged I/O only\n",
ahd_name(ahd), devinfo->channel, devinfo->target,
devinfo->lun, tag_type == MSG_ORDERED_TASK
? "ordered" : "head of queue");
ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_BASIC);
mask = ~0x03;
}
/*
* Resend the identify for this CCB as the target
* may believe that the selection is invalid otherwise.
*/
ahd_outb(ahd, SCB_CONTROL,
ahd_inb_scbram(ahd, SCB_CONTROL) & mask);
scb->hscb->control &= mask;
ahd_set_transaction_tag(scb, /*enabled*/FALSE,
/*type*/MSG_SIMPLE_TASK);
ahd_outb(ahd, MSG_OUT, MSG_IDENTIFYFLAG);
ahd_assert_atn(ahd);
ahd_busy_tcl(ahd, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
SCB_GET_TAG(scb));
/*
* Requeue all tagged commands for this target
* currently in our posession so they can be
* converted to untagged commands.
*/
ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
SCB_GET_CHANNEL(ahd, scb),
SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
ROLE_INITIATOR, CAM_REQUEUE_REQ,
SEARCH_COMPLETE);
} else if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_IDENTIFYFLAG, TRUE)) {
/*
* Most likely the device believes that we had
* previously negotiated packetized.
*/
ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
| MSG_FLAG_IU_REQ_CHANGED;
ahd_force_renegotiation(ahd, devinfo);
ahd->msgout_index = 0;
ahd->msgout_len = 0;
ahd_build_transfer_msg(ahd, devinfo);
ahd->msgout_index = 0;
response = 1;
} else {
/*
* Otherwise, we ignore it.
*/
printf("%s:%c:%d: Message reject for %x -- ignored\n",
ahd_name(ahd), devinfo->channel, devinfo->target,
last_msg);
}
return (response);
}
/*
* Process an ingnore wide residue message.
*/
static void
ahd_handle_ign_wide_residue(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
{
u_int scb_index;
struct scb *scb;
scb_index = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scb_index);
/*
* XXX Actually check data direction in the sequencer?
* Perhaps add datadir to some spare bits in the hscb?
*/
if ((ahd_inb(ahd, SEQ_FLAGS) & DPHASE) == 0
|| ahd_get_transfer_dir(scb) != CAM_DIR_IN) {
/*
* Ignore the message if we haven't
* seen an appropriate data phase yet.
*/
} else {
/*
* If the residual occurred on the last
* transfer and the transfer request was
* expected to end on an odd count, do
* nothing. Otherwise, subtract a byte
* and update the residual count accordingly.
*/
uint32_t sgptr;
sgptr = ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR);
if ((sgptr & SG_LIST_NULL) != 0
&& (ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
& SCB_XFERLEN_ODD) != 0) {
/*
* If the residual occurred on the last
* transfer and the transfer request was
* expected to end on an odd count, do
* nothing.
*/
} else {
uint32_t data_cnt;
uint64_t data_addr;
uint32_t sglen;
/* Pull in the rest of the sgptr */
sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
data_cnt = ahd_inl_scbram(ahd, SCB_RESIDUAL_DATACNT);
if ((sgptr & SG_LIST_NULL) != 0) {
/*
* The residual data count is not updated
* for the command run to completion case.
* Explicitly zero the count.
*/
data_cnt &= ~AHD_SG_LEN_MASK;
}
data_addr = ahd_inq(ahd, SHADDR);
data_cnt += 1;
data_addr -= 1;
sgptr &= SG_PTR_MASK;
if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
struct ahd_dma64_seg *sg;
sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
/*
* The residual sg ptr points to the next S/G
* to load so we must go back one.
*/
sg--;
sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
if (sg != scb->sg_list
&& sglen < (data_cnt & AHD_SG_LEN_MASK)) {
sg--;
sglen = ahd_le32toh(sg->len);
/*
* Preserve High Address and SG_LIST
* bits while setting the count to 1.
*/
data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
data_addr = ahd_le64toh(sg->addr)
+ (sglen & AHD_SG_LEN_MASK)
- 1;
/*
* Increment sg so it points to the
* "next" sg.
*/
sg++;
sgptr = ahd_sg_virt_to_bus(ahd, scb,
sg);
}
} else {
struct ahd_dma_seg *sg;
sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
/*
* The residual sg ptr points to the next S/G
* to load so we must go back one.
*/
sg--;
sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
if (sg != scb->sg_list
&& sglen < (data_cnt & AHD_SG_LEN_MASK)) {
sg--;
sglen = ahd_le32toh(sg->len);
/*
* Preserve High Address and SG_LIST
* bits while setting the count to 1.
*/
data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
data_addr = ahd_le32toh(sg->addr)
+ (sglen & AHD_SG_LEN_MASK)
- 1;
/*
* Increment sg so it points to the
* "next" sg.
*/
sg++;
sgptr = ahd_sg_virt_to_bus(ahd, scb,
sg);
}
}
/*
* Toggle the "oddness" of the transfer length
* to handle this mid-transfer ignore wide
* residue. This ensures that the oddness is
* correct for subsequent data transfers.
*/
ahd_outb(ahd, SCB_TASK_ATTRIBUTE,
ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
^ SCB_XFERLEN_ODD);
ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
ahd_outl(ahd, SCB_RESIDUAL_DATACNT, data_cnt);
/*
* The FIFO's pointers will be updated if/when the
* sequencer re-enters a data phase.
*/
}
}
}
/*
* Reinitialize the data pointers for the active transfer
* based on its current residual.
*/
static void
ahd_reinitialize_dataptrs(struct ahd_softc *ahd)
{
struct scb *scb;
ahd_mode_state saved_modes;
u_int scb_index;
u_int wait;
uint32_t sgptr;
uint32_t resid;
uint64_t dataptr;
AHD_ASSERT_MODES(ahd, AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK,
AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK);
scb_index = ahd_get_scbptr(ahd);
scb = ahd_lookup_scb(ahd, scb_index);
/*
* Release and reacquire the FIFO so we
* have a clean slate.
*/
ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
wait = 1000;
while (--wait && !(ahd_inb(ahd, MDFFSTAT) & FIFOFREE))
ahd_delay(100);
if (wait == 0) {
ahd_print_path(ahd, scb);
printf("ahd_reinitialize_dataptrs: Forcing FIFO free.\n");
ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
}
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, DFFSTAT,
ahd_inb(ahd, DFFSTAT)
| (saved_modes == 0x11 ? CURRFIFO_1 : CURRFIFO_0));
/*
* Determine initial values for data_addr and data_cnt
* for resuming the data phase.
*/
sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
sgptr &= SG_PTR_MASK;
resid = (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 2) << 16)
| (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 1) << 8)
| ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT);
if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
struct ahd_dma64_seg *sg;
sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
/* The residual sg_ptr always points to the next sg */
sg--;
dataptr = ahd_le64toh(sg->addr)
+ (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK)
- resid;
ahd_outl(ahd, HADDR + 4, dataptr >> 32);
} else {
struct ahd_dma_seg *sg;
sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
/* The residual sg_ptr always points to the next sg */
sg--;
dataptr = ahd_le32toh(sg->addr)
+ (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK)
- resid;
ahd_outb(ahd, HADDR + 4,
(ahd_le32toh(sg->len) & ~AHD_SG_LEN_MASK) >> 24);
}
ahd_outl(ahd, HADDR, dataptr);
ahd_outb(ahd, HCNT + 2, resid >> 16);
ahd_outb(ahd, HCNT + 1, resid >> 8);
ahd_outb(ahd, HCNT, resid);
}
/*
* Handle the effects of issuing a bus device reset message.
*/
static void
ahd_handle_devreset(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
u_int lun, cam_status status, char *message,
int verbose_level)
{
#ifdef AHD_TARGET_MODE
struct ahd_tmode_tstate* tstate;
#endif
int found;
found = ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
lun, SCB_LIST_NULL, devinfo->role,
status);
#ifdef AHD_TARGET_MODE
/*
* Send an immediate notify ccb to all target mord peripheral
* drivers affected by this action.
*/
tstate = ahd->enabled_targets[devinfo->our_scsiid];
if (tstate != NULL) {
u_int cur_lun;
u_int max_lun;
if (lun != CAM_LUN_WILDCARD) {
cur_lun = 0;
max_lun = AHD_NUM_LUNS - 1;
} else {
cur_lun = lun;
max_lun = lun;
}
for (;cur_lun <= max_lun; cur_lun++) {
struct ahd_tmode_lstate* lstate;
lstate = tstate->enabled_luns[cur_lun];
if (lstate == NULL)
continue;
ahd_queue_lstate_event(ahd, lstate, devinfo->our_scsiid,
MSG_BUS_DEV_RESET, /*arg*/0);
ahd_send_lstate_events(ahd, lstate);
}
}
#endif
/*
* Go back to async/narrow transfers and renegotiate.
*/
ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_CUR, /*paused*/TRUE);
ahd_set_syncrate(ahd, devinfo, /*period*/0, /*offset*/0,
/*ppr_options*/0, AHD_TRANS_CUR,
/*paused*/TRUE);
if (status != CAM_SEL_TIMEOUT)
ahd_send_async(ahd, devinfo->channel, devinfo->target,
CAM_LUN_WILDCARD, AC_SENT_BDR);
if (message != NULL && bootverbose)
printf("%s: %s on %c:%d. %d SCBs aborted\n", ahd_name(ahd),
message, devinfo->channel, devinfo->target, found);
}
#ifdef AHD_TARGET_MODE
static void
ahd_setup_target_msgin(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
struct scb *scb)
{
/*
* To facilitate adding multiple messages together,
* each routine should increment the index and len
* variables instead of setting them explicitly.
*/
ahd->msgout_index = 0;
ahd->msgout_len = 0;
if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
ahd_build_transfer_msg(ahd, devinfo);
else
panic("ahd_intr: AWAITING target message with no message");
ahd->msgout_index = 0;
ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
}
#endif
/**************************** Initialization **********************************/
static u_int
ahd_sglist_size(struct ahd_softc *ahd)
{
bus_size_t list_size;
list_size = sizeof(struct ahd_dma_seg) * AHD_NSEG;
if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
list_size = sizeof(struct ahd_dma64_seg) * AHD_NSEG;
return (list_size);
}
/*
* Calculate the optimum S/G List allocation size. S/G elements used
* for a given transaction must be physically contiguous. Assume the
* OS will allocate full pages to us, so it doesn't make sense to request
* less than a page.
*/
static u_int
ahd_sglist_allocsize(struct ahd_softc *ahd)
{
bus_size_t sg_list_increment;
bus_size_t sg_list_size;
bus_size_t max_list_size;
bus_size_t best_list_size;
/* Start out with the minimum required for AHD_NSEG. */
sg_list_increment = ahd_sglist_size(ahd);
sg_list_size = sg_list_increment;
/* Get us as close as possible to a page in size. */
while ((sg_list_size + sg_list_increment) <= PAGE_SIZE)
sg_list_size += sg_list_increment;
/*
* Try to reduce the amount of wastage by allocating
* multiple pages.
*/
best_list_size = sg_list_size;
max_list_size = roundup(sg_list_increment, PAGE_SIZE);
if (max_list_size < 4 * PAGE_SIZE)
max_list_size = 4 * PAGE_SIZE;
if (max_list_size > (AHD_SCB_MAX_ALLOC * sg_list_increment))
max_list_size = (AHD_SCB_MAX_ALLOC * sg_list_increment);
while ((sg_list_size + sg_list_increment) <= max_list_size
&& (sg_list_size % PAGE_SIZE) != 0) {
bus_size_t new_mod;
bus_size_t best_mod;
sg_list_size += sg_list_increment;
new_mod = sg_list_size % PAGE_SIZE;
best_mod = best_list_size % PAGE_SIZE;
if (new_mod > best_mod || new_mod == 0) {
best_list_size = sg_list_size;
}
}
return (best_list_size);
}
/*
* Allocate a controller structure for a new device
* and perform initial initializion.
*/
struct ahd_softc *
ahd_alloc(void *platform_arg, char *name)
{
struct ahd_softc *ahd;
#ifndef __FreeBSD__
ahd = malloc(sizeof(*ahd), M_DEVBUF, M_NOWAIT);
if (!ahd) {
printf("aic7xxx: cannot malloc softc!\n");
free(name, M_DEVBUF);
return NULL;
}
#else
ahd = device_get_softc((device_t)platform_arg);
#endif
memset(ahd, 0, sizeof(*ahd));
ahd->seep_config = malloc(sizeof(*ahd->seep_config),
M_DEVBUF, M_NOWAIT);
if (ahd->seep_config == NULL) {
#ifndef __FreeBSD__
free(ahd, M_DEVBUF);
#endif
free(name, M_DEVBUF);
return (NULL);
}
LIST_INIT(&ahd->pending_scbs);
/* We don't know our unit number until the OSM sets it */
ahd->name = name;
ahd->unit = -1;
ahd->description = NULL;
ahd->bus_description = NULL;
ahd->channel = 'A';
ahd->chip = AHD_NONE;
ahd->features = AHD_FENONE;
ahd->bugs = AHD_BUGNONE;
ahd->flags = AHD_SPCHK_ENB_A|AHD_RESET_BUS_A|AHD_TERM_ENB_A
| AHD_EXTENDED_TRANS_A|AHD_STPWLEVEL_A;
ahd_timer_init(&ahd->reset_timer);
ahd_timer_init(&ahd->stat_timer);
ahd->int_coalescing_timer = AHD_INT_COALESCING_TIMER_DEFAULT;
ahd->int_coalescing_maxcmds = AHD_INT_COALESCING_MAXCMDS_DEFAULT;
ahd->int_coalescing_mincmds = AHD_INT_COALESCING_MINCMDS_DEFAULT;
ahd->int_coalescing_threshold = AHD_INT_COALESCING_THRESHOLD_DEFAULT;
ahd->int_coalescing_stop_threshold =
AHD_INT_COALESCING_STOP_THRESHOLD_DEFAULT;
if (ahd_platform_alloc(ahd, platform_arg) != 0) {
ahd_free(ahd);
ahd = NULL;
}
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MEMORY) != 0) {
printf("%s: scb size = 0x%x, hscb size = 0x%x\n",
ahd_name(ahd), (u_int)sizeof(struct scb),
(u_int)sizeof(struct hardware_scb));
}
#endif
return (ahd);
}
int
ahd_softc_init(struct ahd_softc *ahd)
{
ahd->unpause = 0;
ahd->pause = PAUSE;
return (0);
}
void
ahd_set_unit(struct ahd_softc *ahd, int unit)
{
ahd->unit = unit;
}
void
ahd_set_name(struct ahd_softc *ahd, char *name)
{
if (ahd->name != NULL)
free(ahd->name, M_DEVBUF);
ahd->name = name;
}
void
ahd_free(struct ahd_softc *ahd)
{
int i;
switch (ahd->init_level) {
default:
case 5:
ahd_shutdown(ahd);
/* FALLTHROUGH */
case 4:
ahd_dmamap_unload(ahd, ahd->shared_data_dmat,
ahd->shared_data_map.dmamap);
/* FALLTHROUGH */
case 3:
ahd_dmamem_free(ahd, ahd->shared_data_dmat, ahd->qoutfifo,
ahd->shared_data_map.dmamap);
ahd_dmamap_destroy(ahd, ahd->shared_data_dmat,
ahd->shared_data_map.dmamap);
/* FALLTHROUGH */
case 2:
ahd_dma_tag_destroy(ahd, ahd->shared_data_dmat);
case 1:
#ifndef __linux__
ahd_dma_tag_destroy(ahd, ahd->buffer_dmat);
#endif
break;
case 0:
break;
}
#ifndef __linux__
ahd_dma_tag_destroy(ahd, ahd->parent_dmat);
#endif
ahd_platform_free(ahd);
ahd_fini_scbdata(ahd);
for (i = 0; i < AHD_NUM_TARGETS; i++) {
struct ahd_tmode_tstate *tstate;
tstate = ahd->enabled_targets[i];
if (tstate != NULL) {
#ifdef AHD_TARGET_MODE
int j;
for (j = 0; j < AHD_NUM_LUNS; j++) {
struct ahd_tmode_lstate *lstate;
lstate = tstate->enabled_luns[j];
if (lstate != NULL) {
xpt_free_path(lstate->path);
free(lstate, M_DEVBUF);
}
}
#endif
free(tstate, M_DEVBUF);
}
}
#ifdef AHD_TARGET_MODE
if (ahd->black_hole != NULL) {
xpt_free_path(ahd->black_hole->path);
free(ahd->black_hole, M_DEVBUF);
}
#endif
if (ahd->name != NULL)
free(ahd->name, M_DEVBUF);
if (ahd->seep_config != NULL)
free(ahd->seep_config, M_DEVBUF);
if (ahd->saved_stack != NULL)
free(ahd->saved_stack, M_DEVBUF);
#ifndef __FreeBSD__
free(ahd, M_DEVBUF);
#endif
return;
}
static void
ahd_shutdown(void *arg)
{
struct ahd_softc *ahd;
ahd = (struct ahd_softc *)arg;
/*
* Stop periodic timer callbacks.
*/
ahd_timer_stop(&ahd->reset_timer);
ahd_timer_stop(&ahd->stat_timer);
/* This will reset most registers to 0, but not all */
ahd_reset(ahd, /*reinit*/FALSE);
}
/*
* Reset the controller and record some information about it
* that is only available just after a reset. If "reinit" is
* non-zero, this reset occured after initial configuration
* and the caller requests that the chip be fully reinitialized
* to a runable state. Chip interrupts are *not* enabled after
* a reinitialization. The caller must enable interrupts via
* ahd_intr_enable().
*/
int
ahd_reset(struct ahd_softc *ahd, int reinit)
{
u_int sxfrctl1;
int wait;
uint32_t cmd;
/*
* Preserve the value of the SXFRCTL1 register for all channels.
* It contains settings that affect termination and we don't want
* to disturb the integrity of the bus.
*/
ahd_pause(ahd);
ahd_update_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
sxfrctl1 = ahd_inb(ahd, SXFRCTL1);
cmd = ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2);
if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
uint32_t mod_cmd;
/*
* A4 Razor #632
* During the assertion of CHIPRST, the chip
* does not disable its parity logic prior to
* the start of the reset. This may cause a
* parity error to be detected and thus a
* spurious SERR or PERR assertion. Disble
* PERR and SERR responses during the CHIPRST.
*/
mod_cmd = cmd & ~(PCIM_CMD_PERRESPEN|PCIM_CMD_SERRESPEN);
ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
mod_cmd, /*bytes*/2);
}
ahd_outb(ahd, HCNTRL, CHIPRST | ahd->pause);
/*
* Ensure that the reset has finished. We delay 1000us
* prior to reading the register to make sure the chip
* has sufficiently completed its reset to handle register
* accesses.
*/
wait = 1000;
do {
ahd_delay(1000);
} while (--wait && !(ahd_inb(ahd, HCNTRL) & CHIPRSTACK));
if (wait == 0) {
printf("%s: WARNING - Failed chip reset! "
"Trying to initialize anyway.\n", ahd_name(ahd));
}
ahd_outb(ahd, HCNTRL, ahd->pause);
if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
/*
* Clear any latched PCI error status and restore
* previous SERR and PERR response enables.
*/
ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
0xFF, /*bytes*/1);
ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
cmd, /*bytes*/2);
}
/*
* Mode should be SCSI after a chip reset, but lets
* set it just to be safe. We touch the MODE_PTR
* register directly so as to bypass the lazy update
* code in ahd_set_modes().
*/
ahd_known_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, MODE_PTR,
ahd_build_mode_state(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI));
/*
* Restore SXFRCTL1.
*
* We must always initialize STPWEN to 1 before we
* restore the saved values. STPWEN is initialized
* to a tri-state condition which can only be cleared
* by turning it on.
*/
ahd_outb(ahd, SXFRCTL1, sxfrctl1|STPWEN);
ahd_outb(ahd, SXFRCTL1, sxfrctl1);
/* Determine chip configuration */
ahd->features &= ~AHD_WIDE;
if ((ahd_inb(ahd, SBLKCTL) & SELWIDE) != 0)
ahd->features |= AHD_WIDE;
/*
* If a recovery action has forced a chip reset,
* re-initialize the chip to our liking.
*/
if (reinit != 0)
ahd_chip_init(ahd);
return (0);
}
/*
* Determine the number of SCBs available on the controller
*/
static int
ahd_probe_scbs(struct ahd_softc *ahd) {
int i;
AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
for (i = 0; i < AHD_SCB_MAX; i++) {
int j;
ahd_set_scbptr(ahd, i);
ahd_outw(ahd, SCB_BASE, i);
for (j = 2; j < 64; j++)
ahd_outb(ahd, SCB_BASE+j, 0);
/* Start out life as unallocated (needing an abort) */
ahd_outb(ahd, SCB_CONTROL, MK_MESSAGE);
if (ahd_inw_scbram(ahd, SCB_BASE) != i)
break;
ahd_set_scbptr(ahd, 0);
if (ahd_inw_scbram(ahd, SCB_BASE) != 0)
break;
}
return (i);
}
static void
ahd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
dma_addr_t *baddr;
baddr = (dma_addr_t *)arg;
*baddr = segs->ds_addr;
}
static void
ahd_initialize_hscbs(struct ahd_softc *ahd)
{
int i;
for (i = 0; i < ahd->scb_data.maxhscbs; i++) {
ahd_set_scbptr(ahd, i);
/* Clear the control byte. */
ahd_outb(ahd, SCB_CONTROL, 0);
/* Set the next pointer */
ahd_outw(ahd, SCB_NEXT, SCB_LIST_NULL);
}
}
static int
ahd_init_scbdata(struct ahd_softc *ahd)
{
struct scb_data *scb_data;
int i;
scb_data = &ahd->scb_data;
TAILQ_INIT(&scb_data->free_scbs);
for (i = 0; i < AHD_NUM_TARGETS * AHD_NUM_LUNS_NONPKT; i++)
LIST_INIT(&scb_data->free_scb_lists[i]);
LIST_INIT(&scb_data->any_dev_free_scb_list);
SLIST_INIT(&scb_data->hscb_maps);
SLIST_INIT(&scb_data->sg_maps);
SLIST_INIT(&scb_data->sense_maps);
/* Determine the number of hardware SCBs and initialize them */
scb_data->maxhscbs = ahd_probe_scbs(ahd);
if (scb_data->maxhscbs == 0) {
printf("%s: No SCB space found\n", ahd_name(ahd));
return (ENXIO);
}
ahd_initialize_hscbs(ahd);
/*
* Create our DMA tags. These tags define the kinds of device
* accessible memory allocations and memory mappings we will
* need to perform during normal operation.
*
* Unless we need to further restrict the allocation, we rely
* on the restrictions of the parent dmat, hence the common
* use of MAXADDR and MAXSIZE.
*/
/* DMA tag for our hardware scb structures */
if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
PAGE_SIZE, /*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &scb_data->hscb_dmat) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* DMA tag for our S/G structures. */
if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/8,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
ahd_sglist_allocsize(ahd), /*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &scb_data->sg_dmat) != 0) {
goto error_exit;
}
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MEMORY) != 0)
printf("%s: ahd_sglist_allocsize = 0x%x\n", ahd_name(ahd),
ahd_sglist_allocsize(ahd));
#endif
scb_data->init_level++;
/* DMA tag for our sense buffers. We allocate in page sized chunks */
if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
PAGE_SIZE, /*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &scb_data->sense_dmat) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* Perform initial CCB allocation */
ahd_alloc_scbs(ahd);
if (scb_data->numscbs == 0) {
printf("%s: ahd_init_scbdata - "
"Unable to allocate initial scbs\n",
ahd_name(ahd));
goto error_exit;
}
/*
* Note that we were successfull
*/
return (0);
error_exit:
return (ENOMEM);
}
static struct scb *
ahd_find_scb_by_tag(struct ahd_softc *ahd, u_int tag)
{
struct scb *scb;
/*
* Look on the pending list.
*/
LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
if (SCB_GET_TAG(scb) == tag)
return (scb);
}
/*
* Then on all of the collision free lists.
*/
TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
struct scb *list_scb;
list_scb = scb;
do {
if (SCB_GET_TAG(list_scb) == tag)
return (list_scb);
list_scb = LIST_NEXT(list_scb, collision_links);
} while (list_scb);
}
/*
* And finally on the generic free list.
*/
LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
if (SCB_GET_TAG(scb) == tag)
return (scb);
}
return (NULL);
}
static void
ahd_fini_scbdata(struct ahd_softc *ahd)
{
struct scb_data *scb_data;
scb_data = &ahd->scb_data;
if (scb_data == NULL)
return;
switch (scb_data->init_level) {
default:
case 7:
{
struct map_node *sns_map;
while ((sns_map = SLIST_FIRST(&scb_data->sense_maps)) != NULL) {
SLIST_REMOVE_HEAD(&scb_data->sense_maps, links);
ahd_dmamap_unload(ahd, scb_data->sense_dmat,
sns_map->dmamap);
ahd_dmamem_free(ahd, scb_data->sense_dmat,
sns_map->vaddr, sns_map->dmamap);
free(sns_map, M_DEVBUF);
}
ahd_dma_tag_destroy(ahd, scb_data->sense_dmat);
/* FALLTHROUGH */
}
case 6:
{
struct map_node *sg_map;
while ((sg_map = SLIST_FIRST(&scb_data->sg_maps)) != NULL) {
SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
ahd_dmamap_unload(ahd, scb_data->sg_dmat,
sg_map->dmamap);
ahd_dmamem_free(ahd, scb_data->sg_dmat,
sg_map->vaddr, sg_map->dmamap);
free(sg_map, M_DEVBUF);
}
ahd_dma_tag_destroy(ahd, scb_data->sg_dmat);
/* FALLTHROUGH */
}
case 5:
{
struct map_node *hscb_map;
while ((hscb_map = SLIST_FIRST(&scb_data->hscb_maps)) != NULL) {
SLIST_REMOVE_HEAD(&scb_data->hscb_maps, links);
ahd_dmamap_unload(ahd, scb_data->hscb_dmat,
hscb_map->dmamap);
ahd_dmamem_free(ahd, scb_data->hscb_dmat,
hscb_map->vaddr, hscb_map->dmamap);
free(hscb_map, M_DEVBUF);
}
ahd_dma_tag_destroy(ahd, scb_data->hscb_dmat);
/* FALLTHROUGH */
}
case 4:
case 3:
case 2:
case 1:
case 0:
break;
}
}
/*
* DSP filter Bypass must be enabled until the first selection
* after a change in bus mode (Razor #491 and #493).
*/
static void
ahd_setup_iocell_workaround(struct ahd_softc *ahd)
{
ahd_mode_state saved_modes;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
ahd_outb(ahd, DSPDATACTL, ahd_inb(ahd, DSPDATACTL)
| BYPASSENAB | RCVROFFSTDIS | XMITOFFSTDIS);
ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) | (ENSELDO|ENSELDI));
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("%s: Setting up iocell workaround\n", ahd_name(ahd));
#endif
ahd_restore_modes(ahd, saved_modes);
ahd->flags &= ~AHD_HAD_FIRST_SEL;
}
static void
ahd_iocell_first_selection(struct ahd_softc *ahd)
{
ahd_mode_state saved_modes;
u_int sblkctl;
if ((ahd->flags & AHD_HAD_FIRST_SEL) != 0)
return;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
sblkctl = ahd_inb(ahd, SBLKCTL);
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("%s: iocell first selection\n", ahd_name(ahd));
#endif
if ((sblkctl & ENAB40) != 0) {
ahd_outb(ahd, DSPDATACTL,
ahd_inb(ahd, DSPDATACTL) & ~BYPASSENAB);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("%s: BYPASS now disabled\n", ahd_name(ahd));
#endif
}
ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) & ~(ENSELDO|ENSELDI));
ahd_outb(ahd, CLRINT, CLRSCSIINT);
ahd_restore_modes(ahd, saved_modes);
ahd->flags |= AHD_HAD_FIRST_SEL;
}
/*************************** SCB Management ***********************************/
static void
ahd_add_col_list(struct ahd_softc *ahd, struct scb *scb, u_int col_idx)
{
struct scb_list *free_list;
struct scb_tailq *free_tailq;
struct scb *first_scb;
scb->flags |= SCB_ON_COL_LIST;
AHD_SET_SCB_COL_IDX(scb, col_idx);
free_list = &ahd->scb_data.free_scb_lists[col_idx];
free_tailq = &ahd->scb_data.free_scbs;
first_scb = LIST_FIRST(free_list);
if (first_scb != NULL) {
LIST_INSERT_AFTER(first_scb, scb, collision_links);
} else {
LIST_INSERT_HEAD(free_list, scb, collision_links);
TAILQ_INSERT_TAIL(free_tailq, scb, links.tqe);
}
}
static void
ahd_rem_col_list(struct ahd_softc *ahd, struct scb *scb)
{
struct scb_list *free_list;
struct scb_tailq *free_tailq;
struct scb *first_scb;
u_int col_idx;
scb->flags &= ~SCB_ON_COL_LIST;
col_idx = AHD_GET_SCB_COL_IDX(ahd, scb);
free_list = &ahd->scb_data.free_scb_lists[col_idx];
free_tailq = &ahd->scb_data.free_scbs;
first_scb = LIST_FIRST(free_list);
if (first_scb == scb) {
struct scb *next_scb;
/*
* Maintain order in the collision free
* lists for fairness if this device has
* other colliding tags active.
*/
next_scb = LIST_NEXT(scb, collision_links);
if (next_scb != NULL) {
TAILQ_INSERT_AFTER(free_tailq, scb,
next_scb, links.tqe);
}
TAILQ_REMOVE(free_tailq, scb, links.tqe);
}
LIST_REMOVE(scb, collision_links);
}
/*
* Get a free scb. If there are none, see if we can allocate a new SCB.
*/
struct scb *
ahd_get_scb(struct ahd_softc *ahd, u_int col_idx)
{
struct scb *scb;
int tries;
tries = 0;
look_again:
TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
if (AHD_GET_SCB_COL_IDX(ahd, scb) != col_idx) {
ahd_rem_col_list(ahd, scb);
goto found;
}
}
if ((scb = LIST_FIRST(&ahd->scb_data.any_dev_free_scb_list)) == NULL) {
if (tries++ != 0)
return (NULL);
ahd_alloc_scbs(ahd);
goto look_again;
}
LIST_REMOVE(scb, links.le);
if (col_idx != AHD_NEVER_COL_IDX
&& (scb->col_scb != NULL)
&& (scb->col_scb->flags & SCB_ACTIVE) == 0) {
LIST_REMOVE(scb->col_scb, links.le);
ahd_add_col_list(ahd, scb->col_scb, col_idx);
}
found:
scb->flags |= SCB_ACTIVE;
return (scb);
}
/*
* Return an SCB resource to the free list.
*/
void
ahd_free_scb(struct ahd_softc *ahd, struct scb *scb)
{
/* Clean up for the next user */
scb->flags = SCB_FLAG_NONE;
scb->hscb->control = 0;
ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = NULL;
if (scb->col_scb == NULL) {
/*
* No collision possible. Just free normally.
*/
LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
scb, links.le);
} else if ((scb->col_scb->flags & SCB_ON_COL_LIST) != 0) {
/*
* The SCB we might have collided with is on
* a free collision list. Put both SCBs on
* the generic list.
*/
ahd_rem_col_list(ahd, scb->col_scb);
LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
scb, links.le);
LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
scb->col_scb, links.le);
} else if ((scb->col_scb->flags
& (SCB_PACKETIZED|SCB_ACTIVE)) == SCB_ACTIVE
&& (scb->col_scb->hscb->control & TAG_ENB) != 0) {
/*
* The SCB we might collide with on the next allocation
* is still active in a non-packetized, tagged, context.
* Put us on the SCB collision list.
*/
ahd_add_col_list(ahd, scb,
AHD_GET_SCB_COL_IDX(ahd, scb->col_scb));
} else {
/*
* The SCB we might collide with on the next allocation
* is either active in a packetized context, or free.
* Since we can't collide, put this SCB on the generic
* free list.
*/
LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
scb, links.le);
}
ahd_platform_scb_free(ahd, scb);
}
static void
ahd_alloc_scbs(struct ahd_softc *ahd)
{
struct scb_data *scb_data;
struct scb *next_scb;
struct hardware_scb *hscb;
struct map_node *hscb_map;
struct map_node *sg_map;
struct map_node *sense_map;
uint8_t *segs;
uint8_t *sense_data;
dma_addr_t hscb_busaddr;
dma_addr_t sg_busaddr;
dma_addr_t sense_busaddr;
int newcount;
int i;
scb_data = &ahd->scb_data;
if (scb_data->numscbs >= AHD_SCB_MAX_ALLOC)
/* Can't allocate any more */
return;
if (scb_data->scbs_left != 0) {
int offset;
offset = (PAGE_SIZE / sizeof(*hscb)) - scb_data->scbs_left;
hscb_map = SLIST_FIRST(&scb_data->hscb_maps);
hscb = &((struct hardware_scb *)hscb_map->vaddr)[offset];
hscb_busaddr = hscb_map->physaddr + (offset * sizeof(*hscb));
} else {
hscb_map = malloc(sizeof(*hscb_map), M_DEVBUF, M_NOWAIT);
if (hscb_map == NULL)
return;
/* Allocate the next batch of hardware SCBs */
if (ahd_dmamem_alloc(ahd, scb_data->hscb_dmat,
(void **)&hscb_map->vaddr,
BUS_DMA_NOWAIT, &hscb_map->dmamap) != 0) {
free(hscb_map, M_DEVBUF);
return;
}
SLIST_INSERT_HEAD(&scb_data->hscb_maps, hscb_map, links);
ahd_dmamap_load(ahd, scb_data->hscb_dmat, hscb_map->dmamap,
hscb_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
&hscb_map->physaddr, /*flags*/0);
hscb = (struct hardware_scb *)hscb_map->vaddr;
hscb_busaddr = hscb_map->physaddr;
scb_data->scbs_left = PAGE_SIZE / sizeof(*hscb);
}
if (scb_data->sgs_left != 0) {
int offset;
offset = ((ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd))
- scb_data->sgs_left) * ahd_sglist_size(ahd);
sg_map = SLIST_FIRST(&scb_data->sg_maps);
segs = sg_map->vaddr + offset;
sg_busaddr = sg_map->physaddr + offset;
} else {
sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
if (sg_map == NULL)
return;
/* Allocate the next batch of S/G lists */
if (ahd_dmamem_alloc(ahd, scb_data->sg_dmat,
(void **)&sg_map->vaddr,
BUS_DMA_NOWAIT, &sg_map->dmamap) != 0) {
free(sg_map, M_DEVBUF);
return;
}
SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
ahd_dmamap_load(ahd, scb_data->sg_dmat, sg_map->dmamap,
sg_map->vaddr, ahd_sglist_allocsize(ahd),
ahd_dmamap_cb, &sg_map->physaddr, /*flags*/0);
segs = sg_map->vaddr;
sg_busaddr = sg_map->physaddr;
scb_data->sgs_left =
ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd);
#ifdef AHD_DEBUG
if (ahd_debug & AHD_SHOW_MEMORY)
printf("Mapped SG data\n");
#endif
}
if (scb_data->sense_left != 0) {
int offset;
offset = PAGE_SIZE - (AHD_SENSE_BUFSIZE * scb_data->sense_left);
sense_map = SLIST_FIRST(&scb_data->sense_maps);
sense_data = sense_map->vaddr + offset;
sense_busaddr = sense_map->physaddr + offset;
} else {
sense_map = malloc(sizeof(*sense_map), M_DEVBUF, M_NOWAIT);
if (sense_map == NULL)
return;
/* Allocate the next batch of sense buffers */
if (ahd_dmamem_alloc(ahd, scb_data->sense_dmat,
(void **)&sense_map->vaddr,
BUS_DMA_NOWAIT, &sense_map->dmamap) != 0) {
free(sense_map, M_DEVBUF);
return;
}
SLIST_INSERT_HEAD(&scb_data->sense_maps, sense_map, links);
ahd_dmamap_load(ahd, scb_data->sense_dmat, sense_map->dmamap,
sense_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
&sense_map->physaddr, /*flags*/0);
sense_data = sense_map->vaddr;
sense_busaddr = sense_map->physaddr;
scb_data->sense_left = PAGE_SIZE / AHD_SENSE_BUFSIZE;
#ifdef AHD_DEBUG
if (ahd_debug & AHD_SHOW_MEMORY)
printf("Mapped sense data\n");
#endif
}
newcount = min(scb_data->sense_left, scb_data->scbs_left);
newcount = min(newcount, scb_data->sgs_left);
newcount = min(newcount, (AHD_SCB_MAX_ALLOC - scb_data->numscbs));
for (i = 0; i < newcount; i++) {
struct scb_platform_data *pdata;
u_int col_tag;
#ifndef __linux__
int error;
#endif
next_scb = (struct scb *)malloc(sizeof(*next_scb),
M_DEVBUF, M_NOWAIT);
if (next_scb == NULL)
break;
pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
M_DEVBUF, M_NOWAIT);
if (pdata == NULL) {
free(next_scb, M_DEVBUF);
break;
}
next_scb->platform_data = pdata;
next_scb->hscb_map = hscb_map;
next_scb->sg_map = sg_map;
next_scb->sense_map = sense_map;
next_scb->sg_list = segs;
next_scb->sense_data = sense_data;
next_scb->sense_busaddr = sense_busaddr;
memset(hscb, 0, sizeof(*hscb));
next_scb->hscb = hscb;
hscb->hscb_busaddr = ahd_htole32(hscb_busaddr);
/*
* The sequencer always starts with the second entry.
* The first entry is embedded in the scb.
*/
next_scb->sg_list_busaddr = sg_busaddr;
if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
next_scb->sg_list_busaddr
+= sizeof(struct ahd_dma64_seg);
else
next_scb->sg_list_busaddr += sizeof(struct ahd_dma_seg);
next_scb->ahd_softc = ahd;
next_scb->flags = SCB_FLAG_NONE;
#ifndef __linux__
error = ahd_dmamap_create(ahd, ahd->buffer_dmat, /*flags*/0,
&next_scb->dmamap);
if (error != 0) {
free(next_scb, M_DEVBUF);
free(pdata, M_DEVBUF);
break;
}
#endif
next_scb->hscb->tag = ahd_htole16(scb_data->numscbs);
col_tag = scb_data->numscbs ^ 0x100;
next_scb->col_scb = ahd_find_scb_by_tag(ahd, col_tag);
if (next_scb->col_scb != NULL)
next_scb->col_scb->col_scb = next_scb;
ahd_free_scb(ahd, next_scb);
hscb++;
hscb_busaddr += sizeof(*hscb);
segs += ahd_sglist_size(ahd);
sg_busaddr += ahd_sglist_size(ahd);
sense_data += AHD_SENSE_BUFSIZE;
sense_busaddr += AHD_SENSE_BUFSIZE;
scb_data->numscbs++;
scb_data->sense_left--;
scb_data->scbs_left--;
scb_data->sgs_left--;
}
}
void
ahd_controller_info(struct ahd_softc *ahd, char *buf)
{
const char *speed;
const char *type;
int len;
len = sprintf(buf, "%s: ", ahd_chip_names[ahd->chip & AHD_CHIPID_MASK]);
buf += len;
speed = "Ultra320 ";
if ((ahd->features & AHD_WIDE) != 0) {
type = "Wide ";
} else {
type = "Single ";
}
len = sprintf(buf, "%s%sChannel %c, SCSI Id=%d, ",
speed, type, ahd->channel, ahd->our_id);
buf += len;
sprintf(buf, "%s, %d SCBs", ahd->bus_description,
ahd->scb_data.maxhscbs);
}
static const char *channel_strings[] = {
"Primary Low",
"Primary High",
"Secondary Low",
"Secondary High"
};
static const char *termstat_strings[] = {
"Terminated Correctly",
"Over Terminated",
"Under Terminated",
"Not Configured"
};
/*
* Start the board, ready for normal operation
*/
int
ahd_init(struct ahd_softc *ahd)
{
uint8_t *next_vaddr;
dma_addr_t next_baddr;
size_t driver_data_size;
int i;
int error;
u_int warn_user;
uint8_t current_sensing;
uint8_t fstat;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
ahd->stack_size = ahd_probe_stack_size(ahd);
ahd->saved_stack = malloc(ahd->stack_size * sizeof(uint16_t),
M_DEVBUF, M_NOWAIT);
if (ahd->saved_stack == NULL)
return (ENOMEM);
/*
* Verify that the compiler hasn't over-agressively
* padded important structures.
*/
if (sizeof(struct hardware_scb) != 64)
panic("Hardware SCB size is incorrect");
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_DEBUG_SEQUENCER) != 0)
ahd->flags |= AHD_SEQUENCER_DEBUG;
#endif
/*
* Default to allowing initiator operations.
*/
ahd->flags |= AHD_INITIATORROLE;
/*
* Only allow target mode features if this unit has them enabled.
*/
if ((AHD_TMODE_ENABLE & (0x1 << ahd->unit)) == 0)
ahd->features &= ~AHD_TARGETMODE;
#ifndef __linux__
/* DMA tag for mapping buffers into device visible space. */
if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/ahd->flags & AHD_39BIT_ADDRESSING
? (dma_addr_t)0x7FFFFFFFFFULL
: BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
/*maxsize*/(AHD_NSEG - 1) * PAGE_SIZE,
/*nsegments*/AHD_NSEG,
/*maxsegsz*/AHD_MAXTRANSFER_SIZE,
/*flags*/BUS_DMA_ALLOCNOW,
&ahd->buffer_dmat) != 0) {
return (ENOMEM);
}
#endif
ahd->init_level++;
/*
* DMA tag for our command fifos and other data in system memory
* the card's sequencer must be able to access. For initiator
* roles, we need to allocate space for the qoutfifo. When providing
* for the target mode role, we must additionally provide space for
* the incoming target command fifo.
*/
driver_data_size = AHD_SCB_MAX * sizeof(*ahd->qoutfifo)
+ sizeof(struct hardware_scb);
if ((ahd->features & AHD_TARGETMODE) != 0)
driver_data_size += AHD_TMODE_CMDS * sizeof(struct target_cmd);
if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0)
driver_data_size += PKT_OVERRUN_BUFSIZE;
if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
driver_data_size,
/*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &ahd->shared_data_dmat) != 0) {
return (ENOMEM);
}
ahd->init_level++;
/* Allocation of driver data */
if (ahd_dmamem_alloc(ahd, ahd->shared_data_dmat,
(void **)&ahd->shared_data_map.vaddr,
BUS_DMA_NOWAIT,
&ahd->shared_data_map.dmamap) != 0) {
return (ENOMEM);
}
ahd->init_level++;
/* And permanently map it in */
ahd_dmamap_load(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap,
ahd->shared_data_map.vaddr, driver_data_size,
ahd_dmamap_cb, &ahd->shared_data_map.physaddr,
/*flags*/0);
ahd->qoutfifo = (struct ahd_completion *)ahd->shared_data_map.vaddr;
next_vaddr = (uint8_t *)&ahd->qoutfifo[AHD_QOUT_SIZE];
next_baddr = ahd->shared_data_map.physaddr
+ AHD_QOUT_SIZE*sizeof(struct ahd_completion);
if ((ahd->features & AHD_TARGETMODE) != 0) {
ahd->targetcmds = (struct target_cmd *)next_vaddr;
next_vaddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
next_baddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
}
if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0) {
ahd->overrun_buf = next_vaddr;
next_vaddr += PKT_OVERRUN_BUFSIZE;
next_baddr += PKT_OVERRUN_BUFSIZE;
}
/*
* We need one SCB to serve as the "next SCB". Since the
* tag identifier in this SCB will never be used, there is
* no point in using a valid HSCB tag from an SCB pulled from
* the standard free pool. So, we allocate this "sentinel"
* specially from the DMA safe memory chunk used for the QOUTFIFO.
*/
ahd->next_queued_hscb = (struct hardware_scb *)next_vaddr;
ahd->next_queued_hscb_map = &ahd->shared_data_map;
ahd->next_queued_hscb->hscb_busaddr = ahd_htole32(next_baddr);
ahd->init_level++;
/* Allocate SCB data now that buffer_dmat is initialized */
if (ahd_init_scbdata(ahd) != 0)
return (ENOMEM);
if ((ahd->flags & AHD_INITIATORROLE) == 0)
ahd->flags &= ~AHD_RESET_BUS_A;
/*
* Before committing these settings to the chip, give
* the OSM one last chance to modify our configuration.
*/
ahd_platform_init(ahd);
/* Bring up the chip. */
ahd_chip_init(ahd);
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
if ((ahd->flags & AHD_CURRENT_SENSING) == 0)
goto init_done;
/*
* Verify termination based on current draw and
* warn user if the bus is over/under terminated.
*/
error = ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL,
CURSENSE_ENB);
if (error != 0) {
printf("%s: current sensing timeout 1\n", ahd_name(ahd));
goto init_done;
}
for (i = 20, fstat = FLX_FSTAT_BUSY;
(fstat & FLX_FSTAT_BUSY) != 0 && i; i--) {
error = ahd_read_flexport(ahd, FLXADDR_FLEXSTAT, &fstat);
if (error != 0) {
printf("%s: current sensing timeout 2\n",
ahd_name(ahd));
goto init_done;
}
}
if (i == 0) {
printf("%s: Timedout during current-sensing test\n",
ahd_name(ahd));
goto init_done;
}
/* Latch Current Sensing status. */
error = ahd_read_flexport(ahd, FLXADDR_CURRENT_STAT, ¤t_sensing);
if (error != 0) {
printf("%s: current sensing timeout 3\n", ahd_name(ahd));
goto init_done;
}
/* Diable current sensing. */
ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, 0);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_TERMCTL) != 0) {
printf("%s: current_sensing == 0x%x\n",
ahd_name(ahd), current_sensing);
}
#endif
warn_user = 0;
for (i = 0; i < 4; i++, current_sensing >>= FLX_CSTAT_SHIFT) {
u_int term_stat;
term_stat = (current_sensing & FLX_CSTAT_MASK);
switch (term_stat) {
case FLX_CSTAT_OVER:
case FLX_CSTAT_UNDER:
warn_user++;
case FLX_CSTAT_INVALID:
case FLX_CSTAT_OKAY:
if (warn_user == 0 && bootverbose == 0)
break;
printf("%s: %s Channel %s\n", ahd_name(ahd),
channel_strings[i], termstat_strings[term_stat]);
break;
}
}
if (warn_user) {
printf("%s: WARNING. Termination is not configured correctly.\n"
"%s: WARNING. SCSI bus operations may FAIL.\n",
ahd_name(ahd), ahd_name(ahd));
}
init_done:
ahd_restart(ahd);
ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US,
ahd_stat_timer, ahd);
return (0);
}
/*
* (Re)initialize chip state after a chip reset.
*/
static void
ahd_chip_init(struct ahd_softc *ahd)
{
uint32_t busaddr;
u_int sxfrctl1;
u_int scsiseq_template;
u_int wait;
u_int i;
u_int target;
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
/*
* Take the LED out of diagnostic mode
*/
ahd_outb(ahd, SBLKCTL, ahd_inb(ahd, SBLKCTL) & ~(DIAGLEDEN|DIAGLEDON));
/*
* Return HS_MAILBOX to its default value.
*/
ahd->hs_mailbox = 0;
ahd_outb(ahd, HS_MAILBOX, 0);
/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1. */
ahd_outb(ahd, IOWNID, ahd->our_id);
ahd_outb(ahd, TOWNID, ahd->our_id);
sxfrctl1 = (ahd->flags & AHD_TERM_ENB_A) != 0 ? STPWEN : 0;
sxfrctl1 |= (ahd->flags & AHD_SPCHK_ENB_A) != 0 ? ENSPCHK : 0;
if ((ahd->bugs & AHD_LONG_SETIMO_BUG)
&& (ahd->seltime != STIMESEL_MIN)) {
/*
* The selection timer duration is twice as long
* as it should be. Halve it by adding "1" to
* the user specified setting.
*/
sxfrctl1 |= ahd->seltime + STIMESEL_BUG_ADJ;
} else {
sxfrctl1 |= ahd->seltime;
}
ahd_outb(ahd, SXFRCTL0, DFON);
ahd_outb(ahd, SXFRCTL1, sxfrctl1|ahd->seltime|ENSTIMER|ACTNEGEN);
ahd_outb(ahd, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
/*
* Now that termination is set, wait for up
* to 500ms for our transceivers to settle. If
* the adapter does not have a cable attached,
* the transceivers may never settle, so don't
* complain if we fail here.
*/
for (wait = 10000;
(ahd_inb(ahd, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
wait--)
ahd_delay(100);
/* Clear any false bus resets due to the transceivers settling */
ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
/* Initialize mode specific S/G state. */
for (i = 0; i < 2; i++) {
ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
ahd_outb(ahd, SG_STATE, 0);
ahd_outb(ahd, CLRSEQINTSRC, 0xFF);
ahd_outb(ahd, SEQIMODE,
ENSAVEPTRS|ENCFG4DATA|ENCFG4ISTAT
|ENCFG4TSTAT|ENCFG4ICMD|ENCFG4TCMD);
}
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
ahd_outb(ahd, DSCOMMAND0, ahd_inb(ahd, DSCOMMAND0)|MPARCKEN|CACHETHEN);
ahd_outb(ahd, DFF_THRSH, RD_DFTHRSH_75|WR_DFTHRSH_75);
ahd_outb(ahd, SIMODE0, ENIOERR|ENOVERRUN);
ahd_outb(ahd, SIMODE3, ENNTRAMPERR|ENOSRAMPERR);
if ((ahd->bugs & AHD_BUSFREEREV_BUG) != 0) {
ahd_outb(ahd, OPTIONMODE, AUTOACKEN|AUTO_MSGOUT_DE);
} else {
ahd_outb(ahd, OPTIONMODE, AUTOACKEN|BUSFREEREV|AUTO_MSGOUT_DE);
}
ahd_outb(ahd, SCSCHKN, CURRFIFODEF|WIDERESEN|SHVALIDSTDIS);
if ((ahd->chip & AHD_BUS_MASK) == AHD_PCIX)
/*
* Do not issue a target abort when a split completion
* error occurs. Let our PCIX interrupt handler deal
* with it instead. H2A4 Razor #625
*/
ahd_outb(ahd, PCIXCTL, ahd_inb(ahd, PCIXCTL) | SPLTSTADIS);
if ((ahd->bugs & AHD_LQOOVERRUN_BUG) != 0)
ahd_outb(ahd, LQOSCSCTL, LQONOCHKOVER);
/*
* Tweak IOCELL settings.
*/
if ((ahd->flags & AHD_HP_BOARD) != 0) {
for (i = 0; i < NUMDSPS; i++) {
ahd_outb(ahd, DSPSELECT, i);
ahd_outb(ahd, WRTBIASCTL, WRTBIASCTL_HP_DEFAULT);
}
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("%s: WRTBIASCTL now 0x%x\n", ahd_name(ahd),
WRTBIASCTL_HP_DEFAULT);
#endif
}
ahd_setup_iocell_workaround(ahd);
/*
* Enable LQI Manager interrupts.
*/
ahd_outb(ahd, LQIMODE1, ENLQIPHASE_LQ|ENLQIPHASE_NLQ|ENLIQABORT
| ENLQICRCI_LQ|ENLQICRCI_NLQ|ENLQIBADLQI
| ENLQIOVERI_LQ|ENLQIOVERI_NLQ);
ahd_outb(ahd, LQOMODE0, ENLQOATNLQ|ENLQOATNPKT|ENLQOTCRC);
/*
* We choose to have the sequencer catch LQOPHCHGINPKT errors
* manually for the command phase at the start of a packetized
* selection case. ENLQOBUSFREE should be made redundant by
* the BUSFREE interrupt, but it seems that some LQOBUSFREE
* events fail to assert the BUSFREE interrupt so we must
* also enable LQOBUSFREE interrupts.
*/
ahd_outb(ahd, LQOMODE1, ENLQOBUSFREE);
/*
* Setup sequencer interrupt handlers.
*/
ahd_outw(ahd, INTVEC1_ADDR, ahd_resolve_seqaddr(ahd, LABEL_seq_isr));
ahd_outw(ahd, INTVEC2_ADDR, ahd_resolve_seqaddr(ahd, LABEL_timer_isr));
/*
* Setup SCB Offset registers.
*/
if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb,
pkt_long_lun));
} else {
ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb, lun));
}
ahd_outb(ahd, CMDLENPTR, offsetof(struct hardware_scb, cdb_len));
ahd_outb(ahd, ATTRPTR, offsetof(struct hardware_scb, task_attribute));
ahd_outb(ahd, FLAGPTR, offsetof(struct hardware_scb, task_management));
ahd_outb(ahd, CMDPTR, offsetof(struct hardware_scb,
shared_data.idata.cdb));
ahd_outb(ahd, QNEXTPTR,
offsetof(struct hardware_scb, next_hscb_busaddr));
ahd_outb(ahd, ABRTBITPTR, MK_MESSAGE_BIT_OFFSET);
ahd_outb(ahd, ABRTBYTEPTR, offsetof(struct hardware_scb, control));
if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
ahd_outb(ahd, LUNLEN,
sizeof(ahd->next_queued_hscb->pkt_long_lun) - 1);
} else {
ahd_outb(ahd, LUNLEN, LUNLEN_SINGLE_LEVEL_LUN);
}
ahd_outb(ahd, CDBLIMIT, SCB_CDB_LEN_PTR - 1);
ahd_outb(ahd, MAXCMD, 0xFF);
ahd_outb(ahd, SCBAUTOPTR,
AUSCBPTR_EN | offsetof(struct hardware_scb, tag));
/* We haven't been enabled for target mode yet. */
ahd_outb(ahd, MULTARGID, 0);
ahd_outb(ahd, MULTARGID + 1, 0);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
/* Initialize the negotiation table. */
if ((ahd->features & AHD_NEW_IOCELL_OPTS) == 0) {
/*
* Clear the spare bytes in the neg table to avoid
* spurious parity errors.
*/
for (target = 0; target < AHD_NUM_TARGETS; target++) {
ahd_outb(ahd, NEGOADDR, target);
ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PER_DEV0);
for (i = 0; i < AHD_NUM_PER_DEV_ANNEXCOLS; i++)
ahd_outb(ahd, ANNEXDAT, 0);
}
}
for (target = 0; target < AHD_NUM_TARGETS; target++) {
struct ahd_devinfo devinfo;
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
target, &tstate);
ahd_compile_devinfo(&devinfo, ahd->our_id,
target, CAM_LUN_WILDCARD,
'A', ROLE_INITIATOR);
ahd_update_neg_table(ahd, &devinfo, &tinfo->curr);
}
ahd_outb(ahd, CLRSINT3, NTRAMPERR|OSRAMPERR);
ahd_outb(ahd, CLRINT, CLRSCSIINT);
#ifdef NEEDS_MORE_TESTING
/*
* Always enable abort on incoming L_Qs if this feature is
* supported. We use this to catch invalid SCB references.
*/
if ((ahd->bugs & AHD_ABORT_LQI_BUG) == 0)
ahd_outb(ahd, LQCTL1, ABORTPENDING);
else
#endif
ahd_outb(ahd, LQCTL1, 0);
/* All of our queues are empty */
ahd->qoutfifonext = 0;
ahd->qoutfifonext_valid_tag = QOUTFIFO_ENTRY_VALID;
ahd_outb(ahd, QOUTFIFO_ENTRY_VALID_TAG, QOUTFIFO_ENTRY_VALID);
for (i = 0; i < AHD_QOUT_SIZE; i++)
ahd->qoutfifo[i].valid_tag = 0;
ahd_sync_qoutfifo(ahd, BUS_DMASYNC_PREREAD);
ahd->qinfifonext = 0;
for (i = 0; i < AHD_QIN_SIZE; i++)
ahd->qinfifo[i] = SCB_LIST_NULL;
if ((ahd->features & AHD_TARGETMODE) != 0) {
/* All target command blocks start out invalid. */
for (i = 0; i < AHD_TMODE_CMDS; i++)
ahd->targetcmds[i].cmd_valid = 0;
ahd_sync_tqinfifo(ahd, BUS_DMASYNC_PREREAD);
ahd->tqinfifonext = 1;
ahd_outb(ahd, KERNEL_TQINPOS, ahd->tqinfifonext - 1);
ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
}
/* Initialize Scratch Ram. */
ahd_outb(ahd, SEQ_FLAGS, 0);
ahd_outb(ahd, SEQ_FLAGS2, 0);
/* We don't have any waiting selections */
ahd_outw(ahd, WAITING_TID_HEAD, SCB_LIST_NULL);
ahd_outw(ahd, WAITING_TID_TAIL, SCB_LIST_NULL);
ahd_outw(ahd, MK_MESSAGE_SCB, SCB_LIST_NULL);
ahd_outw(ahd, MK_MESSAGE_SCSIID, 0xFF);
for (i = 0; i < AHD_NUM_TARGETS; i++)
ahd_outw(ahd, WAITING_SCB_TAILS + (2 * i), SCB_LIST_NULL);
/*
* Nobody is waiting to be DMAed into the QOUTFIFO.
*/
ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
ahd_outw(ahd, COMPLETE_SCB_DMAINPROG_HEAD, SCB_LIST_NULL);
ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
/*
* The Freeze Count is 0.
*/
ahd->qfreeze_cnt = 0;
ahd_outw(ahd, QFREEZE_COUNT, 0);
ahd_outw(ahd, KERNEL_QFREEZE_COUNT, 0);
/*
* Tell the sequencer where it can find our arrays in memory.
*/
busaddr = ahd->shared_data_map.physaddr;
ahd_outl(ahd, SHARED_DATA_ADDR, busaddr);
ahd_outl(ahd, QOUTFIFO_NEXT_ADDR, busaddr);
/*
* Setup the allowed SCSI Sequences based on operational mode.
* If we are a target, we'll enable select in operations once
* we've had a lun enabled.
*/
scsiseq_template = ENAUTOATNP;
if ((ahd->flags & AHD_INITIATORROLE) != 0)
scsiseq_template |= ENRSELI;
ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq_template);
/* There are no busy SCBs yet. */
for (target = 0; target < AHD_NUM_TARGETS; target++) {
int lun;
for (lun = 0; lun < AHD_NUM_LUNS_NONPKT; lun++)
ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(target, 'A', lun));
}
/*
* Initialize the group code to command length table.
* Vendor Unique codes are set to 0 so we only capture
* the first byte of the cdb. These can be overridden
* when target mode is enabled.
*/
ahd_outb(ahd, CMDSIZE_TABLE, 5);
ahd_outb(ahd, CMDSIZE_TABLE + 1, 9);
ahd_outb(ahd, CMDSIZE_TABLE + 2, 9);
ahd_outb(ahd, CMDSIZE_TABLE + 3, 0);
ahd_outb(ahd, CMDSIZE_TABLE + 4, 15);
ahd_outb(ahd, CMDSIZE_TABLE + 5, 11);
ahd_outb(ahd, CMDSIZE_TABLE + 6, 0);
ahd_outb(ahd, CMDSIZE_TABLE + 7, 0);
/* Tell the sequencer of our initial queue positions */
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
ahd_outb(ahd, QOFF_CTLSTA, SCB_QSIZE_512);
ahd->qinfifonext = 0;
ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
ahd_set_hescb_qoff(ahd, 0);
ahd_set_snscb_qoff(ahd, 0);
ahd_set_sescb_qoff(ahd, 0);
ahd_set_sdscb_qoff(ahd, 0);
/*
* Tell the sequencer which SCB will be the next one it receives.
*/
busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr);
ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
/*
* Default to coalescing disabled.
*/
ahd_outw(ahd, INT_COALESCING_CMDCOUNT, 0);
ahd_outw(ahd, CMDS_PENDING, 0);
ahd_update_coalescing_values(ahd, ahd->int_coalescing_timer,
ahd->int_coalescing_maxcmds,
ahd->int_coalescing_mincmds);
ahd_enable_coalescing(ahd, FALSE);
ahd_loadseq(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
if (ahd->features & AHD_AIC79XXB_SLOWCRC) {
u_int negodat3 = ahd_inb(ahd, NEGCONOPTS);
negodat3 |= ENSLOWCRC;
ahd_outb(ahd, NEGCONOPTS, negodat3);
negodat3 = ahd_inb(ahd, NEGCONOPTS);
if (!(negodat3 & ENSLOWCRC))
printf("aic79xx: failed to set the SLOWCRC bit\n");
else
printf("aic79xx: SLOWCRC bit set\n");
}
}
/*
* Setup default device and controller settings.
* This should only be called if our probe has
* determined that no configuration data is available.
*/
int
ahd_default_config(struct ahd_softc *ahd)
{
int targ;
ahd->our_id = 7;
/*
* Allocate a tstate to house information for our
* initiator presence on the bus as well as the user
* data for any target mode initiator.
*/
if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
printf("%s: unable to allocate ahd_tmode_tstate. "
"Failing attach\n", ahd_name(ahd));
return (ENOMEM);
}
for (targ = 0; targ < AHD_NUM_TARGETS; targ++) {
struct ahd_devinfo devinfo;
struct ahd_initiator_tinfo *tinfo;
struct ahd_tmode_tstate *tstate;
uint16_t target_mask;
tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
targ, &tstate);
/*
* We support SPC2 and SPI4.
*/
tinfo->user.protocol_version = 4;
tinfo->user.transport_version = 4;
target_mask = 0x01 << targ;
ahd->user_discenable |= target_mask;
tstate->discenable |= target_mask;
ahd->user_tagenable |= target_mask;
#ifdef AHD_FORCE_160
tinfo->user.period = AHD_SYNCRATE_DT;
#else
tinfo->user.period = AHD_SYNCRATE_160;
#endif
tinfo->user.offset = MAX_OFFSET;
tinfo->user.ppr_options = MSG_EXT_PPR_RD_STRM
| MSG_EXT_PPR_WR_FLOW
| MSG_EXT_PPR_HOLD_MCS
| MSG_EXT_PPR_IU_REQ
| MSG_EXT_PPR_QAS_REQ
| MSG_EXT_PPR_DT_REQ;
if ((ahd->features & AHD_RTI) != 0)
tinfo->user.ppr_options |= MSG_EXT_PPR_RTI;
tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
/*
* Start out Async/Narrow/Untagged and with
* conservative protocol support.
*/
tinfo->goal.protocol_version = 2;
tinfo->goal.transport_version = 2;
tinfo->curr.protocol_version = 2;
tinfo->curr.transport_version = 2;
ahd_compile_devinfo(&devinfo, ahd->our_id,
targ, CAM_LUN_WILDCARD,
'A', ROLE_INITIATOR);
tstate->tagenable &= ~target_mask;
ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
/*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
/*paused*/TRUE);
}
return (0);
}
/*
* Parse device configuration information.
*/
int
ahd_parse_cfgdata(struct ahd_softc *ahd, struct seeprom_config *sc)
{
int targ;
int max_targ;
max_targ = sc->max_targets & CFMAXTARG;
ahd->our_id = sc->brtime_id & CFSCSIID;
/*
* Allocate a tstate to house information for our
* initiator presence on the bus as well as the user
* data for any target mode initiator.
*/
if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
printf("%s: unable to allocate ahd_tmode_tstate. "
"Failing attach\n", ahd_name(ahd));
return (ENOMEM);
}
for (targ = 0; targ < max_targ; targ++) {
struct ahd_devinfo devinfo;
struct ahd_initiator_tinfo *tinfo;
struct ahd_transinfo *user_tinfo;
struct ahd_tmode_tstate *tstate;
uint16_t target_mask;
tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
targ, &tstate);
user_tinfo = &tinfo->user;
/*
* We support SPC2 and SPI4.
*/
tinfo->user.protocol_version = 4;
tinfo->user.transport_version = 4;
target_mask = 0x01 << targ;
ahd->user_discenable &= ~target_mask;
tstate->discenable &= ~target_mask;
ahd->user_tagenable &= ~target_mask;
if (sc->device_flags[targ] & CFDISC) {
tstate->discenable |= target_mask;
ahd->user_discenable |= target_mask;
ahd->user_tagenable |= target_mask;
} else {
/*
* Cannot be packetized without disconnection.
*/
sc->device_flags[targ] &= ~CFPACKETIZED;
}
user_tinfo->ppr_options = 0;
user_tinfo->period = (sc->device_flags[targ] & CFXFER);
if (user_tinfo->period < CFXFER_ASYNC) {
if (user_tinfo->period <= AHD_PERIOD_10MHz)
user_tinfo->ppr_options |= MSG_EXT_PPR_DT_REQ;
user_tinfo->offset = MAX_OFFSET;
} else {
user_tinfo->offset = 0;
user_tinfo->period = AHD_ASYNC_XFER_PERIOD;
}
#ifdef AHD_FORCE_160
if (user_tinfo->period <= AHD_SYNCRATE_160)
user_tinfo->period = AHD_SYNCRATE_DT;
#endif
if ((sc->device_flags[targ] & CFPACKETIZED) != 0) {
user_tinfo->ppr_options |= MSG_EXT_PPR_RD_STRM
| MSG_EXT_PPR_WR_FLOW
| MSG_EXT_PPR_HOLD_MCS
| MSG_EXT_PPR_IU_REQ;
if ((ahd->features & AHD_RTI) != 0)
user_tinfo->ppr_options |= MSG_EXT_PPR_RTI;
}
if ((sc->device_flags[targ] & CFQAS) != 0)
user_tinfo->ppr_options |= MSG_EXT_PPR_QAS_REQ;
if ((sc->device_flags[targ] & CFWIDEB) != 0)
user_tinfo->width = MSG_EXT_WDTR_BUS_16_BIT;
else
user_tinfo->width = MSG_EXT_WDTR_BUS_8_BIT;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0)
printf("(%d): %x:%x:%x:%x\n", targ, user_tinfo->width,
user_tinfo->period, user_tinfo->offset,
user_tinfo->ppr_options);
#endif
/*
* Start out Async/Narrow/Untagged and with
* conservative protocol support.
*/
tstate->tagenable &= ~target_mask;
tinfo->goal.protocol_version = 2;
tinfo->goal.transport_version = 2;
tinfo->curr.protocol_version = 2;
tinfo->curr.transport_version = 2;
ahd_compile_devinfo(&devinfo, ahd->our_id,
targ, CAM_LUN_WILDCARD,
'A', ROLE_INITIATOR);
ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
/*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
/*paused*/TRUE);
}
ahd->flags &= ~AHD_SPCHK_ENB_A;
if (sc->bios_control & CFSPARITY)
ahd->flags |= AHD_SPCHK_ENB_A;
ahd->flags &= ~AHD_RESET_BUS_A;
if (sc->bios_control & CFRESETB)
ahd->flags |= AHD_RESET_BUS_A;
ahd->flags &= ~AHD_EXTENDED_TRANS_A;
if (sc->bios_control & CFEXTEND)
ahd->flags |= AHD_EXTENDED_TRANS_A;
ahd->flags &= ~AHD_BIOS_ENABLED;
if ((sc->bios_control & CFBIOSSTATE) == CFBS_ENABLED)
ahd->flags |= AHD_BIOS_ENABLED;
ahd->flags &= ~AHD_STPWLEVEL_A;
if ((sc->adapter_control & CFSTPWLEVEL) != 0)
ahd->flags |= AHD_STPWLEVEL_A;
return (0);
}
/*
* Parse device configuration information.
*/
int
ahd_parse_vpddata(struct ahd_softc *ahd, struct vpd_config *vpd)
{
int error;
error = ahd_verify_vpd_cksum(vpd);
if (error == 0)
return (EINVAL);
if ((vpd->bios_flags & VPDBOOTHOST) != 0)
ahd->flags |= AHD_BOOT_CHANNEL;
return (0);
}
void
ahd_intr_enable(struct ahd_softc *ahd, int enable)
{
u_int hcntrl;
hcntrl = ahd_inb(ahd, HCNTRL);
hcntrl &= ~INTEN;
ahd->pause &= ~INTEN;
ahd->unpause &= ~INTEN;
if (enable) {
hcntrl |= INTEN;
ahd->pause |= INTEN;
ahd->unpause |= INTEN;
}
ahd_outb(ahd, HCNTRL, hcntrl);
}
static void
ahd_update_coalescing_values(struct ahd_softc *ahd, u_int timer, u_int maxcmds,
u_int mincmds)
{
if (timer > AHD_TIMER_MAX_US)
timer = AHD_TIMER_MAX_US;
ahd->int_coalescing_timer = timer;
if (maxcmds > AHD_INT_COALESCING_MAXCMDS_MAX)
maxcmds = AHD_INT_COALESCING_MAXCMDS_MAX;
if (mincmds > AHD_INT_COALESCING_MINCMDS_MAX)
mincmds = AHD_INT_COALESCING_MINCMDS_MAX;
ahd->int_coalescing_maxcmds = maxcmds;
ahd_outw(ahd, INT_COALESCING_TIMER, timer / AHD_TIMER_US_PER_TICK);
ahd_outb(ahd, INT_COALESCING_MAXCMDS, -maxcmds);
ahd_outb(ahd, INT_COALESCING_MINCMDS, -mincmds);
}
static void
ahd_enable_coalescing(struct ahd_softc *ahd, int enable)
{
ahd->hs_mailbox &= ~ENINT_COALESCE;
if (enable)
ahd->hs_mailbox |= ENINT_COALESCE;
ahd_outb(ahd, HS_MAILBOX, ahd->hs_mailbox);
ahd_flush_device_writes(ahd);
ahd_run_qoutfifo(ahd);
}
/*
* Ensure that the card is paused in a location
* outside of all critical sections and that all
* pending work is completed prior to returning.
* This routine should only be called from outside
* an interrupt context.
*/
void
ahd_pause_and_flushwork(struct ahd_softc *ahd)
{
u_int intstat;
u_int maxloops;
maxloops = 1000;
ahd->flags |= AHD_ALL_INTERRUPTS;
ahd_pause(ahd);
/*
* Freeze the outgoing selections. We do this only
* until we are safely paused without further selections
* pending.
*/
ahd->qfreeze_cnt--;
ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
ahd_outb(ahd, SEQ_FLAGS2, ahd_inb(ahd, SEQ_FLAGS2) | SELECTOUT_QFROZEN);
do {
ahd_unpause(ahd);
/*
* Give the sequencer some time to service
* any active selections.
*/
ahd_delay(500);
ahd_intr(ahd);
ahd_pause(ahd);
intstat = ahd_inb(ahd, INTSTAT);
if ((intstat & INT_PEND) == 0) {
ahd_clear_critical_section(ahd);
intstat = ahd_inb(ahd, INTSTAT);
}
} while (--maxloops
&& (intstat != 0xFF || (ahd->features & AHD_REMOVABLE) == 0)
&& ((intstat & INT_PEND) != 0
|| (ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
|| (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) != 0));
if (maxloops == 0) {
printf("Infinite interrupt loop, INTSTAT = %x",
ahd_inb(ahd, INTSTAT));
}
ahd->qfreeze_cnt++;
ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
ahd_flush_qoutfifo(ahd);
ahd->flags &= ~AHD_ALL_INTERRUPTS;
}
#if 0
int
ahd_suspend(struct ahd_softc *ahd)
{
ahd_pause_and_flushwork(ahd);
if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
ahd_unpause(ahd);
return (EBUSY);
}
ahd_shutdown(ahd);
return (0);
}
#endif /* 0 */
#if 0
int
ahd_resume(struct ahd_softc *ahd)
{
ahd_reset(ahd, /*reinit*/TRUE);
ahd_intr_enable(ahd, TRUE);
ahd_restart(ahd);
return (0);
}
#endif /* 0 */
/************************** Busy Target Table *********************************/
/*
* Set SCBPTR to the SCB that contains the busy
* table entry for TCL. Return the offset into
* the SCB that contains the entry for TCL.
* saved_scbid is dereferenced and set to the
* scbid that should be restored once manipualtion
* of the TCL entry is complete.
*/
static __inline u_int
ahd_index_busy_tcl(struct ahd_softc *ahd, u_int *saved_scbid, u_int tcl)
{
/*
* Index to the SCB that contains the busy entry.
*/
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
*saved_scbid = ahd_get_scbptr(ahd);
ahd_set_scbptr(ahd, TCL_LUN(tcl)
| ((TCL_TARGET_OFFSET(tcl) & 0xC) << 4));
/*
* And now calculate the SCB offset to the entry.
* Each entry is 2 bytes wide, hence the
* multiplication by 2.
*/
return (((TCL_TARGET_OFFSET(tcl) & 0x3) << 1) + SCB_DISCONNECTED_LISTS);
}
/*
* Return the untagged transaction id for a given target/channel lun.
*/
static u_int
ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl)
{
u_int scbid;
u_int scb_offset;
u_int saved_scbptr;
scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
scbid = ahd_inw_scbram(ahd, scb_offset);
ahd_set_scbptr(ahd, saved_scbptr);
return (scbid);
}
static void
ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl, u_int scbid)
{
u_int scb_offset;
u_int saved_scbptr;
scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
ahd_outw(ahd, scb_offset, scbid);
ahd_set_scbptr(ahd, saved_scbptr);
}
/************************** SCB and SCB queue management **********************/
static int
ahd_match_scb(struct ahd_softc *ahd, struct scb *scb, int target,
char channel, int lun, u_int tag, role_t role)
{
int targ = SCB_GET_TARGET(ahd, scb);
char chan = SCB_GET_CHANNEL(ahd, scb);
int slun = SCB_GET_LUN(scb);
int match;
match = ((chan == channel) || (channel == ALL_CHANNELS));
if (match != 0)
match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
if (match != 0)
match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
if (match != 0) {
#ifdef AHD_TARGET_MODE
int group;
group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
if (role == ROLE_INITIATOR) {
match = (group != XPT_FC_GROUP_TMODE)
&& ((tag == SCB_GET_TAG(scb))
|| (tag == SCB_LIST_NULL));
} else if (role == ROLE_TARGET) {
match = (group == XPT_FC_GROUP_TMODE)
&& ((tag == scb->io_ctx->csio.tag_id)
|| (tag == SCB_LIST_NULL));
}
#else /* !AHD_TARGET_MODE */
match = ((tag == SCB_GET_TAG(scb)) || (tag == SCB_LIST_NULL));
#endif /* AHD_TARGET_MODE */
}
return match;
}
static void
ahd_freeze_devq(struct ahd_softc *ahd, struct scb *scb)
{
int target;
char channel;
int lun;
target = SCB_GET_TARGET(ahd, scb);
lun = SCB_GET_LUN(scb);
channel = SCB_GET_CHANNEL(ahd, scb);
ahd_search_qinfifo(ahd, target, channel, lun,
/*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
CAM_REQUEUE_REQ, SEARCH_COMPLETE);
ahd_platform_freeze_devq(ahd, scb);
}
void
ahd_qinfifo_requeue_tail(struct ahd_softc *ahd, struct scb *scb)
{
struct scb *prev_scb;
ahd_mode_state saved_modes;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
prev_scb = NULL;
if (ahd_qinfifo_count(ahd) != 0) {
u_int prev_tag;
u_int prev_pos;
prev_pos = AHD_QIN_WRAP(ahd->qinfifonext - 1);
prev_tag = ahd->qinfifo[prev_pos];
prev_scb = ahd_lookup_scb(ahd, prev_tag);
}
ahd_qinfifo_requeue(ahd, prev_scb, scb);
ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
ahd_restore_modes(ahd, saved_modes);
}
static void
ahd_qinfifo_requeue(struct ahd_softc *ahd, struct scb *prev_scb,
struct scb *scb)
{
if (prev_scb == NULL) {
uint32_t busaddr;
busaddr = ahd_le32toh(scb->hscb->hscb_busaddr);
ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
} else {
prev_scb->hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr;
ahd_sync_scb(ahd, prev_scb,
BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
}
ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb);
ahd->qinfifonext++;
scb->hscb->next_hscb_busaddr = ahd->next_queued_hscb->hscb_busaddr;
ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
}
static int
ahd_qinfifo_count(struct ahd_softc *ahd)
{
u_int qinpos;
u_int wrap_qinpos;
u_int wrap_qinfifonext;
AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
qinpos = ahd_get_snscb_qoff(ahd);
wrap_qinpos = AHD_QIN_WRAP(qinpos);
wrap_qinfifonext = AHD_QIN_WRAP(ahd->qinfifonext);
if (wrap_qinfifonext >= wrap_qinpos)
return (wrap_qinfifonext - wrap_qinpos);
else
return (wrap_qinfifonext
+ ARRAY_SIZE(ahd->qinfifo) - wrap_qinpos);
}
void
ahd_reset_cmds_pending(struct ahd_softc *ahd)
{
struct scb *scb;
ahd_mode_state saved_modes;
u_int pending_cmds;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
/*
* Don't count any commands as outstanding that the
* sequencer has already marked for completion.
*/
ahd_flush_qoutfifo(ahd);
pending_cmds = 0;
LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
pending_cmds++;
}
ahd_outw(ahd, CMDS_PENDING, pending_cmds - ahd_qinfifo_count(ahd));
ahd_restore_modes(ahd, saved_modes);
ahd->flags &= ~AHD_UPDATE_PEND_CMDS;
}
static void
ahd_done_with_status(struct ahd_softc *ahd, struct scb *scb, uint32_t status)
{
cam_status ostat;
cam_status cstat;
ostat = ahd_get_transaction_status(scb);
if (ostat == CAM_REQ_INPROG)
ahd_set_transaction_status(scb, status);
cstat = ahd_get_transaction_status(scb);
if (cstat != CAM_REQ_CMP)
ahd_freeze_scb(scb);
ahd_done(ahd, scb);
}
int
ahd_search_qinfifo(struct ahd_softc *ahd, int target, char channel,
int lun, u_int tag, role_t role, uint32_t status,
ahd_search_action action)
{
struct scb *scb;
struct scb *mk_msg_scb;
struct scb *prev_scb;
ahd_mode_state saved_modes;
u_int qinstart;
u_int qinpos;
u_int qintail;
u_int tid_next;
u_int tid_prev;
u_int scbid;
u_int seq_flags2;
u_int savedscbptr;
uint32_t busaddr;
int found;
int targets;
/* Must be in CCHAN mode */
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
/*
* Halt any pending SCB DMA. The sequencer will reinitiate
* this dma if the qinfifo is not empty once we unpause.
*/
if ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN|CCSCBDIR))
== (CCARREN|CCSCBEN|CCSCBDIR)) {
ahd_outb(ahd, CCSCBCTL,
ahd_inb(ahd, CCSCBCTL) & ~(CCARREN|CCSCBEN));
while ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN)) != 0)
;
}
/* Determine sequencer's position in the qinfifo. */
qintail = AHD_QIN_WRAP(ahd->qinfifonext);
qinstart = ahd_get_snscb_qoff(ahd);
qinpos = AHD_QIN_WRAP(qinstart);
found = 0;
prev_scb = NULL;
if (action == SEARCH_PRINT) {
printf("qinstart = %d qinfifonext = %d\nQINFIFO:",
qinstart, ahd->qinfifonext);
}
/*
* Start with an empty queue. Entries that are not chosen
* for removal will be re-added to the queue as we go.
*/
ahd->qinfifonext = qinstart;
busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr);
ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
while (qinpos != qintail) {
scb = ahd_lookup_scb(ahd, ahd->qinfifo[qinpos]);
if (scb == NULL) {
printf("qinpos = %d, SCB index = %d\n",
qinpos, ahd->qinfifo[qinpos]);
panic("Loop 1\n");
}
if (ahd_match_scb(ahd, scb, target, channel, lun, tag, role)) {
/*
* We found an scb that needs to be acted on.
*/
found++;
switch (action) {
case SEARCH_COMPLETE:
if ((scb->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB in qinfifo\n");
ahd_done_with_status(ahd, scb, status);
/* FALLTHROUGH */
case SEARCH_REMOVE:
break;
case SEARCH_PRINT:
printf(" 0x%x", ahd->qinfifo[qinpos]);
/* FALLTHROUGH */
case SEARCH_COUNT:
ahd_qinfifo_requeue(ahd, prev_scb, scb);
prev_scb = scb;
break;
}
} else {
ahd_qinfifo_requeue(ahd, prev_scb, scb);
prev_scb = scb;
}
qinpos = AHD_QIN_WRAP(qinpos+1);
}
ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
if (action == SEARCH_PRINT)
printf("\nWAITING_TID_QUEUES:\n");
/*
* Search waiting for selection lists. We traverse the
* list of "their ids" waiting for selection and, if
* appropriate, traverse the SCBs of each "their id"
* looking for matches.
*/
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
seq_flags2 = ahd_inb(ahd, SEQ_FLAGS2);
if ((seq_flags2 & PENDING_MK_MESSAGE) != 0) {
scbid = ahd_inw(ahd, MK_MESSAGE_SCB);
mk_msg_scb = ahd_lookup_scb(ahd, scbid);
} else
mk_msg_scb = NULL;
savedscbptr = ahd_get_scbptr(ahd);
tid_next = ahd_inw(ahd, WAITING_TID_HEAD);
tid_prev = SCB_LIST_NULL;
targets = 0;
for (scbid = tid_next; !SCBID_IS_NULL(scbid); scbid = tid_next) {
u_int tid_head;
u_int tid_tail;
targets++;
if (targets > AHD_NUM_TARGETS)
panic("TID LIST LOOP");
if (scbid >= ahd->scb_data.numscbs) {
printf("%s: Waiting TID List inconsistency. "
"SCB index == 0x%x, yet numscbs == 0x%x.",
ahd_name(ahd), scbid, ahd->scb_data.numscbs);
ahd_dump_card_state(ahd);
panic("for safety");
}
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: SCB = 0x%x Not Active!\n",
ahd_name(ahd), scbid);
panic("Waiting TID List traversal\n");
}
ahd_set_scbptr(ahd, scbid);
tid_next = ahd_inw_scbram(ahd, SCB_NEXT2);
if (ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
SCB_LIST_NULL, ROLE_UNKNOWN) == 0) {
tid_prev = scbid;
continue;
}
/*
* We found a list of scbs that needs to be searched.
*/
if (action == SEARCH_PRINT)
printf(" %d ( ", SCB_GET_TARGET(ahd, scb));
tid_head = scbid;
found += ahd_search_scb_list(ahd, target, channel,
lun, tag, role, status,
action, &tid_head, &tid_tail,
SCB_GET_TARGET(ahd, scb));
/*
* Check any MK_MESSAGE SCB that is still waiting to
* enter this target's waiting for selection queue.
*/
if (mk_msg_scb != NULL
&& ahd_match_scb(ahd, mk_msg_scb, target, channel,
lun, tag, role)) {
/*
* We found an scb that needs to be acted on.
*/
found++;
switch (action) {
case SEARCH_COMPLETE:
if ((mk_msg_scb->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB pending MK_MSG\n");
ahd_done_with_status(ahd, mk_msg_scb, status);
/* FALLTHROUGH */
case SEARCH_REMOVE:
{
u_int tail_offset;
printf("Removing MK_MSG scb\n");
/*
* Reset our tail to the tail of the
* main per-target list.
*/
tail_offset = WAITING_SCB_TAILS
+ (2 * SCB_GET_TARGET(ahd, mk_msg_scb));
ahd_outw(ahd, tail_offset, tid_tail);
seq_flags2 &= ~PENDING_MK_MESSAGE;
ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
ahd_outw(ahd, CMDS_PENDING,
ahd_inw(ahd, CMDS_PENDING)-1);
mk_msg_scb = NULL;
break;
}
case SEARCH_PRINT:
printf(" 0x%x", SCB_GET_TAG(scb));
/* FALLTHROUGH */
case SEARCH_COUNT:
break;
}
}
if (mk_msg_scb != NULL
&& SCBID_IS_NULL(tid_head)
&& ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
SCB_LIST_NULL, ROLE_UNKNOWN)) {
/*
* When removing the last SCB for a target
* queue with a pending MK_MESSAGE scb, we
* must queue the MK_MESSAGE scb.
*/
printf("Queueing mk_msg_scb\n");
tid_head = ahd_inw(ahd, MK_MESSAGE_SCB);
seq_flags2 &= ~PENDING_MK_MESSAGE;
ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
mk_msg_scb = NULL;
}
if (tid_head != scbid)
ahd_stitch_tid_list(ahd, tid_prev, tid_head, tid_next);
if (!SCBID_IS_NULL(tid_head))
tid_prev = tid_head;
if (action == SEARCH_PRINT)
printf(")\n");
}
/* Restore saved state. */
ahd_set_scbptr(ahd, savedscbptr);
ahd_restore_modes(ahd, saved_modes);
return (found);
}
static int
ahd_search_scb_list(struct ahd_softc *ahd, int target, char channel,
int lun, u_int tag, role_t role, uint32_t status,
ahd_search_action action, u_int *list_head,
u_int *list_tail, u_int tid)
{
struct scb *scb;
u_int scbid;
u_int next;
u_int prev;
int found;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
found = 0;
prev = SCB_LIST_NULL;
next = *list_head;
*list_tail = SCB_LIST_NULL;
for (scbid = next; !SCBID_IS_NULL(scbid); scbid = next) {
if (scbid >= ahd->scb_data.numscbs) {
printf("%s:SCB List inconsistency. "
"SCB == 0x%x, yet numscbs == 0x%x.",
ahd_name(ahd), scbid, ahd->scb_data.numscbs);
ahd_dump_card_state(ahd);
panic("for safety");
}
scb = ahd_lookup_scb(ahd, scbid);
if (scb == NULL) {
printf("%s: SCB = %d Not Active!\n",
ahd_name(ahd), scbid);
panic("Waiting List traversal\n");
}
ahd_set_scbptr(ahd, scbid);
*list_tail = scbid;
next = ahd_inw_scbram(ahd, SCB_NEXT);
if (ahd_match_scb(ahd, scb, target, channel,
lun, SCB_LIST_NULL, role) == 0) {
prev = scbid;
continue;
}
found++;
switch (action) {
case SEARCH_COMPLETE:
if ((scb->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB in Waiting List\n");
ahd_done_with_status(ahd, scb, status);
/* FALLTHROUGH */
case SEARCH_REMOVE:
ahd_rem_wscb(ahd, scbid, prev, next, tid);
*list_tail = prev;
if (SCBID_IS_NULL(prev))
*list_head = next;
break;
case SEARCH_PRINT:
printf("0x%x ", scbid);
case SEARCH_COUNT:
prev = scbid;
break;
}
if (found > AHD_SCB_MAX)
panic("SCB LIST LOOP");
}
if (action == SEARCH_COMPLETE
|| action == SEARCH_REMOVE)
ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING) - found);
return (found);
}
static void
ahd_stitch_tid_list(struct ahd_softc *ahd, u_int tid_prev,
u_int tid_cur, u_int tid_next)
{
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
if (SCBID_IS_NULL(tid_cur)) {
/* Bypass current TID list */
if (SCBID_IS_NULL(tid_prev)) {
ahd_outw(ahd, WAITING_TID_HEAD, tid_next);
} else {
ahd_set_scbptr(ahd, tid_prev);
ahd_outw(ahd, SCB_NEXT2, tid_next);
}
if (SCBID_IS_NULL(tid_next))
ahd_outw(ahd, WAITING_TID_TAIL, tid_prev);
} else {
/* Stitch through tid_cur */
if (SCBID_IS_NULL(tid_prev)) {
ahd_outw(ahd, WAITING_TID_HEAD, tid_cur);
} else {
ahd_set_scbptr(ahd, tid_prev);
ahd_outw(ahd, SCB_NEXT2, tid_cur);
}
ahd_set_scbptr(ahd, tid_cur);
ahd_outw(ahd, SCB_NEXT2, tid_next);
if (SCBID_IS_NULL(tid_next))
ahd_outw(ahd, WAITING_TID_TAIL, tid_cur);
}
}
/*
* Manipulate the waiting for selection list and return the
* scb that follows the one that we remove.
*/
static u_int
ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
u_int prev, u_int next, u_int tid)
{
u_int tail_offset;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
if (!SCBID_IS_NULL(prev)) {
ahd_set_scbptr(ahd, prev);
ahd_outw(ahd, SCB_NEXT, next);
}
/*
* SCBs that have MK_MESSAGE set in them may
* cause the tail pointer to be updated without
* setting the next pointer of the previous tail.
* Only clear the tail if the removed SCB was
* the tail.
*/
tail_offset = WAITING_SCB_TAILS + (2 * tid);
if (SCBID_IS_NULL(next)
&& ahd_inw(ahd, tail_offset) == scbid)
ahd_outw(ahd, tail_offset, prev);
ahd_add_scb_to_free_list(ahd, scbid);
return (next);
}
/*
* Add the SCB as selected by SCBPTR onto the on chip list of
* free hardware SCBs. This list is empty/unused if we are not
* performing SCB paging.
*/
static void
ahd_add_scb_to_free_list(struct ahd_softc *ahd, u_int scbid)
{
/* XXX Need some other mechanism to designate "free". */
/*
* Invalidate the tag so that our abort
* routines don't think it's active.
ahd_outb(ahd, SCB_TAG, SCB_LIST_NULL);
*/
}
/******************************** Error Handling ******************************/
/*
* Abort all SCBs that match the given description (target/channel/lun/tag),
* setting their status to the passed in status if the status has not already
* been modified from CAM_REQ_INPROG. This routine assumes that the sequencer
* is paused before it is called.
*/
static int
ahd_abort_scbs(struct ahd_softc *ahd, int target, char channel,
int lun, u_int tag, role_t role, uint32_t status)
{
struct scb *scbp;
struct scb *scbp_next;
u_int i, j;
u_int maxtarget;
u_int minlun;
u_int maxlun;
int found;
ahd_mode_state saved_modes;
/* restore this when we're done */
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
found = ahd_search_qinfifo(ahd, target, channel, lun, SCB_LIST_NULL,
role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
/*
* Clean out the busy target table for any untagged commands.
*/
i = 0;
maxtarget = 16;
if (target != CAM_TARGET_WILDCARD) {
i = target;
if (channel == 'B')
i += 8;
maxtarget = i + 1;
}
if (lun == CAM_LUN_WILDCARD) {
minlun = 0;
maxlun = AHD_NUM_LUNS_NONPKT;
} else if (lun >= AHD_NUM_LUNS_NONPKT) {
minlun = maxlun = 0;
} else {
minlun = lun;
maxlun = lun + 1;
}
if (role != ROLE_TARGET) {
for (;i < maxtarget; i++) {
for (j = minlun;j < maxlun; j++) {
u_int scbid;
u_int tcl;
tcl = BUILD_TCL_RAW(i, 'A', j);
scbid = ahd_find_busy_tcl(ahd, tcl);
scbp = ahd_lookup_scb(ahd, scbid);
if (scbp == NULL
|| ahd_match_scb(ahd, scbp, target, channel,
lun, tag, role) == 0)
continue;
ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(i, 'A', j));
}
}
}
/*
* Don't abort commands that have already completed,
* but haven't quite made it up to the host yet.
*/
ahd_flush_qoutfifo(ahd);
/*
* Go through the pending CCB list and look for
* commands for this target that are still active.
* These are other tagged commands that were
* disconnected when the reset occurred.
*/
scbp_next = LIST_FIRST(&ahd->pending_scbs);
while (scbp_next != NULL) {
scbp = scbp_next;
scbp_next = LIST_NEXT(scbp, pending_links);
if (ahd_match_scb(ahd, scbp, target, channel, lun, tag, role)) {
cam_status ostat;
ostat = ahd_get_transaction_status(scbp);
if (ostat == CAM_REQ_INPROG)
ahd_set_transaction_status(scbp, status);
if (ahd_get_transaction_status(scbp) != CAM_REQ_CMP)
ahd_freeze_scb(scbp);
if ((scbp->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB on pending list\n");
ahd_done(ahd, scbp);
found++;
}
}
ahd_restore_modes(ahd, saved_modes);
ahd_platform_abort_scbs(ahd, target, channel, lun, tag, role, status);
ahd->flags |= AHD_UPDATE_PEND_CMDS;
return found;
}
static void
ahd_reset_current_bus(struct ahd_softc *ahd)
{
uint8_t scsiseq;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~ENSCSIRST);
scsiseq = ahd_inb(ahd, SCSISEQ0) & ~(ENSELO|ENARBO|SCSIRSTO);
ahd_outb(ahd, SCSISEQ0, scsiseq | SCSIRSTO);
ahd_flush_device_writes(ahd);
ahd_delay(AHD_BUSRESET_DELAY);
/* Turn off the bus reset */
ahd_outb(ahd, SCSISEQ0, scsiseq);
ahd_flush_device_writes(ahd);
ahd_delay(AHD_BUSRESET_DELAY);
if ((ahd->bugs & AHD_SCSIRST_BUG) != 0) {
/*
* 2A Razor #474
* Certain chip state is not cleared for
* SCSI bus resets that we initiate, so
* we must reset the chip.
*/
ahd_reset(ahd, /*reinit*/TRUE);
ahd_intr_enable(ahd, /*enable*/TRUE);
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
}
ahd_clear_intstat(ahd);
}
int
ahd_reset_channel(struct ahd_softc *ahd, char channel, int initiate_reset)
{
struct ahd_devinfo devinfo;
u_int initiator;
u_int target;
u_int max_scsiid;
int found;
u_int fifo;
u_int next_fifo;
uint8_t scsiseq;
/*
* Check if the last bus reset is cleared
*/
if (ahd->flags & AHD_BUS_RESET_ACTIVE) {
printf("%s: bus reset still active\n",
ahd_name(ahd));
return 0;
}
ahd->flags |= AHD_BUS_RESET_ACTIVE;
ahd->pending_device = NULL;
ahd_compile_devinfo(&devinfo,
CAM_TARGET_WILDCARD,
CAM_TARGET_WILDCARD,
CAM_LUN_WILDCARD,
channel, ROLE_UNKNOWN);
ahd_pause(ahd);
/* Make sure the sequencer is in a safe location. */
ahd_clear_critical_section(ahd);
/*
* Run our command complete fifos to ensure that we perform
* completion processing on any commands that 'completed'
* before the reset occurred.
*/
ahd_run_qoutfifo(ahd);
#ifdef AHD_TARGET_MODE
if ((ahd->flags & AHD_TARGETROLE) != 0) {
ahd_run_tqinfifo(ahd, /*paused*/TRUE);
}
#endif
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
/*
* Disable selections so no automatic hardware
* functions will modify chip state.
*/
ahd_outb(ahd, SCSISEQ0, 0);
ahd_outb(ahd, SCSISEQ1, 0);
/*
* Safely shut down our DMA engines. Always start with
* the FIFO that is not currently active (if any are
* actively connected).
*/
next_fifo = fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
if (next_fifo > CURRFIFO_1)
/* If disconneced, arbitrarily start with FIFO1. */
next_fifo = fifo = 0;
do {
next_fifo ^= CURRFIFO_1;
ahd_set_modes(ahd, next_fifo, next_fifo);
ahd_outb(ahd, DFCNTRL,
ahd_inb(ahd, DFCNTRL) & ~(SCSIEN|HDMAEN));
while ((ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0)
ahd_delay(10);
/*
* Set CURRFIFO to the now inactive channel.
*/
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, DFFSTAT, next_fifo);
} while (next_fifo != fifo);
/*
* Reset the bus if we are initiating this reset
*/
ahd_clear_msg_state(ahd);
ahd_outb(ahd, SIMODE1,
ahd_inb(ahd, SIMODE1) & ~(ENBUSFREE|ENSCSIRST));
if (initiate_reset)
ahd_reset_current_bus(ahd);
ahd_clear_intstat(ahd);
/*
* Clean up all the state information for the
* pending transactions on this bus.
*/
found = ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, channel,
CAM_LUN_WILDCARD, SCB_LIST_NULL,
ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
/*
* Cleanup anything left in the FIFOs.
*/
ahd_clear_fifo(ahd, 0);
ahd_clear_fifo(ahd, 1);
/*
* Clear SCSI interrupt status
*/
ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
/*
* Reenable selections
*/
ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) | ENSCSIRST);
scsiseq = ahd_inb(ahd, SCSISEQ_TEMPLATE);
ahd_outb(ahd, SCSISEQ1, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
max_scsiid = (ahd->features & AHD_WIDE) ? 15 : 7;
#ifdef AHD_TARGET_MODE
/*
* Send an immediate notify ccb to all target more peripheral
* drivers affected by this action.
*/
for (target = 0; target <= max_scsiid; target++) {
struct ahd_tmode_tstate* tstate;
u_int lun;
tstate = ahd->enabled_targets[target];
if (tstate == NULL)
continue;
for (lun = 0; lun < AHD_NUM_LUNS; lun++) {
struct ahd_tmode_lstate* lstate;
lstate = tstate->enabled_luns[lun];
if (lstate == NULL)
continue;
ahd_queue_lstate_event(ahd, lstate, CAM_TARGET_WILDCARD,
EVENT_TYPE_BUS_RESET, /*arg*/0);
ahd_send_lstate_events(ahd, lstate);
}
}
#endif
/*
* Revert to async/narrow transfers until we renegotiate.
*/
for (target = 0; target <= max_scsiid; target++) {
if (ahd->enabled_targets[target] == NULL)
continue;
for (initiator = 0; initiator <= max_scsiid; initiator++) {
struct ahd_devinfo devinfo;
ahd_compile_devinfo(&devinfo, target, initiator,
CAM_LUN_WILDCARD,
'A', ROLE_UNKNOWN);
ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHD_TRANS_CUR, /*paused*/TRUE);
ahd_set_syncrate(ahd, &devinfo, /*period*/0,
/*offset*/0, /*ppr_options*/0,
AHD_TRANS_CUR, /*paused*/TRUE);
}
}
/* Notify the XPT that a bus reset occurred */
ahd_send_async(ahd, devinfo.channel, CAM_TARGET_WILDCARD,
CAM_LUN_WILDCARD, AC_BUS_RESET);
ahd_restart(ahd);
return (found);
}
/**************************** Statistics Processing ***************************/
static void
ahd_stat_timer(void *arg)
{
struct ahd_softc *ahd = arg;
u_long s;
int enint_coal;
ahd_lock(ahd, &s);
enint_coal = ahd->hs_mailbox & ENINT_COALESCE;
if (ahd->cmdcmplt_total > ahd->int_coalescing_threshold)
enint_coal |= ENINT_COALESCE;
else if (ahd->cmdcmplt_total < ahd->int_coalescing_stop_threshold)
enint_coal &= ~ENINT_COALESCE;
if (enint_coal != (ahd->hs_mailbox & ENINT_COALESCE)) {
ahd_enable_coalescing(ahd, enint_coal);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_INT_COALESCING) != 0)
printf("%s: Interrupt coalescing "
"now %sabled. Cmds %d\n",
ahd_name(ahd),
(enint_coal & ENINT_COALESCE) ? "en" : "dis",
ahd->cmdcmplt_total);
#endif
}
ahd->cmdcmplt_bucket = (ahd->cmdcmplt_bucket+1) & (AHD_STAT_BUCKETS-1);
ahd->cmdcmplt_total -= ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket];
ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket] = 0;
ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US,
ahd_stat_timer, ahd);
ahd_unlock(ahd, &s);
}
/****************************** Status Processing *****************************/
static void
ahd_handle_scsi_status(struct ahd_softc *ahd, struct scb *scb)
{
struct hardware_scb *hscb;
int paused;
/*
* The sequencer freezes its select-out queue
* anytime a SCSI status error occurs. We must
* handle the error and increment our qfreeze count
* to allow the sequencer to continue. We don't
* bother clearing critical sections here since all
* operations are on data structures that the sequencer
* is not touching once the queue is frozen.
*/
hscb = scb->hscb;
if (ahd_is_paused(ahd)) {
paused = 1;
} else {
paused = 0;
ahd_pause(ahd);
}
/* Freeze the queue until the client sees the error. */
ahd_freeze_devq(ahd, scb);
ahd_freeze_scb(scb);
ahd->qfreeze_cnt++;
ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
if (paused == 0)
ahd_unpause(ahd);
/* Don't want to clobber the original sense code */
if ((scb->flags & SCB_SENSE) != 0) {
/*
* Clear the SCB_SENSE Flag and perform
* a normal command completion.
*/
scb->flags &= ~SCB_SENSE;
ahd_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
ahd_done(ahd, scb);
return;
}
ahd_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
ahd_set_scsi_status(scb, hscb->shared_data.istatus.scsi_status);
switch (hscb->shared_data.istatus.scsi_status) {
case STATUS_PKT_SENSE:
{
struct scsi_status_iu_header *siu;
ahd_sync_sense(ahd, scb, BUS_DMASYNC_POSTREAD);
siu = (struct scsi_status_iu_header *)scb->sense_data;
ahd_set_scsi_status(scb, siu->status);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_SENSE) != 0) {
ahd_print_path(ahd, scb);
printf("SCB 0x%x Received PKT Status of 0x%x\n",
SCB_GET_TAG(scb), siu->status);
printf("\tflags = 0x%x, sense len = 0x%x, "
"pktfail = 0x%x\n",
siu->flags, scsi_4btoul(siu->sense_length),
scsi_4btoul(siu->pkt_failures_length));
}
#endif
if ((siu->flags & SIU_RSPVALID) != 0) {
ahd_print_path(ahd, scb);
if (scsi_4btoul(siu->pkt_failures_length) < 4) {
printf("Unable to parse pkt_failures\n");
} else {
switch (SIU_PKTFAIL_CODE(siu)) {
case SIU_PFC_NONE:
printf("No packet failure found\n");
break;
case SIU_PFC_CIU_FIELDS_INVALID:
printf("Invalid Command IU Field\n");
break;
case SIU_PFC_TMF_NOT_SUPPORTED:
printf("TMF not supportd\n");
break;
case SIU_PFC_TMF_FAILED:
printf("TMF failed\n");
break;
case SIU_PFC_INVALID_TYPE_CODE:
printf("Invalid L_Q Type code\n");
break;
case SIU_PFC_ILLEGAL_REQUEST:
printf("Illegal request\n");
default:
break;
}
}
if (siu->status == SCSI_STATUS_OK)
ahd_set_transaction_status(scb,
CAM_REQ_CMP_ERR);
}
if ((siu->flags & SIU_SNSVALID) != 0) {
scb->flags |= SCB_PKT_SENSE;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_SENSE) != 0)
printf("Sense data available\n");
#endif
}
ahd_done(ahd, scb);
break;
}
case SCSI_STATUS_CMD_TERMINATED:
case SCSI_STATUS_CHECK_COND:
{
struct ahd_devinfo devinfo;
struct ahd_dma_seg *sg;
struct scsi_sense *sc;
struct ahd_initiator_tinfo *targ_info;
struct ahd_tmode_tstate *tstate;
struct ahd_transinfo *tinfo;
#ifdef AHD_DEBUG
if (ahd_debug & AHD_SHOW_SENSE) {
ahd_print_path(ahd, scb);
printf("SCB %d: requests Check Status\n",
SCB_GET_TAG(scb));
}
#endif
if (ahd_perform_autosense(scb) == 0)
break;
ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
SCB_GET_TARGET(ahd, scb),
SCB_GET_LUN(scb),
SCB_GET_CHANNEL(ahd, scb),
ROLE_INITIATOR);
targ_info = ahd_fetch_transinfo(ahd,
devinfo.channel,
devinfo.our_scsiid,
devinfo.target,
&tstate);
tinfo = &targ_info->curr;
sg = scb->sg_list;
sc = (struct scsi_sense *)hscb->shared_data.idata.cdb;
/*
* Save off the residual if there is one.
*/
ahd_update_residual(ahd, scb);
#ifdef AHD_DEBUG
if (ahd_debug & AHD_SHOW_SENSE) {
ahd_print_path(ahd, scb);
printf("Sending Sense\n");
}
#endif
scb->sg_count = 0;
sg = ahd_sg_setup(ahd, scb, sg, ahd_get_sense_bufaddr(ahd, scb),
ahd_get_sense_bufsize(ahd, scb),
/*last*/TRUE);
sc->opcode = REQUEST_SENSE;
sc->byte2 = 0;
if (tinfo->protocol_version <= SCSI_REV_2
&& SCB_GET_LUN(scb) < 8)
sc->byte2 = SCB_GET_LUN(scb) << 5;
sc->unused[0] = 0;
sc->unused[1] = 0;
sc->length = ahd_get_sense_bufsize(ahd, scb);
sc->control = 0;
/*
* We can't allow the target to disconnect.
* This will be an untagged transaction and
* having the target disconnect will make this
* transaction indestinguishable from outstanding
* tagged transactions.
*/
hscb->control = 0;
/*
* This request sense could be because the
* the device lost power or in some other
* way has lost our transfer negotiations.
* Renegotiate if appropriate. Unit attention
* errors will be reported before any data
* phases occur.
*/
if (ahd_get_residual(scb) == ahd_get_transfer_length(scb)) {
ahd_update_neg_request(ahd, &devinfo,
tstate, targ_info,
AHD_NEG_IF_NON_ASYNC);
}
if (tstate->auto_negotiate & devinfo.target_mask) {
hscb->control |= MK_MESSAGE;
scb->flags &=
~(SCB_NEGOTIATE|SCB_ABORT|SCB_DEVICE_RESET);
scb->flags |= SCB_AUTO_NEGOTIATE;
}
hscb->cdb_len = sizeof(*sc);
ahd_setup_data_scb(ahd, scb);
scb->flags |= SCB_SENSE;
ahd_queue_scb(ahd, scb);
break;
}
case SCSI_STATUS_OK:
printf("%s: Interrupted for staus of 0???\n",
ahd_name(ahd));
/* FALLTHROUGH */
default:
ahd_done(ahd, scb);
break;
}
}
static void
ahd_handle_scb_status(struct ahd_softc *ahd, struct scb *scb)
{
if (scb->hscb->shared_data.istatus.scsi_status != 0) {
ahd_handle_scsi_status(ahd, scb);
} else {
ahd_calc_residual(ahd, scb);
ahd_done(ahd, scb);
}
}
/*
* Calculate the residual for a just completed SCB.
*/
static void
ahd_calc_residual(struct ahd_softc *ahd, struct scb *scb)
{
struct hardware_scb *hscb;
struct initiator_status *spkt;
uint32_t sgptr;
uint32_t resid_sgptr;
uint32_t resid;
/*
* 5 cases.
* 1) No residual.
* SG_STATUS_VALID clear in sgptr.
* 2) Transferless command
* 3) Never performed any transfers.
* sgptr has SG_FULL_RESID set.
* 4) No residual but target did not
* save data pointers after the
* last transfer, so sgptr was
* never updated.
* 5) We have a partial residual.
* Use residual_sgptr to determine
* where we are.
*/
hscb = scb->hscb;
sgptr = ahd_le32toh(hscb->sgptr);
if ((sgptr & SG_STATUS_VALID) == 0)
/* Case 1 */
return;
sgptr &= ~SG_STATUS_VALID;
if ((sgptr & SG_LIST_NULL) != 0)
/* Case 2 */
return;
/*
* Residual fields are the same in both
* target and initiator status packets,
* so we can always use the initiator fields
* regardless of the role for this SCB.
*/
spkt = &hscb->shared_data.istatus;
resid_sgptr = ahd_le32toh(spkt->residual_sgptr);
if ((sgptr & SG_FULL_RESID) != 0) {
/* Case 3 */
resid = ahd_get_transfer_length(scb);
} else if ((resid_sgptr & SG_LIST_NULL) != 0) {
/* Case 4 */
return;
} else if ((resid_sgptr & SG_OVERRUN_RESID) != 0) {
ahd_print_path(ahd, scb);
printf("data overrun detected Tag == 0x%x.\n",
SCB_GET_TAG(scb));
ahd_freeze_devq(ahd, scb);
ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
ahd_freeze_scb(scb);
return;
} else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
/* NOTREACHED */
} else {
struct ahd_dma_seg *sg;
/*
* Remainder of the SG where the transfer
* stopped.
*/
resid = ahd_le32toh(spkt->residual_datacnt) & AHD_SG_LEN_MASK;
sg = ahd_sg_bus_to_virt(ahd, scb, resid_sgptr & SG_PTR_MASK);
/* The residual sg_ptr always points to the next sg */
sg--;
/*
* Add up the contents of all residual
* SG segments that are after the SG where
* the transfer stopped.
*/
while ((ahd_le32toh(sg->len) & AHD_DMA_LAST_SEG) == 0) {
sg++;
resid += ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
}
}
if ((scb->flags & SCB_SENSE) == 0)
ahd_set_residual(scb, resid);
else
ahd_set_sense_residual(scb, resid);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_MISC) != 0) {
ahd_print_path(ahd, scb);
printf("Handled %sResidual of %d bytes\n",
(scb->flags & SCB_SENSE) ? "Sense " : "", resid);
}
#endif
}
/******************************* Target Mode **********************************/
#ifdef AHD_TARGET_MODE
/*
* Add a target mode event to this lun's queue
*/
static void
ahd_queue_lstate_event(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate,
u_int initiator_id, u_int event_type, u_int event_arg)
{
struct ahd_tmode_event *event;
int pending;
xpt_freeze_devq(lstate->path, /*count*/1);
if (lstate->event_w_idx >= lstate->event_r_idx)
pending = lstate->event_w_idx - lstate->event_r_idx;
else
pending = AHD_TMODE_EVENT_BUFFER_SIZE + 1
- (lstate->event_r_idx - lstate->event_w_idx);
if (event_type == EVENT_TYPE_BUS_RESET
|| event_type == MSG_BUS_DEV_RESET) {
/*
* Any earlier events are irrelevant, so reset our buffer.
* This has the effect of allowing us to deal with reset
* floods (an external device holding down the reset line)
* without losing the event that is really interesting.
*/
lstate->event_r_idx = 0;
lstate->event_w_idx = 0;
xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
}
if (pending == AHD_TMODE_EVENT_BUFFER_SIZE) {
xpt_print_path(lstate->path);
printf("immediate event %x:%x lost\n",
lstate->event_buffer[lstate->event_r_idx].event_type,
lstate->event_buffer[lstate->event_r_idx].event_arg);
lstate->event_r_idx++;
if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
lstate->event_r_idx = 0;
xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
}
event = &lstate->event_buffer[lstate->event_w_idx];
event->initiator_id = initiator_id;
event->event_type = event_type;
event->event_arg = event_arg;
lstate->event_w_idx++;
if (lstate->event_w_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
lstate->event_w_idx = 0;
}
/*
* Send any target mode events queued up waiting
* for immediate notify resources.
*/
void
ahd_send_lstate_events(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate)
{
struct ccb_hdr *ccbh;
struct ccb_immed_notify *inot;
while (lstate->event_r_idx != lstate->event_w_idx
&& (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
struct ahd_tmode_event *event;
event = &lstate->event_buffer[lstate->event_r_idx];
SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
inot = (struct ccb_immed_notify *)ccbh;
switch (event->event_type) {
case EVENT_TYPE_BUS_RESET:
ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
break;
default:
ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
inot->message_args[0] = event->event_type;
inot->message_args[1] = event->event_arg;
break;
}
inot->initiator_id = event->initiator_id;
inot->sense_len = 0;
xpt_done((union ccb *)inot);
lstate->event_r_idx++;
if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
lstate->event_r_idx = 0;
}
}
#endif
/******************** Sequencer Program Patching/Download *********************/
#ifdef AHD_DUMP_SEQ
void
ahd_dumpseq(struct ahd_softc* ahd)
{
int i;
int max_prog;
max_prog = 2048;
ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
ahd_outw(ahd, PRGMCNT, 0);
for (i = 0; i < max_prog; i++) {
uint8_t ins_bytes[4];
ahd_insb(ahd, SEQRAM, ins_bytes, 4);
printf("0x%08x\n", ins_bytes[0] << 24
| ins_bytes[1] << 16
| ins_bytes[2] << 8
| ins_bytes[3]);
}
}
#endif
static void
ahd_loadseq(struct ahd_softc *ahd)
{
struct cs cs_table[num_critical_sections];
u_int begin_set[num_critical_sections];
u_int end_set[num_critical_sections];
struct patch *cur_patch;
u_int cs_count;
u_int cur_cs;
u_int i;
int downloaded;
u_int skip_addr;
u_int sg_prefetch_cnt;
u_int sg_prefetch_cnt_limit;
u_int sg_prefetch_align;
u_int sg_size;
u_int cacheline_mask;
uint8_t download_consts[DOWNLOAD_CONST_COUNT];
if (bootverbose)
printf("%s: Downloading Sequencer Program...",
ahd_name(ahd));
#if DOWNLOAD_CONST_COUNT != 8
#error "Download Const Mismatch"
#endif
/*
* Start out with 0 critical sections
* that apply to this firmware load.
*/
cs_count = 0;
cur_cs = 0;
memset(begin_set, 0, sizeof(begin_set));
memset(end_set, 0, sizeof(end_set));
/*
* Setup downloadable constant table.
*
* The computation for the S/G prefetch variables is
* a bit complicated. We would like to always fetch
* in terms of cachelined sized increments. However,
* if the cacheline is not an even multiple of the
* SG element size or is larger than our SG RAM, using
* just the cache size might leave us with only a portion
* of an SG element at the tail of a prefetch. If the
* cacheline is larger than our S/G prefetch buffer less
* the size of an SG element, we may round down to a cacheline
* that doesn't contain any or all of the S/G of interest
* within the bounds of our S/G ram. Provide variables to
* the sequencer that will allow it to handle these edge
* cases.
*/
/* Start by aligning to the nearest cacheline. */
sg_prefetch_align = ahd->pci_cachesize;
if (sg_prefetch_align == 0)
sg_prefetch_align = 8;
/* Round down to the nearest power of 2. */
while (powerof2(sg_prefetch_align) == 0)
sg_prefetch_align--;
cacheline_mask = sg_prefetch_align - 1;
/*
* If the cacheline boundary is greater than half our prefetch RAM
* we risk not being able to fetch even a single complete S/G
* segment if we align to that boundary.
*/
if (sg_prefetch_align > CCSGADDR_MAX/2)
sg_prefetch_align = CCSGADDR_MAX/2;
/* Start by fetching a single cacheline. */
sg_prefetch_cnt = sg_prefetch_align;
/*
* Increment the prefetch count by cachelines until
* at least one S/G element will fit.
*/
sg_size = sizeof(struct ahd_dma_seg);
if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
sg_size = sizeof(struct ahd_dma64_seg);
while (sg_prefetch_cnt < sg_size)
sg_prefetch_cnt += sg_prefetch_align;
/*
* If the cacheline is not an even multiple of
* the S/G size, we may only get a partial S/G when
* we align. Add a cacheline if this is the case.
*/
if ((sg_prefetch_align % sg_size) != 0
&& (sg_prefetch_cnt < CCSGADDR_MAX))
sg_prefetch_cnt += sg_prefetch_align;
/*
* Lastly, compute a value that the sequencer can use
* to determine if the remainder of the CCSGRAM buffer
* has a full S/G element in it.
*/
sg_prefetch_cnt_limit = -(sg_prefetch_cnt - sg_size + 1);
download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
download_consts[SG_PREFETCH_CNT_LIMIT] = sg_prefetch_cnt_limit;
download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_align - 1);
download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_align - 1);
download_consts[SG_SIZEOF] = sg_size;
download_consts[PKT_OVERRUN_BUFOFFSET] =
(ahd->overrun_buf - (uint8_t *)ahd->qoutfifo) / 256;
download_consts[SCB_TRANSFER_SIZE] = SCB_TRANSFER_SIZE_1BYTE_LUN;
download_consts[CACHELINE_MASK] = cacheline_mask;
cur_patch = patches;
downloaded = 0;
skip_addr = 0;
ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
ahd_outw(ahd, PRGMCNT, 0);
for (i = 0; i < sizeof(seqprog)/4; i++) {
if (ahd_check_patch(ahd, &cur_patch, i, &skip_addr) == 0) {
/*
* Don't download this instruction as it
* is in a patch that was removed.
*/
continue;
}
/*
* Move through the CS table until we find a CS
* that might apply to this instruction.
*/
for (; cur_cs < num_critical_sections; cur_cs++) {
if (critical_sections[cur_cs].end <= i) {
if (begin_set[cs_count] == TRUE
&& end_set[cs_count] == FALSE) {
cs_table[cs_count].end = downloaded;
end_set[cs_count] = TRUE;
cs_count++;
}
continue;
}
if (critical_sections[cur_cs].begin <= i
&& begin_set[cs_count] == FALSE) {
cs_table[cs_count].begin = downloaded;
begin_set[cs_count] = TRUE;
}
break;
}
ahd_download_instr(ahd, i, download_consts);
downloaded++;
}
ahd->num_critical_sections = cs_count;
if (cs_count != 0) {
cs_count *= sizeof(struct cs);
ahd->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
if (ahd->critical_sections == NULL)
panic("ahd_loadseq: Could not malloc");
memcpy(ahd->critical_sections, cs_table, cs_count);
}
ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE);
if (bootverbose) {
printf(" %d instructions downloaded\n", downloaded);
printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
ahd_name(ahd), ahd->features, ahd->bugs, ahd->flags);
}
}
static int
ahd_check_patch(struct ahd_softc *ahd, struct patch **start_patch,
u_int start_instr, u_int *skip_addr)
{
struct patch *cur_patch;
struct patch *last_patch;
u_int num_patches;
num_patches = ARRAY_SIZE(patches);
last_patch = &patches[num_patches];
cur_patch = *start_patch;
while (cur_patch < last_patch && start_instr == cur_patch->begin) {
if (cur_patch->patch_func(ahd) == 0) {
/* Start rejecting code */
*skip_addr = start_instr + cur_patch->skip_instr;
cur_patch += cur_patch->skip_patch;
} else {
/* Accepted this patch. Advance to the next
* one and wait for our intruction pointer to
* hit this point.
*/
cur_patch++;
}
}
*start_patch = cur_patch;
if (start_instr < *skip_addr)
/* Still skipping */
return (0);
return (1);
}
static u_int
ahd_resolve_seqaddr(struct ahd_softc *ahd, u_int address)
{
struct patch *cur_patch;
int address_offset;
u_int skip_addr;
u_int i;
address_offset = 0;
cur_patch = patches;
skip_addr = 0;
for (i = 0; i < address;) {
ahd_check_patch(ahd, &cur_patch, i, &skip_addr);
if (skip_addr > i) {
int end_addr;
end_addr = min(address, skip_addr);
address_offset += end_addr - i;
i = skip_addr;
} else {
i++;
}
}
return (address - address_offset);
}
static void
ahd_download_instr(struct ahd_softc *ahd, u_int instrptr, uint8_t *dconsts)
{
union ins_formats instr;
struct ins_format1 *fmt1_ins;
struct ins_format3 *fmt3_ins;
u_int opcode;
/*
* The firmware is always compiled into a little endian format.
*/
instr.integer = ahd_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
fmt1_ins = &instr.format1;
fmt3_ins = NULL;
/* Pull the opcode */
opcode = instr.format1.opcode;
switch (opcode) {
case AIC_OP_JMP:
case AIC_OP_JC:
case AIC_OP_JNC:
case AIC_OP_CALL:
case AIC_OP_JNE:
case AIC_OP_JNZ:
case AIC_OP_JE:
case AIC_OP_JZ:
{
fmt3_ins = &instr.format3;
fmt3_ins->address = ahd_resolve_seqaddr(ahd, fmt3_ins->address);
/* FALLTHROUGH */
}
case AIC_OP_OR:
case AIC_OP_AND:
case AIC_OP_XOR:
case AIC_OP_ADD:
case AIC_OP_ADC:
case AIC_OP_BMOV:
if (fmt1_ins->parity != 0) {
fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
}
fmt1_ins->parity = 0;
/* FALLTHROUGH */
case AIC_OP_ROL:
{
int i, count;
/* Calculate odd parity for the instruction */
for (i = 0, count = 0; i < 31; i++) {
uint32_t mask;
mask = 0x01 << i;
if ((instr.integer & mask) != 0)
count++;
}
if ((count & 0x01) == 0)
instr.format1.parity = 1;
/* The sequencer is a little endian cpu */
instr.integer = ahd_htole32(instr.integer);
ahd_outsb(ahd, SEQRAM, instr.bytes, 4);
break;
}
default:
panic("Unknown opcode encountered in seq program");
break;
}
}
static int
ahd_probe_stack_size(struct ahd_softc *ahd)
{
int last_probe;
last_probe = 0;
while (1) {
int i;
/*
* We avoid using 0 as a pattern to avoid
* confusion if the stack implementation
* "back-fills" with zeros when "poping'
* entries.
*/
for (i = 1; i <= last_probe+1; i++) {
ahd_outb(ahd, STACK, i & 0xFF);
ahd_outb(ahd, STACK, (i >> 8) & 0xFF);
}
/* Verify */
for (i = last_probe+1; i > 0; i--) {
u_int stack_entry;
stack_entry = ahd_inb(ahd, STACK)
|(ahd_inb(ahd, STACK) << 8);
if (stack_entry != i)
goto sized;
}
last_probe++;
}
sized:
return (last_probe);
}
int
ahd_print_register(ahd_reg_parse_entry_t *table, u_int num_entries,
const char *name, u_int address, u_int value,
u_int *cur_column, u_int wrap_point)
{
int printed;
u_int printed_mask;
if (cur_column != NULL && *cur_column >= wrap_point) {
printf("\n");
*cur_column = 0;
}
printed = printf("%s[0x%x]", name, value);
if (table == NULL) {
printed += printf(" ");
*cur_column += printed;
return (printed);
}
printed_mask = 0;
while (printed_mask != 0xFF) {
int entry;
for (entry = 0; entry < num_entries; entry++) {
if (((value & table[entry].mask)
!= table[entry].value)
|| ((printed_mask & table[entry].mask)
== table[entry].mask))
continue;
printed += printf("%s%s",
printed_mask == 0 ? ":(" : "|",
table[entry].name);
printed_mask |= table[entry].mask;
break;
}
if (entry >= num_entries)
break;
}
if (printed_mask != 0)
printed += printf(") ");
else
printed += printf(" ");
if (cur_column != NULL)
*cur_column += printed;
return (printed);
}
void
ahd_dump_card_state(struct ahd_softc *ahd)
{
struct scb *scb;
ahd_mode_state saved_modes;
u_int dffstat;
int paused;
u_int scb_index;
u_int saved_scb_index;
u_int cur_col;
int i;
if (ahd_is_paused(ahd)) {
paused = 1;
} else {
paused = 0;
ahd_pause(ahd);
}
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
"%s: Dumping Card State at program address 0x%x Mode 0x%x\n",
ahd_name(ahd),
ahd_inw(ahd, CURADDR),
ahd_build_mode_state(ahd, ahd->saved_src_mode,
ahd->saved_dst_mode));
if (paused)
printf("Card was paused\n");
if (ahd_check_cmdcmpltqueues(ahd))
printf("Completions are pending\n");
/*
* Mode independent registers.
*/
cur_col = 0;
ahd_intstat_print(ahd_inb(ahd, INTSTAT), &cur_col, 50);
ahd_seloid_print(ahd_inb(ahd, SELOID), &cur_col, 50);
ahd_selid_print(ahd_inb(ahd, SELID), &cur_col, 50);
ahd_hs_mailbox_print(ahd_inb(ahd, LOCAL_HS_MAILBOX), &cur_col, 50);
ahd_intctl_print(ahd_inb(ahd, INTCTL), &cur_col, 50);
ahd_seqintstat_print(ahd_inb(ahd, SEQINTSTAT), &cur_col, 50);
ahd_saved_mode_print(ahd_inb(ahd, SAVED_MODE), &cur_col, 50);
ahd_dffstat_print(ahd_inb(ahd, DFFSTAT), &cur_col, 50);
ahd_scsisigi_print(ahd_inb(ahd, SCSISIGI), &cur_col, 50);
ahd_scsiphase_print(ahd_inb(ahd, SCSIPHASE), &cur_col, 50);
ahd_scsibus_print(ahd_inb(ahd, SCSIBUS), &cur_col, 50);
ahd_lastphase_print(ahd_inb(ahd, LASTPHASE), &cur_col, 50);
ahd_scsiseq0_print(ahd_inb(ahd, SCSISEQ0), &cur_col, 50);
ahd_scsiseq1_print(ahd_inb(ahd, SCSISEQ1), &cur_col, 50);
ahd_seqctl0_print(ahd_inb(ahd, SEQCTL0), &cur_col, 50);
ahd_seqintctl_print(ahd_inb(ahd, SEQINTCTL), &cur_col, 50);
ahd_seq_flags_print(ahd_inb(ahd, SEQ_FLAGS), &cur_col, 50);
ahd_seq_flags2_print(ahd_inb(ahd, SEQ_FLAGS2), &cur_col, 50);
ahd_qfreeze_count_print(ahd_inw(ahd, QFREEZE_COUNT), &cur_col, 50);
ahd_kernel_qfreeze_count_print(ahd_inw(ahd, KERNEL_QFREEZE_COUNT),
&cur_col, 50);
ahd_mk_message_scb_print(ahd_inw(ahd, MK_MESSAGE_SCB), &cur_col, 50);
ahd_mk_message_scsiid_print(ahd_inb(ahd, MK_MESSAGE_SCSIID),
&cur_col, 50);
ahd_sstat0_print(ahd_inb(ahd, SSTAT0), &cur_col, 50);
ahd_sstat1_print(ahd_inb(ahd, SSTAT1), &cur_col, 50);
ahd_sstat2_print(ahd_inb(ahd, SSTAT2), &cur_col, 50);
ahd_sstat3_print(ahd_inb(ahd, SSTAT3), &cur_col, 50);
ahd_perrdiag_print(ahd_inb(ahd, PERRDIAG), &cur_col, 50);
ahd_simode1_print(ahd_inb(ahd, SIMODE1), &cur_col, 50);
ahd_lqistat0_print(ahd_inb(ahd, LQISTAT0), &cur_col, 50);
ahd_lqistat1_print(ahd_inb(ahd, LQISTAT1), &cur_col, 50);
ahd_lqistat2_print(ahd_inb(ahd, LQISTAT2), &cur_col, 50);
ahd_lqostat0_print(ahd_inb(ahd, LQOSTAT0), &cur_col, 50);
ahd_lqostat1_print(ahd_inb(ahd, LQOSTAT1), &cur_col, 50);
ahd_lqostat2_print(ahd_inb(ahd, LQOSTAT2), &cur_col, 50);
printf("\n");
printf("\nSCB Count = %d CMDS_PENDING = %d LASTSCB 0x%x "
"CURRSCB 0x%x NEXTSCB 0x%x\n",
ahd->scb_data.numscbs, ahd_inw(ahd, CMDS_PENDING),
ahd_inw(ahd, LASTSCB), ahd_inw(ahd, CURRSCB),
ahd_inw(ahd, NEXTSCB));
cur_col = 0;
/* QINFIFO */
ahd_search_qinfifo(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
CAM_LUN_WILDCARD, SCB_LIST_NULL,
ROLE_UNKNOWN, /*status*/0, SEARCH_PRINT);
saved_scb_index = ahd_get_scbptr(ahd);
printf("Pending list:");
i = 0;
LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
if (i++ > AHD_SCB_MAX)
break;
cur_col = printf("\n%3d FIFO_USE[0x%x] ", SCB_GET_TAG(scb),
ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT));
ahd_set_scbptr(ahd, SCB_GET_TAG(scb));
ahd_scb_control_print(ahd_inb_scbram(ahd, SCB_CONTROL),
&cur_col, 60);
ahd_scb_scsiid_print(ahd_inb_scbram(ahd, SCB_SCSIID),
&cur_col, 60);
}
printf("\nTotal %d\n", i);
printf("Kernel Free SCB list: ");
i = 0;
TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
struct scb *list_scb;
list_scb = scb;
do {
printf("%d ", SCB_GET_TAG(list_scb));
list_scb = LIST_NEXT(list_scb, collision_links);
} while (list_scb && i++ < AHD_SCB_MAX);
}
LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
if (i++ > AHD_SCB_MAX)
break;
printf("%d ", SCB_GET_TAG(scb));
}
printf("\n");
printf("Sequencer Complete DMA-inprog list: ");
scb_index = ahd_inw(ahd, COMPLETE_SCB_DMAINPROG_HEAD);
i = 0;
while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
ahd_set_scbptr(ahd, scb_index);
printf("%d ", scb_index);
scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
}
printf("\n");
printf("Sequencer Complete list: ");
scb_index = ahd_inw(ahd, COMPLETE_SCB_HEAD);
i = 0;
while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
ahd_set_scbptr(ahd, scb_index);
printf("%d ", scb_index);
scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
}
printf("\n");
printf("Sequencer DMA-Up and Complete list: ");
scb_index = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
i = 0;
while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
ahd_set_scbptr(ahd, scb_index);
printf("%d ", scb_index);
scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
}
printf("\n");
printf("Sequencer On QFreeze and Complete list: ");
scb_index = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
i = 0;
while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
ahd_set_scbptr(ahd, scb_index);
printf("%d ", scb_index);
scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
}
printf("\n");
ahd_set_scbptr(ahd, saved_scb_index);
dffstat = ahd_inb(ahd, DFFSTAT);
for (i = 0; i < 2; i++) {
#ifdef AHD_DEBUG
struct scb *fifo_scb;
#endif
u_int fifo_scbptr;
ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
fifo_scbptr = ahd_get_scbptr(ahd);
printf("\n\n%s: FIFO%d %s, LONGJMP == 0x%x, SCB 0x%x\n",
ahd_name(ahd), i,
(dffstat & (FIFO0FREE << i)) ? "Free" : "Active",
ahd_inw(ahd, LONGJMP_ADDR), fifo_scbptr);
cur_col = 0;
ahd_seqimode_print(ahd_inb(ahd, SEQIMODE), &cur_col, 50);
ahd_seqintsrc_print(ahd_inb(ahd, SEQINTSRC), &cur_col, 50);
ahd_dfcntrl_print(ahd_inb(ahd, DFCNTRL), &cur_col, 50);
ahd_dfstatus_print(ahd_inb(ahd, DFSTATUS), &cur_col, 50);
ahd_sg_cache_shadow_print(ahd_inb(ahd, SG_CACHE_SHADOW),
&cur_col, 50);
ahd_sg_state_print(ahd_inb(ahd, SG_STATE), &cur_col, 50);
ahd_dffsxfrctl_print(ahd_inb(ahd, DFFSXFRCTL), &cur_col, 50);
ahd_soffcnt_print(ahd_inb(ahd, SOFFCNT), &cur_col, 50);
ahd_mdffstat_print(ahd_inb(ahd, MDFFSTAT), &cur_col, 50);
if (cur_col > 50) {
printf("\n");
cur_col = 0;
}
cur_col += printf("SHADDR = 0x%x%x, SHCNT = 0x%x ",
ahd_inl(ahd, SHADDR+4),
ahd_inl(ahd, SHADDR),
(ahd_inb(ahd, SHCNT)
| (ahd_inb(ahd, SHCNT + 1) << 8)
| (ahd_inb(ahd, SHCNT + 2) << 16)));
if (cur_col > 50) {
printf("\n");
cur_col = 0;
}
cur_col += printf("HADDR = 0x%x%x, HCNT = 0x%x ",
ahd_inl(ahd, HADDR+4),
ahd_inl(ahd, HADDR),
(ahd_inb(ahd, HCNT)
| (ahd_inb(ahd, HCNT + 1) << 8)
| (ahd_inb(ahd, HCNT + 2) << 16)));
ahd_ccsgctl_print(ahd_inb(ahd, CCSGCTL), &cur_col, 50);
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_SG) != 0) {
fifo_scb = ahd_lookup_scb(ahd, fifo_scbptr);
if (fifo_scb != NULL)
ahd_dump_sglist(fifo_scb);
}
#endif
}
printf("\nLQIN: ");
for (i = 0; i < 20; i++)
printf("0x%x ", ahd_inb(ahd, LQIN + i));
printf("\n");
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
printf("%s: LQISTATE = 0x%x, LQOSTATE = 0x%x, OPTIONMODE = 0x%x\n",
ahd_name(ahd), ahd_inb(ahd, LQISTATE), ahd_inb(ahd, LQOSTATE),
ahd_inb(ahd, OPTIONMODE));
printf("%s: OS_SPACE_CNT = 0x%x MAXCMDCNT = 0x%x\n",
ahd_name(ahd), ahd_inb(ahd, OS_SPACE_CNT),
ahd_inb(ahd, MAXCMDCNT));
printf("%s: SAVED_SCSIID = 0x%x SAVED_LUN = 0x%x\n",
ahd_name(ahd), ahd_inb(ahd, SAVED_SCSIID),
ahd_inb(ahd, SAVED_LUN));
ahd_simode0_print(ahd_inb(ahd, SIMODE0), &cur_col, 50);
printf("\n");
ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
cur_col = 0;
ahd_ccscbctl_print(ahd_inb(ahd, CCSCBCTL), &cur_col, 50);
printf("\n");
ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
printf("%s: REG0 == 0x%x, SINDEX = 0x%x, DINDEX = 0x%x\n",
ahd_name(ahd), ahd_inw(ahd, REG0), ahd_inw(ahd, SINDEX),
ahd_inw(ahd, DINDEX));
printf("%s: SCBPTR == 0x%x, SCB_NEXT == 0x%x, SCB_NEXT2 == 0x%x\n",
ahd_name(ahd), ahd_get_scbptr(ahd),
ahd_inw_scbram(ahd, SCB_NEXT),
ahd_inw_scbram(ahd, SCB_NEXT2));
printf("CDB %x %x %x %x %x %x\n",
ahd_inb_scbram(ahd, SCB_CDB_STORE),
ahd_inb_scbram(ahd, SCB_CDB_STORE+1),
ahd_inb_scbram(ahd, SCB_CDB_STORE+2),
ahd_inb_scbram(ahd, SCB_CDB_STORE+3),
ahd_inb_scbram(ahd, SCB_CDB_STORE+4),
ahd_inb_scbram(ahd, SCB_CDB_STORE+5));
printf("STACK:");
for (i = 0; i < ahd->stack_size; i++) {
ahd->saved_stack[i] =
ahd_inb(ahd, STACK)|(ahd_inb(ahd, STACK) << 8);
printf(" 0x%x", ahd->saved_stack[i]);
}
for (i = ahd->stack_size-1; i >= 0; i--) {
ahd_outb(ahd, STACK, ahd->saved_stack[i] & 0xFF);
ahd_outb(ahd, STACK, (ahd->saved_stack[i] >> 8) & 0xFF);
}
printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
ahd_restore_modes(ahd, saved_modes);
if (paused == 0)
ahd_unpause(ahd);
}
#if 0
void
ahd_dump_scbs(struct ahd_softc *ahd)
{
ahd_mode_state saved_modes;
u_int saved_scb_index;
int i;
saved_modes = ahd_save_modes(ahd);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
saved_scb_index = ahd_get_scbptr(ahd);
for (i = 0; i < AHD_SCB_MAX; i++) {
ahd_set_scbptr(ahd, i);
printf("%3d", i);
printf("(CTRL 0x%x ID 0x%x N 0x%x N2 0x%x SG 0x%x, RSG 0x%x)\n",
ahd_inb_scbram(ahd, SCB_CONTROL),
ahd_inb_scbram(ahd, SCB_SCSIID),
ahd_inw_scbram(ahd, SCB_NEXT),
ahd_inw_scbram(ahd, SCB_NEXT2),
ahd_inl_scbram(ahd, SCB_SGPTR),
ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR));
}
printf("\n");
ahd_set_scbptr(ahd, saved_scb_index);
ahd_restore_modes(ahd, saved_modes);
}
#endif /* 0 */
/**************************** Flexport Logic **********************************/
/*
* Read count 16bit words from 16bit word address start_addr from the
* SEEPROM attached to the controller, into buf, using the controller's
* SEEPROM reading state machine. Optionally treat the data as a byte
* stream in terms of byte order.
*/
int
ahd_read_seeprom(struct ahd_softc *ahd, uint16_t *buf,
u_int start_addr, u_int count, int bytestream)
{
u_int cur_addr;
u_int end_addr;
int error;
/*
* If we never make it through the loop even once,
* we were passed invalid arguments.
*/
error = EINVAL;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
end_addr = start_addr + count;
for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
ahd_outb(ahd, SEEADR, cur_addr);
ahd_outb(ahd, SEECTL, SEEOP_READ | SEESTART);
error = ahd_wait_seeprom(ahd);
if (error)
break;
if (bytestream != 0) {
uint8_t *bytestream_ptr;
bytestream_ptr = (uint8_t *)buf;
*bytestream_ptr++ = ahd_inb(ahd, SEEDAT);
*bytestream_ptr = ahd_inb(ahd, SEEDAT+1);
} else {
/*
* ahd_inw() already handles machine byte order.
*/
*buf = ahd_inw(ahd, SEEDAT);
}
buf++;
}
return (error);
}
/*
* Write count 16bit words from buf, into SEEPROM attache to the
* controller starting at 16bit word address start_addr, using the
* controller's SEEPROM writing state machine.
*/
int
ahd_write_seeprom(struct ahd_softc *ahd, uint16_t *buf,
u_int start_addr, u_int count)
{
u_int cur_addr;
u_int end_addr;
int error;
int retval;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
error = ENOENT;
/* Place the chip into write-enable mode */
ahd_outb(ahd, SEEADR, SEEOP_EWEN_ADDR);
ahd_outb(ahd, SEECTL, SEEOP_EWEN | SEESTART);
error = ahd_wait_seeprom(ahd);
if (error)
return (error);
/*
* Write the data. If we don't get throught the loop at
* least once, the arguments were invalid.
*/
retval = EINVAL;
end_addr = start_addr + count;
for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
ahd_outw(ahd, SEEDAT, *buf++);
ahd_outb(ahd, SEEADR, cur_addr);
ahd_outb(ahd, SEECTL, SEEOP_WRITE | SEESTART);
retval = ahd_wait_seeprom(ahd);
if (retval)
break;
}
/*
* Disable writes.
*/
ahd_outb(ahd, SEEADR, SEEOP_EWDS_ADDR);
ahd_outb(ahd, SEECTL, SEEOP_EWDS | SEESTART);
error = ahd_wait_seeprom(ahd);
if (error)
return (error);
return (retval);
}
/*
* Wait ~100us for the serial eeprom to satisfy our request.
*/
static int
ahd_wait_seeprom(struct ahd_softc *ahd)
{
int cnt;
cnt = 5000;
while ((ahd_inb(ahd, SEESTAT) & (SEEARBACK|SEEBUSY)) != 0 && --cnt)
ahd_delay(5);
if (cnt == 0)
return (ETIMEDOUT);
return (0);
}
/*
* Validate the two checksums in the per_channel
* vital product data struct.
*/
static int
ahd_verify_vpd_cksum(struct vpd_config *vpd)
{
int i;
int maxaddr;
uint32_t checksum;
uint8_t *vpdarray;
vpdarray = (uint8_t *)vpd;
maxaddr = offsetof(struct vpd_config, vpd_checksum);
checksum = 0;
for (i = offsetof(struct vpd_config, resource_type); i < maxaddr; i++)
checksum = checksum + vpdarray[i];
if (checksum == 0
|| (-checksum & 0xFF) != vpd->vpd_checksum)
return (0);
checksum = 0;
maxaddr = offsetof(struct vpd_config, checksum);
for (i = offsetof(struct vpd_config, default_target_flags);
i < maxaddr; i++)
checksum = checksum + vpdarray[i];
if (checksum == 0
|| (-checksum & 0xFF) != vpd->checksum)
return (0);
return (1);
}
int
ahd_verify_cksum(struct seeprom_config *sc)
{
int i;
int maxaddr;
uint32_t checksum;
uint16_t *scarray;
maxaddr = (sizeof(*sc)/2) - 1;
checksum = 0;
scarray = (uint16_t *)sc;
for (i = 0; i < maxaddr; i++)
checksum = checksum + scarray[i];
if (checksum == 0
|| (checksum & 0xFFFF) != sc->checksum) {
return (0);
} else {
return (1);
}
}
int
ahd_acquire_seeprom(struct ahd_softc *ahd)
{
/*
* We should be able to determine the SEEPROM type
* from the flexport logic, but unfortunately not
* all implementations have this logic and there is
* no programatic method for determining if the logic
* is present.
*/
return (1);
#if 0
uint8_t seetype;
int error;
error = ahd_read_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, &seetype);
if (error != 0
|| ((seetype & FLX_ROMSTAT_SEECFG) == FLX_ROMSTAT_SEE_NONE))
return (0);
return (1);
#endif
}
void
ahd_release_seeprom(struct ahd_softc *ahd)
{
/* Currently a no-op */
}
/*
* Wait at most 2 seconds for flexport arbitration to succeed.
*/
static int
ahd_wait_flexport(struct ahd_softc *ahd)
{
int cnt;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
cnt = 1000000 * 2 / 5;
while ((ahd_inb(ahd, BRDCTL) & FLXARBACK) == 0 && --cnt)
ahd_delay(5);
if (cnt == 0)
return (ETIMEDOUT);
return (0);
}
int
ahd_write_flexport(struct ahd_softc *ahd, u_int addr, u_int value)
{
int error;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
if (addr > 7)
panic("ahd_write_flexport: address out of range");
ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
error = ahd_wait_flexport(ahd);
if (error != 0)
return (error);
ahd_outb(ahd, BRDDAT, value);
ahd_flush_device_writes(ahd);
ahd_outb(ahd, BRDCTL, BRDSTB|BRDEN|(addr << 3));
ahd_flush_device_writes(ahd);
ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
ahd_flush_device_writes(ahd);
ahd_outb(ahd, BRDCTL, 0);
ahd_flush_device_writes(ahd);
return (0);
}
int
ahd_read_flexport(struct ahd_softc *ahd, u_int addr, uint8_t *value)
{
int error;
AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
if (addr > 7)
panic("ahd_read_flexport: address out of range");
ahd_outb(ahd, BRDCTL, BRDRW|BRDEN|(addr << 3));
error = ahd_wait_flexport(ahd);
if (error != 0)
return (error);
*value = ahd_inb(ahd, BRDDAT);
ahd_outb(ahd, BRDCTL, 0);
ahd_flush_device_writes(ahd);
return (0);
}
/************************* Target Mode ****************************************/
#ifdef AHD_TARGET_MODE
cam_status
ahd_find_tmode_devs(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb,
struct ahd_tmode_tstate **tstate,
struct ahd_tmode_lstate **lstate,
int notfound_failure)
{
if ((ahd->features & AHD_TARGETMODE) == 0)
return (CAM_REQ_INVALID);
/*
* Handle the 'black hole' device that sucks up
* requests to unattached luns on enabled targets.
*/
if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
&& ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
*tstate = NULL;
*lstate = ahd->black_hole;
} else {
u_int max_id;
max_id = (ahd->features & AHD_WIDE) ? 16 : 8;
if (ccb->ccb_h.target_id >= max_id)
return (CAM_TID_INVALID);
if (ccb->ccb_h.target_lun >= AHD_NUM_LUNS)
return (CAM_LUN_INVALID);
*tstate = ahd->enabled_targets[ccb->ccb_h.target_id];
*lstate = NULL;
if (*tstate != NULL)
*lstate =
(*tstate)->enabled_luns[ccb->ccb_h.target_lun];
}
if (notfound_failure != 0 && *lstate == NULL)
return (CAM_PATH_INVALID);
return (CAM_REQ_CMP);
}
void
ahd_handle_en_lun(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb)
{
#if NOT_YET
struct ahd_tmode_tstate *tstate;
struct ahd_tmode_lstate *lstate;
struct ccb_en_lun *cel;
cam_status status;
u_int target;
u_int lun;
u_int target_mask;
u_long s;
char channel;
status = ahd_find_tmode_devs(ahd, sim, ccb, &tstate, &lstate,
/*notfound_failure*/FALSE);
if (status != CAM_REQ_CMP) {
ccb->ccb_h.status = status;
return;
}
if ((ahd->features & AHD_MULTIROLE) != 0) {
u_int our_id;
our_id = ahd->our_id;
if (ccb->ccb_h.target_id != our_id) {
if ((ahd->features & AHD_MULTI_TID) != 0
&& (ahd->flags & AHD_INITIATORROLE) != 0) {
/*
* Only allow additional targets if
* the initiator role is disabled.
* The hardware cannot handle a re-select-in
* on the initiator id during a re-select-out
* on a different target id.
*/
status = CAM_TID_INVALID;
} else if ((ahd->flags & AHD_INITIATORROLE) != 0
|| ahd->enabled_luns > 0) {
/*
* Only allow our target id to change
* if the initiator role is not configured
* and there are no enabled luns which
* are attached to the currently registered
* scsi id.
*/
status = CAM_TID_INVALID;
}
}
}
if (status != CAM_REQ_CMP) {
ccb->ccb_h.status = status;
return;
}
/*
* We now have an id that is valid.
* If we aren't in target mode, switch modes.
*/
if ((ahd->flags & AHD_TARGETROLE) == 0
&& ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
u_long s;
printf("Configuring Target Mode\n");
ahd_lock(ahd, &s);
if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
ccb->ccb_h.status = CAM_BUSY;
ahd_unlock(ahd, &s);
return;
}
ahd->flags |= AHD_TARGETROLE;
if ((ahd->features & AHD_MULTIROLE) == 0)
ahd->flags &= ~AHD_INITIATORROLE;
ahd_pause(ahd);
ahd_loadseq(ahd);
ahd_restart(ahd);
ahd_unlock(ahd, &s);
}
cel = &ccb->cel;
target = ccb->ccb_h.target_id;
lun = ccb->ccb_h.target_lun;
channel = SIM_CHANNEL(ahd, sim);
target_mask = 0x01 << target;
if (channel == 'B')
target_mask <<= 8;
if (cel->enable != 0) {
u_int scsiseq1;
/* Are we already enabled?? */
if (lstate != NULL) {
xpt_print_path(ccb->ccb_h.path);
printf("Lun already enabled\n");
ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
return;
}
if (cel->grp6_len != 0
|| cel->grp7_len != 0) {
/*
* Don't (yet?) support vendor
* specific commands.
*/
ccb->ccb_h.status = CAM_REQ_INVALID;
printf("Non-zero Group Codes\n");
return;
}
/*
* Seems to be okay.
* Setup our data structures.
*/
if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
tstate = ahd_alloc_tstate(ahd, target, channel);
if (tstate == NULL) {
xpt_print_path(ccb->ccb_h.path);
printf("Couldn't allocate tstate\n");
ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
return;
}
}
lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
if (lstate == NULL) {
xpt_print_path(ccb->ccb_h.path);
printf("Couldn't allocate lstate\n");
ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
return;
}
memset(lstate, 0, sizeof(*lstate));
status = xpt_create_path(&lstate->path, /*periph*/NULL,
xpt_path_path_id(ccb->ccb_h.path),
xpt_path_target_id(ccb->ccb_h.path),
xpt_path_lun_id(ccb->ccb_h.path));
if (status != CAM_REQ_CMP) {
free(lstate, M_DEVBUF);
xpt_print_path(ccb->ccb_h.path);
printf("Couldn't allocate path\n");
ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
return;
}
SLIST_INIT(&lstate->accept_tios);
SLIST_INIT(&lstate->immed_notifies);
ahd_lock(ahd, &s);
ahd_pause(ahd);
if (target != CAM_TARGET_WILDCARD) {
tstate->enabled_luns[lun] = lstate;
ahd->enabled_luns++;
if ((ahd->features & AHD_MULTI_TID) != 0) {
u_int targid_mask;
targid_mask = ahd_inw(ahd, TARGID);
targid_mask |= target_mask;
ahd_outw(ahd, TARGID, targid_mask);
ahd_update_scsiid(ahd, targid_mask);
} else {
u_int our_id;
char channel;
channel = SIM_CHANNEL(ahd, sim);
our_id = SIM_SCSI_ID(ahd, sim);
/*
* This can only happen if selections
* are not enabled
*/
if (target != our_id) {
u_int sblkctl;
char cur_channel;
int swap;
sblkctl = ahd_inb(ahd, SBLKCTL);
cur_channel = (sblkctl & SELBUSB)
? 'B' : 'A';
if ((ahd->features & AHD_TWIN) == 0)
cur_channel = 'A';
swap = cur_channel != channel;
ahd->our_id = target;
if (swap)
ahd_outb(ahd, SBLKCTL,
sblkctl ^ SELBUSB);
ahd_outb(ahd, SCSIID, target);
if (swap)
ahd_outb(ahd, SBLKCTL, sblkctl);
}
}
} else
ahd->black_hole = lstate;
/* Allow select-in operations */
if (ahd->black_hole != NULL && ahd->enabled_luns > 0) {
scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
scsiseq1 |= ENSELI;
ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
scsiseq1 = ahd_inb(ahd, SCSISEQ1);
scsiseq1 |= ENSELI;
ahd_outb(ahd, SCSISEQ1, scsiseq1);
}
ahd_unpause(ahd);
ahd_unlock(ahd, &s);
ccb->ccb_h.status = CAM_REQ_CMP;
xpt_print_path(ccb->ccb_h.path);
printf("Lun now enabled for target mode\n");
} else {
struct scb *scb;
int i, empty;
if (lstate == NULL) {
ccb->ccb_h.status = CAM_LUN_INVALID;
return;
}
ahd_lock(ahd, &s);
ccb->ccb_h.status = CAM_REQ_CMP;
LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
struct ccb_hdr *ccbh;
ccbh = &scb->io_ctx->ccb_h;
if (ccbh->func_code == XPT_CONT_TARGET_IO
&& !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
printf("CTIO pending\n");
ccb->ccb_h.status = CAM_REQ_INVALID;
ahd_unlock(ahd, &s);
return;
}
}
if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
printf("ATIOs pending\n");
ccb->ccb_h.status = CAM_REQ_INVALID;
}
if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
printf("INOTs pending\n");
ccb->ccb_h.status = CAM_REQ_INVALID;
}
if (ccb->ccb_h.status != CAM_REQ_CMP) {
ahd_unlock(ahd, &s);
return;
}
xpt_print_path(ccb->ccb_h.path);
printf("Target mode disabled\n");
xpt_free_path(lstate->path);
free(lstate, M_DEVBUF);
ahd_pause(ahd);
/* Can we clean up the target too? */
if (target != CAM_TARGET_WILDCARD) {
tstate->enabled_luns[lun] = NULL;
ahd->enabled_luns--;
for (empty = 1, i = 0; i < 8; i++)
if (tstate->enabled_luns[i] != NULL) {
empty = 0;
break;
}
if (empty) {
ahd_free_tstate(ahd, target, channel,
/*force*/FALSE);
if (ahd->features & AHD_MULTI_TID) {
u_int targid_mask;
targid_mask = ahd_inw(ahd, TARGID);
targid_mask &= ~target_mask;
ahd_outw(ahd, TARGID, targid_mask);
ahd_update_scsiid(ahd, targid_mask);
}
}
} else {
ahd->black_hole = NULL;
/*
* We can't allow selections without
* our black hole device.
*/
empty = TRUE;
}
if (ahd->enabled_luns == 0) {
/* Disallow select-in */
u_int scsiseq1;
scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
scsiseq1 &= ~ENSELI;
ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
scsiseq1 = ahd_inb(ahd, SCSISEQ1);
scsiseq1 &= ~ENSELI;
ahd_outb(ahd, SCSISEQ1, scsiseq1);
if ((ahd->features & AHD_MULTIROLE) == 0) {
printf("Configuring Initiator Mode\n");
ahd->flags &= ~AHD_TARGETROLE;
ahd->flags |= AHD_INITIATORROLE;
ahd_pause(ahd);
ahd_loadseq(ahd);
ahd_restart(ahd);
/*
* Unpaused. The extra unpause
* that follows is harmless.
*/
}
}
ahd_unpause(ahd);
ahd_unlock(ahd, &s);
}
#endif
}
static void
ahd_update_scsiid(struct ahd_softc *ahd, u_int targid_mask)
{
#if NOT_YET
u_int scsiid_mask;
u_int scsiid;
if ((ahd->features & AHD_MULTI_TID) == 0)
panic("ahd_update_scsiid called on non-multitid unit\n");
/*
* Since we will rely on the TARGID mask
* for selection enables, ensure that OID
* in SCSIID is not set to some other ID
* that we don't want to allow selections on.
*/
if ((ahd->features & AHD_ULTRA2) != 0)
scsiid = ahd_inb(ahd, SCSIID_ULTRA2);
else
scsiid = ahd_inb(ahd, SCSIID);
scsiid_mask = 0x1 << (scsiid & OID);
if ((targid_mask & scsiid_mask) == 0) {
u_int our_id;
/* ffs counts from 1 */
our_id = ffs(targid_mask);
if (our_id == 0)
our_id = ahd->our_id;
else
our_id--;
scsiid &= TID;
scsiid |= our_id;
}
if ((ahd->features & AHD_ULTRA2) != 0)
ahd_outb(ahd, SCSIID_ULTRA2, scsiid);
else
ahd_outb(ahd, SCSIID, scsiid);
#endif
}
void
ahd_run_tqinfifo(struct ahd_softc *ahd, int paused)
{
struct target_cmd *cmd;
ahd_sync_tqinfifo(ahd, BUS_DMASYNC_POSTREAD);
while ((cmd = &ahd->targetcmds[ahd->tqinfifonext])->cmd_valid != 0) {
/*
* Only advance through the queue if we
* have the resources to process the command.
*/
if (ahd_handle_target_cmd(ahd, cmd) != 0)
break;
cmd->cmd_valid = 0;
ahd_dmamap_sync(ahd, ahd->shared_data_dmat,
ahd->shared_data_map.dmamap,
ahd_targetcmd_offset(ahd, ahd->tqinfifonext),
sizeof(struct target_cmd),
BUS_DMASYNC_PREREAD);
ahd->tqinfifonext++;
/*
* Lazily update our position in the target mode incoming
* command queue as seen by the sequencer.
*/
if ((ahd->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
u_int hs_mailbox;
hs_mailbox = ahd_inb(ahd, HS_MAILBOX);
hs_mailbox &= ~HOST_TQINPOS;
hs_mailbox |= ahd->tqinfifonext & HOST_TQINPOS;
ahd_outb(ahd, HS_MAILBOX, hs_mailbox);
}
}
}
static int
ahd_handle_target_cmd(struct ahd_softc *ahd, struct target_cmd *cmd)
{
struct ahd_tmode_tstate *tstate;
struct ahd_tmode_lstate *lstate;
struct ccb_accept_tio *atio;
uint8_t *byte;
int initiator;
int target;
int lun;
initiator = SCSIID_TARGET(ahd, cmd->scsiid);
target = SCSIID_OUR_ID(cmd->scsiid);
lun = (cmd->identify & MSG_IDENTIFY_LUNMASK);
byte = cmd->bytes;
tstate = ahd->enabled_targets[target];
lstate = NULL;
if (tstate != NULL)
lstate = tstate->enabled_luns[lun];
/*
* Commands for disabled luns go to the black hole driver.
*/
if (lstate == NULL)
lstate = ahd->black_hole;
atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
if (atio == NULL) {
ahd->flags |= AHD_TQINFIFO_BLOCKED;
/*
* Wait for more ATIOs from the peripheral driver for this lun.
*/
return (1);
} else
ahd->flags &= ~AHD_TQINFIFO_BLOCKED;
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_TQIN) != 0)
printf("Incoming command from %d for %d:%d%s\n",
initiator, target, lun,
lstate == ahd->black_hole ? "(Black Holed)" : "");
#endif
SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
if (lstate == ahd->black_hole) {
/* Fill in the wildcards */
atio->ccb_h.target_id = target;
atio->ccb_h.target_lun = lun;
}
/*
* Package it up and send it off to
* whomever has this lun enabled.
*/
atio->sense_len = 0;
atio->init_id = initiator;
if (byte[0] != 0xFF) {
/* Tag was included */
atio->tag_action = *byte++;
atio->tag_id = *byte++;
atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
} else {
atio->ccb_h.flags = 0;
}
byte++;
/* Okay. Now determine the cdb size based on the command code */
switch (*byte >> CMD_GROUP_CODE_SHIFT) {
case 0:
atio->cdb_len = 6;
break;
case 1:
case 2:
atio->cdb_len = 10;
break;
case 4:
atio->cdb_len = 16;
break;
case 5:
atio->cdb_len = 12;
break;
case 3:
default:
/* Only copy the opcode. */
atio->cdb_len = 1;
printf("Reserved or VU command code type encountered\n");
break;
}
memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
atio->ccb_h.status |= CAM_CDB_RECVD;
if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
/*
* We weren't allowed to disconnect.
* We're hanging on the bus until a
* continue target I/O comes in response
* to this accept tio.
*/
#ifdef AHD_DEBUG
if ((ahd_debug & AHD_SHOW_TQIN) != 0)
printf("Received Immediate Command %d:%d:%d - %p\n",
initiator, target, lun, ahd->pending_device);
#endif
ahd->pending_device = lstate;
ahd_freeze_ccb((union ccb *)atio);
atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
}
xpt_done((union ccb*)atio);
return (0);
}
#endif
| gpl-2.0 |
rmcc/gp_one_kernel | drivers/scsi/megaraid/megaraid_sas.c | 300 | 89932 | /*
*
* Linux MegaRAID driver for SAS based RAID controllers
*
* Copyright (c) 2003-2005 LSI 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.
*
* FILE : megaraid_sas.c
* Version : v00.00.04.01-rc1
*
* Authors:
* (email-id : megaraidlinux@lsi.com)
* Sreenivas Bagalkote
* Sumant Patro
* Bo Yang
*
* List of supported controllers
*
* OEM Product Name VID DID SSVID SSID
* --- ------------ --- --- ---- ----
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/list.h>
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/smp_lock.h>
#include <linux/uio.h>
#include <asm/uaccess.h>
#include <linux/fs.h>
#include <linux/compat.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include "megaraid_sas.h"
/*
* poll_mode_io:1- schedule complete completion from q cmd
*/
static unsigned int poll_mode_io;
module_param_named(poll_mode_io, poll_mode_io, int, 0);
MODULE_PARM_DESC(poll_mode_io,
"Complete cmds from IO path, (default=0)");
MODULE_LICENSE("GPL");
MODULE_VERSION(MEGASAS_VERSION);
MODULE_AUTHOR("megaraidlinux@lsi.com");
MODULE_DESCRIPTION("LSI MegaRAID SAS Driver");
/*
* PCI ID table for all supported controllers
*/
static struct pci_device_id megasas_pci_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
/* xscale IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
/* ppc IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
/* ppc IOP */
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
/* gen2*/
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
/* gen2*/
{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
/* xscale IOP, vega */
{PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
/* xscale IOP */
{}
};
MODULE_DEVICE_TABLE(pci, megasas_pci_table);
static int megasas_mgmt_majorno;
static struct megasas_mgmt_info megasas_mgmt_info;
static struct fasync_struct *megasas_async_queue;
static DEFINE_MUTEX(megasas_async_queue_mutex);
static u32 megasas_dbg_lvl;
static void
megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
u8 alt_status);
/**
* megasas_get_cmd - Get a command from the free pool
* @instance: Adapter soft state
*
* Returns a free command from the pool
*/
static struct megasas_cmd *megasas_get_cmd(struct megasas_instance
*instance)
{
unsigned long flags;
struct megasas_cmd *cmd = NULL;
spin_lock_irqsave(&instance->cmd_pool_lock, flags);
if (!list_empty(&instance->cmd_pool)) {
cmd = list_entry((&instance->cmd_pool)->next,
struct megasas_cmd, list);
list_del_init(&cmd->list);
} else {
printk(KERN_ERR "megasas: Command pool empty!\n");
}
spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
return cmd;
}
/**
* megasas_return_cmd - Return a cmd to free command pool
* @instance: Adapter soft state
* @cmd: Command packet to be returned to free command pool
*/
static inline void
megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
unsigned long flags;
spin_lock_irqsave(&instance->cmd_pool_lock, flags);
cmd->scmd = NULL;
list_add_tail(&cmd->list, &instance->cmd_pool);
spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
}
/**
* The following functions are defined for xscale
* (deviceid : 1064R, PERC5) controllers
*/
/**
* megasas_enable_intr_xscale - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_xscale(struct megasas_register_set __iomem * regs)
{
writel(1, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_xscale -Disables interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_xscale(struct megasas_register_set __iomem * regs)
{
u32 mask = 0x1f;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_xscale - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
{
return readl(&(regs)->outbound_msg_0);
}
/**
* megasas_clear_interrupt_xscale - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
{
u32 status;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (!(status & MFI_OB_INTR_STATUS_MASK)) {
return 1;
}
/*
* Clear the interrupt by writing back the same value
*/
writel(status, ®s->outbound_intr_status);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_status);
return 0;
}
/**
* megasas_fire_cmd_xscale - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_xscale(dma_addr_t frame_phys_addr,u32 frame_count, struct megasas_register_set __iomem *regs)
{
writel((frame_phys_addr >> 3)|(frame_count),
&(regs)->inbound_queue_port);
}
static struct megasas_instance_template megasas_instance_template_xscale = {
.fire_cmd = megasas_fire_cmd_xscale,
.enable_intr = megasas_enable_intr_xscale,
.disable_intr = megasas_disable_intr_xscale,
.clear_intr = megasas_clear_intr_xscale,
.read_fw_status_reg = megasas_read_fw_status_reg_xscale,
};
/**
* This is the end of set of functions & definitions specific
* to xscale (deviceid : 1064R, PERC5) controllers
*/
/**
* The following functions are defined for ppc (deviceid : 0x60)
* controllers
*/
/**
* megasas_enable_intr_ppc - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_ppc(struct megasas_register_set __iomem * regs)
{
writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
writel(~0x80000004, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_ppc - Disable interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_ppc(struct megasas_register_set __iomem * regs)
{
u32 mask = 0xFFFFFFFF;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_ppc - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
{
return readl(&(regs)->outbound_scratch_pad);
}
/**
* megasas_clear_interrupt_ppc - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
{
u32 status;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (!(status & MFI_REPLY_1078_MESSAGE_INTERRUPT)) {
return 1;
}
/*
* Clear the interrupt by writing back the same value
*/
writel(status, ®s->outbound_doorbell_clear);
/* Dummy readl to force pci flush */
readl(®s->outbound_doorbell_clear);
return 0;
}
/**
* megasas_fire_cmd_ppc - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_ppc(dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs)
{
writel((frame_phys_addr | (frame_count<<1))|1,
&(regs)->inbound_queue_port);
}
static struct megasas_instance_template megasas_instance_template_ppc = {
.fire_cmd = megasas_fire_cmd_ppc,
.enable_intr = megasas_enable_intr_ppc,
.disable_intr = megasas_disable_intr_ppc,
.clear_intr = megasas_clear_intr_ppc,
.read_fw_status_reg = megasas_read_fw_status_reg_ppc,
};
/**
* The following functions are defined for gen2 (deviceid : 0x78 0x79)
* controllers
*/
/**
* megasas_enable_intr_gen2 - Enables interrupts
* @regs: MFI register set
*/
static inline void
megasas_enable_intr_gen2(struct megasas_register_set __iomem *regs)
{
writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
/* write ~0x00000005 (4 & 1) to the intr mask*/
writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_disable_intr_gen2 - Disables interrupt
* @regs: MFI register set
*/
static inline void
megasas_disable_intr_gen2(struct megasas_register_set __iomem *regs)
{
u32 mask = 0xFFFFFFFF;
writel(mask, ®s->outbound_intr_mask);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_mask);
}
/**
* megasas_read_fw_status_reg_gen2 - returns the current FW status value
* @regs: MFI register set
*/
static u32
megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs)
{
return readl(&(regs)->outbound_scratch_pad);
}
/**
* megasas_clear_interrupt_gen2 - Check & clear interrupt
* @regs: MFI register set
*/
static int
megasas_clear_intr_gen2(struct megasas_register_set __iomem *regs)
{
u32 status;
/*
* Check if it is our interrupt
*/
status = readl(®s->outbound_intr_status);
if (!(status & MFI_GEN2_ENABLE_INTERRUPT_MASK))
return 1;
/*
* Clear the interrupt by writing back the same value
*/
writel(status, ®s->outbound_doorbell_clear);
/* Dummy readl to force pci flush */
readl(®s->outbound_intr_status);
return 0;
}
/**
* megasas_fire_cmd_gen2 - Sends command to the FW
* @frame_phys_addr : Physical address of cmd
* @frame_count : Number of frames for the command
* @regs : MFI register set
*/
static inline void
megasas_fire_cmd_gen2(dma_addr_t frame_phys_addr, u32 frame_count,
struct megasas_register_set __iomem *regs)
{
writel((frame_phys_addr | (frame_count<<1))|1,
&(regs)->inbound_queue_port);
}
static struct megasas_instance_template megasas_instance_template_gen2 = {
.fire_cmd = megasas_fire_cmd_gen2,
.enable_intr = megasas_enable_intr_gen2,
.disable_intr = megasas_disable_intr_gen2,
.clear_intr = megasas_clear_intr_gen2,
.read_fw_status_reg = megasas_read_fw_status_reg_gen2,
};
/**
* This is the end of set of functions & definitions
* specific to ppc (deviceid : 0x60) controllers
*/
/**
* megasas_issue_polled - Issues a polling command
* @instance: Adapter soft state
* @cmd: Command packet to be issued
*
* For polling, MFI requires the cmd_status to be set to 0xFF before posting.
*/
static int
megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
int i;
u32 msecs = MFI_POLL_TIMEOUT_SECS * 1000;
struct megasas_header *frame_hdr = &cmd->frame->hdr;
frame_hdr->cmd_status = 0xFF;
frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
/*
* Issue the frame using inbound queue port
*/
instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
/*
* Wait for cmd_status to change
*/
for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i++) {
rmb();
msleep(1);
}
if (frame_hdr->cmd_status == 0xff)
return -ETIME;
return 0;
}
/**
* megasas_issue_blocked_cmd - Synchronous wrapper around regular FW cmds
* @instance: Adapter soft state
* @cmd: Command to be issued
*
* This function waits on an event for the command to be returned from ISR.
* Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
* Used to issue ioctl commands.
*/
static int
megasas_issue_blocked_cmd(struct megasas_instance *instance,
struct megasas_cmd *cmd)
{
cmd->cmd_status = ENODATA;
instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
wait_event_timeout(instance->int_cmd_wait_q, (cmd->cmd_status != ENODATA),
MEGASAS_INTERNAL_CMD_WAIT_TIME*HZ);
return 0;
}
/**
* megasas_issue_blocked_abort_cmd - Aborts previously issued cmd
* @instance: Adapter soft state
* @cmd_to_abort: Previously issued cmd to be aborted
*
* MFI firmware can abort previously issued AEN comamnd (automatic event
* notification). The megasas_issue_blocked_abort_cmd() issues such abort
* cmd and waits for return status.
* Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
*/
static int
megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
struct megasas_cmd *cmd_to_abort)
{
struct megasas_cmd *cmd;
struct megasas_abort_frame *abort_fr;
cmd = megasas_get_cmd(instance);
if (!cmd)
return -1;
abort_fr = &cmd->frame->abort;
/*
* Prepare and issue the abort frame
*/
abort_fr->cmd = MFI_CMD_ABORT;
abort_fr->cmd_status = 0xFF;
abort_fr->flags = 0;
abort_fr->abort_context = cmd_to_abort->index;
abort_fr->abort_mfi_phys_addr_lo = cmd_to_abort->frame_phys_addr;
abort_fr->abort_mfi_phys_addr_hi = 0;
cmd->sync_cmd = 1;
cmd->cmd_status = 0xFF;
instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
/*
* Wait for this cmd to complete
*/
wait_event_timeout(instance->abort_cmd_wait_q, (cmd->cmd_status != 0xFF),
MEGASAS_INTERNAL_CMD_WAIT_TIME*HZ);
megasas_return_cmd(instance, cmd);
return 0;
}
/**
* megasas_make_sgl32 - Prepares 32-bit SGL
* @instance: Adapter soft state
* @scp: SCSI command from the mid-layer
* @mfi_sgl: SGL to be filled in
*
* If successful, this function returns the number of SG elements. Otherwise,
* it returnes -1.
*/
static int
megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
union megasas_sgl *mfi_sgl)
{
int i;
int sge_count;
struct scatterlist *os_sgl;
sge_count = scsi_dma_map(scp);
BUG_ON(sge_count < 0);
if (sge_count) {
scsi_for_each_sg(scp, os_sgl, sge_count, i) {
mfi_sgl->sge32[i].length = sg_dma_len(os_sgl);
mfi_sgl->sge32[i].phys_addr = sg_dma_address(os_sgl);
}
}
return sge_count;
}
/**
* megasas_make_sgl64 - Prepares 64-bit SGL
* @instance: Adapter soft state
* @scp: SCSI command from the mid-layer
* @mfi_sgl: SGL to be filled in
*
* If successful, this function returns the number of SG elements. Otherwise,
* it returnes -1.
*/
static int
megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
union megasas_sgl *mfi_sgl)
{
int i;
int sge_count;
struct scatterlist *os_sgl;
sge_count = scsi_dma_map(scp);
BUG_ON(sge_count < 0);
if (sge_count) {
scsi_for_each_sg(scp, os_sgl, sge_count, i) {
mfi_sgl->sge64[i].length = sg_dma_len(os_sgl);
mfi_sgl->sge64[i].phys_addr = sg_dma_address(os_sgl);
}
}
return sge_count;
}
/**
* megasas_get_frame_count - Computes the number of frames
* @frame_type : type of frame- io or pthru frame
* @sge_count : number of sg elements
*
* Returns the number of frames required for numnber of sge's (sge_count)
*/
static u32 megasas_get_frame_count(u8 sge_count, u8 frame_type)
{
int num_cnt;
int sge_bytes;
u32 sge_sz;
u32 frame_count=0;
sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
sizeof(struct megasas_sge32);
/*
* Main frame can contain 2 SGEs for 64-bit SGLs and
* 3 SGEs for 32-bit SGLs for ldio &
* 1 SGEs for 64-bit SGLs and
* 2 SGEs for 32-bit SGLs for pthru frame
*/
if (unlikely(frame_type == PTHRU_FRAME)) {
if (IS_DMA64)
num_cnt = sge_count - 1;
else
num_cnt = sge_count - 2;
} else {
if (IS_DMA64)
num_cnt = sge_count - 2;
else
num_cnt = sge_count - 3;
}
if(num_cnt>0){
sge_bytes = sge_sz * num_cnt;
frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
}
/* Main frame */
frame_count +=1;
if (frame_count > 7)
frame_count = 8;
return frame_count;
}
/**
* megasas_build_dcdb - Prepares a direct cdb (DCDB) command
* @instance: Adapter soft state
* @scp: SCSI command
* @cmd: Command to be prepared in
*
* This function prepares CDB commands. These are typcially pass-through
* commands to the devices.
*/
static int
megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
struct megasas_cmd *cmd)
{
u32 is_logical;
u32 device_id;
u16 flags = 0;
struct megasas_pthru_frame *pthru;
is_logical = MEGASAS_IS_LOGICAL(scp);
device_id = MEGASAS_DEV_INDEX(instance, scp);
pthru = (struct megasas_pthru_frame *)cmd->frame;
if (scp->sc_data_direction == PCI_DMA_TODEVICE)
flags = MFI_FRAME_DIR_WRITE;
else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
flags = MFI_FRAME_DIR_READ;
else if (scp->sc_data_direction == PCI_DMA_NONE)
flags = MFI_FRAME_DIR_NONE;
/*
* Prepare the DCDB frame
*/
pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
pthru->cmd_status = 0x0;
pthru->scsi_status = 0x0;
pthru->target_id = device_id;
pthru->lun = scp->device->lun;
pthru->cdb_len = scp->cmd_len;
pthru->timeout = 0;
pthru->flags = flags;
pthru->data_xfer_len = scsi_bufflen(scp);
memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
/*
* Construct SGL
*/
if (IS_DMA64) {
pthru->flags |= MFI_FRAME_SGL64;
pthru->sge_count = megasas_make_sgl64(instance, scp,
&pthru->sgl);
} else
pthru->sge_count = megasas_make_sgl32(instance, scp,
&pthru->sgl);
/*
* Sense info specific
*/
pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
pthru->sense_buf_phys_addr_hi = 0;
pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
/*
* Compute the total number of frames this command consumes. FW uses
* this number to pull sufficient number of frames from host memory.
*/
cmd->frame_count = megasas_get_frame_count(pthru->sge_count,
PTHRU_FRAME);
return cmd->frame_count;
}
/**
* megasas_build_ldio - Prepares IOs to logical devices
* @instance: Adapter soft state
* @scp: SCSI command
* @cmd: Command to be prepared
*
* Frames (and accompanying SGLs) for regular SCSI IOs use this function.
*/
static int
megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
struct megasas_cmd *cmd)
{
u32 device_id;
u8 sc = scp->cmnd[0];
u16 flags = 0;
struct megasas_io_frame *ldio;
device_id = MEGASAS_DEV_INDEX(instance, scp);
ldio = (struct megasas_io_frame *)cmd->frame;
if (scp->sc_data_direction == PCI_DMA_TODEVICE)
flags = MFI_FRAME_DIR_WRITE;
else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
flags = MFI_FRAME_DIR_READ;
/*
* Prepare the Logical IO frame: 2nd bit is zero for all read cmds
*/
ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
ldio->cmd_status = 0x0;
ldio->scsi_status = 0x0;
ldio->target_id = device_id;
ldio->timeout = 0;
ldio->reserved_0 = 0;
ldio->pad_0 = 0;
ldio->flags = flags;
ldio->start_lba_hi = 0;
ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
/*
* 6-byte READ(0x08) or WRITE(0x0A) cdb
*/
if (scp->cmd_len == 6) {
ldio->lba_count = (u32) scp->cmnd[4];
ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) |
((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
ldio->start_lba_lo &= 0x1FFFFF;
}
/*
* 10-byte READ(0x28) or WRITE(0x2A) cdb
*/
else if (scp->cmd_len == 10) {
ldio->lba_count = (u32) scp->cmnd[8] |
((u32) scp->cmnd[7] << 8);
ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
((u32) scp->cmnd[3] << 16) |
((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
}
/*
* 12-byte READ(0xA8) or WRITE(0xAA) cdb
*/
else if (scp->cmd_len == 12) {
ldio->lba_count = ((u32) scp->cmnd[6] << 24) |
((u32) scp->cmnd[7] << 16) |
((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
((u32) scp->cmnd[3] << 16) |
((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
}
/*
* 16-byte READ(0x88) or WRITE(0x8A) cdb
*/
else if (scp->cmd_len == 16) {
ldio->lba_count = ((u32) scp->cmnd[10] << 24) |
((u32) scp->cmnd[11] << 16) |
((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) |
((u32) scp->cmnd[7] << 16) |
((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) |
((u32) scp->cmnd[3] << 16) |
((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
}
/*
* Construct SGL
*/
if (IS_DMA64) {
ldio->flags |= MFI_FRAME_SGL64;
ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
} else
ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
/*
* Sense info specific
*/
ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
ldio->sense_buf_phys_addr_hi = 0;
ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
/*
* Compute the total number of frames this command consumes. FW uses
* this number to pull sufficient number of frames from host memory.
*/
cmd->frame_count = megasas_get_frame_count(ldio->sge_count, IO_FRAME);
return cmd->frame_count;
}
/**
* megasas_is_ldio - Checks if the cmd is for logical drive
* @scmd: SCSI command
*
* Called by megasas_queue_command to find out if the command to be queued
* is a logical drive command
*/
static inline int megasas_is_ldio(struct scsi_cmnd *cmd)
{
if (!MEGASAS_IS_LOGICAL(cmd))
return 0;
switch (cmd->cmnd[0]) {
case READ_10:
case WRITE_10:
case READ_12:
case WRITE_12:
case READ_6:
case WRITE_6:
case READ_16:
case WRITE_16:
return 1;
default:
return 0;
}
}
/**
* megasas_dump_pending_frames - Dumps the frame address of all pending cmds
* in FW
* @instance: Adapter soft state
*/
static inline void
megasas_dump_pending_frames(struct megasas_instance *instance)
{
struct megasas_cmd *cmd;
int i,n;
union megasas_sgl *mfi_sgl;
struct megasas_io_frame *ldio;
struct megasas_pthru_frame *pthru;
u32 sgcount;
u32 max_cmd = instance->max_fw_cmds;
printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
if (IS_DMA64)
printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
else
printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if(!cmd->scmd)
continue;
printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
if (megasas_is_ldio(cmd->scmd)){
ldio = (struct megasas_io_frame *)cmd->frame;
mfi_sgl = &ldio->sgl;
sgcount = ldio->sge_count;
printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no, cmd->frame_count,ldio->cmd,ldio->target_id, ldio->start_lba_lo,ldio->start_lba_hi,ldio->sense_buf_phys_addr_lo,sgcount);
}
else {
pthru = (struct megasas_pthru_frame *) cmd->frame;
mfi_sgl = &pthru->sgl;
sgcount = pthru->sge_count;
printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no,cmd->frame_count,pthru->cmd,pthru->target_id,pthru->lun,pthru->cdb_len , pthru->data_xfer_len,pthru->sense_buf_phys_addr_lo,sgcount);
}
if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
for (n = 0; n < sgcount; n++){
if (IS_DMA64)
printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%08lx ",mfi_sgl->sge64[n].length , (unsigned long)mfi_sgl->sge64[n].phys_addr) ;
else
printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",mfi_sgl->sge32[n].length , mfi_sgl->sge32[n].phys_addr) ;
}
}
printk(KERN_ERR "\n");
} /*for max_cmd*/
printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if(cmd->sync_cmd == 1){
printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
}
}
printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
}
/**
* megasas_queue_command - Queue entry point
* @scmd: SCSI command to be queued
* @done: Callback entry point
*/
static int
megasas_queue_command(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
{
u32 frame_count;
struct megasas_cmd *cmd;
struct megasas_instance *instance;
instance = (struct megasas_instance *)
scmd->device->host->hostdata;
/* Don't process if we have already declared adapter dead */
if (instance->hw_crit_error)
return SCSI_MLQUEUE_HOST_BUSY;
scmd->scsi_done = done;
scmd->result = 0;
if (MEGASAS_IS_LOGICAL(scmd) &&
(scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
scmd->result = DID_BAD_TARGET << 16;
goto out_done;
}
switch (scmd->cmnd[0]) {
case SYNCHRONIZE_CACHE:
/*
* FW takes care of flush cache on its own
* No need to send it down
*/
scmd->result = DID_OK << 16;
goto out_done;
default:
break;
}
cmd = megasas_get_cmd(instance);
if (!cmd)
return SCSI_MLQUEUE_HOST_BUSY;
/*
* Logical drive command
*/
if (megasas_is_ldio(scmd))
frame_count = megasas_build_ldio(instance, scmd, cmd);
else
frame_count = megasas_build_dcdb(instance, scmd, cmd);
if (!frame_count)
goto out_return_cmd;
cmd->scmd = scmd;
scmd->SCp.ptr = (char *)cmd;
/*
* Issue the command to the FW
*/
atomic_inc(&instance->fw_outstanding);
instance->instancet->fire_cmd(cmd->frame_phys_addr ,cmd->frame_count-1,instance->reg_set);
/*
* Check if we have pend cmds to be completed
*/
if (poll_mode_io && atomic_read(&instance->fw_outstanding))
tasklet_schedule(&instance->isr_tasklet);
return 0;
out_return_cmd:
megasas_return_cmd(instance, cmd);
out_done:
done(scmd);
return 0;
}
static int megasas_slave_configure(struct scsi_device *sdev)
{
/*
* Don't export physical disk devices to the disk driver.
*
* FIXME: Currently we don't export them to the midlayer at all.
* That will be fixed once LSI engineers have audited the
* firmware for possible issues.
*/
if (sdev->channel < MEGASAS_MAX_PD_CHANNELS && sdev->type == TYPE_DISK)
return -ENXIO;
/*
* The RAID firmware may require extended timeouts.
*/
if (sdev->channel >= MEGASAS_MAX_PD_CHANNELS)
blk_queue_rq_timeout(sdev->request_queue,
MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
return 0;
}
/**
* megasas_complete_cmd_dpc - Returns FW's controller structure
* @instance_addr: Address of adapter soft state
*
* Tasklet to complete cmds
*/
static void megasas_complete_cmd_dpc(unsigned long instance_addr)
{
u32 producer;
u32 consumer;
u32 context;
struct megasas_cmd *cmd;
struct megasas_instance *instance =
(struct megasas_instance *)instance_addr;
unsigned long flags;
/* If we have already declared adapter dead, donot complete cmds */
if (instance->hw_crit_error)
return;
spin_lock_irqsave(&instance->completion_lock, flags);
producer = *instance->producer;
consumer = *instance->consumer;
while (consumer != producer) {
context = instance->reply_queue[consumer];
cmd = instance->cmd_list[context];
megasas_complete_cmd(instance, cmd, DID_OK);
consumer++;
if (consumer == (instance->max_fw_cmds + 1)) {
consumer = 0;
}
}
*instance->consumer = producer;
spin_unlock_irqrestore(&instance->completion_lock, flags);
/*
* Check if we can restore can_queue
*/
if (instance->flag & MEGASAS_FW_BUSY
&& time_after(jiffies, instance->last_time + 5 * HZ)
&& atomic_read(&instance->fw_outstanding) < 17) {
spin_lock_irqsave(instance->host->host_lock, flags);
instance->flag &= ~MEGASAS_FW_BUSY;
instance->host->can_queue =
instance->max_fw_cmds - MEGASAS_INT_CMDS;
spin_unlock_irqrestore(instance->host->host_lock, flags);
}
}
/**
* megasas_wait_for_outstanding - Wait for all outstanding cmds
* @instance: Adapter soft state
*
* This function waits for upto MEGASAS_RESET_WAIT_TIME seconds for FW to
* complete all its outstanding commands. Returns error if one or more IOs
* are pending after this time period. It also marks the controller dead.
*/
static int megasas_wait_for_outstanding(struct megasas_instance *instance)
{
int i;
u32 wait_time = MEGASAS_RESET_WAIT_TIME;
for (i = 0; i < wait_time; i++) {
int outstanding = atomic_read(&instance->fw_outstanding);
if (!outstanding)
break;
if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
"commands to complete\n",i,outstanding);
/*
* Call cmd completion routine. Cmd to be
* be completed directly without depending on isr.
*/
megasas_complete_cmd_dpc((unsigned long)instance);
}
msleep(1000);
}
if (atomic_read(&instance->fw_outstanding)) {
/*
* Send signal to FW to stop processing any pending cmds.
* The controller will be taken offline by the OS now.
*/
writel(MFI_STOP_ADP,
&instance->reg_set->inbound_doorbell);
megasas_dump_pending_frames(instance);
instance->hw_crit_error = 1;
return FAILED;
}
return SUCCESS;
}
/**
* megasas_generic_reset - Generic reset routine
* @scmd: Mid-layer SCSI command
*
* This routine implements a generic reset handler for device, bus and host
* reset requests. Device, bus and host specific reset handlers can use this
* function after they do their specific tasks.
*/
static int megasas_generic_reset(struct scsi_cmnd *scmd)
{
int ret_val;
struct megasas_instance *instance;
instance = (struct megasas_instance *)scmd->device->host->hostdata;
scmd_printk(KERN_NOTICE, scmd, "megasas: RESET -%ld cmd=%x retries=%x\n",
scmd->serial_number, scmd->cmnd[0], scmd->retries);
if (instance->hw_crit_error) {
printk(KERN_ERR "megasas: cannot recover from previous reset "
"failures\n");
return FAILED;
}
ret_val = megasas_wait_for_outstanding(instance);
if (ret_val == SUCCESS)
printk(KERN_NOTICE "megasas: reset successful \n");
else
printk(KERN_ERR "megasas: failed to do reset\n");
return ret_val;
}
/**
* megasas_reset_timer - quiesce the adapter if required
* @scmd: scsi cmnd
*
* Sets the FW busy flag and reduces the host->can_queue if the
* cmd has not been completed within the timeout period.
*/
static enum
blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
{
struct megasas_cmd *cmd = (struct megasas_cmd *)scmd->SCp.ptr;
struct megasas_instance *instance;
unsigned long flags;
if (time_after(jiffies, scmd->jiffies_at_alloc +
(MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) {
return BLK_EH_NOT_HANDLED;
}
instance = cmd->instance;
if (!(instance->flag & MEGASAS_FW_BUSY)) {
/* FW is busy, throttle IO */
spin_lock_irqsave(instance->host->host_lock, flags);
instance->host->can_queue = 16;
instance->last_time = jiffies;
instance->flag |= MEGASAS_FW_BUSY;
spin_unlock_irqrestore(instance->host->host_lock, flags);
}
return BLK_EH_RESET_TIMER;
}
/**
* megasas_reset_device - Device reset handler entry point
*/
static int megasas_reset_device(struct scsi_cmnd *scmd)
{
int ret;
/*
* First wait for all commands to complete
*/
ret = megasas_generic_reset(scmd);
return ret;
}
/**
* megasas_reset_bus_host - Bus & host reset handler entry point
*/
static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
{
int ret;
/*
* First wait for all commands to complete
*/
ret = megasas_generic_reset(scmd);
return ret;
}
/**
* megasas_bios_param - Returns disk geometry for a disk
* @sdev: device handle
* @bdev: block device
* @capacity: drive capacity
* @geom: geometry parameters
*/
static int
megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int geom[])
{
int heads;
int sectors;
sector_t cylinders;
unsigned long tmp;
/* Default heads (64) & sectors (32) */
heads = 64;
sectors = 32;
tmp = heads * sectors;
cylinders = capacity;
sector_div(cylinders, tmp);
/*
* Handle extended translation size for logical drives > 1Gb
*/
if (capacity >= 0x200000) {
heads = 255;
sectors = 63;
tmp = heads*sectors;
cylinders = capacity;
sector_div(cylinders, tmp);
}
geom[0] = heads;
geom[1] = sectors;
geom[2] = cylinders;
return 0;
}
/**
* megasas_service_aen - Processes an event notification
* @instance: Adapter soft state
* @cmd: AEN command completed by the ISR
*
* For AEN, driver sends a command down to FW that is held by the FW till an
* event occurs. When an event of interest occurs, FW completes the command
* that it was previously holding.
*
* This routines sends SIGIO signal to processes that have registered with the
* driver for AEN.
*/
static void
megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
/*
* Don't signal app if it is just an aborted previously registered aen
*/
if (!cmd->abort_aen)
kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
else
cmd->abort_aen = 0;
instance->aen_cmd = NULL;
megasas_return_cmd(instance, cmd);
}
/*
* Scsi host template for megaraid_sas driver
*/
static struct scsi_host_template megasas_template = {
.module = THIS_MODULE,
.name = "LSI SAS based MegaRAID driver",
.proc_name = "megaraid_sas",
.slave_configure = megasas_slave_configure,
.queuecommand = megasas_queue_command,
.eh_device_reset_handler = megasas_reset_device,
.eh_bus_reset_handler = megasas_reset_bus_host,
.eh_host_reset_handler = megasas_reset_bus_host,
.eh_timed_out = megasas_reset_timer,
.bios_param = megasas_bios_param,
.use_clustering = ENABLE_CLUSTERING,
};
/**
* megasas_complete_int_cmd - Completes an internal command
* @instance: Adapter soft state
* @cmd: Command to be completed
*
* The megasas_issue_blocked_cmd() function waits for a command to complete
* after it issues a command. This function wakes up that waiting routine by
* calling wake_up() on the wait queue.
*/
static void
megasas_complete_int_cmd(struct megasas_instance *instance,
struct megasas_cmd *cmd)
{
cmd->cmd_status = cmd->frame->io.cmd_status;
if (cmd->cmd_status == ENODATA) {
cmd->cmd_status = 0;
}
wake_up(&instance->int_cmd_wait_q);
}
/**
* megasas_complete_abort - Completes aborting a command
* @instance: Adapter soft state
* @cmd: Cmd that was issued to abort another cmd
*
* The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
* after it issues an abort on a previously issued command. This function
* wakes up all functions waiting on the same wait queue.
*/
static void
megasas_complete_abort(struct megasas_instance *instance,
struct megasas_cmd *cmd)
{
if (cmd->sync_cmd) {
cmd->sync_cmd = 0;
cmd->cmd_status = 0;
wake_up(&instance->abort_cmd_wait_q);
}
return;
}
/**
* megasas_complete_cmd - Completes a command
* @instance: Adapter soft state
* @cmd: Command to be completed
* @alt_status: If non-zero, use this value as status to
* SCSI mid-layer instead of the value returned
* by the FW. This should be used if caller wants
* an alternate status (as in the case of aborted
* commands)
*/
static void
megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
u8 alt_status)
{
int exception = 0;
struct megasas_header *hdr = &cmd->frame->hdr;
if (cmd->scmd)
cmd->scmd->SCp.ptr = NULL;
switch (hdr->cmd) {
case MFI_CMD_PD_SCSI_IO:
case MFI_CMD_LD_SCSI_IO:
/*
* MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
* issued either through an IO path or an IOCTL path. If it
* was via IOCTL, we will send it to internal completion.
*/
if (cmd->sync_cmd) {
cmd->sync_cmd = 0;
megasas_complete_int_cmd(instance, cmd);
break;
}
case MFI_CMD_LD_READ:
case MFI_CMD_LD_WRITE:
if (alt_status) {
cmd->scmd->result = alt_status << 16;
exception = 1;
}
if (exception) {
atomic_dec(&instance->fw_outstanding);
scsi_dma_unmap(cmd->scmd);
cmd->scmd->scsi_done(cmd->scmd);
megasas_return_cmd(instance, cmd);
break;
}
switch (hdr->cmd_status) {
case MFI_STAT_OK:
cmd->scmd->result = DID_OK << 16;
break;
case MFI_STAT_SCSI_IO_FAILED:
case MFI_STAT_LD_INIT_IN_PROGRESS:
cmd->scmd->result =
(DID_ERROR << 16) | hdr->scsi_status;
break;
case MFI_STAT_SCSI_DONE_WITH_ERROR:
cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
memset(cmd->scmd->sense_buffer, 0,
SCSI_SENSE_BUFFERSIZE);
memcpy(cmd->scmd->sense_buffer, cmd->sense,
hdr->sense_len);
cmd->scmd->result |= DRIVER_SENSE << 24;
}
break;
case MFI_STAT_LD_OFFLINE:
case MFI_STAT_DEVICE_NOT_FOUND:
cmd->scmd->result = DID_BAD_TARGET << 16;
break;
default:
printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
hdr->cmd_status);
cmd->scmd->result = DID_ERROR << 16;
break;
}
atomic_dec(&instance->fw_outstanding);
scsi_dma_unmap(cmd->scmd);
cmd->scmd->scsi_done(cmd->scmd);
megasas_return_cmd(instance, cmd);
break;
case MFI_CMD_SMP:
case MFI_CMD_STP:
case MFI_CMD_DCMD:
/*
* See if got an event notification
*/
if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
megasas_service_aen(instance, cmd);
else
megasas_complete_int_cmd(instance, cmd);
break;
case MFI_CMD_ABORT:
/*
* Cmd issued to abort another cmd returned
*/
megasas_complete_abort(instance, cmd);
break;
default:
printk("megasas: Unknown command completed! [0x%X]\n",
hdr->cmd);
break;
}
}
/**
* megasas_deplete_reply_queue - Processes all completed commands
* @instance: Adapter soft state
* @alt_status: Alternate status to be returned to
* SCSI mid-layer instead of the status
* returned by the FW
*/
static int
megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status)
{
/*
* Check if it is our interrupt
* Clear the interrupt
*/
if(instance->instancet->clear_intr(instance->reg_set))
return IRQ_NONE;
if (instance->hw_crit_error)
goto out_done;
/*
* Schedule the tasklet for cmd completion
*/
tasklet_schedule(&instance->isr_tasklet);
out_done:
return IRQ_HANDLED;
}
/**
* megasas_isr - isr entry point
*/
static irqreturn_t megasas_isr(int irq, void *devp)
{
return megasas_deplete_reply_queue((struct megasas_instance *)devp,
DID_OK);
}
/**
* megasas_transition_to_ready - Move the FW to READY state
* @instance: Adapter soft state
*
* During the initialization, FW passes can potentially be in any one of
* several possible states. If the FW in operational, waiting-for-handshake
* states, driver must take steps to bring it to ready state. Otherwise, it
* has to wait for the ready state.
*/
static int
megasas_transition_to_ready(struct megasas_instance* instance)
{
int i;
u8 max_wait;
u32 fw_state;
u32 cur_state;
fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
if (fw_state != MFI_STATE_READY)
printk(KERN_INFO "megasas: Waiting for FW to come to ready"
" state\n");
while (fw_state != MFI_STATE_READY) {
switch (fw_state) {
case MFI_STATE_FAULT:
printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
return -ENODEV;
case MFI_STATE_WAIT_HANDSHAKE:
/*
* Set the CLR bit in inbound doorbell
*/
writel(MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
&instance->reg_set->inbound_doorbell);
max_wait = 2;
cur_state = MFI_STATE_WAIT_HANDSHAKE;
break;
case MFI_STATE_BOOT_MESSAGE_PENDING:
writel(MFI_INIT_HOTPLUG,
&instance->reg_set->inbound_doorbell);
max_wait = 10;
cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
break;
case MFI_STATE_OPERATIONAL:
/*
* Bring it to READY state; assuming max wait 10 secs
*/
instance->instancet->disable_intr(instance->reg_set);
writel(MFI_RESET_FLAGS, &instance->reg_set->inbound_doorbell);
max_wait = 60;
cur_state = MFI_STATE_OPERATIONAL;
break;
case MFI_STATE_UNDEFINED:
/*
* This state should not last for more than 2 seconds
*/
max_wait = 2;
cur_state = MFI_STATE_UNDEFINED;
break;
case MFI_STATE_BB_INIT:
max_wait = 2;
cur_state = MFI_STATE_BB_INIT;
break;
case MFI_STATE_FW_INIT:
max_wait = 20;
cur_state = MFI_STATE_FW_INIT;
break;
case MFI_STATE_FW_INIT_2:
max_wait = 20;
cur_state = MFI_STATE_FW_INIT_2;
break;
case MFI_STATE_DEVICE_SCAN:
max_wait = 20;
cur_state = MFI_STATE_DEVICE_SCAN;
break;
case MFI_STATE_FLUSH_CACHE:
max_wait = 20;
cur_state = MFI_STATE_FLUSH_CACHE;
break;
default:
printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
fw_state);
return -ENODEV;
}
/*
* The cur_state should not last for more than max_wait secs
*/
for (i = 0; i < (max_wait * 1000); i++) {
fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &
MFI_STATE_MASK ;
if (fw_state == cur_state) {
msleep(1);
} else
break;
}
/*
* Return error if fw_state hasn't changed after max_wait
*/
if (fw_state == cur_state) {
printk(KERN_DEBUG "FW state [%d] hasn't changed "
"in %d secs\n", fw_state, max_wait);
return -ENODEV;
}
};
printk(KERN_INFO "megasas: FW now in Ready state\n");
return 0;
}
/**
* megasas_teardown_frame_pool - Destroy the cmd frame DMA pool
* @instance: Adapter soft state
*/
static void megasas_teardown_frame_pool(struct megasas_instance *instance)
{
int i;
u32 max_cmd = instance->max_fw_cmds;
struct megasas_cmd *cmd;
if (!instance->frame_dma_pool)
return;
/*
* Return all frames to pool
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
if (cmd->frame)
pci_pool_free(instance->frame_dma_pool, cmd->frame,
cmd->frame_phys_addr);
if (cmd->sense)
pci_pool_free(instance->sense_dma_pool, cmd->sense,
cmd->sense_phys_addr);
}
/*
* Now destroy the pool itself
*/
pci_pool_destroy(instance->frame_dma_pool);
pci_pool_destroy(instance->sense_dma_pool);
instance->frame_dma_pool = NULL;
instance->sense_dma_pool = NULL;
}
/**
* megasas_create_frame_pool - Creates DMA pool for cmd frames
* @instance: Adapter soft state
*
* Each command packet has an embedded DMA memory buffer that is used for
* filling MFI frame and the SG list that immediately follows the frame. This
* function creates those DMA memory buffers for each command packet by using
* PCI pool facility.
*/
static int megasas_create_frame_pool(struct megasas_instance *instance)
{
int i;
u32 max_cmd;
u32 sge_sz;
u32 sgl_sz;
u32 total_sz;
u32 frame_count;
struct megasas_cmd *cmd;
max_cmd = instance->max_fw_cmds;
/*
* Size of our frame is 64 bytes for MFI frame, followed by max SG
* elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
*/
sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
sizeof(struct megasas_sge32);
/*
* Calculated the number of 64byte frames required for SGL
*/
sgl_sz = sge_sz * instance->max_num_sge;
frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
/*
* We need one extra frame for the MFI command
*/
frame_count++;
total_sz = MEGAMFI_FRAME_SIZE * frame_count;
/*
* Use DMA pool facility provided by PCI layer
*/
instance->frame_dma_pool = pci_pool_create("megasas frame pool",
instance->pdev, total_sz, 64,
0);
if (!instance->frame_dma_pool) {
printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
return -ENOMEM;
}
instance->sense_dma_pool = pci_pool_create("megasas sense pool",
instance->pdev, 128, 4, 0);
if (!instance->sense_dma_pool) {
printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
pci_pool_destroy(instance->frame_dma_pool);
instance->frame_dma_pool = NULL;
return -ENOMEM;
}
/*
* Allocate and attach a frame to each of the commands in cmd_list.
* By making cmd->index as the context instead of the &cmd, we can
* always use 32bit context regardless of the architecture
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
GFP_KERNEL, &cmd->frame_phys_addr);
cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
GFP_KERNEL, &cmd->sense_phys_addr);
/*
* megasas_teardown_frame_pool() takes care of freeing
* whatever has been allocated
*/
if (!cmd->frame || !cmd->sense) {
printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
megasas_teardown_frame_pool(instance);
return -ENOMEM;
}
cmd->frame->io.context = cmd->index;
}
return 0;
}
/**
* megasas_free_cmds - Free all the cmds in the free cmd pool
* @instance: Adapter soft state
*/
static void megasas_free_cmds(struct megasas_instance *instance)
{
int i;
/* First free the MFI frame pool */
megasas_teardown_frame_pool(instance);
/* Free all the commands in the cmd_list */
for (i = 0; i < instance->max_fw_cmds; i++)
kfree(instance->cmd_list[i]);
/* Free the cmd_list buffer itself */
kfree(instance->cmd_list);
instance->cmd_list = NULL;
INIT_LIST_HEAD(&instance->cmd_pool);
}
/**
* megasas_alloc_cmds - Allocates the command packets
* @instance: Adapter soft state
*
* Each command that is issued to the FW, whether IO commands from the OS or
* internal commands like IOCTLs, are wrapped in local data structure called
* megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
* the FW.
*
* Each frame has a 32-bit field called context (tag). This context is used
* to get back the megasas_cmd from the frame when a frame gets completed in
* the ISR. Typically the address of the megasas_cmd itself would be used as
* the context. But we wanted to keep the differences between 32 and 64 bit
* systems to the mininum. We always use 32 bit integers for the context. In
* this driver, the 32 bit values are the indices into an array cmd_list.
* This array is used only to look up the megasas_cmd given the context. The
* free commands themselves are maintained in a linked list called cmd_pool.
*/
static int megasas_alloc_cmds(struct megasas_instance *instance)
{
int i;
int j;
u32 max_cmd;
struct megasas_cmd *cmd;
max_cmd = instance->max_fw_cmds;
/*
* instance->cmd_list is an array of struct megasas_cmd pointers.
* Allocate the dynamic array first and then allocate individual
* commands.
*/
instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
if (!instance->cmd_list) {
printk(KERN_DEBUG "megasas: out of memory\n");
return -ENOMEM;
}
for (i = 0; i < max_cmd; i++) {
instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
GFP_KERNEL);
if (!instance->cmd_list[i]) {
for (j = 0; j < i; j++)
kfree(instance->cmd_list[j]);
kfree(instance->cmd_list);
instance->cmd_list = NULL;
return -ENOMEM;
}
}
/*
* Add all the commands to command pool (instance->cmd_pool)
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
memset(cmd, 0, sizeof(struct megasas_cmd));
cmd->index = i;
cmd->instance = instance;
list_add_tail(&cmd->list, &instance->cmd_pool);
}
/*
* Create a frame pool and assign one frame to each cmd
*/
if (megasas_create_frame_pool(instance)) {
printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
megasas_free_cmds(instance);
}
return 0;
}
/**
* megasas_get_controller_info - Returns FW's controller structure
* @instance: Adapter soft state
* @ctrl_info: Controller information structure
*
* Issues an internal command (DCMD) to get the FW's controller structure.
* This information is mainly used to find out the maximum IO transfer per
* command supported by the FW.
*/
static int
megasas_get_ctrl_info(struct megasas_instance *instance,
struct megasas_ctrl_info *ctrl_info)
{
int ret = 0;
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
struct megasas_ctrl_info *ci;
dma_addr_t ci_h = 0;
cmd = megasas_get_cmd(instance);
if (!cmd) {
printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
return -ENOMEM;
}
dcmd = &cmd->frame->dcmd;
ci = pci_alloc_consistent(instance->pdev,
sizeof(struct megasas_ctrl_info), &ci_h);
if (!ci) {
printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
megasas_return_cmd(instance, cmd);
return -ENOMEM;
}
memset(ci, 0, sizeof(*ci));
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0xFF;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
dcmd->sgl.sge32[0].phys_addr = ci_h;
dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
if (!megasas_issue_polled(instance, cmd)) {
ret = 0;
memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
} else {
ret = -1;
}
pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
ci, ci_h);
megasas_return_cmd(instance, cmd);
return ret;
}
/**
* megasas_issue_init_mfi - Initializes the FW
* @instance: Adapter soft state
*
* Issues the INIT MFI cmd
*/
static int
megasas_issue_init_mfi(struct megasas_instance *instance)
{
u32 context;
struct megasas_cmd *cmd;
struct megasas_init_frame *init_frame;
struct megasas_init_queue_info *initq_info;
dma_addr_t init_frame_h;
dma_addr_t initq_info_h;
/*
* Prepare a init frame. Note the init frame points to queue info
* structure. Each frame has SGL allocated after first 64 bytes. For
* this frame - since we don't need any SGL - we use SGL's space as
* queue info structure
*
* We will not get a NULL command below. We just created the pool.
*/
cmd = megasas_get_cmd(instance);
init_frame = (struct megasas_init_frame *)cmd->frame;
initq_info = (struct megasas_init_queue_info *)
((unsigned long)init_frame + 64);
init_frame_h = cmd->frame_phys_addr;
initq_info_h = init_frame_h + 64;
context = init_frame->context;
memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
init_frame->context = context;
initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
initq_info->producer_index_phys_addr_lo = instance->producer_h;
initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
init_frame->cmd = MFI_CMD_INIT;
init_frame->cmd_status = 0xFF;
init_frame->queue_info_new_phys_addr_lo = initq_info_h;
init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
/*
* disable the intr before firing the init frame to FW
*/
instance->instancet->disable_intr(instance->reg_set);
/*
* Issue the init frame in polled mode
*/
if (megasas_issue_polled(instance, cmd)) {
printk(KERN_ERR "megasas: Failed to init firmware\n");
megasas_return_cmd(instance, cmd);
goto fail_fw_init;
}
megasas_return_cmd(instance, cmd);
return 0;
fail_fw_init:
return -EINVAL;
}
/**
* megasas_start_timer - Initializes a timer object
* @instance: Adapter soft state
* @timer: timer object to be initialized
* @fn: timer function
* @interval: time interval between timer function call
*/
static inline void
megasas_start_timer(struct megasas_instance *instance,
struct timer_list *timer,
void *fn, unsigned long interval)
{
init_timer(timer);
timer->expires = jiffies + interval;
timer->data = (unsigned long)instance;
timer->function = fn;
add_timer(timer);
}
/**
* megasas_io_completion_timer - Timer fn
* @instance_addr: Address of adapter soft state
*
* Schedules tasklet for cmd completion
* if poll_mode_io is set
*/
static void
megasas_io_completion_timer(unsigned long instance_addr)
{
struct megasas_instance *instance =
(struct megasas_instance *)instance_addr;
if (atomic_read(&instance->fw_outstanding))
tasklet_schedule(&instance->isr_tasklet);
/* Restart timer */
if (poll_mode_io)
mod_timer(&instance->io_completion_timer,
jiffies + MEGASAS_COMPLETION_TIMER_INTERVAL);
}
/**
* megasas_init_mfi - Initializes the FW
* @instance: Adapter soft state
*
* This is the main function for initializing MFI firmware.
*/
static int megasas_init_mfi(struct megasas_instance *instance)
{
u32 context_sz;
u32 reply_q_sz;
u32 max_sectors_1;
u32 max_sectors_2;
u32 tmp_sectors;
struct megasas_register_set __iomem *reg_set;
struct megasas_ctrl_info *ctrl_info;
/*
* Map the message registers
*/
if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0079GEN2)) {
instance->base_addr = pci_resource_start(instance->pdev, 1);
} else {
instance->base_addr = pci_resource_start(instance->pdev, 0);
}
if (pci_request_regions(instance->pdev, "megasas: LSI")) {
printk(KERN_DEBUG "megasas: IO memory region busy!\n");
return -EBUSY;
}
instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
if (!instance->reg_set) {
printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
goto fail_ioremap;
}
reg_set = instance->reg_set;
switch(instance->pdev->device)
{
case PCI_DEVICE_ID_LSI_SAS1078R:
case PCI_DEVICE_ID_LSI_SAS1078DE:
instance->instancet = &megasas_instance_template_ppc;
break;
case PCI_DEVICE_ID_LSI_SAS1078GEN2:
case PCI_DEVICE_ID_LSI_SAS0079GEN2:
instance->instancet = &megasas_instance_template_gen2;
break;
case PCI_DEVICE_ID_LSI_SAS1064R:
case PCI_DEVICE_ID_DELL_PERC5:
default:
instance->instancet = &megasas_instance_template_xscale;
break;
}
/*
* We expect the FW state to be READY
*/
if (megasas_transition_to_ready(instance))
goto fail_ready_state;
/*
* Get various operational parameters from status register
*/
instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
/*
* Reduce the max supported cmds by 1. This is to ensure that the
* reply_q_sz (1 more than the max cmd that driver may send)
* does not exceed max cmds that the FW can support
*/
instance->max_fw_cmds = instance->max_fw_cmds-1;
instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >>
0x10;
/*
* Create a pool of commands
*/
if (megasas_alloc_cmds(instance))
goto fail_alloc_cmds;
/*
* Allocate memory for reply queue. Length of reply queue should
* be _one_ more than the maximum commands handled by the firmware.
*
* Note: When FW completes commands, it places corresponding contex
* values in this circular reply queue. This circular queue is a fairly
* typical producer-consumer queue. FW is the producer (of completed
* commands) and the driver is the consumer.
*/
context_sz = sizeof(u32);
reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
instance->reply_queue = pci_alloc_consistent(instance->pdev,
reply_q_sz,
&instance->reply_queue_h);
if (!instance->reply_queue) {
printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
goto fail_reply_queue;
}
if (megasas_issue_init_mfi(instance))
goto fail_fw_init;
ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
/*
* Compute the max allowed sectors per IO: The controller info has two
* limits on max sectors. Driver should use the minimum of these two.
*
* 1 << stripe_sz_ops.min = max sectors per strip
*
* Note that older firmwares ( < FW ver 30) didn't report information
* to calculate max_sectors_1. So the number ended up as zero always.
*/
tmp_sectors = 0;
if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
ctrl_info->max_strips_per_io;
max_sectors_2 = ctrl_info->max_request_size;
tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
}
instance->max_sectors_per_req = instance->max_num_sge *
PAGE_SIZE / 512;
if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
instance->max_sectors_per_req = tmp_sectors;
kfree(ctrl_info);
/*
* Setup tasklet for cmd completion
*/
tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
(unsigned long)instance);
/* Initialize the cmd completion timer */
if (poll_mode_io)
megasas_start_timer(instance, &instance->io_completion_timer,
megasas_io_completion_timer,
MEGASAS_COMPLETION_TIMER_INTERVAL);
return 0;
fail_fw_init:
pci_free_consistent(instance->pdev, reply_q_sz,
instance->reply_queue, instance->reply_queue_h);
fail_reply_queue:
megasas_free_cmds(instance);
fail_alloc_cmds:
fail_ready_state:
iounmap(instance->reg_set);
fail_ioremap:
pci_release_regions(instance->pdev);
return -EINVAL;
}
/**
* megasas_release_mfi - Reverses the FW initialization
* @intance: Adapter soft state
*/
static void megasas_release_mfi(struct megasas_instance *instance)
{
u32 reply_q_sz = sizeof(u32) * (instance->max_fw_cmds + 1);
pci_free_consistent(instance->pdev, reply_q_sz,
instance->reply_queue, instance->reply_queue_h);
megasas_free_cmds(instance);
iounmap(instance->reg_set);
pci_release_regions(instance->pdev);
}
/**
* megasas_get_seq_num - Gets latest event sequence numbers
* @instance: Adapter soft state
* @eli: FW event log sequence numbers information
*
* FW maintains a log of all events in a non-volatile area. Upper layers would
* usually find out the latest sequence number of the events, the seq number at
* the boot etc. They would "read" all the events below the latest seq number
* by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
* number), they would subsribe to AEN (asynchronous event notification) and
* wait for the events to happen.
*/
static int
megasas_get_seq_num(struct megasas_instance *instance,
struct megasas_evt_log_info *eli)
{
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
struct megasas_evt_log_info *el_info;
dma_addr_t el_info_h = 0;
cmd = megasas_get_cmd(instance);
if (!cmd) {
return -ENOMEM;
}
dcmd = &cmd->frame->dcmd;
el_info = pci_alloc_consistent(instance->pdev,
sizeof(struct megasas_evt_log_info),
&el_info_h);
if (!el_info) {
megasas_return_cmd(instance, cmd);
return -ENOMEM;
}
memset(el_info, 0, sizeof(*el_info));
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
dcmd->sgl.sge32[0].phys_addr = el_info_h;
dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
megasas_issue_blocked_cmd(instance, cmd);
/*
* Copy the data back into callers buffer
*/
memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
el_info, el_info_h);
megasas_return_cmd(instance, cmd);
return 0;
}
/**
* megasas_register_aen - Registers for asynchronous event notification
* @instance: Adapter soft state
* @seq_num: The starting sequence number
* @class_locale: Class of the event
*
* This function subscribes for AEN for events beyond the @seq_num. It requests
* to be notified if and only if the event is of type @class_locale
*/
static int
megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
u32 class_locale_word)
{
int ret_val;
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
union megasas_evt_class_locale curr_aen;
union megasas_evt_class_locale prev_aen;
/*
* If there an AEN pending already (aen_cmd), check if the
* class_locale of that pending AEN is inclusive of the new
* AEN request we currently have. If it is, then we don't have
* to do anything. In other words, whichever events the current
* AEN request is subscribing to, have already been subscribed
* to.
*
* If the old_cmd is _not_ inclusive, then we have to abort
* that command, form a class_locale that is superset of both
* old and current and re-issue to the FW
*/
curr_aen.word = class_locale_word;
if (instance->aen_cmd) {
prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
/*
* A class whose enum value is smaller is inclusive of all
* higher values. If a PROGRESS (= -1) was previously
* registered, then a new registration requests for higher
* classes need not be sent to FW. They are automatically
* included.
*
* Locale numbers don't have such hierarchy. They are bitmap
* values
*/
if ((prev_aen.members.class <= curr_aen.members.class) &&
!((prev_aen.members.locale & curr_aen.members.locale) ^
curr_aen.members.locale)) {
/*
* Previously issued event registration includes
* current request. Nothing to do.
*/
return 0;
} else {
curr_aen.members.locale |= prev_aen.members.locale;
if (prev_aen.members.class < curr_aen.members.class)
curr_aen.members.class = prev_aen.members.class;
instance->aen_cmd->abort_aen = 1;
ret_val = megasas_issue_blocked_abort_cmd(instance,
instance->
aen_cmd);
if (ret_val) {
printk(KERN_DEBUG "megasas: Failed to abort "
"previous AEN command\n");
return ret_val;
}
}
}
cmd = megasas_get_cmd(instance);
if (!cmd)
return -ENOMEM;
dcmd = &cmd->frame->dcmd;
memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
/*
* Prepare DCMD for aen registration
*/
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 1;
dcmd->flags = MFI_FRAME_DIR_READ;
dcmd->timeout = 0;
dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
dcmd->mbox.w[0] = seq_num;
dcmd->mbox.w[1] = curr_aen.word;
dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
/*
* Store reference to the cmd used to register for AEN. When an
* application wants us to register for AEN, we have to abort this
* cmd and re-register with a new EVENT LOCALE supplied by that app
*/
instance->aen_cmd = cmd;
/*
* Issue the aen registration frame
*/
instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
return 0;
}
/**
* megasas_start_aen - Subscribes to AEN during driver load time
* @instance: Adapter soft state
*/
static int megasas_start_aen(struct megasas_instance *instance)
{
struct megasas_evt_log_info eli;
union megasas_evt_class_locale class_locale;
/*
* Get the latest sequence number from FW
*/
memset(&eli, 0, sizeof(eli));
if (megasas_get_seq_num(instance, &eli))
return -1;
/*
* Register AEN with FW for latest sequence number plus 1
*/
class_locale.members.reserved = 0;
class_locale.members.locale = MR_EVT_LOCALE_ALL;
class_locale.members.class = MR_EVT_CLASS_DEBUG;
return megasas_register_aen(instance, eli.newest_seq_num + 1,
class_locale.word);
}
/**
* megasas_io_attach - Attaches this driver to SCSI mid-layer
* @instance: Adapter soft state
*/
static int megasas_io_attach(struct megasas_instance *instance)
{
struct Scsi_Host *host = instance->host;
/*
* Export parameters required by SCSI mid-layer
*/
host->irq = instance->pdev->irq;
host->unique_id = instance->unique_id;
host->can_queue = instance->max_fw_cmds - MEGASAS_INT_CMDS;
host->this_id = instance->init_id;
host->sg_tablesize = instance->max_num_sge;
host->max_sectors = instance->max_sectors_per_req;
host->cmd_per_lun = 128;
host->max_channel = MEGASAS_MAX_CHANNELS - 1;
host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
host->max_lun = MEGASAS_MAX_LUN;
host->max_cmd_len = 16;
/*
* Notify the mid-layer about the new controller
*/
if (scsi_add_host(host, &instance->pdev->dev)) {
printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
return -ENODEV;
}
/*
* Trigger SCSI to scan our drives
*/
scsi_scan_host(host);
return 0;
}
static int
megasas_set_dma_mask(struct pci_dev *pdev)
{
/*
* All our contollers are capable of performing 64-bit DMA
*/
if (IS_DMA64) {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
goto fail_set_dma_mask;
}
} else {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
goto fail_set_dma_mask;
}
return 0;
fail_set_dma_mask:
return 1;
}
/**
* megasas_probe_one - PCI hotplug entry point
* @pdev: PCI device structure
* @id: PCI ids of supported hotplugged adapter
*/
static int __devinit
megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
{
int rval;
struct Scsi_Host *host;
struct megasas_instance *instance;
/*
* Announce PCI information
*/
printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
pdev->vendor, pdev->device, pdev->subsystem_vendor,
pdev->subsystem_device);
printk("bus %d:slot %d:func %d\n",
pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
/*
* PCI prepping: enable device set bus mastering and dma mask
*/
rval = pci_enable_device(pdev);
if (rval) {
return rval;
}
pci_set_master(pdev);
if (megasas_set_dma_mask(pdev))
goto fail_set_dma_mask;
host = scsi_host_alloc(&megasas_template,
sizeof(struct megasas_instance));
if (!host) {
printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
goto fail_alloc_instance;
}
instance = (struct megasas_instance *)host->hostdata;
memset(instance, 0, sizeof(*instance));
instance->producer = pci_alloc_consistent(pdev, sizeof(u32),
&instance->producer_h);
instance->consumer = pci_alloc_consistent(pdev, sizeof(u32),
&instance->consumer_h);
if (!instance->producer || !instance->consumer) {
printk(KERN_DEBUG "megasas: Failed to allocate memory for "
"producer, consumer\n");
goto fail_alloc_dma_buf;
}
*instance->producer = 0;
*instance->consumer = 0;
instance->evt_detail = pci_alloc_consistent(pdev,
sizeof(struct
megasas_evt_detail),
&instance->evt_detail_h);
if (!instance->evt_detail) {
printk(KERN_DEBUG "megasas: Failed to allocate memory for "
"event detail structure\n");
goto fail_alloc_dma_buf;
}
/*
* Initialize locks and queues
*/
INIT_LIST_HEAD(&instance->cmd_pool);
atomic_set(&instance->fw_outstanding,0);
init_waitqueue_head(&instance->int_cmd_wait_q);
init_waitqueue_head(&instance->abort_cmd_wait_q);
spin_lock_init(&instance->cmd_pool_lock);
spin_lock_init(&instance->completion_lock);
mutex_init(&instance->aen_mutex);
sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
/*
* Initialize PCI related and misc parameters
*/
instance->pdev = pdev;
instance->host = host;
instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
instance->init_id = MEGASAS_DEFAULT_INIT_ID;
megasas_dbg_lvl = 0;
instance->flag = 0;
instance->last_time = 0;
/*
* Initialize MFI Firmware
*/
if (megasas_init_mfi(instance))
goto fail_init_mfi;
/*
* Register IRQ
*/
if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED, "megasas", instance)) {
printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
goto fail_irq;
}
instance->instancet->enable_intr(instance->reg_set);
/*
* Store instance in PCI softstate
*/
pci_set_drvdata(pdev, instance);
/*
* Add this controller to megasas_mgmt_info structure so that it
* can be exported to management applications
*/
megasas_mgmt_info.count++;
megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
megasas_mgmt_info.max_index++;
/*
* Initiate AEN (Asynchronous Event Notification)
*/
if (megasas_start_aen(instance)) {
printk(KERN_DEBUG "megasas: start aen failed\n");
goto fail_start_aen;
}
/*
* Register with SCSI mid-layer
*/
if (megasas_io_attach(instance))
goto fail_io_attach;
return 0;
fail_start_aen:
fail_io_attach:
megasas_mgmt_info.count--;
megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
megasas_mgmt_info.max_index--;
pci_set_drvdata(pdev, NULL);
instance->instancet->disable_intr(instance->reg_set);
free_irq(instance->pdev->irq, instance);
megasas_release_mfi(instance);
fail_irq:
fail_init_mfi:
fail_alloc_dma_buf:
if (instance->evt_detail)
pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
instance->evt_detail,
instance->evt_detail_h);
if (instance->producer)
pci_free_consistent(pdev, sizeof(u32), instance->producer,
instance->producer_h);
if (instance->consumer)
pci_free_consistent(pdev, sizeof(u32), instance->consumer,
instance->consumer_h);
scsi_host_put(host);
fail_alloc_instance:
fail_set_dma_mask:
pci_disable_device(pdev);
return -ENODEV;
}
/**
* megasas_flush_cache - Requests FW to flush all its caches
* @instance: Adapter soft state
*/
static void megasas_flush_cache(struct megasas_instance *instance)
{
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
cmd = megasas_get_cmd(instance);
if (!cmd)
return;
dcmd = &cmd->frame->dcmd;
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 0;
dcmd->flags = MFI_FRAME_DIR_NONE;
dcmd->timeout = 0;
dcmd->data_xfer_len = 0;
dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
megasas_issue_blocked_cmd(instance, cmd);
megasas_return_cmd(instance, cmd);
return;
}
/**
* megasas_shutdown_controller - Instructs FW to shutdown the controller
* @instance: Adapter soft state
* @opcode: Shutdown/Hibernate
*/
static void megasas_shutdown_controller(struct megasas_instance *instance,
u32 opcode)
{
struct megasas_cmd *cmd;
struct megasas_dcmd_frame *dcmd;
cmd = megasas_get_cmd(instance);
if (!cmd)
return;
if (instance->aen_cmd)
megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
dcmd = &cmd->frame->dcmd;
memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
dcmd->cmd = MFI_CMD_DCMD;
dcmd->cmd_status = 0x0;
dcmd->sge_count = 0;
dcmd->flags = MFI_FRAME_DIR_NONE;
dcmd->timeout = 0;
dcmd->data_xfer_len = 0;
dcmd->opcode = opcode;
megasas_issue_blocked_cmd(instance, cmd);
megasas_return_cmd(instance, cmd);
return;
}
#ifdef CONFIG_PM
/**
* megasas_suspend - driver suspend entry point
* @pdev: PCI device structure
* @state: PCI power state to suspend routine
*/
static int
megasas_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct Scsi_Host *host;
struct megasas_instance *instance;
instance = pci_get_drvdata(pdev);
host = instance->host;
if (poll_mode_io)
del_timer_sync(&instance->io_completion_timer);
megasas_flush_cache(instance);
megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
tasklet_kill(&instance->isr_tasklet);
pci_set_drvdata(instance->pdev, instance);
instance->instancet->disable_intr(instance->reg_set);
free_irq(instance->pdev->irq, instance);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
/**
* megasas_resume- driver resume entry point
* @pdev: PCI device structure
*/
static int
megasas_resume(struct pci_dev *pdev)
{
int rval;
struct Scsi_Host *host;
struct megasas_instance *instance;
instance = pci_get_drvdata(pdev);
host = instance->host;
pci_set_power_state(pdev, PCI_D0);
pci_enable_wake(pdev, PCI_D0, 0);
pci_restore_state(pdev);
/*
* PCI prepping: enable device set bus mastering and dma mask
*/
rval = pci_enable_device(pdev);
if (rval) {
printk(KERN_ERR "megasas: Enable device failed\n");
return rval;
}
pci_set_master(pdev);
if (megasas_set_dma_mask(pdev))
goto fail_set_dma_mask;
/*
* Initialize MFI Firmware
*/
*instance->producer = 0;
*instance->consumer = 0;
atomic_set(&instance->fw_outstanding, 0);
/*
* We expect the FW state to be READY
*/
if (megasas_transition_to_ready(instance))
goto fail_ready_state;
if (megasas_issue_init_mfi(instance))
goto fail_init_mfi;
tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
(unsigned long)instance);
/*
* Register IRQ
*/
if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED,
"megasas", instance)) {
printk(KERN_ERR "megasas: Failed to register IRQ\n");
goto fail_irq;
}
instance->instancet->enable_intr(instance->reg_set);
/*
* Initiate AEN (Asynchronous Event Notification)
*/
if (megasas_start_aen(instance))
printk(KERN_ERR "megasas: Start AEN failed\n");
/* Initialize the cmd completion timer */
if (poll_mode_io)
megasas_start_timer(instance, &instance->io_completion_timer,
megasas_io_completion_timer,
MEGASAS_COMPLETION_TIMER_INTERVAL);
return 0;
fail_irq:
fail_init_mfi:
if (instance->evt_detail)
pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
instance->evt_detail,
instance->evt_detail_h);
if (instance->producer)
pci_free_consistent(pdev, sizeof(u32), instance->producer,
instance->producer_h);
if (instance->consumer)
pci_free_consistent(pdev, sizeof(u32), instance->consumer,
instance->consumer_h);
scsi_host_put(host);
fail_set_dma_mask:
fail_ready_state:
pci_disable_device(pdev);
return -ENODEV;
}
#else
#define megasas_suspend NULL
#define megasas_resume NULL
#endif
/**
* megasas_detach_one - PCI hot"un"plug entry point
* @pdev: PCI device structure
*/
static void __devexit megasas_detach_one(struct pci_dev *pdev)
{
int i;
struct Scsi_Host *host;
struct megasas_instance *instance;
instance = pci_get_drvdata(pdev);
host = instance->host;
if (poll_mode_io)
del_timer_sync(&instance->io_completion_timer);
scsi_remove_host(instance->host);
megasas_flush_cache(instance);
megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
tasklet_kill(&instance->isr_tasklet);
/*
* Take the instance off the instance array. Note that we will not
* decrement the max_index. We let this array be sparse array
*/
for (i = 0; i < megasas_mgmt_info.max_index; i++) {
if (megasas_mgmt_info.instance[i] == instance) {
megasas_mgmt_info.count--;
megasas_mgmt_info.instance[i] = NULL;
break;
}
}
pci_set_drvdata(instance->pdev, NULL);
instance->instancet->disable_intr(instance->reg_set);
free_irq(instance->pdev->irq, instance);
megasas_release_mfi(instance);
pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
instance->evt_detail, instance->evt_detail_h);
pci_free_consistent(pdev, sizeof(u32), instance->producer,
instance->producer_h);
pci_free_consistent(pdev, sizeof(u32), instance->consumer,
instance->consumer_h);
scsi_host_put(host);
pci_set_drvdata(pdev, NULL);
pci_disable_device(pdev);
return;
}
/**
* megasas_shutdown - Shutdown entry point
* @device: Generic device structure
*/
static void megasas_shutdown(struct pci_dev *pdev)
{
struct megasas_instance *instance = pci_get_drvdata(pdev);
megasas_flush_cache(instance);
megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
}
/**
* megasas_mgmt_open - char node "open" entry point
*/
static int megasas_mgmt_open(struct inode *inode, struct file *filep)
{
cycle_kernel_lock();
/*
* Allow only those users with admin rights
*/
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return 0;
}
/**
* megasas_mgmt_fasync - Async notifier registration from applications
*
* This function adds the calling process to a driver global queue. When an
* event occurs, SIGIO will be sent to all processes in this queue.
*/
static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
{
int rc;
mutex_lock(&megasas_async_queue_mutex);
rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
mutex_unlock(&megasas_async_queue_mutex);
if (rc >= 0) {
/* For sanity check when we get ioctl */
filep->private_data = filep;
return 0;
}
printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
return rc;
}
/**
* megasas_mgmt_fw_ioctl - Issues management ioctls to FW
* @instance: Adapter soft state
* @argp: User's ioctl packet
*/
static int
megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
struct megasas_iocpacket __user * user_ioc,
struct megasas_iocpacket *ioc)
{
struct megasas_sge32 *kern_sge32;
struct megasas_cmd *cmd;
void *kbuff_arr[MAX_IOCTL_SGE];
dma_addr_t buf_handle = 0;
int error = 0, i;
void *sense = NULL;
dma_addr_t sense_handle;
unsigned long *sense_ptr;
memset(kbuff_arr, 0, sizeof(kbuff_arr));
if (ioc->sge_count > MAX_IOCTL_SGE) {
printk(KERN_DEBUG "megasas: SGE count [%d] > max limit [%d]\n",
ioc->sge_count, MAX_IOCTL_SGE);
return -EINVAL;
}
cmd = megasas_get_cmd(instance);
if (!cmd) {
printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
return -ENOMEM;
}
/*
* User's IOCTL packet has 2 frames (maximum). Copy those two
* frames into our cmd's frames. cmd->frame's context will get
* overwritten when we copy from user's frames. So set that value
* alone separately
*/
memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
cmd->frame->hdr.context = cmd->index;
/*
* The management interface between applications and the fw uses
* MFI frames. E.g, RAID configuration changes, LD property changes
* etc are accomplishes through different kinds of MFI frames. The
* driver needs to care only about substituting user buffers with
* kernel buffers in SGLs. The location of SGL is embedded in the
* struct iocpacket itself.
*/
kern_sge32 = (struct megasas_sge32 *)
((unsigned long)cmd->frame + ioc->sgl_off);
/*
* For each user buffer, create a mirror buffer and copy in
*/
for (i = 0; i < ioc->sge_count; i++) {
kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
ioc->sgl[i].iov_len,
&buf_handle, GFP_KERNEL);
if (!kbuff_arr[i]) {
printk(KERN_DEBUG "megasas: Failed to alloc "
"kernel SGL buffer for IOCTL \n");
error = -ENOMEM;
goto out;
}
/*
* We don't change the dma_coherent_mask, so
* pci_alloc_consistent only returns 32bit addresses
*/
kern_sge32[i].phys_addr = (u32) buf_handle;
kern_sge32[i].length = ioc->sgl[i].iov_len;
/*
* We created a kernel buffer corresponding to the
* user buffer. Now copy in from the user buffer
*/
if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
(u32) (ioc->sgl[i].iov_len))) {
error = -EFAULT;
goto out;
}
}
if (ioc->sense_len) {
sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
&sense_handle, GFP_KERNEL);
if (!sense) {
error = -ENOMEM;
goto out;
}
sense_ptr =
(unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
*sense_ptr = sense_handle;
}
/*
* Set the sync_cmd flag so that the ISR knows not to complete this
* cmd to the SCSI mid-layer
*/
cmd->sync_cmd = 1;
megasas_issue_blocked_cmd(instance, cmd);
cmd->sync_cmd = 0;
/*
* copy out the kernel buffers to user buffers
*/
for (i = 0; i < ioc->sge_count; i++) {
if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
ioc->sgl[i].iov_len)) {
error = -EFAULT;
goto out;
}
}
/*
* copy out the sense
*/
if (ioc->sense_len) {
/*
* sense_ptr points to the location that has the user
* sense buffer address
*/
sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
ioc->sense_off);
if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
sense, ioc->sense_len)) {
printk(KERN_ERR "megasas: Failed to copy out to user "
"sense data\n");
error = -EFAULT;
goto out;
}
}
/*
* copy the status codes returned by the fw
*/
if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
&cmd->frame->hdr.cmd_status, sizeof(u8))) {
printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
error = -EFAULT;
}
out:
if (sense) {
dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
sense, sense_handle);
}
for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
dma_free_coherent(&instance->pdev->dev,
kern_sge32[i].length,
kbuff_arr[i], kern_sge32[i].phys_addr);
}
megasas_return_cmd(instance, cmd);
return error;
}
static struct megasas_instance *megasas_lookup_instance(u16 host_no)
{
int i;
for (i = 0; i < megasas_mgmt_info.max_index; i++) {
if ((megasas_mgmt_info.instance[i]) &&
(megasas_mgmt_info.instance[i]->host->host_no == host_no))
return megasas_mgmt_info.instance[i];
}
return NULL;
}
static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
{
struct megasas_iocpacket __user *user_ioc =
(struct megasas_iocpacket __user *)arg;
struct megasas_iocpacket *ioc;
struct megasas_instance *instance;
int error;
ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
if (!ioc)
return -ENOMEM;
if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
error = -EFAULT;
goto out_kfree_ioc;
}
instance = megasas_lookup_instance(ioc->host_no);
if (!instance) {
error = -ENODEV;
goto out_kfree_ioc;
}
/*
* We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
*/
if (down_interruptible(&instance->ioctl_sem)) {
error = -ERESTARTSYS;
goto out_kfree_ioc;
}
error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
up(&instance->ioctl_sem);
out_kfree_ioc:
kfree(ioc);
return error;
}
static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
{
struct megasas_instance *instance;
struct megasas_aen aen;
int error;
if (file->private_data != file) {
printk(KERN_DEBUG "megasas: fasync_helper was not "
"called first\n");
return -EINVAL;
}
if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
return -EFAULT;
instance = megasas_lookup_instance(aen.host_no);
if (!instance)
return -ENODEV;
mutex_lock(&instance->aen_mutex);
error = megasas_register_aen(instance, aen.seq_num,
aen.class_locale_word);
mutex_unlock(&instance->aen_mutex);
return error;
}
/**
* megasas_mgmt_ioctl - char node ioctl entry point
*/
static long
megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case MEGASAS_IOC_FIRMWARE:
return megasas_mgmt_ioctl_fw(file, arg);
case MEGASAS_IOC_GET_AEN:
return megasas_mgmt_ioctl_aen(file, arg);
}
return -ENOTTY;
}
#ifdef CONFIG_COMPAT
static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
{
struct compat_megasas_iocpacket __user *cioc =
(struct compat_megasas_iocpacket __user *)arg;
struct megasas_iocpacket __user *ioc =
compat_alloc_user_space(sizeof(struct megasas_iocpacket));
int i;
int error = 0;
if (clear_user(ioc, sizeof(*ioc)))
return -EFAULT;
if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
return -EFAULT;
for (i = 0; i < MAX_IOCTL_SGE; i++) {
compat_uptr_t ptr;
if (get_user(ptr, &cioc->sgl[i].iov_base) ||
put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
copy_in_user(&ioc->sgl[i].iov_len,
&cioc->sgl[i].iov_len, sizeof(compat_size_t)))
return -EFAULT;
}
error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
if (copy_in_user(&cioc->frame.hdr.cmd_status,
&ioc->frame.hdr.cmd_status, sizeof(u8))) {
printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
return -EFAULT;
}
return error;
}
static long
megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
switch (cmd) {
case MEGASAS_IOC_FIRMWARE32:
return megasas_mgmt_compat_ioctl_fw(file, arg);
case MEGASAS_IOC_GET_AEN:
return megasas_mgmt_ioctl_aen(file, arg);
}
return -ENOTTY;
}
#endif
/*
* File operations structure for management interface
*/
static const struct file_operations megasas_mgmt_fops = {
.owner = THIS_MODULE,
.open = megasas_mgmt_open,
.fasync = megasas_mgmt_fasync,
.unlocked_ioctl = megasas_mgmt_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = megasas_mgmt_compat_ioctl,
#endif
};
/*
* PCI hotplug support registration structure
*/
static struct pci_driver megasas_pci_driver = {
.name = "megaraid_sas",
.id_table = megasas_pci_table,
.probe = megasas_probe_one,
.remove = __devexit_p(megasas_detach_one),
.suspend = megasas_suspend,
.resume = megasas_resume,
.shutdown = megasas_shutdown,
};
/*
* Sysfs driver attributes
*/
static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
{
return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
MEGASAS_VERSION);
}
static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
static ssize_t
megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
{
return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
MEGASAS_RELDATE);
}
static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
NULL);
static ssize_t
megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
{
return sprintf(buf, "%u\n", megasas_dbg_lvl);
}
static ssize_t
megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
{
int retval = count;
if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
printk(KERN_ERR "megasas: could not set dbg_lvl\n");
retval = -EINVAL;
}
return retval;
}
static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl,
megasas_sysfs_set_dbg_lvl);
static ssize_t
megasas_sysfs_show_poll_mode_io(struct device_driver *dd, char *buf)
{
return sprintf(buf, "%u\n", poll_mode_io);
}
static ssize_t
megasas_sysfs_set_poll_mode_io(struct device_driver *dd,
const char *buf, size_t count)
{
int retval = count;
int tmp = poll_mode_io;
int i;
struct megasas_instance *instance;
if (sscanf(buf, "%u", &poll_mode_io) < 1) {
printk(KERN_ERR "megasas: could not set poll_mode_io\n");
retval = -EINVAL;
}
/*
* Check if poll_mode_io is already set or is same as previous value
*/
if ((tmp && poll_mode_io) || (tmp == poll_mode_io))
goto out;
if (poll_mode_io) {
/*
* Start timers for all adapters
*/
for (i = 0; i < megasas_mgmt_info.max_index; i++) {
instance = megasas_mgmt_info.instance[i];
if (instance) {
megasas_start_timer(instance,
&instance->io_completion_timer,
megasas_io_completion_timer,
MEGASAS_COMPLETION_TIMER_INTERVAL);
}
}
} else {
/*
* Delete timers for all adapters
*/
for (i = 0; i < megasas_mgmt_info.max_index; i++) {
instance = megasas_mgmt_info.instance[i];
if (instance)
del_timer_sync(&instance->io_completion_timer);
}
}
out:
return retval;
}
static DRIVER_ATTR(poll_mode_io, S_IRUGO|S_IWUSR,
megasas_sysfs_show_poll_mode_io,
megasas_sysfs_set_poll_mode_io);
/**
* megasas_init - Driver load entry point
*/
static int __init megasas_init(void)
{
int rval;
/*
* Announce driver version and other information
*/
printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
MEGASAS_EXT_VERSION);
memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
/*
* Register character device node
*/
rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
if (rval < 0) {
printk(KERN_DEBUG "megasas: failed to open device node\n");
return rval;
}
megasas_mgmt_majorno = rval;
/*
* Register ourselves as PCI hotplug module
*/
rval = pci_register_driver(&megasas_pci_driver);
if (rval) {
printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
goto err_pcidrv;
}
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_version);
if (rval)
goto err_dcf_attr_ver;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_release_date);
if (rval)
goto err_dcf_rel_date;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_dbg_lvl);
if (rval)
goto err_dcf_dbg_lvl;
rval = driver_create_file(&megasas_pci_driver.driver,
&driver_attr_poll_mode_io);
if (rval)
goto err_dcf_poll_mode_io;
return rval;
err_dcf_poll_mode_io:
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_dbg_lvl);
err_dcf_dbg_lvl:
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_release_date);
err_dcf_rel_date:
driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
err_dcf_attr_ver:
pci_unregister_driver(&megasas_pci_driver);
err_pcidrv:
unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
return rval;
}
/**
* megasas_exit - Driver unload entry point
*/
static void __exit megasas_exit(void)
{
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_poll_mode_io);
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_dbg_lvl);
driver_remove_file(&megasas_pci_driver.driver,
&driver_attr_release_date);
driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
pci_unregister_driver(&megasas_pci_driver);
unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
}
module_init(megasas_init);
module_exit(megasas_exit);
| gpl-2.0 |
1N4148/android_kernel_samsung_msm7x27a | arch/powerpc/kvm/e500.c | 300 | 3855 | /*
* Copyright (C) 2008 Freescale Semiconductor, Inc. All rights reserved.
*
* Author: Yu Liu, <yu.liu@freescale.com>
*
* Description:
* This file is derived from arch/powerpc/kvm/44x.c,
* by Hollis Blanchard <hollisb@us.ibm.com>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*/
#include <linux/kvm_host.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <asm/reg.h>
#include <asm/cputable.h>
#include <asm/tlbflush.h>
#include <asm/kvm_e500.h>
#include <asm/kvm_ppc.h>
#include "booke.h"
#include "e500_tlb.h"
void kvmppc_core_load_host_debugstate(struct kvm_vcpu *vcpu)
{
}
void kvmppc_core_load_guest_debugstate(struct kvm_vcpu *vcpu)
{
}
void kvmppc_core_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
kvmppc_e500_tlb_load(vcpu, cpu);
}
void kvmppc_core_vcpu_put(struct kvm_vcpu *vcpu)
{
kvmppc_e500_tlb_put(vcpu);
}
int kvmppc_core_check_processor_compat(void)
{
int r;
if (strcmp(cur_cpu_spec->cpu_name, "e500v2") == 0)
r = 0;
else
r = -ENOTSUPP;
return r;
}
int kvmppc_core_vcpu_setup(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
kvmppc_e500_tlb_setup(vcpu_e500);
/* Registers init */
vcpu->arch.pvr = mfspr(SPRN_PVR);
/* Since booke kvm only support one core, update all vcpus' PIR to 0 */
vcpu->vcpu_id = 0;
return 0;
}
/* 'linear_address' is actually an encoding of AS|PID|EADDR . */
int kvmppc_core_vcpu_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
int index;
gva_t eaddr;
u8 pid;
u8 as;
eaddr = tr->linear_address;
pid = (tr->linear_address >> 32) & 0xff;
as = (tr->linear_address >> 40) & 0x1;
index = kvmppc_e500_tlb_search(vcpu, eaddr, pid, as);
if (index < 0) {
tr->valid = 0;
return 0;
}
tr->physical_address = kvmppc_mmu_xlate(vcpu, index, eaddr);
/* XXX what does "writeable" and "usermode" even mean? */
tr->valid = 1;
return 0;
}
struct kvm_vcpu *kvmppc_core_vcpu_create(struct kvm *kvm, unsigned int id)
{
struct kvmppc_vcpu_e500 *vcpu_e500;
struct kvm_vcpu *vcpu;
int err;
vcpu_e500 = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
if (!vcpu_e500) {
err = -ENOMEM;
goto out;
}
vcpu = &vcpu_e500->vcpu;
err = kvm_vcpu_init(vcpu, kvm, id);
if (err)
goto free_vcpu;
err = kvmppc_e500_tlb_init(vcpu_e500);
if (err)
goto uninit_vcpu;
vcpu->arch.shared = (void*)__get_free_page(GFP_KERNEL|__GFP_ZERO);
if (!vcpu->arch.shared)
goto uninit_tlb;
return vcpu;
uninit_tlb:
kvmppc_e500_tlb_uninit(vcpu_e500);
uninit_vcpu:
kvm_vcpu_uninit(vcpu);
free_vcpu:
kmem_cache_free(kvm_vcpu_cache, vcpu_e500);
out:
return ERR_PTR(err);
}
void kvmppc_core_vcpu_free(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
free_page((unsigned long)vcpu->arch.shared);
kvm_vcpu_uninit(vcpu);
kvmppc_e500_tlb_uninit(vcpu_e500);
kmem_cache_free(kvm_vcpu_cache, vcpu_e500);
}
static int __init kvmppc_e500_init(void)
{
int r, i;
unsigned long ivor[3];
unsigned long max_ivor = 0;
r = kvmppc_booke_init();
if (r)
return r;
/* copy extra E500 exception handlers */
ivor[0] = mfspr(SPRN_IVOR32);
ivor[1] = mfspr(SPRN_IVOR33);
ivor[2] = mfspr(SPRN_IVOR34);
for (i = 0; i < 3; i++) {
if (ivor[i] > max_ivor)
max_ivor = ivor[i];
memcpy((void *)kvmppc_booke_handlers + ivor[i],
kvmppc_handlers_start + (i + 16) * kvmppc_handler_len,
kvmppc_handler_len);
}
flush_icache_range(kvmppc_booke_handlers,
kvmppc_booke_handlers + max_ivor + kvmppc_handler_len);
return kvm_init(NULL, sizeof(struct kvmppc_vcpu_e500), 0, THIS_MODULE);
}
static void __exit kvmppc_e500_exit(void)
{
kvmppc_booke_exit();
}
module_init(kvmppc_e500_init);
module_exit(kvmppc_e500_exit);
| gpl-2.0 |
edoko/Air_Kernel-POP | arch/arm/plat-s5p/dev-ace.c | 556 | 1053 | /*
* linux/arch/arm/plat-s5p/dev-ace.c
*
* Copyright (C) 2011 Samsung Electronics
*
* Base S5P Crypto Engine resource and device definitions
*
* 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/platform_device.h>
#include <mach/map.h>
#include <mach/irqs.h>
static struct resource s5p_ace_resource[] = {
[0] = {
.start = S5P_PA_ACE,
.end = S5P_PA_ACE + SZ_32K - 1,
.flags = IORESOURCE_MEM,
},
#if defined(CONFIG_ARCH_S5PV210)
[1] = {
.start = IRQ_SSS_INT,
.end = IRQ_SSS_HASH,
.flags = IORESOURCE_IRQ,
},
#elif defined(CONFIG_ARCH_EXYNOS4) || defined(CONFIG_ARCH_EXYNOS5)
[1] = {
.start = IRQ_INTFEEDCTRL_SSS,
.end = IRQ_INTFEEDCTRL_SSS,
.flags = IORESOURCE_IRQ,
},
#endif
};
struct platform_device s5p_device_ace = {
.name = "s5p-ace",
.id = 0,
.num_resources = ARRAY_SIZE(s5p_ace_resource),
.resource = s5p_ace_resource,
};
EXPORT_SYMBOL(s5p_device_ace);
| gpl-2.0 |
nycbjr/tf700t_kernel | arch/arm/mach-at91/board-eco920.c | 556 | 3532 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/board.h>
#include <mach/at91rm9200_mc.h>
#include <mach/cpu.h>
#include "generic.h"
static void __init eco920_init_early(void)
{
/* Set cpu type: PQFP */
at91rm9200_set_type(ARCH_REVISON_9200_PQFP);
at91_initialize(18432000);
/* Setup the LEDs */
at91_init_leds(AT91_PIN_PB0, AT91_PIN_PB1);
/* DBGU on ttyS0. (Rx & Tx only */
at91_register_uart(0, 0, 0);
/* set serial console to ttyS0 (ie, DBGU) */
at91_set_serial_console(0);
}
static struct at91_eth_data __initdata eco920_eth_data = {
.phy_irq_pin = AT91_PIN_PC2,
.is_rmii = 1,
};
static struct at91_usbh_data __initdata eco920_usbh_data = {
.ports = 1,
};
static struct at91_udc_data __initdata eco920_udc_data = {
.vbus_pin = AT91_PIN_PB12,
.pullup_pin = AT91_PIN_PB13,
};
static struct at91_mmc_data __initdata eco920_mmc_data = {
.slot_b = 0,
.wire4 = 0,
};
static struct physmap_flash_data eco920_flash_data = {
.width = 2,
};
static struct resource eco920_flash_resource = {
.start = 0x11000000,
.end = 0x11ffffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device eco920_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &eco920_flash_data,
},
.resource = &eco920_flash_resource,
.num_resources = 1,
};
static struct spi_board_info eco920_spi_devices[] = {
{ /* CAN controller */
.modalias = "tlv5638",
.chip_select = 3,
.max_speed_hz = 20 * 1000 * 1000,
.mode = SPI_CPHA,
},
};
static void __init eco920_board_init(void)
{
at91_add_device_serial();
at91_add_device_eth(&eco920_eth_data);
at91_add_device_usbh(&eco920_usbh_data);
at91_add_device_udc(&eco920_udc_data);
at91_add_device_mmc(0, &eco920_mmc_data);
platform_device_register(&eco920_flash);
at91_sys_write(AT91_SMC_CSR(7), AT91_SMC_RWHOLD_(1)
| AT91_SMC_RWSETUP_(1)
| AT91_SMC_DBW_8
| AT91_SMC_WSEN
| AT91_SMC_NWS_(15));
at91_set_A_periph(AT91_PIN_PC6, 1);
at91_set_gpio_input(AT91_PIN_PA23, 0);
at91_set_deglitch(AT91_PIN_PA23, 1);
/* Initialization of the Static Memory Controller for Chip Select 3 */
at91_sys_write(AT91_SMC_CSR(3),
AT91_SMC_DBW_16 | /* 16 bit */
AT91_SMC_WSEN |
AT91_SMC_NWS_(5) | /* wait states */
AT91_SMC_TDF_(1) /* float time */
);
at91_add_device_spi(eco920_spi_devices, ARRAY_SIZE(eco920_spi_devices));
}
MACHINE_START(ECO920, "eco920")
/* Maintainer: Sascha Hauer */
.timer = &at91rm9200_timer,
.map_io = at91_map_io,
.init_early = eco920_init_early,
.init_irq = at91_init_irq_default,
.init_machine = eco920_board_init,
MACHINE_END
| gpl-2.0 |
cwyy/linux-3.4.69 | net/8021q/vlan_core.c | 812 | 8310 | #include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/if_vlan.h>
#include <linux/netpoll.h>
#include <linux/export.h>
#include "vlan.h"
bool vlan_do_receive(struct sk_buff **skbp)
{
struct sk_buff *skb = *skbp;
u16 vlan_id = skb->vlan_tci & VLAN_VID_MASK;
struct net_device *vlan_dev;
struct vlan_pcpu_stats *rx_stats;
vlan_dev = vlan_find_dev(skb->dev, vlan_id);
if (!vlan_dev)
return false;
skb = *skbp = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(!skb))
return false;
skb->dev = vlan_dev;
if (skb->pkt_type == PACKET_OTHERHOST) {
/* Our lower layer thinks this is not local, let's make sure.
* This allows the VLAN to have a different MAC than the
* underlying device, and still route correctly. */
if (!compare_ether_addr(eth_hdr(skb)->h_dest,
vlan_dev->dev_addr))
skb->pkt_type = PACKET_HOST;
}
if (!(vlan_dev_priv(vlan_dev)->flags & VLAN_FLAG_REORDER_HDR)) {
unsigned int offset = skb->data - skb_mac_header(skb);
/*
* vlan_insert_tag expect skb->data pointing to mac header.
* So change skb->data before calling it and change back to
* original position later
*/
skb_push(skb, offset);
skb = *skbp = vlan_insert_tag(skb, skb->vlan_tci);
if (!skb)
return false;
skb_pull(skb, offset + VLAN_HLEN);
skb_reset_mac_len(skb);
}
skb->priority = vlan_get_ingress_priority(vlan_dev, skb->vlan_tci);
skb->vlan_tci = 0;
rx_stats = this_cpu_ptr(vlan_dev_priv(vlan_dev)->vlan_pcpu_stats);
u64_stats_update_begin(&rx_stats->syncp);
rx_stats->rx_packets++;
rx_stats->rx_bytes += skb->len;
if (skb->pkt_type == PACKET_MULTICAST)
rx_stats->rx_multicast++;
u64_stats_update_end(&rx_stats->syncp);
return true;
}
/* Must be invoked with rcu_read_lock or with RTNL. */
struct net_device *__vlan_find_dev_deep(struct net_device *real_dev,
u16 vlan_id)
{
struct vlan_info *vlan_info = rcu_dereference_rtnl(real_dev->vlan_info);
if (vlan_info) {
return vlan_group_get_device(&vlan_info->grp, vlan_id);
} else {
/*
* Bonding slaves do not have grp assigned to themselves.
* Grp is assigned to bonding master instead.
*/
if (netif_is_bond_slave(real_dev))
return __vlan_find_dev_deep(real_dev->master, vlan_id);
}
return NULL;
}
EXPORT_SYMBOL(__vlan_find_dev_deep);
struct net_device *vlan_dev_real_dev(const struct net_device *dev)
{
return vlan_dev_priv(dev)->real_dev;
}
EXPORT_SYMBOL(vlan_dev_real_dev);
u16 vlan_dev_vlan_id(const struct net_device *dev)
{
return vlan_dev_priv(dev)->vlan_id;
}
EXPORT_SYMBOL(vlan_dev_vlan_id);
static struct sk_buff *vlan_reorder_header(struct sk_buff *skb)
{
if (skb_cow(skb, skb_headroom(skb)) < 0)
return NULL;
memmove(skb->data - ETH_HLEN, skb->data - VLAN_ETH_HLEN, 2 * ETH_ALEN);
skb->mac_header += VLAN_HLEN;
return skb;
}
struct sk_buff *vlan_untag(struct sk_buff *skb)
{
struct vlan_hdr *vhdr;
u16 vlan_tci;
if (unlikely(vlan_tx_tag_present(skb))) {
/* vlan_tci is already set-up so leave this for another time */
return skb;
}
skb = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(!skb))
goto err_free;
if (unlikely(!pskb_may_pull(skb, VLAN_HLEN)))
goto err_free;
vhdr = (struct vlan_hdr *) skb->data;
vlan_tci = ntohs(vhdr->h_vlan_TCI);
__vlan_hwaccel_put_tag(skb, vlan_tci);
skb_pull_rcsum(skb, VLAN_HLEN);
vlan_set_encap_proto(skb, vhdr);
skb = vlan_reorder_header(skb);
if (unlikely(!skb))
goto err_free;
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb_reset_mac_len(skb);
return skb;
err_free:
kfree_skb(skb);
return NULL;
}
/*
* vlan info and vid list
*/
static void vlan_group_free(struct vlan_group *grp)
{
int i;
for (i = 0; i < VLAN_GROUP_ARRAY_SPLIT_PARTS; i++)
kfree(grp->vlan_devices_arrays[i]);
}
static void vlan_info_free(struct vlan_info *vlan_info)
{
vlan_group_free(&vlan_info->grp);
kfree(vlan_info);
}
static void vlan_info_rcu_free(struct rcu_head *rcu)
{
vlan_info_free(container_of(rcu, struct vlan_info, rcu));
}
static struct vlan_info *vlan_info_alloc(struct net_device *dev)
{
struct vlan_info *vlan_info;
vlan_info = kzalloc(sizeof(struct vlan_info), GFP_KERNEL);
if (!vlan_info)
return NULL;
vlan_info->real_dev = dev;
INIT_LIST_HEAD(&vlan_info->vid_list);
return vlan_info;
}
struct vlan_vid_info {
struct list_head list;
unsigned short vid;
int refcount;
};
static struct vlan_vid_info *vlan_vid_info_get(struct vlan_info *vlan_info,
unsigned short vid)
{
struct vlan_vid_info *vid_info;
list_for_each_entry(vid_info, &vlan_info->vid_list, list) {
if (vid_info->vid == vid)
return vid_info;
}
return NULL;
}
static struct vlan_vid_info *vlan_vid_info_alloc(unsigned short vid)
{
struct vlan_vid_info *vid_info;
vid_info = kzalloc(sizeof(struct vlan_vid_info), GFP_KERNEL);
if (!vid_info)
return NULL;
vid_info->vid = vid;
return vid_info;
}
static int __vlan_vid_add(struct vlan_info *vlan_info, unsigned short vid,
struct vlan_vid_info **pvid_info)
{
struct net_device *dev = vlan_info->real_dev;
const struct net_device_ops *ops = dev->netdev_ops;
struct vlan_vid_info *vid_info;
int err;
vid_info = vlan_vid_info_alloc(vid);
if (!vid_info)
return -ENOMEM;
if ((dev->features & NETIF_F_HW_VLAN_FILTER) &&
ops->ndo_vlan_rx_add_vid) {
err = ops->ndo_vlan_rx_add_vid(dev, vid);
if (err) {
kfree(vid_info);
return err;
}
}
list_add(&vid_info->list, &vlan_info->vid_list);
vlan_info->nr_vids++;
*pvid_info = vid_info;
return 0;
}
int vlan_vid_add(struct net_device *dev, unsigned short vid)
{
struct vlan_info *vlan_info;
struct vlan_vid_info *vid_info;
bool vlan_info_created = false;
int err;
ASSERT_RTNL();
vlan_info = rtnl_dereference(dev->vlan_info);
if (!vlan_info) {
vlan_info = vlan_info_alloc(dev);
if (!vlan_info)
return -ENOMEM;
vlan_info_created = true;
}
vid_info = vlan_vid_info_get(vlan_info, vid);
if (!vid_info) {
err = __vlan_vid_add(vlan_info, vid, &vid_info);
if (err)
goto out_free_vlan_info;
}
vid_info->refcount++;
if (vlan_info_created)
rcu_assign_pointer(dev->vlan_info, vlan_info);
return 0;
out_free_vlan_info:
if (vlan_info_created)
kfree(vlan_info);
return err;
}
EXPORT_SYMBOL(vlan_vid_add);
static void __vlan_vid_del(struct vlan_info *vlan_info,
struct vlan_vid_info *vid_info)
{
struct net_device *dev = vlan_info->real_dev;
const struct net_device_ops *ops = dev->netdev_ops;
unsigned short vid = vid_info->vid;
int err;
if ((dev->features & NETIF_F_HW_VLAN_FILTER) &&
ops->ndo_vlan_rx_kill_vid) {
err = ops->ndo_vlan_rx_kill_vid(dev, vid);
if (err) {
pr_warn("failed to kill vid %d for device %s\n",
vid, dev->name);
}
}
list_del(&vid_info->list);
kfree(vid_info);
vlan_info->nr_vids--;
}
void vlan_vid_del(struct net_device *dev, unsigned short vid)
{
struct vlan_info *vlan_info;
struct vlan_vid_info *vid_info;
ASSERT_RTNL();
vlan_info = rtnl_dereference(dev->vlan_info);
if (!vlan_info)
return;
vid_info = vlan_vid_info_get(vlan_info, vid);
if (!vid_info)
return;
vid_info->refcount--;
if (vid_info->refcount == 0) {
__vlan_vid_del(vlan_info, vid_info);
if (vlan_info->nr_vids == 0) {
RCU_INIT_POINTER(dev->vlan_info, NULL);
call_rcu(&vlan_info->rcu, vlan_info_rcu_free);
}
}
}
EXPORT_SYMBOL(vlan_vid_del);
int vlan_vids_add_by_dev(struct net_device *dev,
const struct net_device *by_dev)
{
struct vlan_vid_info *vid_info;
struct vlan_info *vlan_info;
int err;
ASSERT_RTNL();
vlan_info = rtnl_dereference(by_dev->vlan_info);
if (!vlan_info)
return 0;
list_for_each_entry(vid_info, &vlan_info->vid_list, list) {
err = vlan_vid_add(dev, vid_info->vid);
if (err)
goto unwind;
}
return 0;
unwind:
list_for_each_entry_continue_reverse(vid_info,
&vlan_info->vid_list,
list) {
vlan_vid_del(dev, vid_info->vid);
}
return err;
}
EXPORT_SYMBOL(vlan_vids_add_by_dev);
void vlan_vids_del_by_dev(struct net_device *dev,
const struct net_device *by_dev)
{
struct vlan_vid_info *vid_info;
struct vlan_info *vlan_info;
ASSERT_RTNL();
vlan_info = rtnl_dereference(by_dev->vlan_info);
if (!vlan_info)
return;
list_for_each_entry(vid_info, &vlan_info->vid_list, list)
vlan_vid_del(dev, vid_info->vid);
}
EXPORT_SYMBOL(vlan_vids_del_by_dev);
| gpl-2.0 |
AospPlus/android_kernel_x86 | drivers/xen/cpu_hotplug.c | 1836 | 2119 | #define pr_fmt(fmt) "xen:" KBUILD_MODNAME ": " fmt
#include <linux/notifier.h>
#include <xen/xen.h>
#include <xen/xenbus.h>
#include <asm/xen/hypervisor.h>
#include <asm/cpu.h>
static void enable_hotplug_cpu(int cpu)
{
if (!cpu_present(cpu))
arch_register_cpu(cpu);
set_cpu_present(cpu, true);
}
static void disable_hotplug_cpu(int cpu)
{
if (cpu_present(cpu))
arch_unregister_cpu(cpu);
set_cpu_present(cpu, false);
}
static int vcpu_online(unsigned int cpu)
{
int err;
char dir[16], state[16];
sprintf(dir, "cpu/%u", cpu);
err = xenbus_scanf(XBT_NIL, dir, "availability", "%15s", state);
if (err != 1) {
if (!xen_initial_domain())
pr_err("Unable to read cpu state\n");
return err;
}
if (strcmp(state, "online") == 0)
return 1;
else if (strcmp(state, "offline") == 0)
return 0;
pr_err("unknown state(%s) on CPU%d\n", state, cpu);
return -EINVAL;
}
static void vcpu_hotplug(unsigned int cpu)
{
if (!cpu_possible(cpu))
return;
switch (vcpu_online(cpu)) {
case 1:
enable_hotplug_cpu(cpu);
break;
case 0:
(void)cpu_down(cpu);
disable_hotplug_cpu(cpu);
break;
default:
break;
}
}
static void handle_vcpu_hotplug_event(struct xenbus_watch *watch,
const char **vec, unsigned int len)
{
unsigned int cpu;
char *cpustr;
const char *node = vec[XS_WATCH_PATH];
cpustr = strstr(node, "cpu/");
if (cpustr != NULL) {
sscanf(cpustr, "cpu/%u", &cpu);
vcpu_hotplug(cpu);
}
}
static int setup_cpu_watcher(struct notifier_block *notifier,
unsigned long event, void *data)
{
int cpu;
static struct xenbus_watch cpu_watch = {
.node = "cpu",
.callback = handle_vcpu_hotplug_event};
(void)register_xenbus_watch(&cpu_watch);
for_each_possible_cpu(cpu) {
if (vcpu_online(cpu) == 0) {
(void)cpu_down(cpu);
set_cpu_present(cpu, false);
}
}
return NOTIFY_DONE;
}
static int __init setup_vcpu_hotplug_event(void)
{
static struct notifier_block xsn_cpu = {
.notifier_call = setup_cpu_watcher };
if (!xen_pv_domain())
return -ENODEV;
register_xenstore_notifier(&xsn_cpu);
return 0;
}
arch_initcall(setup_vcpu_hotplug_event);
| gpl-2.0 |
UBERMALLOW/kernel_htc_flounder | drivers/bcma/driver_chipcommon_pmu.c | 2092 | 16242 | /*
* Broadcom specific AMBA
* ChipCommon Power Management Unit driver
*
* Copyright 2009, Michael Buesch <m@bues.ch>
* Copyright 2007, 2011, Broadcom Corporation
* Copyright 2011, 2012, Hauke Mehrtens <hauke@hauke-m.de>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include "bcma_private.h"
#include <linux/export.h>
#include <linux/bcma/bcma.h>
u32 bcma_chipco_pll_read(struct bcma_drv_cc *cc, u32 offset)
{
bcma_cc_write32(cc, BCMA_CC_PLLCTL_ADDR, offset);
bcma_cc_read32(cc, BCMA_CC_PLLCTL_ADDR);
return bcma_cc_read32(cc, BCMA_CC_PLLCTL_DATA);
}
EXPORT_SYMBOL_GPL(bcma_chipco_pll_read);
void bcma_chipco_pll_write(struct bcma_drv_cc *cc, u32 offset, u32 value)
{
bcma_cc_write32(cc, BCMA_CC_PLLCTL_ADDR, offset);
bcma_cc_read32(cc, BCMA_CC_PLLCTL_ADDR);
bcma_cc_write32(cc, BCMA_CC_PLLCTL_DATA, value);
}
EXPORT_SYMBOL_GPL(bcma_chipco_pll_write);
void bcma_chipco_pll_maskset(struct bcma_drv_cc *cc, u32 offset, u32 mask,
u32 set)
{
bcma_cc_write32(cc, BCMA_CC_PLLCTL_ADDR, offset);
bcma_cc_read32(cc, BCMA_CC_PLLCTL_ADDR);
bcma_cc_maskset32(cc, BCMA_CC_PLLCTL_DATA, mask, set);
}
EXPORT_SYMBOL_GPL(bcma_chipco_pll_maskset);
void bcma_chipco_chipctl_maskset(struct bcma_drv_cc *cc,
u32 offset, u32 mask, u32 set)
{
bcma_cc_write32(cc, BCMA_CC_CHIPCTL_ADDR, offset);
bcma_cc_read32(cc, BCMA_CC_CHIPCTL_ADDR);
bcma_cc_maskset32(cc, BCMA_CC_CHIPCTL_DATA, mask, set);
}
EXPORT_SYMBOL_GPL(bcma_chipco_chipctl_maskset);
void bcma_chipco_regctl_maskset(struct bcma_drv_cc *cc, u32 offset, u32 mask,
u32 set)
{
bcma_cc_write32(cc, BCMA_CC_REGCTL_ADDR, offset);
bcma_cc_read32(cc, BCMA_CC_REGCTL_ADDR);
bcma_cc_maskset32(cc, BCMA_CC_REGCTL_DATA, mask, set);
}
EXPORT_SYMBOL_GPL(bcma_chipco_regctl_maskset);
static void bcma_pmu_resources_init(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
u32 min_msk = 0, max_msk = 0;
switch (bus->chipinfo.id) {
case BCMA_CHIP_ID_BCM4313:
min_msk = 0x200D;
max_msk = 0xFFFF;
break;
default:
bcma_debug(bus, "PMU resource config unknown or not needed for device 0x%04X\n",
bus->chipinfo.id);
}
/* Set the resource masks. */
if (min_msk)
bcma_cc_write32(cc, BCMA_CC_PMU_MINRES_MSK, min_msk);
if (max_msk)
bcma_cc_write32(cc, BCMA_CC_PMU_MAXRES_MSK, max_msk);
/*
* Add some delay; allow resources to come up and settle.
* Delay is required for SoC (early init).
*/
mdelay(2);
}
/* Disable to allow reading SPROM. Don't know the adventages of enabling it. */
void bcma_chipco_bcm4331_ext_pa_lines_ctl(struct bcma_drv_cc *cc, bool enable)
{
struct bcma_bus *bus = cc->core->bus;
u32 val;
val = bcma_cc_read32(cc, BCMA_CC_CHIPCTL);
if (enable) {
val |= BCMA_CHIPCTL_4331_EXTPA_EN;
if (bus->chipinfo.pkg == 9 || bus->chipinfo.pkg == 11)
val |= BCMA_CHIPCTL_4331_EXTPA_ON_GPIO2_5;
else if (bus->chipinfo.rev > 0)
val |= BCMA_CHIPCTL_4331_EXTPA_EN2;
} else {
val &= ~BCMA_CHIPCTL_4331_EXTPA_EN;
val &= ~BCMA_CHIPCTL_4331_EXTPA_EN2;
val &= ~BCMA_CHIPCTL_4331_EXTPA_ON_GPIO2_5;
}
bcma_cc_write32(cc, BCMA_CC_CHIPCTL, val);
}
static void bcma_pmu_workarounds(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
switch (bus->chipinfo.id) {
case BCMA_CHIP_ID_BCM4313:
/* enable 12 mA drive strenth for 4313 and set chipControl
register bit 1 */
bcma_chipco_chipctl_maskset(cc, 0,
~BCMA_CCTRL_4313_12MA_LED_DRIVE,
BCMA_CCTRL_4313_12MA_LED_DRIVE);
break;
case BCMA_CHIP_ID_BCM4331:
case BCMA_CHIP_ID_BCM43431:
/* Ext PA lines must be enabled for tx on BCM4331 */
bcma_chipco_bcm4331_ext_pa_lines_ctl(cc, true);
break;
case BCMA_CHIP_ID_BCM43224:
case BCMA_CHIP_ID_BCM43421:
/* enable 12 mA drive strenth for 43224 and set chipControl
register bit 15 */
if (bus->chipinfo.rev == 0) {
bcma_cc_maskset32(cc, BCMA_CC_CHIPCTL,
~BCMA_CCTRL_43224_GPIO_TOGGLE,
BCMA_CCTRL_43224_GPIO_TOGGLE);
bcma_chipco_chipctl_maskset(cc, 0,
~BCMA_CCTRL_43224A0_12MA_LED_DRIVE,
BCMA_CCTRL_43224A0_12MA_LED_DRIVE);
} else {
bcma_chipco_chipctl_maskset(cc, 0,
~BCMA_CCTRL_43224B0_12MA_LED_DRIVE,
BCMA_CCTRL_43224B0_12MA_LED_DRIVE);
}
break;
default:
bcma_debug(bus, "Workarounds unknown or not needed for device 0x%04X\n",
bus->chipinfo.id);
}
}
void bcma_pmu_early_init(struct bcma_drv_cc *cc)
{
u32 pmucap;
pmucap = bcma_cc_read32(cc, BCMA_CC_PMU_CAP);
cc->pmu.rev = (pmucap & BCMA_CC_PMU_CAP_REVISION);
bcma_debug(cc->core->bus, "Found rev %u PMU (capabilities 0x%08X)\n",
cc->pmu.rev, pmucap);
}
void bcma_pmu_init(struct bcma_drv_cc *cc)
{
if (cc->pmu.rev == 1)
bcma_cc_mask32(cc, BCMA_CC_PMU_CTL,
~BCMA_CC_PMU_CTL_NOILPONW);
else
bcma_cc_set32(cc, BCMA_CC_PMU_CTL,
BCMA_CC_PMU_CTL_NOILPONW);
bcma_pmu_resources_init(cc);
bcma_pmu_workarounds(cc);
}
u32 bcma_pmu_get_alp_clock(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
switch (bus->chipinfo.id) {
case BCMA_CHIP_ID_BCM4313:
case BCMA_CHIP_ID_BCM43224:
case BCMA_CHIP_ID_BCM43225:
case BCMA_CHIP_ID_BCM43227:
case BCMA_CHIP_ID_BCM43228:
case BCMA_CHIP_ID_BCM4331:
case BCMA_CHIP_ID_BCM43421:
case BCMA_CHIP_ID_BCM43428:
case BCMA_CHIP_ID_BCM43431:
case BCMA_CHIP_ID_BCM4716:
case BCMA_CHIP_ID_BCM47162:
case BCMA_CHIP_ID_BCM4748:
case BCMA_CHIP_ID_BCM4749:
case BCMA_CHIP_ID_BCM5357:
case BCMA_CHIP_ID_BCM53572:
case BCMA_CHIP_ID_BCM6362:
/* always 20Mhz */
return 20000 * 1000;
case BCMA_CHIP_ID_BCM4706:
case BCMA_CHIP_ID_BCM5356:
/* always 25Mhz */
return 25000 * 1000;
case BCMA_CHIP_ID_BCM43460:
case BCMA_CHIP_ID_BCM4352:
case BCMA_CHIP_ID_BCM4360:
if (cc->status & BCMA_CC_CHIPST_4360_XTAL_40MZ)
return 40000 * 1000;
else
return 20000 * 1000;
default:
bcma_warn(bus, "No ALP clock specified for %04X device, pmu rev. %d, using default %d Hz\n",
bus->chipinfo.id, cc->pmu.rev, BCMA_CC_PMU_ALP_CLOCK);
}
return BCMA_CC_PMU_ALP_CLOCK;
}
/* Find the output of the "m" pll divider given pll controls that start with
* pllreg "pll0" i.e. 12 for main 6 for phy, 0 for misc.
*/
static u32 bcma_pmu_pll_clock(struct bcma_drv_cc *cc, u32 pll0, u32 m)
{
u32 tmp, div, ndiv, p1, p2, fc;
struct bcma_bus *bus = cc->core->bus;
BUG_ON((pll0 & 3) || (pll0 > BCMA_CC_PMU4716_MAINPLL_PLL0));
BUG_ON(!m || m > 4);
if (bus->chipinfo.id == BCMA_CHIP_ID_BCM5357 ||
bus->chipinfo.id == BCMA_CHIP_ID_BCM4749) {
/* Detect failure in clock setting */
tmp = bcma_cc_read32(cc, BCMA_CC_CHIPSTAT);
if (tmp & 0x40000)
return 133 * 1000000;
}
tmp = bcma_chipco_pll_read(cc, pll0 + BCMA_CC_PPL_P1P2_OFF);
p1 = (tmp & BCMA_CC_PPL_P1_MASK) >> BCMA_CC_PPL_P1_SHIFT;
p2 = (tmp & BCMA_CC_PPL_P2_MASK) >> BCMA_CC_PPL_P2_SHIFT;
tmp = bcma_chipco_pll_read(cc, pll0 + BCMA_CC_PPL_M14_OFF);
div = (tmp >> ((m - 1) * BCMA_CC_PPL_MDIV_WIDTH)) &
BCMA_CC_PPL_MDIV_MASK;
tmp = bcma_chipco_pll_read(cc, pll0 + BCMA_CC_PPL_NM5_OFF);
ndiv = (tmp & BCMA_CC_PPL_NDIV_MASK) >> BCMA_CC_PPL_NDIV_SHIFT;
/* Do calculation in Mhz */
fc = bcma_pmu_get_alp_clock(cc) / 1000000;
fc = (p1 * ndiv * fc) / p2;
/* Return clock in Hertz */
return (fc / div) * 1000000;
}
static u32 bcma_pmu_pll_clock_bcm4706(struct bcma_drv_cc *cc, u32 pll0, u32 m)
{
u32 tmp, ndiv, p1div, p2div;
u32 clock;
BUG_ON(!m || m > 4);
/* Get N, P1 and P2 dividers to determine CPU clock */
tmp = bcma_chipco_pll_read(cc, pll0 + BCMA_CC_PMU6_4706_PROCPLL_OFF);
ndiv = (tmp & BCMA_CC_PMU6_4706_PROC_NDIV_INT_MASK)
>> BCMA_CC_PMU6_4706_PROC_NDIV_INT_SHIFT;
p1div = (tmp & BCMA_CC_PMU6_4706_PROC_P1DIV_MASK)
>> BCMA_CC_PMU6_4706_PROC_P1DIV_SHIFT;
p2div = (tmp & BCMA_CC_PMU6_4706_PROC_P2DIV_MASK)
>> BCMA_CC_PMU6_4706_PROC_P2DIV_SHIFT;
tmp = bcma_cc_read32(cc, BCMA_CC_CHIPSTAT);
if (tmp & BCMA_CC_CHIPST_4706_PKG_OPTION)
/* Low cost bonding: Fixed reference clock 25MHz and m = 4 */
clock = (25000000 / 4) * ndiv * p2div / p1div;
else
/* Fixed reference clock 25MHz and m = 2 */
clock = (25000000 / 2) * ndiv * p2div / p1div;
if (m == BCMA_CC_PMU5_MAINPLL_SSB)
clock = clock / 4;
return clock;
}
/* query bus clock frequency for PMU-enabled chipcommon */
u32 bcma_pmu_get_bus_clock(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
switch (bus->chipinfo.id) {
case BCMA_CHIP_ID_BCM4716:
case BCMA_CHIP_ID_BCM4748:
case BCMA_CHIP_ID_BCM47162:
return bcma_pmu_pll_clock(cc, BCMA_CC_PMU4716_MAINPLL_PLL0,
BCMA_CC_PMU5_MAINPLL_SSB);
case BCMA_CHIP_ID_BCM5356:
return bcma_pmu_pll_clock(cc, BCMA_CC_PMU5356_MAINPLL_PLL0,
BCMA_CC_PMU5_MAINPLL_SSB);
case BCMA_CHIP_ID_BCM5357:
case BCMA_CHIP_ID_BCM4749:
return bcma_pmu_pll_clock(cc, BCMA_CC_PMU5357_MAINPLL_PLL0,
BCMA_CC_PMU5_MAINPLL_SSB);
case BCMA_CHIP_ID_BCM4706:
return bcma_pmu_pll_clock_bcm4706(cc,
BCMA_CC_PMU4706_MAINPLL_PLL0,
BCMA_CC_PMU5_MAINPLL_SSB);
case BCMA_CHIP_ID_BCM53572:
return 75000000;
default:
bcma_warn(bus, "No bus clock specified for %04X device, pmu rev. %d, using default %d Hz\n",
bus->chipinfo.id, cc->pmu.rev, BCMA_CC_PMU_HT_CLOCK);
}
return BCMA_CC_PMU_HT_CLOCK;
}
EXPORT_SYMBOL_GPL(bcma_pmu_get_bus_clock);
/* query cpu clock frequency for PMU-enabled chipcommon */
u32 bcma_pmu_get_cpu_clock(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
if (bus->chipinfo.id == BCMA_CHIP_ID_BCM53572)
return 300000000;
/* New PMUs can have different clock for bus and CPU */
if (cc->pmu.rev >= 5) {
u32 pll;
switch (bus->chipinfo.id) {
case BCMA_CHIP_ID_BCM4706:
return bcma_pmu_pll_clock_bcm4706(cc,
BCMA_CC_PMU4706_MAINPLL_PLL0,
BCMA_CC_PMU5_MAINPLL_CPU);
case BCMA_CHIP_ID_BCM5356:
pll = BCMA_CC_PMU5356_MAINPLL_PLL0;
break;
case BCMA_CHIP_ID_BCM5357:
case BCMA_CHIP_ID_BCM4749:
pll = BCMA_CC_PMU5357_MAINPLL_PLL0;
break;
default:
pll = BCMA_CC_PMU4716_MAINPLL_PLL0;
break;
}
return bcma_pmu_pll_clock(cc, pll, BCMA_CC_PMU5_MAINPLL_CPU);
}
/* On old PMUs CPU has the same clock as the bus */
return bcma_pmu_get_bus_clock(cc);
}
static void bcma_pmu_spuravoid_pll_write(struct bcma_drv_cc *cc, u32 offset,
u32 value)
{
bcma_cc_write32(cc, BCMA_CC_PLLCTL_ADDR, offset);
bcma_cc_write32(cc, BCMA_CC_PLLCTL_DATA, value);
}
void bcma_pmu_spuravoid_pllupdate(struct bcma_drv_cc *cc, int spuravoid)
{
u32 tmp = 0;
u8 phypll_offset = 0;
u8 bcm5357_bcm43236_p1div[] = {0x1, 0x5, 0x5};
u8 bcm5357_bcm43236_ndiv[] = {0x30, 0xf6, 0xfc};
struct bcma_bus *bus = cc->core->bus;
switch (bus->chipinfo.id) {
case BCMA_CHIP_ID_BCM5357:
case BCMA_CHIP_ID_BCM4749:
case BCMA_CHIP_ID_BCM53572:
/* 5357[ab]0, 43236[ab]0, and 6362b0 */
/* BCM5357 needs to touch PLL1_PLLCTL[02],
so offset PLL0_PLLCTL[02] by 6 */
phypll_offset = (bus->chipinfo.id == BCMA_CHIP_ID_BCM5357 ||
bus->chipinfo.id == BCMA_CHIP_ID_BCM4749 ||
bus->chipinfo.id == BCMA_CHIP_ID_BCM53572) ? 6 : 0;
/* RMW only the P1 divider */
bcma_cc_write32(cc, BCMA_CC_PLLCTL_ADDR,
BCMA_CC_PMU_PLL_CTL0 + phypll_offset);
tmp = bcma_cc_read32(cc, BCMA_CC_PLLCTL_DATA);
tmp &= (~(BCMA_CC_PMU1_PLL0_PC0_P1DIV_MASK));
tmp |= (bcm5357_bcm43236_p1div[spuravoid] << BCMA_CC_PMU1_PLL0_PC0_P1DIV_SHIFT);
bcma_cc_write32(cc, BCMA_CC_PLLCTL_DATA, tmp);
/* RMW only the int feedback divider */
bcma_cc_write32(cc, BCMA_CC_PLLCTL_ADDR,
BCMA_CC_PMU_PLL_CTL2 + phypll_offset);
tmp = bcma_cc_read32(cc, BCMA_CC_PLLCTL_DATA);
tmp &= ~(BCMA_CC_PMU1_PLL0_PC2_NDIV_INT_MASK);
tmp |= (bcm5357_bcm43236_ndiv[spuravoid]) << BCMA_CC_PMU1_PLL0_PC2_NDIV_INT_SHIFT;
bcma_cc_write32(cc, BCMA_CC_PLLCTL_DATA, tmp);
tmp = BCMA_CC_PMU_CTL_PLL_UPD;
break;
case BCMA_CHIP_ID_BCM4331:
case BCMA_CHIP_ID_BCM43431:
if (spuravoid == 2) {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11500014);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x0FC00a08);
} else if (spuravoid == 1) {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11500014);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x0F600a08);
} else {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11100014);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x03000a08);
}
tmp = BCMA_CC_PMU_CTL_PLL_UPD;
break;
case BCMA_CHIP_ID_BCM43224:
case BCMA_CHIP_ID_BCM43225:
case BCMA_CHIP_ID_BCM43421:
if (spuravoid == 1) {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11500010);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL1,
0x000C0C06);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x0F600a08);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL3,
0x00000000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL4,
0x2001E920);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL5,
0x88888815);
} else {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11100010);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL1,
0x000c0c06);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x03000a08);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL3,
0x00000000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL4,
0x200005c0);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL5,
0x88888815);
}
tmp = BCMA_CC_PMU_CTL_PLL_UPD;
break;
case BCMA_CHIP_ID_BCM4716:
case BCMA_CHIP_ID_BCM4748:
case BCMA_CHIP_ID_BCM47162:
if (spuravoid == 1) {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11500060);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL1,
0x080C0C06);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x0F600000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL3,
0x00000000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL4,
0x2001E924);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL5,
0x88888815);
} else {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11100060);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL1,
0x080c0c06);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x03000000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL3,
0x00000000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL4,
0x200005c0);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL5,
0x88888815);
}
tmp = BCMA_CC_PMU_CTL_PLL_UPD | BCMA_CC_PMU_CTL_NOILPONW;
break;
case BCMA_CHIP_ID_BCM43227:
case BCMA_CHIP_ID_BCM43228:
case BCMA_CHIP_ID_BCM43428:
/* LCNXN */
/* PLL Settings for spur avoidance on/off mode,
no on2 support for 43228A0 */
if (spuravoid == 1) {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x01100014);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL1,
0x040C0C06);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x03140A08);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL3,
0x00333333);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL4,
0x202C2820);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL5,
0x88888815);
} else {
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL0,
0x11100014);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL1,
0x040c0c06);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL2,
0x03000a08);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL3,
0x00000000);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL4,
0x200005c0);
bcma_pmu_spuravoid_pll_write(cc, BCMA_CC_PMU_PLL_CTL5,
0x88888815);
}
tmp = BCMA_CC_PMU_CTL_PLL_UPD;
break;
default:
bcma_err(bus, "Unknown spuravoidance settings for chip 0x%04X, not changing PLL\n",
bus->chipinfo.id);
break;
}
tmp |= bcma_cc_read32(cc, BCMA_CC_PMU_CTL);
bcma_cc_write32(cc, BCMA_CC_PMU_CTL, tmp);
}
EXPORT_SYMBOL_GPL(bcma_pmu_spuravoid_pllupdate);
| gpl-2.0 |
javilonas/Enki-SM-G901F | drivers/net/ethernet/micrel/ks8842.c | 2092 | 33262 | /*
* ks8842.c timberdale KS8842 ethernet driver
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Supports:
* The Micrel KS8842 behind the timberdale FPGA
* The genuine Micrel KS8841/42 device with ISA 16/32bit bus interface
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/ks8842.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/scatterlist.h>
#define DRV_NAME "ks8842"
/* Timberdale specific Registers */
#define REG_TIMB_RST 0x1c
#define REG_TIMB_FIFO 0x20
#define REG_TIMB_ISR 0x24
#define REG_TIMB_IER 0x28
#define REG_TIMB_IAR 0x2C
#define REQ_TIMB_DMA_RESUME 0x30
/* KS8842 registers */
#define REG_SELECT_BANK 0x0e
/* bank 0 registers */
#define REG_QRFCR 0x04
/* bank 2 registers */
#define REG_MARL 0x00
#define REG_MARM 0x02
#define REG_MARH 0x04
/* bank 3 registers */
#define REG_GRR 0x06
/* bank 16 registers */
#define REG_TXCR 0x00
#define REG_TXSR 0x02
#define REG_RXCR 0x04
#define REG_TXMIR 0x08
#define REG_RXMIR 0x0A
/* bank 17 registers */
#define REG_TXQCR 0x00
#define REG_RXQCR 0x02
#define REG_TXFDPR 0x04
#define REG_RXFDPR 0x06
#define REG_QMU_DATA_LO 0x08
#define REG_QMU_DATA_HI 0x0A
/* bank 18 registers */
#define REG_IER 0x00
#define IRQ_LINK_CHANGE 0x8000
#define IRQ_TX 0x4000
#define IRQ_RX 0x2000
#define IRQ_RX_OVERRUN 0x0800
#define IRQ_TX_STOPPED 0x0200
#define IRQ_RX_STOPPED 0x0100
#define IRQ_RX_ERROR 0x0080
#define ENABLED_IRQS (IRQ_LINK_CHANGE | IRQ_TX | IRQ_RX | IRQ_RX_STOPPED | \
IRQ_TX_STOPPED | IRQ_RX_OVERRUN | IRQ_RX_ERROR)
/* When running via timberdale in DMA mode, the RX interrupt should be
enabled in the KS8842, but not in the FPGA IP, since the IP handles
RX DMA internally.
TX interrupts are not needed it is handled by the FPGA the driver is
notified via DMA callbacks.
*/
#define ENABLED_IRQS_DMA_IP (IRQ_LINK_CHANGE | IRQ_RX_STOPPED | \
IRQ_TX_STOPPED | IRQ_RX_OVERRUN | IRQ_RX_ERROR)
#define ENABLED_IRQS_DMA (ENABLED_IRQS_DMA_IP | IRQ_RX)
#define REG_ISR 0x02
#define REG_RXSR 0x04
#define RXSR_VALID 0x8000
#define RXSR_BROADCAST 0x80
#define RXSR_MULTICAST 0x40
#define RXSR_UNICAST 0x20
#define RXSR_FRAMETYPE 0x08
#define RXSR_TOO_LONG 0x04
#define RXSR_RUNT 0x02
#define RXSR_CRC_ERROR 0x01
#define RXSR_ERROR (RXSR_TOO_LONG | RXSR_RUNT | RXSR_CRC_ERROR)
/* bank 32 registers */
#define REG_SW_ID_AND_ENABLE 0x00
#define REG_SGCR1 0x02
#define REG_SGCR2 0x04
#define REG_SGCR3 0x06
/* bank 39 registers */
#define REG_MACAR1 0x00
#define REG_MACAR2 0x02
#define REG_MACAR3 0x04
/* bank 45 registers */
#define REG_P1MBCR 0x00
#define REG_P1MBSR 0x02
/* bank 46 registers */
#define REG_P2MBCR 0x00
#define REG_P2MBSR 0x02
/* bank 48 registers */
#define REG_P1CR2 0x02
/* bank 49 registers */
#define REG_P1CR4 0x02
#define REG_P1SR 0x04
/* flags passed by platform_device for configuration */
#define MICREL_KS884X 0x01 /* 0=Timeberdale(FPGA), 1=Micrel */
#define KS884X_16BIT 0x02 /* 1=16bit, 0=32bit */
#define DMA_BUFFER_SIZE 2048
struct ks8842_tx_dma_ctl {
struct dma_chan *chan;
struct dma_async_tx_descriptor *adesc;
void *buf;
struct scatterlist sg;
int channel;
};
struct ks8842_rx_dma_ctl {
struct dma_chan *chan;
struct dma_async_tx_descriptor *adesc;
struct sk_buff *skb;
struct scatterlist sg;
struct tasklet_struct tasklet;
int channel;
};
#define KS8842_USE_DMA(adapter) (((adapter)->dma_tx.channel != -1) && \
((adapter)->dma_rx.channel != -1))
struct ks8842_adapter {
void __iomem *hw_addr;
int irq;
unsigned long conf_flags; /* copy of platform_device config */
struct tasklet_struct tasklet;
spinlock_t lock; /* spinlock to be interrupt safe */
struct work_struct timeout_work;
struct net_device *netdev;
struct device *dev;
struct ks8842_tx_dma_ctl dma_tx;
struct ks8842_rx_dma_ctl dma_rx;
};
static void ks8842_dma_rx_cb(void *data);
static void ks8842_dma_tx_cb(void *data);
static inline void ks8842_resume_dma(struct ks8842_adapter *adapter)
{
iowrite32(1, adapter->hw_addr + REQ_TIMB_DMA_RESUME);
}
static inline void ks8842_select_bank(struct ks8842_adapter *adapter, u16 bank)
{
iowrite16(bank, adapter->hw_addr + REG_SELECT_BANK);
}
static inline void ks8842_write8(struct ks8842_adapter *adapter, u16 bank,
u8 value, int offset)
{
ks8842_select_bank(adapter, bank);
iowrite8(value, adapter->hw_addr + offset);
}
static inline void ks8842_write16(struct ks8842_adapter *adapter, u16 bank,
u16 value, int offset)
{
ks8842_select_bank(adapter, bank);
iowrite16(value, adapter->hw_addr + offset);
}
static inline void ks8842_enable_bits(struct ks8842_adapter *adapter, u16 bank,
u16 bits, int offset)
{
u16 reg;
ks8842_select_bank(adapter, bank);
reg = ioread16(adapter->hw_addr + offset);
reg |= bits;
iowrite16(reg, adapter->hw_addr + offset);
}
static inline void ks8842_clear_bits(struct ks8842_adapter *adapter, u16 bank,
u16 bits, int offset)
{
u16 reg;
ks8842_select_bank(adapter, bank);
reg = ioread16(adapter->hw_addr + offset);
reg &= ~bits;
iowrite16(reg, adapter->hw_addr + offset);
}
static inline void ks8842_write32(struct ks8842_adapter *adapter, u16 bank,
u32 value, int offset)
{
ks8842_select_bank(adapter, bank);
iowrite32(value, adapter->hw_addr + offset);
}
static inline u8 ks8842_read8(struct ks8842_adapter *adapter, u16 bank,
int offset)
{
ks8842_select_bank(adapter, bank);
return ioread8(adapter->hw_addr + offset);
}
static inline u16 ks8842_read16(struct ks8842_adapter *adapter, u16 bank,
int offset)
{
ks8842_select_bank(adapter, bank);
return ioread16(adapter->hw_addr + offset);
}
static inline u32 ks8842_read32(struct ks8842_adapter *adapter, u16 bank,
int offset)
{
ks8842_select_bank(adapter, bank);
return ioread32(adapter->hw_addr + offset);
}
static void ks8842_reset(struct ks8842_adapter *adapter)
{
if (adapter->conf_flags & MICREL_KS884X) {
ks8842_write16(adapter, 3, 1, REG_GRR);
msleep(10);
iowrite16(0, adapter->hw_addr + REG_GRR);
} else {
/* The KS8842 goes haywire when doing softare reset
* a work around in the timberdale IP is implemented to
* do a hardware reset instead
ks8842_write16(adapter, 3, 1, REG_GRR);
msleep(10);
iowrite16(0, adapter->hw_addr + REG_GRR);
*/
iowrite32(0x1, adapter->hw_addr + REG_TIMB_RST);
msleep(20);
}
}
static void ks8842_update_link_status(struct net_device *netdev,
struct ks8842_adapter *adapter)
{
/* check the status of the link */
if (ks8842_read16(adapter, 45, REG_P1MBSR) & 0x4) {
netif_carrier_on(netdev);
netif_wake_queue(netdev);
} else {
netif_stop_queue(netdev);
netif_carrier_off(netdev);
}
}
static void ks8842_enable_tx(struct ks8842_adapter *adapter)
{
ks8842_enable_bits(adapter, 16, 0x01, REG_TXCR);
}
static void ks8842_disable_tx(struct ks8842_adapter *adapter)
{
ks8842_clear_bits(adapter, 16, 0x01, REG_TXCR);
}
static void ks8842_enable_rx(struct ks8842_adapter *adapter)
{
ks8842_enable_bits(adapter, 16, 0x01, REG_RXCR);
}
static void ks8842_disable_rx(struct ks8842_adapter *adapter)
{
ks8842_clear_bits(adapter, 16, 0x01, REG_RXCR);
}
static void ks8842_reset_hw(struct ks8842_adapter *adapter)
{
/* reset the HW */
ks8842_reset(adapter);
/* Enable QMU Transmit flow control / transmit padding / Transmit CRC */
ks8842_write16(adapter, 16, 0x000E, REG_TXCR);
/* enable the receiver, uni + multi + broadcast + flow ctrl
+ crc strip */
ks8842_write16(adapter, 16, 0x8 | 0x20 | 0x40 | 0x80 | 0x400,
REG_RXCR);
/* TX frame pointer autoincrement */
ks8842_write16(adapter, 17, 0x4000, REG_TXFDPR);
/* RX frame pointer autoincrement */
ks8842_write16(adapter, 17, 0x4000, REG_RXFDPR);
/* RX 2 kb high watermark */
ks8842_write16(adapter, 0, 0x1000, REG_QRFCR);
/* aggressive back off in half duplex */
ks8842_enable_bits(adapter, 32, 1 << 8, REG_SGCR1);
/* enable no excessive collison drop */
ks8842_enable_bits(adapter, 32, 1 << 3, REG_SGCR2);
/* Enable port 1 force flow control / back pressure / transmit / recv */
ks8842_write16(adapter, 48, 0x1E07, REG_P1CR2);
/* restart port auto-negotiation */
ks8842_enable_bits(adapter, 49, 1 << 13, REG_P1CR4);
/* Enable the transmitter */
ks8842_enable_tx(adapter);
/* Enable the receiver */
ks8842_enable_rx(adapter);
/* clear all interrupts */
ks8842_write16(adapter, 18, 0xffff, REG_ISR);
/* enable interrupts */
if (KS8842_USE_DMA(adapter)) {
/* When running in DMA Mode the RX interrupt is not enabled in
timberdale because RX data is received by DMA callbacks
it must still be enabled in the KS8842 because it indicates
to timberdale when there is RX data for it's DMA FIFOs */
iowrite16(ENABLED_IRQS_DMA_IP, adapter->hw_addr + REG_TIMB_IER);
ks8842_write16(adapter, 18, ENABLED_IRQS_DMA, REG_IER);
} else {
if (!(adapter->conf_flags & MICREL_KS884X))
iowrite16(ENABLED_IRQS,
adapter->hw_addr + REG_TIMB_IER);
ks8842_write16(adapter, 18, ENABLED_IRQS, REG_IER);
}
/* enable the switch */
ks8842_write16(adapter, 32, 0x1, REG_SW_ID_AND_ENABLE);
}
static void ks8842_read_mac_addr(struct ks8842_adapter *adapter, u8 *dest)
{
int i;
u16 mac;
for (i = 0; i < ETH_ALEN; i++)
dest[ETH_ALEN - i - 1] = ks8842_read8(adapter, 2, REG_MARL + i);
if (adapter->conf_flags & MICREL_KS884X) {
/*
the sequence of saving mac addr between MAC and Switch is
different.
*/
mac = ks8842_read16(adapter, 2, REG_MARL);
ks8842_write16(adapter, 39, mac, REG_MACAR3);
mac = ks8842_read16(adapter, 2, REG_MARM);
ks8842_write16(adapter, 39, mac, REG_MACAR2);
mac = ks8842_read16(adapter, 2, REG_MARH);
ks8842_write16(adapter, 39, mac, REG_MACAR1);
} else {
/* make sure the switch port uses the same MAC as the QMU */
mac = ks8842_read16(adapter, 2, REG_MARL);
ks8842_write16(adapter, 39, mac, REG_MACAR1);
mac = ks8842_read16(adapter, 2, REG_MARM);
ks8842_write16(adapter, 39, mac, REG_MACAR2);
mac = ks8842_read16(adapter, 2, REG_MARH);
ks8842_write16(adapter, 39, mac, REG_MACAR3);
}
}
static void ks8842_write_mac_addr(struct ks8842_adapter *adapter, u8 *mac)
{
unsigned long flags;
unsigned i;
spin_lock_irqsave(&adapter->lock, flags);
for (i = 0; i < ETH_ALEN; i++) {
ks8842_write8(adapter, 2, mac[ETH_ALEN - i - 1], REG_MARL + i);
if (!(adapter->conf_flags & MICREL_KS884X))
ks8842_write8(adapter, 39, mac[ETH_ALEN - i - 1],
REG_MACAR1 + i);
}
if (adapter->conf_flags & MICREL_KS884X) {
/*
the sequence of saving mac addr between MAC and Switch is
different.
*/
u16 mac;
mac = ks8842_read16(adapter, 2, REG_MARL);
ks8842_write16(adapter, 39, mac, REG_MACAR3);
mac = ks8842_read16(adapter, 2, REG_MARM);
ks8842_write16(adapter, 39, mac, REG_MACAR2);
mac = ks8842_read16(adapter, 2, REG_MARH);
ks8842_write16(adapter, 39, mac, REG_MACAR1);
}
spin_unlock_irqrestore(&adapter->lock, flags);
}
static inline u16 ks8842_tx_fifo_space(struct ks8842_adapter *adapter)
{
return ks8842_read16(adapter, 16, REG_TXMIR) & 0x1fff;
}
static int ks8842_tx_frame_dma(struct sk_buff *skb, struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct ks8842_tx_dma_ctl *ctl = &adapter->dma_tx;
u8 *buf = ctl->buf;
if (ctl->adesc) {
netdev_dbg(netdev, "%s: TX ongoing\n", __func__);
/* transfer ongoing */
return NETDEV_TX_BUSY;
}
sg_dma_len(&ctl->sg) = skb->len + sizeof(u32);
/* copy data to the TX buffer */
/* the control word, enable IRQ, port 1 and the length */
*buf++ = 0x00;
*buf++ = 0x01; /* Port 1 */
*buf++ = skb->len & 0xff;
*buf++ = (skb->len >> 8) & 0xff;
skb_copy_from_linear_data(skb, buf, skb->len);
dma_sync_single_range_for_device(adapter->dev,
sg_dma_address(&ctl->sg), 0, sg_dma_len(&ctl->sg),
DMA_TO_DEVICE);
/* make sure the length is a multiple of 4 */
if (sg_dma_len(&ctl->sg) % 4)
sg_dma_len(&ctl->sg) += 4 - sg_dma_len(&ctl->sg) % 4;
ctl->adesc = dmaengine_prep_slave_sg(ctl->chan,
&ctl->sg, 1, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_COMPL_SKIP_SRC_UNMAP);
if (!ctl->adesc)
return NETDEV_TX_BUSY;
ctl->adesc->callback_param = netdev;
ctl->adesc->callback = ks8842_dma_tx_cb;
ctl->adesc->tx_submit(ctl->adesc);
netdev->stats.tx_bytes += skb->len;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static int ks8842_tx_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
int len = skb->len;
netdev_dbg(netdev, "%s: len %u head %p data %p tail %p end %p\n",
__func__, skb->len, skb->head, skb->data,
skb_tail_pointer(skb), skb_end_pointer(skb));
/* check FIFO buffer space, we need space for CRC and command bits */
if (ks8842_tx_fifo_space(adapter) < len + 8)
return NETDEV_TX_BUSY;
if (adapter->conf_flags & KS884X_16BIT) {
u16 *ptr16 = (u16 *)skb->data;
ks8842_write16(adapter, 17, 0x8000 | 0x100, REG_QMU_DATA_LO);
ks8842_write16(adapter, 17, (u16)len, REG_QMU_DATA_HI);
netdev->stats.tx_bytes += len;
/* copy buffer */
while (len > 0) {
iowrite16(*ptr16++, adapter->hw_addr + REG_QMU_DATA_LO);
iowrite16(*ptr16++, adapter->hw_addr + REG_QMU_DATA_HI);
len -= sizeof(u32);
}
} else {
u32 *ptr = (u32 *)skb->data;
u32 ctrl;
/* the control word, enable IRQ, port 1 and the length */
ctrl = 0x8000 | 0x100 | (len << 16);
ks8842_write32(adapter, 17, ctrl, REG_QMU_DATA_LO);
netdev->stats.tx_bytes += len;
/* copy buffer */
while (len > 0) {
iowrite32(*ptr, adapter->hw_addr + REG_QMU_DATA_LO);
len -= sizeof(u32);
ptr++;
}
}
/* enqueue packet */
ks8842_write16(adapter, 17, 1, REG_TXQCR);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static void ks8842_update_rx_err_counters(struct net_device *netdev, u32 status)
{
netdev_dbg(netdev, "RX error, status: %x\n", status);
netdev->stats.rx_errors++;
if (status & RXSR_TOO_LONG)
netdev->stats.rx_length_errors++;
if (status & RXSR_CRC_ERROR)
netdev->stats.rx_crc_errors++;
if (status & RXSR_RUNT)
netdev->stats.rx_frame_errors++;
}
static void ks8842_update_rx_counters(struct net_device *netdev, u32 status,
int len)
{
netdev_dbg(netdev, "RX packet, len: %d\n", len);
netdev->stats.rx_packets++;
netdev->stats.rx_bytes += len;
if (status & RXSR_MULTICAST)
netdev->stats.multicast++;
}
static int __ks8842_start_new_rx_dma(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct ks8842_rx_dma_ctl *ctl = &adapter->dma_rx;
struct scatterlist *sg = &ctl->sg;
int err;
ctl->skb = netdev_alloc_skb(netdev, DMA_BUFFER_SIZE);
if (ctl->skb) {
sg_init_table(sg, 1);
sg_dma_address(sg) = dma_map_single(adapter->dev,
ctl->skb->data, DMA_BUFFER_SIZE, DMA_FROM_DEVICE);
err = dma_mapping_error(adapter->dev, sg_dma_address(sg));
if (unlikely(err)) {
sg_dma_address(sg) = 0;
goto out;
}
sg_dma_len(sg) = DMA_BUFFER_SIZE;
ctl->adesc = dmaengine_prep_slave_sg(ctl->chan,
sg, 1, DMA_DEV_TO_MEM,
DMA_PREP_INTERRUPT | DMA_COMPL_SKIP_SRC_UNMAP);
if (!ctl->adesc)
goto out;
ctl->adesc->callback_param = netdev;
ctl->adesc->callback = ks8842_dma_rx_cb;
ctl->adesc->tx_submit(ctl->adesc);
} else {
err = -ENOMEM;
sg_dma_address(sg) = 0;
goto out;
}
return err;
out:
if (sg_dma_address(sg))
dma_unmap_single(adapter->dev, sg_dma_address(sg),
DMA_BUFFER_SIZE, DMA_FROM_DEVICE);
sg_dma_address(sg) = 0;
if (ctl->skb)
dev_kfree_skb(ctl->skb);
ctl->skb = NULL;
printk(KERN_ERR DRV_NAME": Failed to start RX DMA: %d\n", err);
return err;
}
static void ks8842_rx_frame_dma_tasklet(unsigned long arg)
{
struct net_device *netdev = (struct net_device *)arg;
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct ks8842_rx_dma_ctl *ctl = &adapter->dma_rx;
struct sk_buff *skb = ctl->skb;
dma_addr_t addr = sg_dma_address(&ctl->sg);
u32 status;
ctl->adesc = NULL;
/* kick next transfer going */
__ks8842_start_new_rx_dma(netdev);
/* now handle the data we got */
dma_unmap_single(adapter->dev, addr, DMA_BUFFER_SIZE, DMA_FROM_DEVICE);
status = *((u32 *)skb->data);
netdev_dbg(netdev, "%s - rx_data: status: %x\n",
__func__, status & 0xffff);
/* check the status */
if ((status & RXSR_VALID) && !(status & RXSR_ERROR)) {
int len = (status >> 16) & 0x7ff;
ks8842_update_rx_counters(netdev, status, len);
/* reserve 4 bytes which is the status word */
skb_reserve(skb, 4);
skb_put(skb, len);
skb->protocol = eth_type_trans(skb, netdev);
netif_rx(skb);
} else {
ks8842_update_rx_err_counters(netdev, status);
dev_kfree_skb(skb);
}
}
static void ks8842_rx_frame(struct net_device *netdev,
struct ks8842_adapter *adapter)
{
u32 status;
int len;
if (adapter->conf_flags & KS884X_16BIT) {
status = ks8842_read16(adapter, 17, REG_QMU_DATA_LO);
len = ks8842_read16(adapter, 17, REG_QMU_DATA_HI);
netdev_dbg(netdev, "%s - rx_data: status: %x\n",
__func__, status);
} else {
status = ks8842_read32(adapter, 17, REG_QMU_DATA_LO);
len = (status >> 16) & 0x7ff;
status &= 0xffff;
netdev_dbg(netdev, "%s - rx_data: status: %x\n",
__func__, status);
}
/* check the status */
if ((status & RXSR_VALID) && !(status & RXSR_ERROR)) {
struct sk_buff *skb = netdev_alloc_skb_ip_align(netdev, len + 3);
if (skb) {
ks8842_update_rx_counters(netdev, status, len);
if (adapter->conf_flags & KS884X_16BIT) {
u16 *data16 = (u16 *)skb_put(skb, len);
ks8842_select_bank(adapter, 17);
while (len > 0) {
*data16++ = ioread16(adapter->hw_addr +
REG_QMU_DATA_LO);
*data16++ = ioread16(adapter->hw_addr +
REG_QMU_DATA_HI);
len -= sizeof(u32);
}
} else {
u32 *data = (u32 *)skb_put(skb, len);
ks8842_select_bank(adapter, 17);
while (len > 0) {
*data++ = ioread32(adapter->hw_addr +
REG_QMU_DATA_LO);
len -= sizeof(u32);
}
}
skb->protocol = eth_type_trans(skb, netdev);
netif_rx(skb);
} else
netdev->stats.rx_dropped++;
} else
ks8842_update_rx_err_counters(netdev, status);
/* set high watermark to 3K */
ks8842_clear_bits(adapter, 0, 1 << 12, REG_QRFCR);
/* release the frame */
ks8842_write16(adapter, 17, 0x01, REG_RXQCR);
/* set high watermark to 2K */
ks8842_enable_bits(adapter, 0, 1 << 12, REG_QRFCR);
}
void ks8842_handle_rx(struct net_device *netdev, struct ks8842_adapter *adapter)
{
u16 rx_data = ks8842_read16(adapter, 16, REG_RXMIR) & 0x1fff;
netdev_dbg(netdev, "%s Entry - rx_data: %d\n", __func__, rx_data);
while (rx_data) {
ks8842_rx_frame(netdev, adapter);
rx_data = ks8842_read16(adapter, 16, REG_RXMIR) & 0x1fff;
}
}
void ks8842_handle_tx(struct net_device *netdev, struct ks8842_adapter *adapter)
{
u16 sr = ks8842_read16(adapter, 16, REG_TXSR);
netdev_dbg(netdev, "%s - entry, sr: %x\n", __func__, sr);
netdev->stats.tx_packets++;
if (netif_queue_stopped(netdev))
netif_wake_queue(netdev);
}
void ks8842_handle_rx_overrun(struct net_device *netdev,
struct ks8842_adapter *adapter)
{
netdev_dbg(netdev, "%s: entry\n", __func__);
netdev->stats.rx_errors++;
netdev->stats.rx_fifo_errors++;
}
void ks8842_tasklet(unsigned long arg)
{
struct net_device *netdev = (struct net_device *)arg;
struct ks8842_adapter *adapter = netdev_priv(netdev);
u16 isr;
unsigned long flags;
u16 entry_bank;
/* read current bank to be able to set it back */
spin_lock_irqsave(&adapter->lock, flags);
entry_bank = ioread16(adapter->hw_addr + REG_SELECT_BANK);
spin_unlock_irqrestore(&adapter->lock, flags);
isr = ks8842_read16(adapter, 18, REG_ISR);
netdev_dbg(netdev, "%s - ISR: 0x%x\n", __func__, isr);
/* when running in DMA mode, do not ack RX interrupts, it is handled
internally by timberdale, otherwise it's DMA FIFO:s would stop
*/
if (KS8842_USE_DMA(adapter))
isr &= ~IRQ_RX;
/* Ack */
ks8842_write16(adapter, 18, isr, REG_ISR);
if (!(adapter->conf_flags & MICREL_KS884X))
/* Ack in the timberdale IP as well */
iowrite32(0x1, adapter->hw_addr + REG_TIMB_IAR);
if (!netif_running(netdev))
return;
if (isr & IRQ_LINK_CHANGE)
ks8842_update_link_status(netdev, adapter);
/* should not get IRQ_RX when running DMA mode */
if (isr & (IRQ_RX | IRQ_RX_ERROR) && !KS8842_USE_DMA(adapter))
ks8842_handle_rx(netdev, adapter);
/* should only happen when in PIO mode */
if (isr & IRQ_TX)
ks8842_handle_tx(netdev, adapter);
if (isr & IRQ_RX_OVERRUN)
ks8842_handle_rx_overrun(netdev, adapter);
if (isr & IRQ_TX_STOPPED) {
ks8842_disable_tx(adapter);
ks8842_enable_tx(adapter);
}
if (isr & IRQ_RX_STOPPED) {
ks8842_disable_rx(adapter);
ks8842_enable_rx(adapter);
}
/* re-enable interrupts, put back the bank selection register */
spin_lock_irqsave(&adapter->lock, flags);
if (KS8842_USE_DMA(adapter))
ks8842_write16(adapter, 18, ENABLED_IRQS_DMA, REG_IER);
else
ks8842_write16(adapter, 18, ENABLED_IRQS, REG_IER);
iowrite16(entry_bank, adapter->hw_addr + REG_SELECT_BANK);
/* Make sure timberdale continues DMA operations, they are stopped while
we are handling the ks8842 because we might change bank */
if (KS8842_USE_DMA(adapter))
ks8842_resume_dma(adapter);
spin_unlock_irqrestore(&adapter->lock, flags);
}
static irqreturn_t ks8842_irq(int irq, void *devid)
{
struct net_device *netdev = devid;
struct ks8842_adapter *adapter = netdev_priv(netdev);
u16 isr;
u16 entry_bank = ioread16(adapter->hw_addr + REG_SELECT_BANK);
irqreturn_t ret = IRQ_NONE;
isr = ks8842_read16(adapter, 18, REG_ISR);
netdev_dbg(netdev, "%s - ISR: 0x%x\n", __func__, isr);
if (isr) {
if (KS8842_USE_DMA(adapter))
/* disable all but RX IRQ, since the FPGA relies on it*/
ks8842_write16(adapter, 18, IRQ_RX, REG_IER);
else
/* disable IRQ */
ks8842_write16(adapter, 18, 0x00, REG_IER);
/* schedule tasklet */
tasklet_schedule(&adapter->tasklet);
ret = IRQ_HANDLED;
}
iowrite16(entry_bank, adapter->hw_addr + REG_SELECT_BANK);
/* After an interrupt, tell timberdale to continue DMA operations.
DMA is disabled while we are handling the ks8842 because we might
change bank */
ks8842_resume_dma(adapter);
return ret;
}
static void ks8842_dma_rx_cb(void *data)
{
struct net_device *netdev = data;
struct ks8842_adapter *adapter = netdev_priv(netdev);
netdev_dbg(netdev, "RX DMA finished\n");
/* schedule tasklet */
if (adapter->dma_rx.adesc)
tasklet_schedule(&adapter->dma_rx.tasklet);
}
static void ks8842_dma_tx_cb(void *data)
{
struct net_device *netdev = data;
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct ks8842_tx_dma_ctl *ctl = &adapter->dma_tx;
netdev_dbg(netdev, "TX DMA finished\n");
if (!ctl->adesc)
return;
netdev->stats.tx_packets++;
ctl->adesc = NULL;
if (netif_queue_stopped(netdev))
netif_wake_queue(netdev);
}
static void ks8842_stop_dma(struct ks8842_adapter *adapter)
{
struct ks8842_tx_dma_ctl *tx_ctl = &adapter->dma_tx;
struct ks8842_rx_dma_ctl *rx_ctl = &adapter->dma_rx;
tx_ctl->adesc = NULL;
if (tx_ctl->chan)
tx_ctl->chan->device->device_control(tx_ctl->chan,
DMA_TERMINATE_ALL, 0);
rx_ctl->adesc = NULL;
if (rx_ctl->chan)
rx_ctl->chan->device->device_control(rx_ctl->chan,
DMA_TERMINATE_ALL, 0);
if (sg_dma_address(&rx_ctl->sg))
dma_unmap_single(adapter->dev, sg_dma_address(&rx_ctl->sg),
DMA_BUFFER_SIZE, DMA_FROM_DEVICE);
sg_dma_address(&rx_ctl->sg) = 0;
dev_kfree_skb(rx_ctl->skb);
rx_ctl->skb = NULL;
}
static void ks8842_dealloc_dma_bufs(struct ks8842_adapter *adapter)
{
struct ks8842_tx_dma_ctl *tx_ctl = &adapter->dma_tx;
struct ks8842_rx_dma_ctl *rx_ctl = &adapter->dma_rx;
ks8842_stop_dma(adapter);
if (tx_ctl->chan)
dma_release_channel(tx_ctl->chan);
tx_ctl->chan = NULL;
if (rx_ctl->chan)
dma_release_channel(rx_ctl->chan);
rx_ctl->chan = NULL;
tasklet_kill(&rx_ctl->tasklet);
if (sg_dma_address(&tx_ctl->sg))
dma_unmap_single(adapter->dev, sg_dma_address(&tx_ctl->sg),
DMA_BUFFER_SIZE, DMA_TO_DEVICE);
sg_dma_address(&tx_ctl->sg) = 0;
kfree(tx_ctl->buf);
tx_ctl->buf = NULL;
}
static bool ks8842_dma_filter_fn(struct dma_chan *chan, void *filter_param)
{
return chan->chan_id == (long)filter_param;
}
static int ks8842_alloc_dma_bufs(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct ks8842_tx_dma_ctl *tx_ctl = &adapter->dma_tx;
struct ks8842_rx_dma_ctl *rx_ctl = &adapter->dma_rx;
int err;
dma_cap_mask_t mask;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
dma_cap_set(DMA_PRIVATE, mask);
sg_init_table(&tx_ctl->sg, 1);
tx_ctl->chan = dma_request_channel(mask, ks8842_dma_filter_fn,
(void *)(long)tx_ctl->channel);
if (!tx_ctl->chan) {
err = -ENODEV;
goto err;
}
/* allocate DMA buffer */
tx_ctl->buf = kmalloc(DMA_BUFFER_SIZE, GFP_KERNEL);
if (!tx_ctl->buf) {
err = -ENOMEM;
goto err;
}
sg_dma_address(&tx_ctl->sg) = dma_map_single(adapter->dev,
tx_ctl->buf, DMA_BUFFER_SIZE, DMA_TO_DEVICE);
err = dma_mapping_error(adapter->dev,
sg_dma_address(&tx_ctl->sg));
if (err) {
sg_dma_address(&tx_ctl->sg) = 0;
goto err;
}
rx_ctl->chan = dma_request_channel(mask, ks8842_dma_filter_fn,
(void *)(long)rx_ctl->channel);
if (!rx_ctl->chan) {
err = -ENODEV;
goto err;
}
tasklet_init(&rx_ctl->tasklet, ks8842_rx_frame_dma_tasklet,
(unsigned long)netdev);
return 0;
err:
ks8842_dealloc_dma_bufs(adapter);
return err;
}
/* Netdevice operations */
static int ks8842_open(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
int err;
netdev_dbg(netdev, "%s - entry\n", __func__);
if (KS8842_USE_DMA(adapter)) {
err = ks8842_alloc_dma_bufs(netdev);
if (!err) {
/* start RX dma */
err = __ks8842_start_new_rx_dma(netdev);
if (err)
ks8842_dealloc_dma_bufs(adapter);
}
if (err) {
printk(KERN_WARNING DRV_NAME
": Failed to initiate DMA, running PIO\n");
ks8842_dealloc_dma_bufs(adapter);
adapter->dma_rx.channel = -1;
adapter->dma_tx.channel = -1;
}
}
/* reset the HW */
ks8842_reset_hw(adapter);
ks8842_write_mac_addr(adapter, netdev->dev_addr);
ks8842_update_link_status(netdev, adapter);
err = request_irq(adapter->irq, ks8842_irq, IRQF_SHARED, DRV_NAME,
netdev);
if (err) {
pr_err("Failed to request IRQ: %d: %d\n", adapter->irq, err);
return err;
}
return 0;
}
static int ks8842_close(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
netdev_dbg(netdev, "%s - entry\n", __func__);
cancel_work_sync(&adapter->timeout_work);
if (KS8842_USE_DMA(adapter))
ks8842_dealloc_dma_bufs(adapter);
/* free the irq */
free_irq(adapter->irq, netdev);
/* disable the switch */
ks8842_write16(adapter, 32, 0x0, REG_SW_ID_AND_ENABLE);
return 0;
}
static netdev_tx_t ks8842_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
int ret;
struct ks8842_adapter *adapter = netdev_priv(netdev);
netdev_dbg(netdev, "%s: entry\n", __func__);
if (KS8842_USE_DMA(adapter)) {
unsigned long flags;
ret = ks8842_tx_frame_dma(skb, netdev);
/* for now only allow one transfer at the time */
spin_lock_irqsave(&adapter->lock, flags);
if (adapter->dma_tx.adesc)
netif_stop_queue(netdev);
spin_unlock_irqrestore(&adapter->lock, flags);
return ret;
}
ret = ks8842_tx_frame(skb, netdev);
if (ks8842_tx_fifo_space(adapter) < netdev->mtu + 8)
netif_stop_queue(netdev);
return ret;
}
static int ks8842_set_mac(struct net_device *netdev, void *p)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
char *mac = (u8 *)addr->sa_data;
netdev_dbg(netdev, "%s: entry\n", __func__);
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, mac, netdev->addr_len);
ks8842_write_mac_addr(adapter, mac);
return 0;
}
static void ks8842_tx_timeout_work(struct work_struct *work)
{
struct ks8842_adapter *adapter =
container_of(work, struct ks8842_adapter, timeout_work);
struct net_device *netdev = adapter->netdev;
unsigned long flags;
netdev_dbg(netdev, "%s: entry\n", __func__);
spin_lock_irqsave(&adapter->lock, flags);
if (KS8842_USE_DMA(adapter))
ks8842_stop_dma(adapter);
/* disable interrupts */
ks8842_write16(adapter, 18, 0, REG_IER);
ks8842_write16(adapter, 18, 0xFFFF, REG_ISR);
netif_stop_queue(netdev);
spin_unlock_irqrestore(&adapter->lock, flags);
ks8842_reset_hw(adapter);
ks8842_write_mac_addr(adapter, netdev->dev_addr);
ks8842_update_link_status(netdev, adapter);
if (KS8842_USE_DMA(adapter))
__ks8842_start_new_rx_dma(netdev);
}
static void ks8842_tx_timeout(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
netdev_dbg(netdev, "%s: entry\n", __func__);
schedule_work(&adapter->timeout_work);
}
static const struct net_device_ops ks8842_netdev_ops = {
.ndo_open = ks8842_open,
.ndo_stop = ks8842_close,
.ndo_start_xmit = ks8842_xmit_frame,
.ndo_set_mac_address = ks8842_set_mac,
.ndo_tx_timeout = ks8842_tx_timeout,
.ndo_validate_addr = eth_validate_addr
};
static const struct ethtool_ops ks8842_ethtool_ops = {
.get_link = ethtool_op_get_link,
};
static int ks8842_probe(struct platform_device *pdev)
{
int err = -ENOMEM;
struct resource *iomem;
struct net_device *netdev;
struct ks8842_adapter *adapter;
struct ks8842_platform_data *pdata = pdev->dev.platform_data;
u16 id;
unsigned i;
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!request_mem_region(iomem->start, resource_size(iomem), DRV_NAME))
goto err_mem_region;
netdev = alloc_etherdev(sizeof(struct ks8842_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
INIT_WORK(&adapter->timeout_work, ks8842_tx_timeout_work);
adapter->hw_addr = ioremap(iomem->start, resource_size(iomem));
adapter->conf_flags = iomem->flags;
if (!adapter->hw_addr)
goto err_ioremap;
adapter->irq = platform_get_irq(pdev, 0);
if (adapter->irq < 0) {
err = adapter->irq;
goto err_get_irq;
}
adapter->dev = (pdev->dev.parent) ? pdev->dev.parent : &pdev->dev;
/* DMA is only supported when accessed via timberdale */
if (!(adapter->conf_flags & MICREL_KS884X) && pdata &&
(pdata->tx_dma_channel != -1) &&
(pdata->rx_dma_channel != -1)) {
adapter->dma_rx.channel = pdata->rx_dma_channel;
adapter->dma_tx.channel = pdata->tx_dma_channel;
} else {
adapter->dma_rx.channel = -1;
adapter->dma_tx.channel = -1;
}
tasklet_init(&adapter->tasklet, ks8842_tasklet, (unsigned long)netdev);
spin_lock_init(&adapter->lock);
netdev->netdev_ops = &ks8842_netdev_ops;
netdev->ethtool_ops = &ks8842_ethtool_ops;
/* Check if a mac address was given */
i = netdev->addr_len;
if (pdata) {
for (i = 0; i < netdev->addr_len; i++)
if (pdata->macaddr[i] != 0)
break;
if (i < netdev->addr_len)
/* an address was passed, use it */
memcpy(netdev->dev_addr, pdata->macaddr,
netdev->addr_len);
}
if (i == netdev->addr_len) {
ks8842_read_mac_addr(adapter, netdev->dev_addr);
if (!is_valid_ether_addr(netdev->dev_addr))
eth_hw_addr_random(netdev);
}
id = ks8842_read16(adapter, 32, REG_SW_ID_AND_ENABLE);
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_register;
platform_set_drvdata(pdev, netdev);
pr_info("Found chip, family: 0x%x, id: 0x%x, rev: 0x%x\n",
(id >> 8) & 0xff, (id >> 4) & 0xf, (id >> 1) & 0x7);
return 0;
err_register:
err_get_irq:
iounmap(adapter->hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
release_mem_region(iomem->start, resource_size(iomem));
err_mem_region:
return err;
}
static int ks8842_remove(struct platform_device *pdev)
{
struct net_device *netdev = platform_get_drvdata(pdev);
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct resource *iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
unregister_netdev(netdev);
tasklet_kill(&adapter->tasklet);
iounmap(adapter->hw_addr);
free_netdev(netdev);
release_mem_region(iomem->start, resource_size(iomem));
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver ks8842_platform_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ks8842_probe,
.remove = ks8842_remove,
};
module_platform_driver(ks8842_platform_driver);
MODULE_DESCRIPTION("Timberdale KS8842 ethernet driver");
MODULE_AUTHOR("Mocean Laboratories <info@mocean-labs.com>");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:ks8842");
| gpl-2.0 |
kkfong/android_kernel_oneplus_msm8974 | sound/pci/hda/patch_via.c | 2860 | 106702 | /*
* Universal Interface for Intel High Definition Audio Codec
*
* HD audio interface patch for VIA VT17xx/VT18xx/VT20xx codec
*
* (C) 2006-2009 VIA Technology, Inc.
* (C) 2006-2008 Takashi Iwai <tiwai@suse.de>
*
* This driver is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* * * * * * * * * * * * * * Release History * * * * * * * * * * * * * * * * */
/* */
/* 2006-03-03 Lydia Wang Create the basic patch to support VT1708 codec */
/* 2006-03-14 Lydia Wang Modify hard code for some pin widget nid */
/* 2006-08-02 Lydia Wang Add support to VT1709 codec */
/* 2006-09-08 Lydia Wang Fix internal loopback recording source select bug */
/* 2007-09-12 Lydia Wang Add EAPD enable during driver initialization */
/* 2007-09-17 Lydia Wang Add VT1708B codec support */
/* 2007-11-14 Lydia Wang Add VT1708A codec HP and CD pin connect config */
/* 2008-02-03 Lydia Wang Fix Rear channels and Back channels inverse issue */
/* 2008-03-06 Lydia Wang Add VT1702 codec and VT1708S codec support */
/* 2008-04-09 Lydia Wang Add mute front speaker when HP plugin */
/* 2008-04-09 Lydia Wang Add Independent HP feature */
/* 2008-05-28 Lydia Wang Add second S/PDIF Out support for VT1702 */
/* 2008-09-15 Logan Li Add VT1708S Mic Boost workaround/backdoor */
/* 2009-02-16 Logan Li Add support for VT1718S */
/* 2009-03-13 Logan Li Add support for VT1716S */
/* 2009-04-14 Lydai Wang Add support for VT1828S and VT2020 */
/* 2009-07-08 Lydia Wang Add support for VT2002P */
/* 2009-07-21 Lydia Wang Add support for VT1812 */
/* 2009-09-19 Lydia Wang Add support for VT1818S */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/asoundef.h>
#include "hda_codec.h"
#include "hda_local.h"
#include "hda_jack.h"
/* Pin Widget NID */
#define VT1708_HP_PIN_NID 0x20
#define VT1708_CD_PIN_NID 0x24
enum VIA_HDA_CODEC {
UNKNOWN = -1,
VT1708,
VT1709_10CH,
VT1709_6CH,
VT1708B_8CH,
VT1708B_4CH,
VT1708S,
VT1708BCE,
VT1702,
VT1718S,
VT1716S,
VT2002P,
VT1812,
VT1802,
CODEC_TYPES,
};
#define VT2002P_COMPATIBLE(spec) \
((spec)->codec_type == VT2002P ||\
(spec)->codec_type == VT1812 ||\
(spec)->codec_type == VT1802)
#define MAX_NID_PATH_DEPTH 5
/* output-path: DAC -> ... -> pin
* idx[] contains the source index number of the next widget;
* e.g. idx[0] is the index of the DAC selected by path[1] widget
* multi[] indicates whether it's a selector widget with multi-connectors
* (i.e. the connection selection is mandatory)
* vol_ctl and mute_ctl contains the NIDs for the assigned mixers
*/
struct nid_path {
int depth;
hda_nid_t path[MAX_NID_PATH_DEPTH];
unsigned char idx[MAX_NID_PATH_DEPTH];
unsigned char multi[MAX_NID_PATH_DEPTH];
unsigned int vol_ctl;
unsigned int mute_ctl;
};
/* input-path */
struct via_input {
hda_nid_t pin; /* input-pin or aa-mix */
int adc_idx; /* ADC index to be used */
int mux_idx; /* MUX index (if any) */
const char *label; /* input-source label */
};
#define VIA_MAX_ADCS 3
enum {
STREAM_MULTI_OUT = (1 << 0),
STREAM_INDEP_HP = (1 << 1),
};
struct via_spec {
/* codec parameterization */
const struct snd_kcontrol_new *mixers[6];
unsigned int num_mixers;
const struct hda_verb *init_verbs[5];
unsigned int num_iverbs;
char stream_name_analog[32];
char stream_name_hp[32];
const struct hda_pcm_stream *stream_analog_playback;
const struct hda_pcm_stream *stream_analog_capture;
char stream_name_digital[32];
const struct hda_pcm_stream *stream_digital_playback;
const struct hda_pcm_stream *stream_digital_capture;
/* playback */
struct hda_multi_out multiout;
hda_nid_t slave_dig_outs[2];
hda_nid_t hp_dac_nid;
hda_nid_t speaker_dac_nid;
int hp_indep_shared; /* indep HP-DAC is shared with side ch */
int opened_streams; /* STREAM_* bits */
int active_streams; /* STREAM_* bits */
int aamix_mode; /* loopback is enabled for output-path? */
/* Output-paths:
* There are different output-paths depending on the setup.
* out_path, hp_path and speaker_path are primary paths. If both
* direct DAC and aa-loopback routes are available, these contain
* the former paths. Meanwhile *_mix_path contain the paths with
* loopback mixer. (Since the loopback is only for front channel,
* no out_mix_path for surround channels.)
* The HP output has another path, hp_indep_path, which is used in
* the independent-HP mode.
*/
struct nid_path out_path[HDA_SIDE + 1];
struct nid_path out_mix_path;
struct nid_path hp_path;
struct nid_path hp_mix_path;
struct nid_path hp_indep_path;
struct nid_path speaker_path;
struct nid_path speaker_mix_path;
/* capture */
unsigned int num_adc_nids;
hda_nid_t adc_nids[VIA_MAX_ADCS];
hda_nid_t mux_nids[VIA_MAX_ADCS];
hda_nid_t aa_mix_nid;
hda_nid_t dig_in_nid;
/* capture source */
bool dyn_adc_switch;
int num_inputs;
struct via_input inputs[AUTO_CFG_MAX_INS + 1];
unsigned int cur_mux[VIA_MAX_ADCS];
/* dynamic DAC switching */
unsigned int cur_dac_stream_tag;
unsigned int cur_dac_format;
unsigned int cur_hp_stream_tag;
unsigned int cur_hp_format;
/* dynamic ADC switching */
hda_nid_t cur_adc;
unsigned int cur_adc_stream_tag;
unsigned int cur_adc_format;
/* PCM information */
struct hda_pcm pcm_rec[3];
/* dynamic controls, init_verbs and input_mux */
struct auto_pin_cfg autocfg;
struct snd_array kctls;
hda_nid_t private_dac_nids[AUTO_CFG_MAX_OUTS];
/* HP mode source */
unsigned int hp_independent_mode;
unsigned int dmic_enabled;
unsigned int no_pin_power_ctl;
enum VIA_HDA_CODEC codec_type;
/* analog low-power control */
bool alc_mode;
/* smart51 setup */
unsigned int smart51_nums;
hda_nid_t smart51_pins[2];
int smart51_idxs[2];
const char *smart51_labels[2];
unsigned int smart51_enabled;
/* work to check hp jack state */
struct hda_codec *codec;
struct delayed_work vt1708_hp_work;
int hp_work_active;
int vt1708_jack_detect;
int vt1708_hp_present;
void (*set_widgets_power_state)(struct hda_codec *codec);
struct hda_loopback_check loopback;
int num_loopbacks;
struct hda_amp_list loopback_list[8];
/* bind capture-volume */
struct hda_bind_ctls *bind_cap_vol;
struct hda_bind_ctls *bind_cap_sw;
struct mutex config_mutex;
};
static enum VIA_HDA_CODEC get_codec_type(struct hda_codec *codec);
static struct via_spec * via_new_spec(struct hda_codec *codec)
{
struct via_spec *spec;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return NULL;
mutex_init(&spec->config_mutex);
codec->spec = spec;
spec->codec = codec;
spec->codec_type = get_codec_type(codec);
/* VT1708BCE & VT1708S are almost same */
if (spec->codec_type == VT1708BCE)
spec->codec_type = VT1708S;
return spec;
}
static enum VIA_HDA_CODEC get_codec_type(struct hda_codec *codec)
{
u32 vendor_id = codec->vendor_id;
u16 ven_id = vendor_id >> 16;
u16 dev_id = vendor_id & 0xffff;
enum VIA_HDA_CODEC codec_type;
/* get codec type */
if (ven_id != 0x1106)
codec_type = UNKNOWN;
else if (dev_id >= 0x1708 && dev_id <= 0x170b)
codec_type = VT1708;
else if (dev_id >= 0xe710 && dev_id <= 0xe713)
codec_type = VT1709_10CH;
else if (dev_id >= 0xe714 && dev_id <= 0xe717)
codec_type = VT1709_6CH;
else if (dev_id >= 0xe720 && dev_id <= 0xe723) {
codec_type = VT1708B_8CH;
if (snd_hda_param_read(codec, 0x16, AC_PAR_CONNLIST_LEN) == 0x7)
codec_type = VT1708BCE;
} else if (dev_id >= 0xe724 && dev_id <= 0xe727)
codec_type = VT1708B_4CH;
else if ((dev_id & 0xfff) == 0x397
&& (dev_id >> 12) < 8)
codec_type = VT1708S;
else if ((dev_id & 0xfff) == 0x398
&& (dev_id >> 12) < 8)
codec_type = VT1702;
else if ((dev_id & 0xfff) == 0x428
&& (dev_id >> 12) < 8)
codec_type = VT1718S;
else if (dev_id == 0x0433 || dev_id == 0xa721)
codec_type = VT1716S;
else if (dev_id == 0x0441 || dev_id == 0x4441)
codec_type = VT1718S;
else if (dev_id == 0x0438 || dev_id == 0x4438)
codec_type = VT2002P;
else if (dev_id == 0x0448)
codec_type = VT1812;
else if (dev_id == 0x0440)
codec_type = VT1708S;
else if ((dev_id & 0xfff) == 0x446)
codec_type = VT1802;
else
codec_type = UNKNOWN;
return codec_type;
};
#define VIA_JACK_EVENT 0x20
#define VIA_HP_EVENT 0x01
#define VIA_GPIO_EVENT 0x02
#define VIA_LINE_EVENT 0x03
enum {
VIA_CTL_WIDGET_VOL,
VIA_CTL_WIDGET_MUTE,
VIA_CTL_WIDGET_ANALOG_MUTE,
};
static void analog_low_current_mode(struct hda_codec *codec);
static bool is_aa_path_mute(struct hda_codec *codec);
#define hp_detect_with_aa(codec) \
(snd_hda_get_bool_hint(codec, "analog_loopback_hp_detect") == 1 && \
!is_aa_path_mute(codec))
static void vt1708_stop_hp_work(struct via_spec *spec)
{
if (spec->codec_type != VT1708 || spec->autocfg.hp_pins[0] == 0)
return;
if (spec->hp_work_active) {
snd_hda_codec_write(spec->codec, 0x1, 0, 0xf81, 1);
cancel_delayed_work_sync(&spec->vt1708_hp_work);
spec->hp_work_active = 0;
}
}
static void vt1708_update_hp_work(struct via_spec *spec)
{
if (spec->codec_type != VT1708 || spec->autocfg.hp_pins[0] == 0)
return;
if (spec->vt1708_jack_detect &&
(spec->active_streams || hp_detect_with_aa(spec->codec))) {
if (!spec->hp_work_active) {
snd_hda_codec_write(spec->codec, 0x1, 0, 0xf81, 0);
schedule_delayed_work(&spec->vt1708_hp_work,
msecs_to_jiffies(100));
spec->hp_work_active = 1;
}
} else if (!hp_detect_with_aa(spec->codec))
vt1708_stop_hp_work(spec);
}
static void set_widgets_power_state(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (spec->set_widgets_power_state)
spec->set_widgets_power_state(codec);
}
static int analog_input_switch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
set_widgets_power_state(codec);
analog_low_current_mode(snd_kcontrol_chip(kcontrol));
vt1708_update_hp_work(codec->spec);
return change;
}
/* modify .put = snd_hda_mixer_amp_switch_put */
#define ANALOG_INPUT_MUTE \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = NULL, \
.index = 0, \
.info = snd_hda_mixer_amp_switch_info, \
.get = snd_hda_mixer_amp_switch_get, \
.put = analog_input_switch_put, \
.private_value = HDA_COMPOSE_AMP_VAL(0, 3, 0, 0) }
static const struct snd_kcontrol_new via_control_templates[] = {
HDA_CODEC_VOLUME(NULL, 0, 0, 0),
HDA_CODEC_MUTE(NULL, 0, 0, 0),
ANALOG_INPUT_MUTE,
};
/* add dynamic controls */
static struct snd_kcontrol_new *__via_clone_ctl(struct via_spec *spec,
const struct snd_kcontrol_new *tmpl,
const char *name)
{
struct snd_kcontrol_new *knew;
snd_array_init(&spec->kctls, sizeof(*knew), 32);
knew = snd_array_new(&spec->kctls);
if (!knew)
return NULL;
*knew = *tmpl;
if (!name)
name = tmpl->name;
if (name) {
knew->name = kstrdup(name, GFP_KERNEL);
if (!knew->name)
return NULL;
}
return knew;
}
static int __via_add_control(struct via_spec *spec, int type, const char *name,
int idx, unsigned long val)
{
struct snd_kcontrol_new *knew;
knew = __via_clone_ctl(spec, &via_control_templates[type], name);
if (!knew)
return -ENOMEM;
knew->index = idx;
if (get_amp_nid_(val))
knew->subdevice = HDA_SUBDEV_AMP_FLAG;
knew->private_value = val;
return 0;
}
#define via_add_control(spec, type, name, val) \
__via_add_control(spec, type, name, 0, val)
#define via_clone_control(spec, tmpl) __via_clone_ctl(spec, tmpl, NULL)
static void via_free_kctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (spec->kctls.list) {
struct snd_kcontrol_new *kctl = spec->kctls.list;
int i;
for (i = 0; i < spec->kctls.used; i++)
kfree(kctl[i].name);
}
snd_array_free(&spec->kctls);
}
/* create input playback/capture controls for the given pin */
static int via_new_analog_input(struct via_spec *spec, const char *ctlname,
int type_idx, int idx, int mix_nid)
{
char name[32];
int err;
sprintf(name, "%s Playback Volume", ctlname);
err = __via_add_control(spec, VIA_CTL_WIDGET_VOL, name, type_idx,
HDA_COMPOSE_AMP_VAL(mix_nid, 3, idx, HDA_INPUT));
if (err < 0)
return err;
sprintf(name, "%s Playback Switch", ctlname);
err = __via_add_control(spec, VIA_CTL_WIDGET_ANALOG_MUTE, name, type_idx,
HDA_COMPOSE_AMP_VAL(mix_nid, 3, idx, HDA_INPUT));
if (err < 0)
return err;
return 0;
}
#define get_connection_index(codec, mux, nid) \
snd_hda_get_conn_index(codec, mux, nid, 0)
static bool check_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir,
unsigned int mask)
{
unsigned int caps;
if (!nid)
return false;
caps = get_wcaps(codec, nid);
if (dir == HDA_INPUT)
caps &= AC_WCAP_IN_AMP;
else
caps &= AC_WCAP_OUT_AMP;
if (!caps)
return false;
if (query_amp_caps(codec, nid, dir) & mask)
return true;
return false;
}
#define have_mute(codec, nid, dir) \
check_amp_caps(codec, nid, dir, AC_AMPCAP_MUTE)
/* enable/disable the output-route mixers */
static void activate_output_mix(struct hda_codec *codec, struct nid_path *path,
hda_nid_t mix_nid, int idx, bool enable)
{
int i, num, val;
if (!path)
return;
num = snd_hda_get_conn_list(codec, mix_nid, NULL);
for (i = 0; i < num; i++) {
if (i == idx)
val = AMP_IN_UNMUTE(i);
else
val = AMP_IN_MUTE(i);
snd_hda_codec_write(codec, mix_nid, 0,
AC_VERB_SET_AMP_GAIN_MUTE, val);
}
}
/* enable/disable the output-route */
static void activate_output_path(struct hda_codec *codec, struct nid_path *path,
bool enable, bool force)
{
struct via_spec *spec = codec->spec;
int i;
for (i = 0; i < path->depth; i++) {
hda_nid_t src, dst;
int idx = path->idx[i];
src = path->path[i];
if (i < path->depth - 1)
dst = path->path[i + 1];
else
dst = 0;
if (enable && path->multi[i])
snd_hda_codec_write(codec, dst, 0,
AC_VERB_SET_CONNECT_SEL, idx);
if (!force && (dst == spec->aa_mix_nid))
continue;
if (have_mute(codec, dst, HDA_INPUT))
activate_output_mix(codec, path, dst, idx, enable);
if (!force && (src == path->vol_ctl || src == path->mute_ctl))
continue;
if (have_mute(codec, src, HDA_OUTPUT)) {
int val = enable ? AMP_OUT_UNMUTE : AMP_OUT_MUTE;
snd_hda_codec_write(codec, src, 0,
AC_VERB_SET_AMP_GAIN_MUTE, val);
}
}
}
/* set the given pin as output */
static void init_output_pin(struct hda_codec *codec, hda_nid_t pin,
int pin_type)
{
if (!pin)
return;
snd_hda_codec_write(codec, pin, 0, AC_VERB_SET_PIN_WIDGET_CONTROL,
pin_type);
if (snd_hda_query_pin_caps(codec, pin) & AC_PINCAP_EAPD)
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_EAPD_BTLENABLE, 0x02);
}
static void via_auto_init_output(struct hda_codec *codec,
struct nid_path *path, int pin_type)
{
unsigned int caps;
hda_nid_t pin;
if (!path->depth)
return;
pin = path->path[path->depth - 1];
init_output_pin(codec, pin, pin_type);
if (get_wcaps(codec, pin) & AC_WCAP_OUT_AMP)
caps = query_amp_caps(codec, pin, HDA_OUTPUT);
else
caps = 0;
if (caps & AC_AMPCAP_MUTE) {
unsigned int val;
val = (caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT;
snd_hda_codec_write(codec, pin, 0, AC_VERB_SET_AMP_GAIN_MUTE,
AMP_OUT_MUTE | val);
}
activate_output_path(codec, path, true, true); /* force on */
}
static void via_auto_init_multi_out(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct nid_path *path;
int i;
for (i = 0; i < spec->autocfg.line_outs + spec->smart51_nums; i++) {
path = &spec->out_path[i];
if (!i && spec->aamix_mode && spec->out_mix_path.depth)
path = &spec->out_mix_path;
via_auto_init_output(codec, path, PIN_OUT);
}
}
/* deactivate the inactive headphone-paths */
static void deactivate_hp_paths(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int shared = spec->hp_indep_shared;
if (spec->hp_independent_mode) {
activate_output_path(codec, &spec->hp_path, false, false);
activate_output_path(codec, &spec->hp_mix_path, false, false);
if (shared)
activate_output_path(codec, &spec->out_path[shared],
false, false);
} else if (spec->aamix_mode || !spec->hp_path.depth) {
activate_output_path(codec, &spec->hp_indep_path, false, false);
activate_output_path(codec, &spec->hp_path, false, false);
} else {
activate_output_path(codec, &spec->hp_indep_path, false, false);
activate_output_path(codec, &spec->hp_mix_path, false, false);
}
}
static void via_auto_init_hp_out(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (!spec->hp_path.depth) {
via_auto_init_output(codec, &spec->hp_mix_path, PIN_HP);
return;
}
deactivate_hp_paths(codec);
if (spec->hp_independent_mode)
via_auto_init_output(codec, &spec->hp_indep_path, PIN_HP);
else if (spec->aamix_mode)
via_auto_init_output(codec, &spec->hp_mix_path, PIN_HP);
else
via_auto_init_output(codec, &spec->hp_path, PIN_HP);
}
static void via_auto_init_speaker_out(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (!spec->autocfg.speaker_outs)
return;
if (!spec->speaker_path.depth) {
via_auto_init_output(codec, &spec->speaker_mix_path, PIN_OUT);
return;
}
if (!spec->aamix_mode) {
activate_output_path(codec, &spec->speaker_mix_path,
false, false);
via_auto_init_output(codec, &spec->speaker_path, PIN_OUT);
} else {
activate_output_path(codec, &spec->speaker_path, false, false);
via_auto_init_output(codec, &spec->speaker_mix_path, PIN_OUT);
}
}
static bool is_smart51_pins(struct hda_codec *codec, hda_nid_t pin);
static void via_hp_automute(struct hda_codec *codec);
static void via_auto_init_analog_input(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
const struct auto_pin_cfg *cfg = &spec->autocfg;
hda_nid_t conn[HDA_MAX_CONNECTIONS];
unsigned int ctl;
int i, num_conns;
/* init ADCs */
for (i = 0; i < spec->num_adc_nids; i++) {
hda_nid_t nid = spec->adc_nids[i];
if (!(get_wcaps(codec, nid) & AC_WCAP_IN_AMP) ||
!(query_amp_caps(codec, nid, HDA_INPUT) & AC_AMPCAP_MUTE))
continue;
snd_hda_codec_write(codec, spec->adc_nids[i], 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_UNMUTE(0));
}
/* init pins */
for (i = 0; i < cfg->num_inputs; i++) {
hda_nid_t nid = cfg->inputs[i].pin;
if (spec->smart51_enabled && is_smart51_pins(codec, nid))
ctl = PIN_OUT;
else if (cfg->inputs[i].type == AUTO_PIN_MIC)
ctl = PIN_VREF50;
else
ctl = PIN_IN;
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, ctl);
}
/* init input-src */
for (i = 0; i < spec->num_adc_nids; i++) {
int adc_idx = spec->inputs[spec->cur_mux[i]].adc_idx;
/* secondary ADCs must have the unique MUX */
if (i > 0 && !spec->mux_nids[i])
break;
if (spec->mux_nids[adc_idx]) {
int mux_idx = spec->inputs[spec->cur_mux[i]].mux_idx;
snd_hda_codec_write(codec, spec->mux_nids[adc_idx], 0,
AC_VERB_SET_CONNECT_SEL,
mux_idx);
}
if (spec->dyn_adc_switch)
break; /* only one input-src */
}
/* init aa-mixer */
if (!spec->aa_mix_nid)
return;
num_conns = snd_hda_get_connections(codec, spec->aa_mix_nid, conn,
ARRAY_SIZE(conn));
for (i = 0; i < num_conns; i++) {
unsigned int caps = get_wcaps(codec, conn[i]);
if (get_wcaps_type(caps) == AC_WID_PIN)
snd_hda_codec_write(codec, spec->aa_mix_nid, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_MUTE(i));
}
}
static void update_power_state(struct hda_codec *codec, hda_nid_t nid,
unsigned int parm)
{
if (snd_hda_codec_read(codec, nid, 0,
AC_VERB_GET_POWER_STATE, 0) == parm)
return;
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_POWER_STATE, parm);
}
static void set_pin_power_state(struct hda_codec *codec, hda_nid_t nid,
unsigned int *affected_parm)
{
unsigned parm;
unsigned def_conf = snd_hda_codec_get_pincfg(codec, nid);
unsigned no_presence = (def_conf & AC_DEFCFG_MISC)
>> AC_DEFCFG_MISC_SHIFT
& AC_DEFCFG_MISC_NO_PRESENCE; /* do not support pin sense */
struct via_spec *spec = codec->spec;
unsigned present = 0;
no_presence |= spec->no_pin_power_ctl;
if (!no_presence)
present = snd_hda_jack_detect(codec, nid);
if ((spec->smart51_enabled && is_smart51_pins(codec, nid))
|| ((no_presence || present)
&& get_defcfg_connect(def_conf) != AC_JACK_PORT_NONE)) {
*affected_parm = AC_PWRST_D0; /* if it's connected */
parm = AC_PWRST_D0;
} else
parm = AC_PWRST_D3;
update_power_state(codec, nid, parm);
}
static int via_pin_power_ctl_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char * const texts[] = {
"Disabled", "Enabled"
};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int via_pin_power_ctl_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = !spec->no_pin_power_ctl;
return 0;
}
static int via_pin_power_ctl_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
unsigned int val = !ucontrol->value.enumerated.item[0];
if (val == spec->no_pin_power_ctl)
return 0;
spec->no_pin_power_ctl = val;
set_widgets_power_state(codec);
analog_low_current_mode(codec);
return 1;
}
static const struct snd_kcontrol_new via_pin_power_ctl_enum = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Dynamic Power-Control",
.info = via_pin_power_ctl_info,
.get = via_pin_power_ctl_get,
.put = via_pin_power_ctl_put,
};
static int via_independent_hp_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char * const texts[] = { "OFF", "ON" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item >= 2)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int via_independent_hp_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = spec->hp_independent_mode;
return 0;
}
/* adjust spec->multiout setup according to the current flags */
static void setup_playback_multi_pcm(struct via_spec *spec)
{
const struct auto_pin_cfg *cfg = &spec->autocfg;
spec->multiout.num_dacs = cfg->line_outs + spec->smart51_nums;
spec->multiout.hp_nid = 0;
if (!spec->hp_independent_mode) {
if (!spec->hp_indep_shared)
spec->multiout.hp_nid = spec->hp_dac_nid;
} else {
if (spec->hp_indep_shared)
spec->multiout.num_dacs = cfg->line_outs - 1;
}
}
/* update DAC setups according to indep-HP switch;
* this function is called only when indep-HP is modified
*/
static void switch_indep_hp_dacs(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int shared = spec->hp_indep_shared;
hda_nid_t shared_dac, hp_dac;
if (!spec->opened_streams)
return;
shared_dac = shared ? spec->multiout.dac_nids[shared] : 0;
hp_dac = spec->hp_dac_nid;
if (spec->hp_independent_mode) {
/* switch to indep-HP mode */
if (spec->active_streams & STREAM_MULTI_OUT) {
__snd_hda_codec_cleanup_stream(codec, hp_dac, 1);
__snd_hda_codec_cleanup_stream(codec, shared_dac, 1);
}
if (spec->active_streams & STREAM_INDEP_HP)
snd_hda_codec_setup_stream(codec, hp_dac,
spec->cur_hp_stream_tag, 0,
spec->cur_hp_format);
} else {
/* back to HP or shared-DAC */
if (spec->active_streams & STREAM_INDEP_HP)
__snd_hda_codec_cleanup_stream(codec, hp_dac, 1);
if (spec->active_streams & STREAM_MULTI_OUT) {
hda_nid_t dac;
int ch;
if (shared_dac) { /* reset mutli-ch DAC */
dac = shared_dac;
ch = shared * 2;
} else { /* reset HP DAC */
dac = hp_dac;
ch = 0;
}
snd_hda_codec_setup_stream(codec, dac,
spec->cur_dac_stream_tag, ch,
spec->cur_dac_format);
}
}
setup_playback_multi_pcm(spec);
}
static int via_independent_hp_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
int cur, shared;
mutex_lock(&spec->config_mutex);
cur = !!ucontrol->value.enumerated.item[0];
if (spec->hp_independent_mode == cur) {
mutex_unlock(&spec->config_mutex);
return 0;
}
spec->hp_independent_mode = cur;
shared = spec->hp_indep_shared;
deactivate_hp_paths(codec);
if (cur)
activate_output_path(codec, &spec->hp_indep_path, true, false);
else {
if (shared)
activate_output_path(codec, &spec->out_path[shared],
true, false);
if (spec->aamix_mode || !spec->hp_path.depth)
activate_output_path(codec, &spec->hp_mix_path,
true, false);
else
activate_output_path(codec, &spec->hp_path,
true, false);
}
switch_indep_hp_dacs(codec);
mutex_unlock(&spec->config_mutex);
/* update jack power state */
set_widgets_power_state(codec);
via_hp_automute(codec);
return 1;
}
static const struct snd_kcontrol_new via_hp_mixer = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Independent HP",
.info = via_independent_hp_info,
.get = via_independent_hp_get,
.put = via_independent_hp_put,
};
static int via_hp_build(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct snd_kcontrol_new *knew;
hda_nid_t nid;
nid = spec->autocfg.hp_pins[0];
knew = via_clone_control(spec, &via_hp_mixer);
if (knew == NULL)
return -ENOMEM;
knew->subdevice = HDA_SUBDEV_NID_FLAG | nid;
return 0;
}
static void notify_aa_path_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->smart51_nums; i++) {
struct snd_kcontrol *ctl;
struct snd_ctl_elem_id id;
memset(&id, 0, sizeof(id));
id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
sprintf(id.name, "%s Playback Volume", spec->smart51_labels[i]);
ctl = snd_hda_find_mixer_ctl(codec, id.name);
if (ctl)
snd_ctl_notify(codec->bus->card,
SNDRV_CTL_EVENT_MASK_VALUE,
&ctl->id);
}
}
static void mute_aa_path(struct hda_codec *codec, int mute)
{
struct via_spec *spec = codec->spec;
int val = mute ? HDA_AMP_MUTE : HDA_AMP_UNMUTE;
int i;
/* check AA path's mute status */
for (i = 0; i < spec->smart51_nums; i++) {
if (spec->smart51_idxs[i] < 0)
continue;
snd_hda_codec_amp_stereo(codec, spec->aa_mix_nid,
HDA_INPUT, spec->smart51_idxs[i],
HDA_AMP_MUTE, val);
}
}
static bool is_smart51_pins(struct hda_codec *codec, hda_nid_t pin)
{
struct via_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->smart51_nums; i++)
if (spec->smart51_pins[i] == pin)
return true;
return false;
}
static int via_smart51_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
*ucontrol->value.integer.value = spec->smart51_enabled;
return 0;
}
static int via_smart51_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
int out_in = *ucontrol->value.integer.value
? AC_PINCTL_OUT_EN : AC_PINCTL_IN_EN;
int i;
for (i = 0; i < spec->smart51_nums; i++) {
hda_nid_t nid = spec->smart51_pins[i];
unsigned int parm;
parm = snd_hda_codec_read(codec, nid, 0,
AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
parm &= ~(AC_PINCTL_IN_EN | AC_PINCTL_OUT_EN);
parm |= out_in;
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
parm);
if (out_in == AC_PINCTL_OUT_EN) {
mute_aa_path(codec, 1);
notify_aa_path_ctls(codec);
}
}
spec->smart51_enabled = *ucontrol->value.integer.value;
set_widgets_power_state(codec);
return 1;
}
static const struct snd_kcontrol_new via_smart51_mixer = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Smart 5.1",
.count = 1,
.info = snd_ctl_boolean_mono_info,
.get = via_smart51_get,
.put = via_smart51_put,
};
static int via_smart51_build(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (!spec->smart51_nums)
return 0;
if (!via_clone_control(spec, &via_smart51_mixer))
return -ENOMEM;
return 0;
}
/* check AA path's mute status */
static bool is_aa_path_mute(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
const struct hda_amp_list *p;
int i, ch, v;
for (i = 0; i < spec->num_loopbacks; i++) {
p = &spec->loopback_list[i];
for (ch = 0; ch < 2; ch++) {
v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
p->idx);
if (!(v & HDA_AMP_MUTE) && v > 0)
return false;
}
}
return true;
}
/* enter/exit analog low-current mode */
static void __analog_low_current_mode(struct hda_codec *codec, bool force)
{
struct via_spec *spec = codec->spec;
bool enable;
unsigned int verb, parm;
if (spec->no_pin_power_ctl)
enable = false;
else
enable = is_aa_path_mute(codec) && !spec->opened_streams;
if (enable == spec->alc_mode && !force)
return;
spec->alc_mode = enable;
/* decide low current mode's verb & parameter */
switch (spec->codec_type) {
case VT1708B_8CH:
case VT1708B_4CH:
verb = 0xf70;
parm = enable ? 0x02 : 0x00; /* 0x02: 2/3x, 0x00: 1x */
break;
case VT1708S:
case VT1718S:
case VT1716S:
verb = 0xf73;
parm = enable ? 0x51 : 0xe1; /* 0x51: 4/28x, 0xe1: 1x */
break;
case VT1702:
verb = 0xf73;
parm = enable ? 0x01 : 0x1d; /* 0x01: 4/40x, 0x1d: 1x */
break;
case VT2002P:
case VT1812:
case VT1802:
verb = 0xf93;
parm = enable ? 0x00 : 0xe0; /* 0x00: 4/40x, 0xe0: 1x */
break;
default:
return; /* other codecs are not supported */
}
/* send verb */
snd_hda_codec_write(codec, codec->afg, 0, verb, parm);
}
static void analog_low_current_mode(struct hda_codec *codec)
{
return __analog_low_current_mode(codec, false);
}
/*
* generic initialization of ADC, input mixers and output mixers
*/
static const struct hda_verb vt1708_init_verbs[] = {
/* power down jack detect function */
{0x1, 0xf81, 0x1},
{ }
};
static void set_stream_open(struct hda_codec *codec, int bit, bool active)
{
struct via_spec *spec = codec->spec;
if (active)
spec->opened_streams |= bit;
else
spec->opened_streams &= ~bit;
analog_low_current_mode(codec);
}
static int via_playback_multi_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
const struct auto_pin_cfg *cfg = &spec->autocfg;
int err;
spec->multiout.num_dacs = cfg->line_outs + spec->smart51_nums;
spec->multiout.max_channels = spec->multiout.num_dacs * 2;
set_stream_open(codec, STREAM_MULTI_OUT, true);
err = snd_hda_multi_out_analog_open(codec, &spec->multiout, substream,
hinfo);
if (err < 0) {
set_stream_open(codec, STREAM_MULTI_OUT, false);
return err;
}
return 0;
}
static int via_playback_multi_pcm_close(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
set_stream_open(codec, STREAM_MULTI_OUT, false);
return 0;
}
static int via_playback_hp_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
if (snd_BUG_ON(!spec->hp_dac_nid))
return -EINVAL;
set_stream_open(codec, STREAM_INDEP_HP, true);
return 0;
}
static int via_playback_hp_pcm_close(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
set_stream_open(codec, STREAM_INDEP_HP, false);
return 0;
}
static int via_playback_multi_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
mutex_lock(&spec->config_mutex);
setup_playback_multi_pcm(spec);
snd_hda_multi_out_analog_prepare(codec, &spec->multiout, stream_tag,
format, substream);
/* remember for dynamic DAC switch with indep-HP */
spec->active_streams |= STREAM_MULTI_OUT;
spec->cur_dac_stream_tag = stream_tag;
spec->cur_dac_format = format;
mutex_unlock(&spec->config_mutex);
vt1708_update_hp_work(spec);
return 0;
}
static int via_playback_hp_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
mutex_lock(&spec->config_mutex);
if (spec->hp_independent_mode)
snd_hda_codec_setup_stream(codec, spec->hp_dac_nid,
stream_tag, 0, format);
spec->active_streams |= STREAM_INDEP_HP;
spec->cur_hp_stream_tag = stream_tag;
spec->cur_hp_format = format;
mutex_unlock(&spec->config_mutex);
vt1708_update_hp_work(spec);
return 0;
}
static int via_playback_multi_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
mutex_lock(&spec->config_mutex);
snd_hda_multi_out_analog_cleanup(codec, &spec->multiout);
spec->active_streams &= ~STREAM_MULTI_OUT;
mutex_unlock(&spec->config_mutex);
vt1708_update_hp_work(spec);
return 0;
}
static int via_playback_hp_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
mutex_lock(&spec->config_mutex);
if (spec->hp_independent_mode)
snd_hda_codec_setup_stream(codec, spec->hp_dac_nid, 0, 0, 0);
spec->active_streams &= ~STREAM_INDEP_HP;
mutex_unlock(&spec->config_mutex);
vt1708_update_hp_work(spec);
return 0;
}
/*
* Digital out
*/
static int via_dig_playback_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
return snd_hda_multi_out_dig_open(codec, &spec->multiout);
}
static int via_dig_playback_pcm_close(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
return snd_hda_multi_out_dig_close(codec, &spec->multiout);
}
static int via_dig_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
return snd_hda_multi_out_dig_prepare(codec, &spec->multiout,
stream_tag, format, substream);
}
static int via_dig_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
snd_hda_multi_out_dig_cleanup(codec, &spec->multiout);
return 0;
}
/*
* Analog capture
*/
static int via_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
snd_hda_codec_setup_stream(codec, spec->adc_nids[substream->number],
stream_tag, 0, format);
return 0;
}
static int via_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
snd_hda_codec_cleanup_stream(codec, spec->adc_nids[substream->number]);
return 0;
}
/* analog capture with dynamic ADC switching */
static int via_dyn_adc_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
int adc_idx = spec->inputs[spec->cur_mux[0]].adc_idx;
mutex_lock(&spec->config_mutex);
spec->cur_adc = spec->adc_nids[adc_idx];
spec->cur_adc_stream_tag = stream_tag;
spec->cur_adc_format = format;
snd_hda_codec_setup_stream(codec, spec->cur_adc, stream_tag, 0, format);
mutex_unlock(&spec->config_mutex);
return 0;
}
static int via_dyn_adc_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct via_spec *spec = codec->spec;
mutex_lock(&spec->config_mutex);
snd_hda_codec_cleanup_stream(codec, spec->cur_adc);
spec->cur_adc = 0;
mutex_unlock(&spec->config_mutex);
return 0;
}
/* re-setup the stream if running; called from input-src put */
static bool via_dyn_adc_pcm_resetup(struct hda_codec *codec, int cur)
{
struct via_spec *spec = codec->spec;
int adc_idx = spec->inputs[cur].adc_idx;
hda_nid_t adc = spec->adc_nids[adc_idx];
bool ret = false;
mutex_lock(&spec->config_mutex);
if (spec->cur_adc && spec->cur_adc != adc) {
/* stream is running, let's swap the current ADC */
__snd_hda_codec_cleanup_stream(codec, spec->cur_adc, 1);
spec->cur_adc = adc;
snd_hda_codec_setup_stream(codec, adc,
spec->cur_adc_stream_tag, 0,
spec->cur_adc_format);
ret = true;
}
mutex_unlock(&spec->config_mutex);
return ret;
}
static const struct hda_pcm_stream via_pcm_analog_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 8,
/* NID is set in via_build_pcms */
.ops = {
.open = via_playback_multi_pcm_open,
.close = via_playback_multi_pcm_close,
.prepare = via_playback_multi_pcm_prepare,
.cleanup = via_playback_multi_pcm_cleanup
},
};
static const struct hda_pcm_stream via_pcm_hp_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
/* NID is set in via_build_pcms */
.ops = {
.open = via_playback_hp_pcm_open,
.close = via_playback_hp_pcm_close,
.prepare = via_playback_hp_pcm_prepare,
.cleanup = via_playback_hp_pcm_cleanup
},
};
static const struct hda_pcm_stream vt1708_pcm_analog_s16_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 8,
/* NID is set in via_build_pcms */
/* We got noisy outputs on the right channel on VT1708 when
* 24bit samples are used. Until any workaround is found,
* disable the 24bit format, so far.
*/
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.ops = {
.open = via_playback_multi_pcm_open,
.close = via_playback_multi_pcm_close,
.prepare = via_playback_multi_pcm_prepare,
.cleanup = via_playback_multi_pcm_cleanup
},
};
static const struct hda_pcm_stream via_pcm_analog_capture = {
.substreams = 1, /* will be changed in via_build_pcms() */
.channels_min = 2,
.channels_max = 2,
/* NID is set in via_build_pcms */
.ops = {
.prepare = via_capture_pcm_prepare,
.cleanup = via_capture_pcm_cleanup
},
};
static const struct hda_pcm_stream via_pcm_dyn_adc_analog_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
/* NID is set in via_build_pcms */
.ops = {
.prepare = via_dyn_adc_capture_pcm_prepare,
.cleanup = via_dyn_adc_capture_pcm_cleanup,
},
};
static const struct hda_pcm_stream via_pcm_digital_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
/* NID is set in via_build_pcms */
.ops = {
.open = via_dig_playback_pcm_open,
.close = via_dig_playback_pcm_close,
.prepare = via_dig_playback_pcm_prepare,
.cleanup = via_dig_playback_pcm_cleanup
},
};
static const struct hda_pcm_stream via_pcm_digital_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
};
/*
* slave controls for virtual master
*/
static const char * const via_slave_pfxs[] = {
"Front", "Surround", "Center", "LFE", "Side",
"Headphone", "Speaker",
NULL,
};
static int via_build_controls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct snd_kcontrol *kctl;
int err, i;
spec->no_pin_power_ctl = 1;
if (spec->set_widgets_power_state)
if (!via_clone_control(spec, &via_pin_power_ctl_enum))
return -ENOMEM;
for (i = 0; i < spec->num_mixers; i++) {
err = snd_hda_add_new_ctls(codec, spec->mixers[i]);
if (err < 0)
return err;
}
if (spec->multiout.dig_out_nid) {
err = snd_hda_create_spdif_out_ctls(codec,
spec->multiout.dig_out_nid,
spec->multiout.dig_out_nid);
if (err < 0)
return err;
err = snd_hda_create_spdif_share_sw(codec,
&spec->multiout);
if (err < 0)
return err;
spec->multiout.share_spdif = 1;
}
if (spec->dig_in_nid) {
err = snd_hda_create_spdif_in_ctls(codec, spec->dig_in_nid);
if (err < 0)
return err;
}
/* if we have no master control, let's create it */
if (!snd_hda_find_mixer_ctl(codec, "Master Playback Volume")) {
unsigned int vmaster_tlv[4];
snd_hda_set_vmaster_tlv(codec, spec->multiout.dac_nids[0],
HDA_OUTPUT, vmaster_tlv);
err = snd_hda_add_vmaster(codec, "Master Playback Volume",
vmaster_tlv, via_slave_pfxs,
"Playback Volume");
if (err < 0)
return err;
}
if (!snd_hda_find_mixer_ctl(codec, "Master Playback Switch")) {
err = snd_hda_add_vmaster(codec, "Master Playback Switch",
NULL, via_slave_pfxs,
"Playback Switch");
if (err < 0)
return err;
}
/* assign Capture Source enums to NID */
kctl = snd_hda_find_mixer_ctl(codec, "Input Source");
for (i = 0; kctl && i < kctl->count; i++) {
if (!spec->mux_nids[i])
continue;
err = snd_hda_add_nid(codec, kctl, i, spec->mux_nids[i]);
if (err < 0)
return err;
}
via_free_kctls(codec); /* no longer needed */
err = snd_hda_jack_add_kctls(codec, &spec->autocfg);
if (err < 0)
return err;
return 0;
}
static int via_build_pcms(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct hda_pcm *info = spec->pcm_rec;
codec->num_pcms = 0;
codec->pcm_info = info;
if (spec->multiout.num_dacs || spec->num_adc_nids) {
snprintf(spec->stream_name_analog,
sizeof(spec->stream_name_analog),
"%s Analog", codec->chip_name);
info->name = spec->stream_name_analog;
if (spec->multiout.num_dacs) {
if (!spec->stream_analog_playback)
spec->stream_analog_playback =
&via_pcm_analog_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK] =
*spec->stream_analog_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid =
spec->multiout.dac_nids[0];
info->stream[SNDRV_PCM_STREAM_PLAYBACK].channels_max =
spec->multiout.max_channels;
}
if (!spec->stream_analog_capture) {
if (spec->dyn_adc_switch)
spec->stream_analog_capture =
&via_pcm_dyn_adc_analog_capture;
else
spec->stream_analog_capture =
&via_pcm_analog_capture;
}
if (spec->num_adc_nids) {
info->stream[SNDRV_PCM_STREAM_CAPTURE] =
*spec->stream_analog_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid =
spec->adc_nids[0];
if (!spec->dyn_adc_switch)
info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams =
spec->num_adc_nids;
}
codec->num_pcms++;
info++;
}
if (spec->multiout.dig_out_nid || spec->dig_in_nid) {
snprintf(spec->stream_name_digital,
sizeof(spec->stream_name_digital),
"%s Digital", codec->chip_name);
info->name = spec->stream_name_digital;
info->pcm_type = HDA_PCM_TYPE_SPDIF;
if (spec->multiout.dig_out_nid) {
if (!spec->stream_digital_playback)
spec->stream_digital_playback =
&via_pcm_digital_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK] =
*spec->stream_digital_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid =
spec->multiout.dig_out_nid;
}
if (spec->dig_in_nid) {
if (!spec->stream_digital_capture)
spec->stream_digital_capture =
&via_pcm_digital_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE] =
*spec->stream_digital_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid =
spec->dig_in_nid;
}
codec->num_pcms++;
info++;
}
if (spec->hp_dac_nid) {
snprintf(spec->stream_name_hp, sizeof(spec->stream_name_hp),
"%s HP", codec->chip_name);
info->name = spec->stream_name_hp;
info->stream[SNDRV_PCM_STREAM_PLAYBACK] = via_pcm_hp_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid =
spec->hp_dac_nid;
codec->num_pcms++;
info++;
}
return 0;
}
static void via_free(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (!spec)
return;
via_free_kctls(codec);
vt1708_stop_hp_work(spec);
kfree(spec->bind_cap_vol);
kfree(spec->bind_cap_sw);
kfree(spec);
}
/* mute/unmute outputs */
static void toggle_output_mutes(struct hda_codec *codec, int num_pins,
hda_nid_t *pins, bool mute)
{
int i;
for (i = 0; i < num_pins; i++) {
unsigned int parm = snd_hda_codec_read(codec, pins[i], 0,
AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
if (parm & AC_PINCTL_IN_EN)
continue;
if (mute)
parm &= ~AC_PINCTL_OUT_EN;
else
parm |= AC_PINCTL_OUT_EN;
snd_hda_codec_write(codec, pins[i], 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, parm);
}
}
/* mute internal speaker if line-out is plugged */
static void via_line_automute(struct hda_codec *codec, int present)
{
struct via_spec *spec = codec->spec;
if (!spec->autocfg.speaker_outs)
return;
if (!present)
present = snd_hda_jack_detect(codec,
spec->autocfg.line_out_pins[0]);
toggle_output_mutes(codec, spec->autocfg.speaker_outs,
spec->autocfg.speaker_pins,
present);
}
/* mute internal speaker if HP is plugged */
static void via_hp_automute(struct hda_codec *codec)
{
int present = 0;
int nums;
struct via_spec *spec = codec->spec;
if (!spec->hp_independent_mode && spec->autocfg.hp_pins[0] &&
(spec->codec_type != VT1708 || spec->vt1708_jack_detect))
present = snd_hda_jack_detect(codec, spec->autocfg.hp_pins[0]);
if (spec->smart51_enabled)
nums = spec->autocfg.line_outs + spec->smart51_nums;
else
nums = spec->autocfg.line_outs;
toggle_output_mutes(codec, nums, spec->autocfg.line_out_pins, present);
via_line_automute(codec, present);
}
static void via_gpio_control(struct hda_codec *codec)
{
unsigned int gpio_data;
unsigned int vol_counter;
unsigned int vol;
unsigned int master_vol;
struct via_spec *spec = codec->spec;
gpio_data = snd_hda_codec_read(codec, codec->afg, 0,
AC_VERB_GET_GPIO_DATA, 0) & 0x03;
vol_counter = (snd_hda_codec_read(codec, codec->afg, 0,
0xF84, 0) & 0x3F0000) >> 16;
vol = vol_counter & 0x1F;
master_vol = snd_hda_codec_read(codec, 0x1A, 0,
AC_VERB_GET_AMP_GAIN_MUTE,
AC_AMP_GET_INPUT);
if (gpio_data == 0x02) {
/* unmute line out */
snd_hda_codec_write(codec, spec->autocfg.line_out_pins[0], 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
PIN_OUT);
if (vol_counter & 0x20) {
/* decrease volume */
if (vol > master_vol)
vol = master_vol;
snd_hda_codec_amp_stereo(codec, 0x1A, HDA_INPUT,
0, HDA_AMP_VOLMASK,
master_vol-vol);
} else {
/* increase volume */
snd_hda_codec_amp_stereo(codec, 0x1A, HDA_INPUT, 0,
HDA_AMP_VOLMASK,
((master_vol+vol) > 0x2A) ? 0x2A :
(master_vol+vol));
}
} else if (!(gpio_data & 0x02)) {
/* mute line out */
snd_hda_codec_write(codec, spec->autocfg.line_out_pins[0], 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
0);
}
}
/* unsolicited event for jack sensing */
static void via_unsol_event(struct hda_codec *codec,
unsigned int res)
{
res >>= 26;
res = snd_hda_jack_get_action(codec, res);
if (res & VIA_JACK_EVENT)
set_widgets_power_state(codec);
res &= ~VIA_JACK_EVENT;
if (res == VIA_HP_EVENT || res == VIA_LINE_EVENT)
via_hp_automute(codec);
else if (res == VIA_GPIO_EVENT)
via_gpio_control(codec);
snd_hda_jack_report_sync(codec);
}
#ifdef CONFIG_PM
static int via_suspend(struct hda_codec *codec, pm_message_t state)
{
struct via_spec *spec = codec->spec;
vt1708_stop_hp_work(spec);
return 0;
}
#endif
#ifdef CONFIG_SND_HDA_POWER_SAVE
static int via_check_power_status(struct hda_codec *codec, hda_nid_t nid)
{
struct via_spec *spec = codec->spec;
return snd_hda_check_amp_list_power(codec, &spec->loopback, nid);
}
#endif
/*
*/
static int via_init(struct hda_codec *codec);
static const struct hda_codec_ops via_patch_ops = {
.build_controls = via_build_controls,
.build_pcms = via_build_pcms,
.init = via_init,
.free = via_free,
.unsol_event = via_unsol_event,
#ifdef CONFIG_PM
.suspend = via_suspend,
#endif
#ifdef CONFIG_SND_HDA_POWER_SAVE
.check_power_status = via_check_power_status,
#endif
};
static bool is_empty_dac(struct hda_codec *codec, hda_nid_t dac)
{
struct via_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->multiout.num_dacs; i++) {
if (spec->multiout.dac_nids[i] == dac)
return false;
}
if (spec->hp_dac_nid == dac)
return false;
return true;
}
static bool __parse_output_path(struct hda_codec *codec, hda_nid_t nid,
hda_nid_t target_dac, int with_aa_mix,
struct nid_path *path, int depth)
{
struct via_spec *spec = codec->spec;
hda_nid_t conn[8];
int i, nums;
if (nid == spec->aa_mix_nid) {
if (!with_aa_mix)
return false;
with_aa_mix = 2; /* mark aa-mix is included */
}
nums = snd_hda_get_connections(codec, nid, conn, ARRAY_SIZE(conn));
for (i = 0; i < nums; i++) {
if (get_wcaps_type(get_wcaps(codec, conn[i])) != AC_WID_AUD_OUT)
continue;
if (conn[i] == target_dac || is_empty_dac(codec, conn[i])) {
/* aa-mix is requested but not included? */
if (!(spec->aa_mix_nid && with_aa_mix == 1))
goto found;
}
}
if (depth >= MAX_NID_PATH_DEPTH)
return false;
for (i = 0; i < nums; i++) {
unsigned int type;
type = get_wcaps_type(get_wcaps(codec, conn[i]));
if (type == AC_WID_AUD_OUT)
continue;
if (__parse_output_path(codec, conn[i], target_dac,
with_aa_mix, path, depth + 1))
goto found;
}
return false;
found:
path->path[path->depth] = conn[i];
path->idx[path->depth] = i;
if (nums > 1 && get_wcaps_type(get_wcaps(codec, nid)) != AC_WID_AUD_MIX)
path->multi[path->depth] = 1;
path->depth++;
return true;
}
static bool parse_output_path(struct hda_codec *codec, hda_nid_t nid,
hda_nid_t target_dac, int with_aa_mix,
struct nid_path *path)
{
if (__parse_output_path(codec, nid, target_dac, with_aa_mix, path, 1)) {
path->path[path->depth] = nid;
path->depth++;
snd_printdd("output-path: depth=%d, %02x/%02x/%02x/%02x/%02x\n",
path->depth, path->path[0], path->path[1],
path->path[2], path->path[3], path->path[4]);
return true;
}
return false;
}
static int via_auto_fill_dac_nids(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
const struct auto_pin_cfg *cfg = &spec->autocfg;
int i, dac_num;
hda_nid_t nid;
spec->multiout.dac_nids = spec->private_dac_nids;
dac_num = 0;
for (i = 0; i < cfg->line_outs; i++) {
hda_nid_t dac = 0;
nid = cfg->line_out_pins[i];
if (!nid)
continue;
if (parse_output_path(codec, nid, 0, 0, &spec->out_path[i]))
dac = spec->out_path[i].path[0];
if (!i && parse_output_path(codec, nid, dac, 1,
&spec->out_mix_path))
dac = spec->out_mix_path.path[0];
if (dac) {
spec->private_dac_nids[i] = dac;
dac_num++;
}
}
if (!spec->out_path[0].depth && spec->out_mix_path.depth) {
spec->out_path[0] = spec->out_mix_path;
spec->out_mix_path.depth = 0;
}
spec->multiout.num_dacs = dac_num;
return 0;
}
static int create_ch_ctls(struct hda_codec *codec, const char *pfx,
int chs, bool check_dac, struct nid_path *path)
{
struct via_spec *spec = codec->spec;
char name[32];
hda_nid_t dac, pin, sel, nid;
int err;
dac = check_dac ? path->path[0] : 0;
pin = path->path[path->depth - 1];
sel = path->depth > 1 ? path->path[1] : 0;
if (dac && check_amp_caps(codec, dac, HDA_OUTPUT, AC_AMPCAP_NUM_STEPS))
nid = dac;
else if (check_amp_caps(codec, pin, HDA_OUTPUT, AC_AMPCAP_NUM_STEPS))
nid = pin;
else if (check_amp_caps(codec, sel, HDA_OUTPUT, AC_AMPCAP_NUM_STEPS))
nid = sel;
else
nid = 0;
if (nid) {
sprintf(name, "%s Playback Volume", pfx);
err = via_add_control(spec, VIA_CTL_WIDGET_VOL, name,
HDA_COMPOSE_AMP_VAL(nid, chs, 0, HDA_OUTPUT));
if (err < 0)
return err;
path->vol_ctl = nid;
}
if (dac && check_amp_caps(codec, dac, HDA_OUTPUT, AC_AMPCAP_MUTE))
nid = dac;
else if (check_amp_caps(codec, pin, HDA_OUTPUT, AC_AMPCAP_MUTE))
nid = pin;
else if (check_amp_caps(codec, sel, HDA_OUTPUT, AC_AMPCAP_MUTE))
nid = sel;
else
nid = 0;
if (nid) {
sprintf(name, "%s Playback Switch", pfx);
err = via_add_control(spec, VIA_CTL_WIDGET_MUTE, name,
HDA_COMPOSE_AMP_VAL(nid, chs, 0, HDA_OUTPUT));
if (err < 0)
return err;
path->mute_ctl = nid;
}
return 0;
}
static void mangle_smart51(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
struct auto_pin_cfg_item *ins = cfg->inputs;
int i, j, nums, attr;
int pins[AUTO_CFG_MAX_INS];
for (attr = INPUT_PIN_ATTR_REAR; attr >= INPUT_PIN_ATTR_NORMAL; attr--) {
nums = 0;
for (i = 0; i < cfg->num_inputs; i++) {
unsigned int def;
if (ins[i].type > AUTO_PIN_LINE_IN)
continue;
def = snd_hda_codec_get_pincfg(codec, ins[i].pin);
if (snd_hda_get_input_pin_attr(def) != attr)
continue;
for (j = 0; j < nums; j++)
if (ins[pins[j]].type < ins[i].type) {
memmove(pins + j + 1, pins + j,
(nums - j) * sizeof(int));
break;
}
pins[j] = i;
nums++;
}
if (cfg->line_outs + nums < 3)
continue;
for (i = 0; i < nums; i++) {
hda_nid_t pin = ins[pins[i]].pin;
spec->smart51_pins[spec->smart51_nums++] = pin;
cfg->line_out_pins[cfg->line_outs++] = pin;
if (cfg->line_outs == 3)
break;
}
return;
}
}
static void copy_path_mixer_ctls(struct nid_path *dst, struct nid_path *src)
{
dst->vol_ctl = src->vol_ctl;
dst->mute_ctl = src->mute_ctl;
}
/* add playback controls from the parsed DAC table */
static int via_auto_create_multi_out_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
struct nid_path *path;
static const char * const chname[4] = {
"Front", "Surround", "C/LFE", "Side"
};
int i, idx, err;
int old_line_outs;
/* check smart51 */
old_line_outs = cfg->line_outs;
if (cfg->line_outs == 1)
mangle_smart51(codec);
err = via_auto_fill_dac_nids(codec);
if (err < 0)
return err;
if (spec->multiout.num_dacs < 3) {
spec->smart51_nums = 0;
cfg->line_outs = old_line_outs;
}
for (i = 0; i < cfg->line_outs; i++) {
hda_nid_t pin, dac;
pin = cfg->line_out_pins[i];
dac = spec->multiout.dac_nids[i];
if (!pin || !dac)
continue;
path = spec->out_path + i;
if (i == HDA_CLFE) {
err = create_ch_ctls(codec, "Center", 1, true, path);
if (err < 0)
return err;
err = create_ch_ctls(codec, "LFE", 2, true, path);
if (err < 0)
return err;
} else {
const char *pfx = chname[i];
if (cfg->line_out_type == AUTO_PIN_SPEAKER_OUT &&
cfg->line_outs == 1)
pfx = "Speaker";
err = create_ch_ctls(codec, pfx, 3, true, path);
if (err < 0)
return err;
}
if (path != spec->out_path + i)
copy_path_mixer_ctls(&spec->out_path[i], path);
if (path == spec->out_path && spec->out_mix_path.depth)
copy_path_mixer_ctls(&spec->out_mix_path, path);
}
idx = get_connection_index(codec, spec->aa_mix_nid,
spec->multiout.dac_nids[0]);
if (idx >= 0) {
/* add control to mixer */
const char *name;
name = spec->out_mix_path.depth ?
"PCM Loopback Playback Volume" : "PCM Playback Volume";
err = via_add_control(spec, VIA_CTL_WIDGET_VOL, name,
HDA_COMPOSE_AMP_VAL(spec->aa_mix_nid, 3,
idx, HDA_INPUT));
if (err < 0)
return err;
name = spec->out_mix_path.depth ?
"PCM Loopback Playback Switch" : "PCM Playback Switch";
err = via_add_control(spec, VIA_CTL_WIDGET_MUTE, name,
HDA_COMPOSE_AMP_VAL(spec->aa_mix_nid, 3,
idx, HDA_INPUT));
if (err < 0)
return err;
}
cfg->line_outs = old_line_outs;
return 0;
}
static int via_auto_create_hp_ctls(struct hda_codec *codec, hda_nid_t pin)
{
struct via_spec *spec = codec->spec;
struct nid_path *path;
bool check_dac;
int i, err;
if (!pin)
return 0;
if (!parse_output_path(codec, pin, 0, 0, &spec->hp_indep_path)) {
for (i = HDA_SIDE; i >= HDA_CLFE; i--) {
if (i < spec->multiout.num_dacs &&
parse_output_path(codec, pin,
spec->multiout.dac_nids[i], 0,
&spec->hp_indep_path)) {
spec->hp_indep_shared = i;
break;
}
}
}
if (spec->hp_indep_path.depth) {
spec->hp_dac_nid = spec->hp_indep_path.path[0];
if (!spec->hp_indep_shared)
spec->hp_path = spec->hp_indep_path;
}
/* optionally check front-path w/o AA-mix */
if (!spec->hp_path.depth)
parse_output_path(codec, pin,
spec->multiout.dac_nids[HDA_FRONT], 0,
&spec->hp_path);
if (!parse_output_path(codec, pin, spec->multiout.dac_nids[HDA_FRONT],
1, &spec->hp_mix_path) && !spec->hp_path.depth)
return 0;
if (spec->hp_path.depth) {
path = &spec->hp_path;
check_dac = true;
} else {
path = &spec->hp_mix_path;
check_dac = false;
}
err = create_ch_ctls(codec, "Headphone", 3, check_dac, path);
if (err < 0)
return err;
if (check_dac)
copy_path_mixer_ctls(&spec->hp_mix_path, path);
else
copy_path_mixer_ctls(&spec->hp_path, path);
if (spec->hp_indep_path.depth)
copy_path_mixer_ctls(&spec->hp_indep_path, path);
return 0;
}
static int via_auto_create_speaker_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct nid_path *path;
bool check_dac;
hda_nid_t pin, dac = 0;
int err;
pin = spec->autocfg.speaker_pins[0];
if (!spec->autocfg.speaker_outs || !pin)
return 0;
if (parse_output_path(codec, pin, 0, 0, &spec->speaker_path))
dac = spec->speaker_path.path[0];
if (!dac)
parse_output_path(codec, pin,
spec->multiout.dac_nids[HDA_FRONT], 0,
&spec->speaker_path);
if (!parse_output_path(codec, pin, spec->multiout.dac_nids[HDA_FRONT],
1, &spec->speaker_mix_path) && !dac)
return 0;
/* no AA-path for front? */
if (!spec->out_mix_path.depth && spec->speaker_mix_path.depth)
dac = 0;
spec->speaker_dac_nid = dac;
spec->multiout.extra_out_nid[0] = dac;
if (dac) {
path = &spec->speaker_path;
check_dac = true;
} else {
path = &spec->speaker_mix_path;
check_dac = false;
}
err = create_ch_ctls(codec, "Speaker", 3, check_dac, path);
if (err < 0)
return err;
if (check_dac)
copy_path_mixer_ctls(&spec->speaker_mix_path, path);
else
copy_path_mixer_ctls(&spec->speaker_path, path);
return 0;
}
#define via_aamix_ctl_info via_pin_power_ctl_info
static int via_aamix_ctl_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = spec->aamix_mode;
return 0;
}
static void update_aamix_paths(struct hda_codec *codec, int do_mix,
struct nid_path *nomix, struct nid_path *mix)
{
if (do_mix) {
activate_output_path(codec, nomix, false, false);
activate_output_path(codec, mix, true, false);
} else {
activate_output_path(codec, mix, false, false);
activate_output_path(codec, nomix, true, false);
}
}
static int via_aamix_ctl_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
unsigned int val = ucontrol->value.enumerated.item[0];
if (val == spec->aamix_mode)
return 0;
spec->aamix_mode = val;
/* update front path */
update_aamix_paths(codec, val, &spec->out_path[0], &spec->out_mix_path);
/* update HP path */
if (!spec->hp_independent_mode) {
update_aamix_paths(codec, val, &spec->hp_path,
&spec->hp_mix_path);
}
/* update speaker path */
update_aamix_paths(codec, val, &spec->speaker_path,
&spec->speaker_mix_path);
return 1;
}
static const struct snd_kcontrol_new via_aamix_ctl_enum = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Loopback Mixing",
.info = via_aamix_ctl_info,
.get = via_aamix_ctl_get,
.put = via_aamix_ctl_put,
};
static int via_auto_create_loopback_switch(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (!spec->aa_mix_nid)
return 0; /* no loopback switching available */
if (!(spec->out_mix_path.depth || spec->hp_mix_path.depth ||
spec->speaker_path.depth))
return 0; /* no loopback switching available */
if (!via_clone_control(spec, &via_aamix_ctl_enum))
return -ENOMEM;
return 0;
}
/* look for ADCs */
static int via_fill_adcs(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
hda_nid_t nid = codec->start_nid;
int i;
for (i = 0; i < codec->num_nodes; i++, nid++) {
unsigned int wcaps = get_wcaps(codec, nid);
if (get_wcaps_type(wcaps) != AC_WID_AUD_IN)
continue;
if (wcaps & AC_WCAP_DIGITAL)
continue;
if (!(wcaps & AC_WCAP_CONN_LIST))
continue;
if (spec->num_adc_nids >= ARRAY_SIZE(spec->adc_nids))
return -ENOMEM;
spec->adc_nids[spec->num_adc_nids++] = nid;
}
return 0;
}
/* input-src control */
static int via_mux_enum_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = spec->num_inputs;
if (uinfo->value.enumerated.item >= spec->num_inputs)
uinfo->value.enumerated.item = spec->num_inputs - 1;
strcpy(uinfo->value.enumerated.name,
spec->inputs[uinfo->value.enumerated.item].label);
return 0;
}
static int via_mux_enum_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
ucontrol->value.enumerated.item[0] = spec->cur_mux[idx];
return 0;
}
static int via_mux_enum_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
hda_nid_t mux;
int cur;
cur = ucontrol->value.enumerated.item[0];
if (cur < 0 || cur >= spec->num_inputs)
return -EINVAL;
if (spec->cur_mux[idx] == cur)
return 0;
spec->cur_mux[idx] = cur;
if (spec->dyn_adc_switch) {
int adc_idx = spec->inputs[cur].adc_idx;
mux = spec->mux_nids[adc_idx];
via_dyn_adc_pcm_resetup(codec, cur);
} else {
mux = spec->mux_nids[idx];
if (snd_BUG_ON(!mux))
return -EINVAL;
}
if (mux) {
/* switch to D0 beofre change index */
update_power_state(codec, mux, AC_PWRST_D0);
snd_hda_codec_write(codec, mux, 0,
AC_VERB_SET_CONNECT_SEL,
spec->inputs[cur].mux_idx);
}
/* update jack power state */
set_widgets_power_state(codec);
return 0;
}
static const struct snd_kcontrol_new via_input_src_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.info = via_mux_enum_info,
.get = via_mux_enum_get,
.put = via_mux_enum_put,
};
static int create_input_src_ctls(struct hda_codec *codec, int count)
{
struct via_spec *spec = codec->spec;
struct snd_kcontrol_new *knew;
if (spec->num_inputs <= 1 || !count)
return 0; /* no need for single src */
knew = via_clone_control(spec, &via_input_src_ctl);
if (!knew)
return -ENOMEM;
knew->count = count;
return 0;
}
/* add the powersave loopback-list entry */
static void add_loopback_list(struct via_spec *spec, hda_nid_t mix, int idx)
{
struct hda_amp_list *list;
if (spec->num_loopbacks >= ARRAY_SIZE(spec->loopback_list) - 1)
return;
list = spec->loopback_list + spec->num_loopbacks;
list->nid = mix;
list->dir = HDA_INPUT;
list->idx = idx;
spec->num_loopbacks++;
spec->loopback.amplist = spec->loopback_list;
}
static bool is_reachable_nid(struct hda_codec *codec, hda_nid_t src,
hda_nid_t dst)
{
return snd_hda_get_conn_index(codec, src, dst, 1) >= 0;
}
/* add the input-route to the given pin */
static bool add_input_route(struct hda_codec *codec, hda_nid_t pin)
{
struct via_spec *spec = codec->spec;
int c, idx;
spec->inputs[spec->num_inputs].adc_idx = -1;
spec->inputs[spec->num_inputs].pin = pin;
for (c = 0; c < spec->num_adc_nids; c++) {
if (spec->mux_nids[c]) {
idx = get_connection_index(codec, spec->mux_nids[c],
pin);
if (idx < 0)
continue;
spec->inputs[spec->num_inputs].mux_idx = idx;
} else {
if (!is_reachable_nid(codec, spec->adc_nids[c], pin))
continue;
}
spec->inputs[spec->num_inputs].adc_idx = c;
/* Can primary ADC satisfy all inputs? */
if (!spec->dyn_adc_switch &&
spec->num_inputs > 0 && spec->inputs[0].adc_idx != c) {
snd_printd(KERN_INFO
"via: dynamic ADC switching enabled\n");
spec->dyn_adc_switch = 1;
}
return true;
}
return false;
}
static int get_mux_nids(struct hda_codec *codec);
/* parse input-routes; fill ADCs, MUXs and input-src entries */
static int parse_analog_inputs(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
const struct auto_pin_cfg *cfg = &spec->autocfg;
int i, err;
err = via_fill_adcs(codec);
if (err < 0)
return err;
err = get_mux_nids(codec);
if (err < 0)
return err;
/* fill all input-routes */
for (i = 0; i < cfg->num_inputs; i++) {
if (add_input_route(codec, cfg->inputs[i].pin))
spec->inputs[spec->num_inputs++].label =
hda_get_autocfg_input_label(codec, cfg, i);
}
/* check for internal loopback recording */
if (spec->aa_mix_nid &&
add_input_route(codec, spec->aa_mix_nid))
spec->inputs[spec->num_inputs++].label = "Stereo Mixer";
return 0;
}
/* create analog-loopback volume/switch controls */
static int create_loopback_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
const struct auto_pin_cfg *cfg = &spec->autocfg;
const char *prev_label = NULL;
int type_idx = 0;
int i, j, err, idx;
if (!spec->aa_mix_nid)
return 0;
for (i = 0; i < cfg->num_inputs; i++) {
hda_nid_t pin = cfg->inputs[i].pin;
const char *label = hda_get_autocfg_input_label(codec, cfg, i);
if (prev_label && !strcmp(label, prev_label))
type_idx++;
else
type_idx = 0;
prev_label = label;
idx = get_connection_index(codec, spec->aa_mix_nid, pin);
if (idx >= 0) {
err = via_new_analog_input(spec, label, type_idx,
idx, spec->aa_mix_nid);
if (err < 0)
return err;
add_loopback_list(spec, spec->aa_mix_nid, idx);
}
/* remember the label for smart51 control */
for (j = 0; j < spec->smart51_nums; j++) {
if (spec->smart51_pins[j] == pin) {
spec->smart51_idxs[j] = idx;
spec->smart51_labels[j] = label;
break;
}
}
}
return 0;
}
/* create mic-boost controls (if present) */
static int create_mic_boost_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
const struct auto_pin_cfg *cfg = &spec->autocfg;
const char *prev_label = NULL;
int type_idx = 0;
int i, err;
for (i = 0; i < cfg->num_inputs; i++) {
hda_nid_t pin = cfg->inputs[i].pin;
unsigned int caps;
const char *label;
char name[32];
if (cfg->inputs[i].type != AUTO_PIN_MIC)
continue;
caps = query_amp_caps(codec, pin, HDA_INPUT);
if (caps == -1 || !(caps & AC_AMPCAP_NUM_STEPS))
continue;
label = hda_get_autocfg_input_label(codec, cfg, i);
if (prev_label && !strcmp(label, prev_label))
type_idx++;
else
type_idx = 0;
prev_label = label;
snprintf(name, sizeof(name), "%s Boost Volume", label);
err = __via_add_control(spec, VIA_CTL_WIDGET_VOL, name, type_idx,
HDA_COMPOSE_AMP_VAL(pin, 3, 0, HDA_INPUT));
if (err < 0)
return err;
}
return 0;
}
/* create capture and input-src controls for multiple streams */
static int create_multi_adc_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int i, err;
/* create capture mixer elements */
for (i = 0; i < spec->num_adc_nids; i++) {
hda_nid_t adc = spec->adc_nids[i];
err = __via_add_control(spec, VIA_CTL_WIDGET_VOL,
"Capture Volume", i,
HDA_COMPOSE_AMP_VAL(adc, 3, 0,
HDA_INPUT));
if (err < 0)
return err;
err = __via_add_control(spec, VIA_CTL_WIDGET_MUTE,
"Capture Switch", i,
HDA_COMPOSE_AMP_VAL(adc, 3, 0,
HDA_INPUT));
if (err < 0)
return err;
}
/* input-source control */
for (i = 0; i < spec->num_adc_nids; i++)
if (!spec->mux_nids[i])
break;
err = create_input_src_ctls(codec, i);
if (err < 0)
return err;
return 0;
}
/* bind capture volume/switch */
static struct snd_kcontrol_new via_bind_cap_vol_ctl =
HDA_BIND_VOL("Capture Volume", 0);
static struct snd_kcontrol_new via_bind_cap_sw_ctl =
HDA_BIND_SW("Capture Switch", 0);
static int init_bind_ctl(struct via_spec *spec, struct hda_bind_ctls **ctl_ret,
struct hda_ctl_ops *ops)
{
struct hda_bind_ctls *ctl;
int i;
ctl = kzalloc(sizeof(*ctl) + sizeof(long) * 4, GFP_KERNEL);
if (!ctl)
return -ENOMEM;
ctl->ops = ops;
for (i = 0; i < spec->num_adc_nids; i++)
ctl->values[i] =
HDA_COMPOSE_AMP_VAL(spec->adc_nids[i], 3, 0, HDA_INPUT);
*ctl_ret = ctl;
return 0;
}
/* create capture and input-src controls for dynamic ADC-switch case */
static int create_dyn_adc_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct snd_kcontrol_new *knew;
int err;
/* set up the bind capture ctls */
err = init_bind_ctl(spec, &spec->bind_cap_vol, &snd_hda_bind_vol);
if (err < 0)
return err;
err = init_bind_ctl(spec, &spec->bind_cap_sw, &snd_hda_bind_sw);
if (err < 0)
return err;
/* create capture mixer elements */
knew = via_clone_control(spec, &via_bind_cap_vol_ctl);
if (!knew)
return -ENOMEM;
knew->private_value = (long)spec->bind_cap_vol;
knew = via_clone_control(spec, &via_bind_cap_sw_ctl);
if (!knew)
return -ENOMEM;
knew->private_value = (long)spec->bind_cap_sw;
/* input-source control */
err = create_input_src_ctls(codec, 1);
if (err < 0)
return err;
return 0;
}
/* parse and create capture-related stuff */
static int via_auto_create_analog_input_ctls(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int err;
err = parse_analog_inputs(codec);
if (err < 0)
return err;
if (spec->dyn_adc_switch)
err = create_dyn_adc_ctls(codec);
else
err = create_multi_adc_ctls(codec);
if (err < 0)
return err;
err = create_loopback_ctls(codec);
if (err < 0)
return err;
err = create_mic_boost_ctls(codec);
if (err < 0)
return err;
return 0;
}
static void vt1708_set_pinconfig_connect(struct hda_codec *codec, hda_nid_t nid)
{
unsigned int def_conf;
unsigned char seqassoc;
def_conf = snd_hda_codec_get_pincfg(codec, nid);
seqassoc = (unsigned char) get_defcfg_association(def_conf);
seqassoc = (seqassoc << 4) | get_defcfg_sequence(def_conf);
if (get_defcfg_connect(def_conf) == AC_JACK_PORT_NONE
&& (seqassoc == 0xf0 || seqassoc == 0xff)) {
def_conf = def_conf & (~(AC_JACK_PORT_BOTH << 30));
snd_hda_codec_set_pincfg(codec, nid, def_conf);
}
return;
}
static int vt1708_jack_detect_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
if (spec->codec_type != VT1708)
return 0;
ucontrol->value.integer.value[0] = spec->vt1708_jack_detect;
return 0;
}
static int vt1708_jack_detect_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
int val;
if (spec->codec_type != VT1708)
return 0;
val = !!ucontrol->value.integer.value[0];
if (spec->vt1708_jack_detect == val)
return 0;
spec->vt1708_jack_detect = val;
if (spec->vt1708_jack_detect &&
snd_hda_get_bool_hint(codec, "analog_loopback_hp_detect") != 1) {
mute_aa_path(codec, 1);
notify_aa_path_ctls(codec);
}
via_hp_automute(codec);
vt1708_update_hp_work(spec);
return 1;
}
static const struct snd_kcontrol_new vt1708_jack_detect_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Jack Detect",
.count = 1,
.info = snd_ctl_boolean_mono_info,
.get = vt1708_jack_detect_get,
.put = vt1708_jack_detect_put,
};
static void fill_dig_outs(struct hda_codec *codec);
static void fill_dig_in(struct hda_codec *codec);
static int via_parse_auto_config(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int err;
err = snd_hda_parse_pin_def_config(codec, &spec->autocfg, NULL);
if (err < 0)
return err;
if (!spec->autocfg.line_outs && !spec->autocfg.hp_pins[0])
return -EINVAL;
err = via_auto_create_multi_out_ctls(codec);
if (err < 0)
return err;
err = via_auto_create_hp_ctls(codec, spec->autocfg.hp_pins[0]);
if (err < 0)
return err;
err = via_auto_create_speaker_ctls(codec);
if (err < 0)
return err;
err = via_auto_create_loopback_switch(codec);
if (err < 0)
return err;
err = via_auto_create_analog_input_ctls(codec);
if (err < 0)
return err;
spec->multiout.max_channels = spec->multiout.num_dacs * 2;
fill_dig_outs(codec);
fill_dig_in(codec);
if (spec->kctls.list)
spec->mixers[spec->num_mixers++] = spec->kctls.list;
if (spec->hp_dac_nid && spec->hp_mix_path.depth) {
err = via_hp_build(codec);
if (err < 0)
return err;
}
err = via_smart51_build(codec);
if (err < 0)
return err;
/* assign slave outs */
if (spec->slave_dig_outs[0])
codec->slave_dig_outs = spec->slave_dig_outs;
return 1;
}
static void via_auto_init_dig_outs(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (spec->multiout.dig_out_nid)
init_output_pin(codec, spec->autocfg.dig_out_pins[0], PIN_OUT);
if (spec->slave_dig_outs[0])
init_output_pin(codec, spec->autocfg.dig_out_pins[1], PIN_OUT);
}
static void via_auto_init_dig_in(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
if (!spec->dig_in_nid)
return;
snd_hda_codec_write(codec, spec->autocfg.dig_in_pin, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN);
}
/* initialize the unsolicited events */
static void via_auto_init_unsol_event(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
unsigned int ev;
int i;
if (cfg->hp_pins[0] && is_jack_detectable(codec, cfg->hp_pins[0]))
snd_hda_jack_detect_enable(codec, cfg->hp_pins[0],
VIA_HP_EVENT | VIA_JACK_EVENT);
if (cfg->speaker_pins[0])
ev = VIA_LINE_EVENT;
else
ev = 0;
for (i = 0; i < cfg->line_outs; i++) {
if (cfg->line_out_pins[i] &&
is_jack_detectable(codec, cfg->line_out_pins[i]))
snd_hda_jack_detect_enable(codec, cfg->line_out_pins[i],
ev | VIA_JACK_EVENT);
}
for (i = 0; i < cfg->num_inputs; i++) {
if (is_jack_detectable(codec, cfg->inputs[i].pin))
snd_hda_jack_detect_enable(codec, cfg->inputs[i].pin,
VIA_JACK_EVENT);
}
}
static int via_init(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->num_iverbs; i++)
snd_hda_sequence_write(codec, spec->init_verbs[i]);
/* init power states */
set_widgets_power_state(codec);
__analog_low_current_mode(codec, true);
via_auto_init_multi_out(codec);
via_auto_init_hp_out(codec);
via_auto_init_speaker_out(codec);
via_auto_init_analog_input(codec);
via_auto_init_dig_outs(codec);
via_auto_init_dig_in(codec);
via_auto_init_unsol_event(codec);
via_hp_automute(codec);
vt1708_update_hp_work(spec);
snd_hda_jack_report_sync(codec);
return 0;
}
static void vt1708_update_hp_jack_state(struct work_struct *work)
{
struct via_spec *spec = container_of(work, struct via_spec,
vt1708_hp_work.work);
if (spec->codec_type != VT1708)
return;
snd_hda_jack_set_dirty_all(spec->codec);
/* if jack state toggled */
if (spec->vt1708_hp_present
!= snd_hda_jack_detect(spec->codec, spec->autocfg.hp_pins[0])) {
spec->vt1708_hp_present ^= 1;
via_hp_automute(spec->codec);
}
if (spec->vt1708_jack_detect)
schedule_delayed_work(&spec->vt1708_hp_work,
msecs_to_jiffies(100));
}
static int get_mux_nids(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
hda_nid_t nid, conn[8];
unsigned int type;
int i, n;
for (i = 0; i < spec->num_adc_nids; i++) {
nid = spec->adc_nids[i];
while (nid) {
type = get_wcaps_type(get_wcaps(codec, nid));
if (type == AC_WID_PIN)
break;
n = snd_hda_get_connections(codec, nid, conn,
ARRAY_SIZE(conn));
if (n <= 0)
break;
if (n > 1) {
spec->mux_nids[i] = nid;
break;
}
nid = conn[0];
}
}
return 0;
}
static int patch_vt1708(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x17;
/* Add HP and CD pin config connect bit re-config action */
vt1708_set_pinconfig_connect(codec, VT1708_HP_PIN_NID);
vt1708_set_pinconfig_connect(codec, VT1708_CD_PIN_NID);
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
/* add jack detect on/off control */
if (!via_clone_control(spec, &vt1708_jack_detect_ctl))
return -ENOMEM;
/* disable 32bit format on VT1708 */
if (codec->vendor_id == 0x11061708)
spec->stream_analog_playback = &vt1708_pcm_analog_s16_playback;
spec->init_verbs[spec->num_iverbs++] = vt1708_init_verbs;
codec->patch_ops = via_patch_ops;
INIT_DELAYED_WORK(&spec->vt1708_hp_work, vt1708_update_hp_jack_state);
return 0;
}
static int patch_vt1709(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x18;
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
codec->patch_ops = via_patch_ops;
return 0;
}
static void set_widgets_power_state_vt1708B(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int imux_is_smixer;
unsigned int parm;
int is_8ch = 0;
if ((spec->codec_type != VT1708B_4CH) &&
(codec->vendor_id != 0x11064397))
is_8ch = 1;
/* SW0 (17h) = stereo mixer */
imux_is_smixer =
(snd_hda_codec_read(codec, 0x17, 0, AC_VERB_GET_CONNECT_SEL, 0x00)
== ((spec->codec_type == VT1708S) ? 5 : 0));
/* inputs */
/* PW 1/2/5 (1ah/1bh/1eh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x1a, &parm);
set_pin_power_state(codec, 0x1b, &parm);
set_pin_power_state(codec, 0x1e, &parm);
if (imux_is_smixer)
parm = AC_PWRST_D0;
/* SW0 (17h), AIW 0/1 (13h/14h) */
update_power_state(codec, 0x17, parm);
update_power_state(codec, 0x13, parm);
update_power_state(codec, 0x14, parm);
/* outputs */
/* PW0 (19h), SW1 (18h), AOW1 (11h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x19, &parm);
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x1b, &parm);
update_power_state(codec, 0x18, parm);
update_power_state(codec, 0x11, parm);
/* PW6 (22h), SW2 (26h), AOW2 (24h) */
if (is_8ch) {
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x22, &parm);
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x1a, &parm);
update_power_state(codec, 0x26, parm);
update_power_state(codec, 0x24, parm);
} else if (codec->vendor_id == 0x11064397) {
/* PW7(23h), SW2(27h), AOW2(25h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x23, &parm);
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x1a, &parm);
update_power_state(codec, 0x27, parm);
update_power_state(codec, 0x25, parm);
}
/* PW 3/4/7 (1ch/1dh/23h) */
parm = AC_PWRST_D3;
/* force to D0 for internal Speaker */
set_pin_power_state(codec, 0x1c, &parm);
set_pin_power_state(codec, 0x1d, &parm);
if (is_8ch)
set_pin_power_state(codec, 0x23, &parm);
/* MW0 (16h), Sw3 (27h), AOW 0/3 (10h/25h) */
update_power_state(codec, 0x16, imux_is_smixer ? AC_PWRST_D0 : parm);
update_power_state(codec, 0x10, parm);
if (is_8ch) {
update_power_state(codec, 0x25, parm);
update_power_state(codec, 0x27, parm);
} else if (codec->vendor_id == 0x11064397 && spec->hp_independent_mode)
update_power_state(codec, 0x25, parm);
}
static int patch_vt1708S(struct hda_codec *codec);
static int patch_vt1708B(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
if (get_codec_type(codec) == VT1708BCE)
return patch_vt1708S(codec);
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x16;
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
codec->patch_ops = via_patch_ops;
spec->set_widgets_power_state = set_widgets_power_state_vt1708B;
return 0;
}
/* Patch for VT1708S */
static const struct hda_verb vt1708S_init_verbs[] = {
/* Enable Mic Boost Volume backdoor */
{0x1, 0xf98, 0x1},
/* don't bybass mixer */
{0x1, 0xf88, 0xc0},
{ }
};
/* fill out digital output widgets; one for master and one for slave outputs */
static void fill_dig_outs(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->autocfg.dig_outs; i++) {
hda_nid_t nid;
int conn;
nid = spec->autocfg.dig_out_pins[i];
if (!nid)
continue;
conn = snd_hda_get_connections(codec, nid, &nid, 1);
if (conn < 1)
continue;
if (!spec->multiout.dig_out_nid)
spec->multiout.dig_out_nid = nid;
else {
spec->slave_dig_outs[0] = nid;
break; /* at most two dig outs */
}
}
}
static void fill_dig_in(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
hda_nid_t dig_nid;
int i, err;
if (!spec->autocfg.dig_in_pin)
return;
dig_nid = codec->start_nid;
for (i = 0; i < codec->num_nodes; i++, dig_nid++) {
unsigned int wcaps = get_wcaps(codec, dig_nid);
if (get_wcaps_type(wcaps) != AC_WID_AUD_IN)
continue;
if (!(wcaps & AC_WCAP_DIGITAL))
continue;
if (!(wcaps & AC_WCAP_CONN_LIST))
continue;
err = get_connection_index(codec, dig_nid,
spec->autocfg.dig_in_pin);
if (err >= 0) {
spec->dig_in_nid = dig_nid;
break;
}
}
}
static void override_mic_boost(struct hda_codec *codec, hda_nid_t pin,
int offset, int num_steps, int step_size)
{
snd_hda_override_amp_caps(codec, pin, HDA_INPUT,
(offset << AC_AMPCAP_OFFSET_SHIFT) |
(num_steps << AC_AMPCAP_NUM_STEPS_SHIFT) |
(step_size << AC_AMPCAP_STEP_SIZE_SHIFT) |
(0 << AC_AMPCAP_MUTE_SHIFT));
}
static int patch_vt1708S(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x16;
override_mic_boost(codec, 0x1a, 0, 3, 40);
override_mic_boost(codec, 0x1e, 0, 3, 40);
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
spec->init_verbs[spec->num_iverbs++] = vt1708S_init_verbs;
codec->patch_ops = via_patch_ops;
/* correct names for VT1708BCE */
if (get_codec_type(codec) == VT1708BCE) {
kfree(codec->chip_name);
codec->chip_name = kstrdup("VT1708BCE", GFP_KERNEL);
snprintf(codec->bus->card->mixername,
sizeof(codec->bus->card->mixername),
"%s %s", codec->vendor_name, codec->chip_name);
}
/* correct names for VT1705 */
if (codec->vendor_id == 0x11064397) {
kfree(codec->chip_name);
codec->chip_name = kstrdup("VT1705", GFP_KERNEL);
snprintf(codec->bus->card->mixername,
sizeof(codec->bus->card->mixername),
"%s %s", codec->vendor_name, codec->chip_name);
}
spec->set_widgets_power_state = set_widgets_power_state_vt1708B;
return 0;
}
/* Patch for VT1702 */
static const struct hda_verb vt1702_init_verbs[] = {
/* mixer enable */
{0x1, 0xF88, 0x3},
/* GPIO 0~2 */
{0x1, 0xF82, 0x3F},
{ }
};
static void set_widgets_power_state_vt1702(struct hda_codec *codec)
{
int imux_is_smixer =
snd_hda_codec_read(codec, 0x13, 0, AC_VERB_GET_CONNECT_SEL, 0x00) == 3;
unsigned int parm;
/* inputs */
/* PW 1/2/5 (14h/15h/18h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x14, &parm);
set_pin_power_state(codec, 0x15, &parm);
set_pin_power_state(codec, 0x18, &parm);
if (imux_is_smixer)
parm = AC_PWRST_D0; /* SW0 (13h) = stereo mixer (idx 3) */
/* SW0 (13h), AIW 0/1/2 (12h/1fh/20h) */
update_power_state(codec, 0x13, parm);
update_power_state(codec, 0x12, parm);
update_power_state(codec, 0x1f, parm);
update_power_state(codec, 0x20, parm);
/* outputs */
/* PW 3/4 (16h/17h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x17, &parm);
set_pin_power_state(codec, 0x16, &parm);
/* MW0 (1ah), AOW 0/1 (10h/1dh) */
update_power_state(codec, 0x1a, imux_is_smixer ? AC_PWRST_D0 : parm);
update_power_state(codec, 0x10, parm);
update_power_state(codec, 0x1d, parm);
}
static int patch_vt1702(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x1a;
/* limit AA path volume to 0 dB */
snd_hda_override_amp_caps(codec, 0x1A, HDA_INPUT,
(0x17 << AC_AMPCAP_OFFSET_SHIFT) |
(0x17 << AC_AMPCAP_NUM_STEPS_SHIFT) |
(0x5 << AC_AMPCAP_STEP_SIZE_SHIFT) |
(1 << AC_AMPCAP_MUTE_SHIFT));
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
spec->init_verbs[spec->num_iverbs++] = vt1702_init_verbs;
codec->patch_ops = via_patch_ops;
spec->set_widgets_power_state = set_widgets_power_state_vt1702;
return 0;
}
/* Patch for VT1718S */
static const struct hda_verb vt1718S_init_verbs[] = {
/* Enable MW0 adjust Gain 5 */
{0x1, 0xfb2, 0x10},
/* Enable Boost Volume backdoor */
{0x1, 0xf88, 0x8},
{ }
};
static void set_widgets_power_state_vt1718S(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int imux_is_smixer;
unsigned int parm;
/* MUX6 (1eh) = stereo mixer */
imux_is_smixer =
snd_hda_codec_read(codec, 0x1e, 0, AC_VERB_GET_CONNECT_SEL, 0x00) == 5;
/* inputs */
/* PW 5/6/7 (29h/2ah/2bh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x29, &parm);
set_pin_power_state(codec, 0x2a, &parm);
set_pin_power_state(codec, 0x2b, &parm);
if (imux_is_smixer)
parm = AC_PWRST_D0;
/* MUX6/7 (1eh/1fh), AIW 0/1 (10h/11h) */
update_power_state(codec, 0x1e, parm);
update_power_state(codec, 0x1f, parm);
update_power_state(codec, 0x10, parm);
update_power_state(codec, 0x11, parm);
/* outputs */
/* PW3 (27h), MW2 (1ah), AOW3 (bh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x27, &parm);
update_power_state(codec, 0x1a, parm);
update_power_state(codec, 0xb, parm);
/* PW2 (26h), AOW2 (ah) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x26, &parm);
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x2b, &parm);
update_power_state(codec, 0xa, parm);
/* PW0 (24h), AOW0 (8h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x24, &parm);
if (!spec->hp_independent_mode) /* check for redirected HP */
set_pin_power_state(codec, 0x28, &parm);
update_power_state(codec, 0x8, parm);
/* MW9 (21h), Mw2 (1ah), AOW0 (8h) */
update_power_state(codec, 0x21, imux_is_smixer ? AC_PWRST_D0 : parm);
/* PW1 (25h), AOW1 (9h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x25, &parm);
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x2a, &parm);
update_power_state(codec, 0x9, parm);
if (spec->hp_independent_mode) {
/* PW4 (28h), MW3 (1bh), MUX1(34h), AOW4 (ch) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x28, &parm);
update_power_state(codec, 0x1b, parm);
update_power_state(codec, 0x34, parm);
update_power_state(codec, 0xc, parm);
}
}
/* Add a connection to the primary DAC from AA-mixer for some codecs
* This isn't listed from the raw info, but the chip has a secret connection.
*/
static int add_secret_dac_path(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int i, nums;
hda_nid_t conn[8];
hda_nid_t nid;
if (!spec->aa_mix_nid)
return 0;
nums = snd_hda_get_connections(codec, spec->aa_mix_nid, conn,
ARRAY_SIZE(conn) - 1);
for (i = 0; i < nums; i++) {
if (get_wcaps_type(get_wcaps(codec, conn[i])) == AC_WID_AUD_OUT)
return 0;
}
/* find the primary DAC and add to the connection list */
nid = codec->start_nid;
for (i = 0; i < codec->num_nodes; i++, nid++) {
unsigned int caps = get_wcaps(codec, nid);
if (get_wcaps_type(caps) == AC_WID_AUD_OUT &&
!(caps & AC_WCAP_DIGITAL)) {
conn[nums++] = nid;
return snd_hda_override_conn_list(codec,
spec->aa_mix_nid,
nums, conn);
}
}
return 0;
}
static int patch_vt1718S(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x21;
override_mic_boost(codec, 0x2b, 0, 3, 40);
override_mic_boost(codec, 0x29, 0, 3, 40);
add_secret_dac_path(codec);
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
spec->init_verbs[spec->num_iverbs++] = vt1718S_init_verbs;
codec->patch_ops = via_patch_ops;
spec->set_widgets_power_state = set_widgets_power_state_vt1718S;
return 0;
}
/* Patch for VT1716S */
static int vt1716s_dmic_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
static int vt1716s_dmic_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
int index = 0;
index = snd_hda_codec_read(codec, 0x26, 0,
AC_VERB_GET_CONNECT_SEL, 0);
if (index != -1)
*ucontrol->value.integer.value = index;
return 0;
}
static int vt1716s_dmic_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct via_spec *spec = codec->spec;
int index = *ucontrol->value.integer.value;
snd_hda_codec_write(codec, 0x26, 0,
AC_VERB_SET_CONNECT_SEL, index);
spec->dmic_enabled = index;
set_widgets_power_state(codec);
return 1;
}
static const struct snd_kcontrol_new vt1716s_dmic_mixer[] = {
HDA_CODEC_VOLUME("Digital Mic Capture Volume", 0x22, 0x0, HDA_INPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Digital Mic Capture Switch",
.subdevice = HDA_SUBDEV_NID_FLAG | 0x26,
.count = 1,
.info = vt1716s_dmic_info,
.get = vt1716s_dmic_get,
.put = vt1716s_dmic_put,
},
{} /* end */
};
/* mono-out mixer elements */
static const struct snd_kcontrol_new vt1716S_mono_out_mixer[] = {
HDA_CODEC_MUTE("Mono Playback Switch", 0x2a, 0x0, HDA_OUTPUT),
{ } /* end */
};
static const struct hda_verb vt1716S_init_verbs[] = {
/* Enable Boost Volume backdoor */
{0x1, 0xf8a, 0x80},
/* don't bybass mixer */
{0x1, 0xf88, 0xc0},
/* Enable mono output */
{0x1, 0xf90, 0x08},
{ }
};
static void set_widgets_power_state_vt1716S(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int imux_is_smixer;
unsigned int parm;
unsigned int mono_out, present;
/* SW0 (17h) = stereo mixer */
imux_is_smixer =
(snd_hda_codec_read(codec, 0x17, 0,
AC_VERB_GET_CONNECT_SEL, 0x00) == 5);
/* inputs */
/* PW 1/2/5 (1ah/1bh/1eh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x1a, &parm);
set_pin_power_state(codec, 0x1b, &parm);
set_pin_power_state(codec, 0x1e, &parm);
if (imux_is_smixer)
parm = AC_PWRST_D0;
/* SW0 (17h), AIW0(13h) */
update_power_state(codec, 0x17, parm);
update_power_state(codec, 0x13, parm);
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x1e, &parm);
/* PW11 (22h) */
if (spec->dmic_enabled)
set_pin_power_state(codec, 0x22, &parm);
else
update_power_state(codec, 0x22, AC_PWRST_D3);
/* SW2(26h), AIW1(14h) */
update_power_state(codec, 0x26, parm);
update_power_state(codec, 0x14, parm);
/* outputs */
/* PW0 (19h), SW1 (18h), AOW1 (11h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x19, &parm);
/* Smart 5.1 PW2(1bh) */
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x1b, &parm);
update_power_state(codec, 0x18, parm);
update_power_state(codec, 0x11, parm);
/* PW7 (23h), SW3 (27h), AOW3 (25h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x23, &parm);
/* Smart 5.1 PW1(1ah) */
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x1a, &parm);
update_power_state(codec, 0x27, parm);
/* Smart 5.1 PW5(1eh) */
if (spec->smart51_enabled)
set_pin_power_state(codec, 0x1e, &parm);
update_power_state(codec, 0x25, parm);
/* Mono out */
/* SW4(28h)->MW1(29h)-> PW12 (2ah)*/
present = snd_hda_jack_detect(codec, 0x1c);
if (present)
mono_out = 0;
else {
present = snd_hda_jack_detect(codec, 0x1d);
if (!spec->hp_independent_mode && present)
mono_out = 0;
else
mono_out = 1;
}
parm = mono_out ? AC_PWRST_D0 : AC_PWRST_D3;
update_power_state(codec, 0x28, parm);
update_power_state(codec, 0x29, parm);
update_power_state(codec, 0x2a, parm);
/* PW 3/4 (1ch/1dh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x1c, &parm);
set_pin_power_state(codec, 0x1d, &parm);
/* HP Independent Mode, power on AOW3 */
if (spec->hp_independent_mode)
update_power_state(codec, 0x25, parm);
/* force to D0 for internal Speaker */
/* MW0 (16h), AOW0 (10h) */
update_power_state(codec, 0x16, imux_is_smixer ? AC_PWRST_D0 : parm);
update_power_state(codec, 0x10, mono_out ? AC_PWRST_D0 : parm);
}
static int patch_vt1716S(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x16;
override_mic_boost(codec, 0x1a, 0, 3, 40);
override_mic_boost(codec, 0x1e, 0, 3, 40);
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
spec->init_verbs[spec->num_iverbs++] = vt1716S_init_verbs;
spec->mixers[spec->num_mixers] = vt1716s_dmic_mixer;
spec->num_mixers++;
spec->mixers[spec->num_mixers++] = vt1716S_mono_out_mixer;
codec->patch_ops = via_patch_ops;
spec->set_widgets_power_state = set_widgets_power_state_vt1716S;
return 0;
}
/* for vt2002P */
static const struct hda_verb vt2002P_init_verbs[] = {
/* Class-D speaker related verbs */
{0x1, 0xfe0, 0x4},
{0x1, 0xfe9, 0x80},
{0x1, 0xfe2, 0x22},
/* Enable Boost Volume backdoor */
{0x1, 0xfb9, 0x24},
/* Enable AOW0 to MW9 */
{0x1, 0xfb8, 0x88},
{ }
};
static const struct hda_verb vt1802_init_verbs[] = {
/* Enable Boost Volume backdoor */
{0x1, 0xfb9, 0x24},
/* Enable AOW0 to MW9 */
{0x1, 0xfb8, 0x88},
{ }
};
static void set_widgets_power_state_vt2002P(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
int imux_is_smixer;
unsigned int parm;
unsigned int present;
/* MUX9 (1eh) = stereo mixer */
imux_is_smixer =
snd_hda_codec_read(codec, 0x1e, 0, AC_VERB_GET_CONNECT_SEL, 0x00) == 3;
/* inputs */
/* PW 5/6/7 (29h/2ah/2bh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x29, &parm);
set_pin_power_state(codec, 0x2a, &parm);
set_pin_power_state(codec, 0x2b, &parm);
parm = AC_PWRST_D0;
/* MUX9/10 (1eh/1fh), AIW 0/1 (10h/11h) */
update_power_state(codec, 0x1e, parm);
update_power_state(codec, 0x1f, parm);
update_power_state(codec, 0x10, parm);
update_power_state(codec, 0x11, parm);
/* outputs */
/* AOW0 (8h)*/
update_power_state(codec, 0x8, parm);
if (spec->codec_type == VT1802) {
/* PW4 (28h), MW4 (18h), MUX4(38h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x28, &parm);
update_power_state(codec, 0x18, parm);
update_power_state(codec, 0x38, parm);
} else {
/* PW4 (26h), MW4 (1ch), MUX4(37h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x26, &parm);
update_power_state(codec, 0x1c, parm);
update_power_state(codec, 0x37, parm);
}
if (spec->codec_type == VT1802) {
/* PW1 (25h), MW1 (15h), MUX1(35h), AOW1 (9h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x25, &parm);
update_power_state(codec, 0x15, parm);
update_power_state(codec, 0x35, parm);
} else {
/* PW1 (25h), MW1 (19h), MUX1(35h), AOW1 (9h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x25, &parm);
update_power_state(codec, 0x19, parm);
update_power_state(codec, 0x35, parm);
}
if (spec->hp_independent_mode)
update_power_state(codec, 0x9, AC_PWRST_D0);
/* Class-D */
/* PW0 (24h), MW0(18h/14h), MUX0(34h) */
present = snd_hda_jack_detect(codec, 0x25);
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x24, &parm);
parm = present ? AC_PWRST_D3 : AC_PWRST_D0;
if (spec->codec_type == VT1802)
update_power_state(codec, 0x14, parm);
else
update_power_state(codec, 0x18, parm);
update_power_state(codec, 0x34, parm);
/* Mono Out */
present = snd_hda_jack_detect(codec, 0x26);
parm = present ? AC_PWRST_D3 : AC_PWRST_D0;
if (spec->codec_type == VT1802) {
/* PW15 (33h), MW8(1ch), MUX8(3ch) */
update_power_state(codec, 0x33, parm);
update_power_state(codec, 0x1c, parm);
update_power_state(codec, 0x3c, parm);
} else {
/* PW15 (31h), MW8(17h), MUX8(3bh) */
update_power_state(codec, 0x31, parm);
update_power_state(codec, 0x17, parm);
update_power_state(codec, 0x3b, parm);
}
/* MW9 (21h) */
if (imux_is_smixer || !is_aa_path_mute(codec))
update_power_state(codec, 0x21, AC_PWRST_D0);
else
update_power_state(codec, 0x21, AC_PWRST_D3);
}
/* patch for vt2002P */
static int patch_vt2002P(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x21;
override_mic_boost(codec, 0x2b, 0, 3, 40);
override_mic_boost(codec, 0x29, 0, 3, 40);
add_secret_dac_path(codec);
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
if (spec->codec_type == VT1802)
spec->init_verbs[spec->num_iverbs++] = vt1802_init_verbs;
else
spec->init_verbs[spec->num_iverbs++] = vt2002P_init_verbs;
codec->patch_ops = via_patch_ops;
spec->set_widgets_power_state = set_widgets_power_state_vt2002P;
return 0;
}
/* for vt1812 */
static const struct hda_verb vt1812_init_verbs[] = {
/* Enable Boost Volume backdoor */
{0x1, 0xfb9, 0x24},
/* Enable AOW0 to MW9 */
{0x1, 0xfb8, 0xa8},
{ }
};
static void set_widgets_power_state_vt1812(struct hda_codec *codec)
{
struct via_spec *spec = codec->spec;
unsigned int parm;
unsigned int present;
/* inputs */
/* PW 5/6/7 (29h/2ah/2bh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x29, &parm);
set_pin_power_state(codec, 0x2a, &parm);
set_pin_power_state(codec, 0x2b, &parm);
parm = AC_PWRST_D0;
/* MUX10/11 (1eh/1fh), AIW 0/1 (10h/11h) */
update_power_state(codec, 0x1e, parm);
update_power_state(codec, 0x1f, parm);
update_power_state(codec, 0x10, parm);
update_power_state(codec, 0x11, parm);
/* outputs */
/* AOW0 (8h)*/
update_power_state(codec, 0x8, AC_PWRST_D0);
/* PW4 (28h), MW4 (18h), MUX4(38h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x28, &parm);
update_power_state(codec, 0x18, parm);
update_power_state(codec, 0x38, parm);
/* PW1 (25h), MW1 (15h), MUX1(35h), AOW1 (9h) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x25, &parm);
update_power_state(codec, 0x15, parm);
update_power_state(codec, 0x35, parm);
if (spec->hp_independent_mode)
update_power_state(codec, 0x9, AC_PWRST_D0);
/* Internal Speaker */
/* PW0 (24h), MW0(14h), MUX0(34h) */
present = snd_hda_jack_detect(codec, 0x25);
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x24, &parm);
if (present) {
update_power_state(codec, 0x14, AC_PWRST_D3);
update_power_state(codec, 0x34, AC_PWRST_D3);
} else {
update_power_state(codec, 0x14, AC_PWRST_D0);
update_power_state(codec, 0x34, AC_PWRST_D0);
}
/* Mono Out */
/* PW13 (31h), MW13(1ch), MUX13(3ch), MW14(3eh) */
present = snd_hda_jack_detect(codec, 0x28);
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x31, &parm);
if (present) {
update_power_state(codec, 0x1c, AC_PWRST_D3);
update_power_state(codec, 0x3c, AC_PWRST_D3);
update_power_state(codec, 0x3e, AC_PWRST_D3);
} else {
update_power_state(codec, 0x1c, AC_PWRST_D0);
update_power_state(codec, 0x3c, AC_PWRST_D0);
update_power_state(codec, 0x3e, AC_PWRST_D0);
}
/* PW15 (33h), MW15 (1dh), MUX15(3dh) */
parm = AC_PWRST_D3;
set_pin_power_state(codec, 0x33, &parm);
update_power_state(codec, 0x1d, parm);
update_power_state(codec, 0x3d, parm);
}
/* patch for vt1812 */
static int patch_vt1812(struct hda_codec *codec)
{
struct via_spec *spec;
int err;
/* create a codec specific record */
spec = via_new_spec(codec);
if (spec == NULL)
return -ENOMEM;
spec->aa_mix_nid = 0x21;
override_mic_boost(codec, 0x2b, 0, 3, 40);
override_mic_boost(codec, 0x29, 0, 3, 40);
add_secret_dac_path(codec);
/* automatic parse from the BIOS config */
err = via_parse_auto_config(codec);
if (err < 0) {
via_free(codec);
return err;
}
spec->init_verbs[spec->num_iverbs++] = vt1812_init_verbs;
codec->patch_ops = via_patch_ops;
spec->set_widgets_power_state = set_widgets_power_state_vt1812;
return 0;
}
/*
* patch entries
*/
static const struct hda_codec_preset snd_hda_preset_via[] = {
{ .id = 0x11061708, .name = "VT1708", .patch = patch_vt1708},
{ .id = 0x11061709, .name = "VT1708", .patch = patch_vt1708},
{ .id = 0x1106170a, .name = "VT1708", .patch = patch_vt1708},
{ .id = 0x1106170b, .name = "VT1708", .patch = patch_vt1708},
{ .id = 0x1106e710, .name = "VT1709 10-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e711, .name = "VT1709 10-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e712, .name = "VT1709 10-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e713, .name = "VT1709 10-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e714, .name = "VT1709 6-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e715, .name = "VT1709 6-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e716, .name = "VT1709 6-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e717, .name = "VT1709 6-Ch",
.patch = patch_vt1709},
{ .id = 0x1106e720, .name = "VT1708B 8-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e721, .name = "VT1708B 8-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e722, .name = "VT1708B 8-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e723, .name = "VT1708B 8-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e724, .name = "VT1708B 4-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e725, .name = "VT1708B 4-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e726, .name = "VT1708B 4-Ch",
.patch = patch_vt1708B},
{ .id = 0x1106e727, .name = "VT1708B 4-Ch",
.patch = patch_vt1708B},
{ .id = 0x11060397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11061397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11062397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11063397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11064397, .name = "VT1705",
.patch = patch_vt1708S},
{ .id = 0x11065397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11066397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11067397, .name = "VT1708S",
.patch = patch_vt1708S},
{ .id = 0x11060398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11061398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11062398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11063398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11064398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11065398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11066398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11067398, .name = "VT1702",
.patch = patch_vt1702},
{ .id = 0x11060428, .name = "VT1718S",
.patch = patch_vt1718S},
{ .id = 0x11064428, .name = "VT1718S",
.patch = patch_vt1718S},
{ .id = 0x11060441, .name = "VT2020",
.patch = patch_vt1718S},
{ .id = 0x11064441, .name = "VT1828S",
.patch = patch_vt1718S},
{ .id = 0x11060433, .name = "VT1716S",
.patch = patch_vt1716S},
{ .id = 0x1106a721, .name = "VT1716S",
.patch = patch_vt1716S},
{ .id = 0x11060438, .name = "VT2002P", .patch = patch_vt2002P},
{ .id = 0x11064438, .name = "VT2002P", .patch = patch_vt2002P},
{ .id = 0x11060448, .name = "VT1812", .patch = patch_vt1812},
{ .id = 0x11060440, .name = "VT1818S",
.patch = patch_vt1708S},
{ .id = 0x11060446, .name = "VT1802",
.patch = patch_vt2002P},
{ .id = 0x11068446, .name = "VT1802",
.patch = patch_vt2002P},
{} /* terminator */
};
MODULE_ALIAS("snd-hda-codec-id:1106*");
static struct hda_codec_preset_list via_list = {
.preset = snd_hda_preset_via,
.owner = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("VIA HD-audio codec");
static int __init patch_via_init(void)
{
return snd_hda_add_codec_preset(&via_list);
}
static void __exit patch_via_exit(void)
{
snd_hda_delete_codec_preset(&via_list);
}
module_init(patch_via_init)
module_exit(patch_via_exit)
| gpl-2.0 |
edgestorm/lu3700-cm-gin | drivers/base/devres.c | 3628 | 16330 | /*
* drivers/base/devres.c - device resource management
*
* Copyright (c) 2006 SUSE Linux Products GmbH
* Copyright (c) 2006 Tejun Heo <teheo@suse.de>
*
* This file is released under the GPLv2.
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "base.h"
struct devres_node {
struct list_head entry;
dr_release_t release;
#ifdef CONFIG_DEBUG_DEVRES
const char *name;
size_t size;
#endif
};
struct devres {
struct devres_node node;
/* -- 3 pointers */
unsigned long long data[]; /* guarantee ull alignment */
};
struct devres_group {
struct devres_node node[2];
void *id;
int color;
/* -- 8 pointers */
};
#ifdef CONFIG_DEBUG_DEVRES
static int log_devres = 0;
module_param_named(log, log_devres, int, S_IRUGO | S_IWUSR);
static void set_node_dbginfo(struct devres_node *node, const char *name,
size_t size)
{
node->name = name;
node->size = size;
}
static void devres_log(struct device *dev, struct devres_node *node,
const char *op)
{
if (unlikely(log_devres))
dev_printk(KERN_ERR, dev, "DEVRES %3s %p %s (%lu bytes)\n",
op, node, node->name, (unsigned long)node->size);
}
#else /* CONFIG_DEBUG_DEVRES */
#define set_node_dbginfo(node, n, s) do {} while (0)
#define devres_log(dev, node, op) do {} while (0)
#endif /* CONFIG_DEBUG_DEVRES */
/*
* Release functions for devres group. These callbacks are used only
* for identification.
*/
static void group_open_release(struct device *dev, void *res)
{
/* noop */
}
static void group_close_release(struct device *dev, void *res)
{
/* noop */
}
static struct devres_group * node_to_group(struct devres_node *node)
{
if (node->release == &group_open_release)
return container_of(node, struct devres_group, node[0]);
if (node->release == &group_close_release)
return container_of(node, struct devres_group, node[1]);
return NULL;
}
static __always_inline struct devres * alloc_dr(dr_release_t release,
size_t size, gfp_t gfp)
{
size_t tot_size = sizeof(struct devres) + size;
struct devres *dr;
dr = kmalloc_track_caller(tot_size, gfp);
if (unlikely(!dr))
return NULL;
memset(dr, 0, tot_size);
INIT_LIST_HEAD(&dr->node.entry);
dr->node.release = release;
return dr;
}
static void add_dr(struct device *dev, struct devres_node *node)
{
devres_log(dev, node, "ADD");
BUG_ON(!list_empty(&node->entry));
list_add_tail(&node->entry, &dev->devres_head);
}
#ifdef CONFIG_DEBUG_DEVRES
void * __devres_alloc(dr_release_t release, size_t size, gfp_t gfp,
const char *name)
{
struct devres *dr;
dr = alloc_dr(release, size, gfp);
if (unlikely(!dr))
return NULL;
set_node_dbginfo(&dr->node, name, size);
return dr->data;
}
EXPORT_SYMBOL_GPL(__devres_alloc);
#else
/**
* devres_alloc - Allocate device resource data
* @release: Release function devres will be associated with
* @size: Allocation size
* @gfp: Allocation flags
*
* Allocate devres of @size bytes. The allocated area is zeroed, then
* associated with @release. The returned pointer can be passed to
* other devres_*() functions.
*
* RETURNS:
* Pointer to allocated devres on success, NULL on failure.
*/
void * devres_alloc(dr_release_t release, size_t size, gfp_t gfp)
{
struct devres *dr;
dr = alloc_dr(release, size, gfp);
if (unlikely(!dr))
return NULL;
return dr->data;
}
EXPORT_SYMBOL_GPL(devres_alloc);
#endif
/**
* devres_free - Free device resource data
* @res: Pointer to devres data to free
*
* Free devres created with devres_alloc().
*/
void devres_free(void *res)
{
if (res) {
struct devres *dr = container_of(res, struct devres, data);
BUG_ON(!list_empty(&dr->node.entry));
kfree(dr);
}
}
EXPORT_SYMBOL_GPL(devres_free);
/**
* devres_add - Register device resource
* @dev: Device to add resource to
* @res: Resource to register
*
* Register devres @res to @dev. @res should have been allocated
* using devres_alloc(). On driver detach, the associated release
* function will be invoked and devres will be freed automatically.
*/
void devres_add(struct device *dev, void *res)
{
struct devres *dr = container_of(res, struct devres, data);
unsigned long flags;
spin_lock_irqsave(&dev->devres_lock, flags);
add_dr(dev, &dr->node);
spin_unlock_irqrestore(&dev->devres_lock, flags);
}
EXPORT_SYMBOL_GPL(devres_add);
static struct devres *find_dr(struct device *dev, dr_release_t release,
dr_match_t match, void *match_data)
{
struct devres_node *node;
list_for_each_entry_reverse(node, &dev->devres_head, entry) {
struct devres *dr = container_of(node, struct devres, node);
if (node->release != release)
continue;
if (match && !match(dev, dr->data, match_data))
continue;
return dr;
}
return NULL;
}
/**
* devres_find - Find device resource
* @dev: Device to lookup resource from
* @release: Look for resources associated with this release function
* @match: Match function (optional)
* @match_data: Data for the match function
*
* Find the latest devres of @dev which is associated with @release
* and for which @match returns 1. If @match is NULL, it's considered
* to match all.
*
* RETURNS:
* Pointer to found devres, NULL if not found.
*/
void * devres_find(struct device *dev, dr_release_t release,
dr_match_t match, void *match_data)
{
struct devres *dr;
unsigned long flags;
spin_lock_irqsave(&dev->devres_lock, flags);
dr = find_dr(dev, release, match, match_data);
spin_unlock_irqrestore(&dev->devres_lock, flags);
if (dr)
return dr->data;
return NULL;
}
EXPORT_SYMBOL_GPL(devres_find);
/**
* devres_get - Find devres, if non-existent, add one atomically
* @dev: Device to lookup or add devres for
* @new_res: Pointer to new initialized devres to add if not found
* @match: Match function (optional)
* @match_data: Data for the match function
*
* Find the latest devres of @dev which has the same release function
* as @new_res and for which @match return 1. If found, @new_res is
* freed; otherwise, @new_res is added atomically.
*
* RETURNS:
* Pointer to found or added devres.
*/
void * devres_get(struct device *dev, void *new_res,
dr_match_t match, void *match_data)
{
struct devres *new_dr = container_of(new_res, struct devres, data);
struct devres *dr;
unsigned long flags;
spin_lock_irqsave(&dev->devres_lock, flags);
dr = find_dr(dev, new_dr->node.release, match, match_data);
if (!dr) {
add_dr(dev, &new_dr->node);
dr = new_dr;
new_dr = NULL;
}
spin_unlock_irqrestore(&dev->devres_lock, flags);
devres_free(new_dr);
return dr->data;
}
EXPORT_SYMBOL_GPL(devres_get);
/**
* devres_remove - Find a device resource and remove it
* @dev: Device to find resource from
* @release: Look for resources associated with this release function
* @match: Match function (optional)
* @match_data: Data for the match function
*
* Find the latest devres of @dev associated with @release and for
* which @match returns 1. If @match is NULL, it's considered to
* match all. If found, the resource is removed atomically and
* returned.
*
* RETURNS:
* Pointer to removed devres on success, NULL if not found.
*/
void * devres_remove(struct device *dev, dr_release_t release,
dr_match_t match, void *match_data)
{
struct devres *dr;
unsigned long flags;
spin_lock_irqsave(&dev->devres_lock, flags);
dr = find_dr(dev, release, match, match_data);
if (dr) {
list_del_init(&dr->node.entry);
devres_log(dev, &dr->node, "REM");
}
spin_unlock_irqrestore(&dev->devres_lock, flags);
if (dr)
return dr->data;
return NULL;
}
EXPORT_SYMBOL_GPL(devres_remove);
/**
* devres_destroy - Find a device resource and destroy it
* @dev: Device to find resource from
* @release: Look for resources associated with this release function
* @match: Match function (optional)
* @match_data: Data for the match function
*
* Find the latest devres of @dev associated with @release and for
* which @match returns 1. If @match is NULL, it's considered to
* match all. If found, the resource is removed atomically and freed.
*
* RETURNS:
* 0 if devres is found and freed, -ENOENT if not found.
*/
int devres_destroy(struct device *dev, dr_release_t release,
dr_match_t match, void *match_data)
{
void *res;
res = devres_remove(dev, release, match, match_data);
if (unlikely(!res))
return -ENOENT;
devres_free(res);
return 0;
}
EXPORT_SYMBOL_GPL(devres_destroy);
static int remove_nodes(struct device *dev,
struct list_head *first, struct list_head *end,
struct list_head *todo)
{
int cnt = 0, nr_groups = 0;
struct list_head *cur;
/* First pass - move normal devres entries to @todo and clear
* devres_group colors.
*/
cur = first;
while (cur != end) {
struct devres_node *node;
struct devres_group *grp;
node = list_entry(cur, struct devres_node, entry);
cur = cur->next;
grp = node_to_group(node);
if (grp) {
/* clear color of group markers in the first pass */
grp->color = 0;
nr_groups++;
} else {
/* regular devres entry */
if (&node->entry == first)
first = first->next;
list_move_tail(&node->entry, todo);
cnt++;
}
}
if (!nr_groups)
return cnt;
/* Second pass - Scan groups and color them. A group gets
* color value of two iff the group is wholly contained in
* [cur, end). That is, for a closed group, both opening and
* closing markers should be in the range, while just the
* opening marker is enough for an open group.
*/
cur = first;
while (cur != end) {
struct devres_node *node;
struct devres_group *grp;
node = list_entry(cur, struct devres_node, entry);
cur = cur->next;
grp = node_to_group(node);
BUG_ON(!grp || list_empty(&grp->node[0].entry));
grp->color++;
if (list_empty(&grp->node[1].entry))
grp->color++;
BUG_ON(grp->color <= 0 || grp->color > 2);
if (grp->color == 2) {
/* No need to update cur or end. The removed
* nodes are always before both.
*/
list_move_tail(&grp->node[0].entry, todo);
list_del_init(&grp->node[1].entry);
}
}
return cnt;
}
static int release_nodes(struct device *dev, struct list_head *first,
struct list_head *end, unsigned long flags)
{
LIST_HEAD(todo);
int cnt;
struct devres *dr, *tmp;
cnt = remove_nodes(dev, first, end, &todo);
spin_unlock_irqrestore(&dev->devres_lock, flags);
/* Release. Note that both devres and devres_group are
* handled as devres in the following loop. This is safe.
*/
list_for_each_entry_safe_reverse(dr, tmp, &todo, node.entry) {
devres_log(dev, &dr->node, "REL");
dr->node.release(dev, dr->data);
kfree(dr);
}
return cnt;
}
/**
* devres_release_all - Release all managed resources
* @dev: Device to release resources for
*
* Release all resources associated with @dev. This function is
* called on driver detach.
*/
int devres_release_all(struct device *dev)
{
unsigned long flags;
/* Looks like an uninitialized device structure */
if (WARN_ON(dev->devres_head.next == NULL))
return -ENODEV;
spin_lock_irqsave(&dev->devres_lock, flags);
return release_nodes(dev, dev->devres_head.next, &dev->devres_head,
flags);
}
/**
* devres_open_group - Open a new devres group
* @dev: Device to open devres group for
* @id: Separator ID
* @gfp: Allocation flags
*
* Open a new devres group for @dev with @id. For @id, using a
* pointer to an object which won't be used for another group is
* recommended. If @id is NULL, address-wise unique ID is created.
*
* RETURNS:
* ID of the new group, NULL on failure.
*/
void * devres_open_group(struct device *dev, void *id, gfp_t gfp)
{
struct devres_group *grp;
unsigned long flags;
grp = kmalloc(sizeof(*grp), gfp);
if (unlikely(!grp))
return NULL;
grp->node[0].release = &group_open_release;
grp->node[1].release = &group_close_release;
INIT_LIST_HEAD(&grp->node[0].entry);
INIT_LIST_HEAD(&grp->node[1].entry);
set_node_dbginfo(&grp->node[0], "grp<", 0);
set_node_dbginfo(&grp->node[1], "grp>", 0);
grp->id = grp;
if (id)
grp->id = id;
spin_lock_irqsave(&dev->devres_lock, flags);
add_dr(dev, &grp->node[0]);
spin_unlock_irqrestore(&dev->devres_lock, flags);
return grp->id;
}
EXPORT_SYMBOL_GPL(devres_open_group);
/* Find devres group with ID @id. If @id is NULL, look for the latest. */
static struct devres_group * find_group(struct device *dev, void *id)
{
struct devres_node *node;
list_for_each_entry_reverse(node, &dev->devres_head, entry) {
struct devres_group *grp;
if (node->release != &group_open_release)
continue;
grp = container_of(node, struct devres_group, node[0]);
if (id) {
if (grp->id == id)
return grp;
} else if (list_empty(&grp->node[1].entry))
return grp;
}
return NULL;
}
/**
* devres_close_group - Close a devres group
* @dev: Device to close devres group for
* @id: ID of target group, can be NULL
*
* Close the group identified by @id. If @id is NULL, the latest open
* group is selected.
*/
void devres_close_group(struct device *dev, void *id)
{
struct devres_group *grp;
unsigned long flags;
spin_lock_irqsave(&dev->devres_lock, flags);
grp = find_group(dev, id);
if (grp)
add_dr(dev, &grp->node[1]);
else
WARN_ON(1);
spin_unlock_irqrestore(&dev->devres_lock, flags);
}
EXPORT_SYMBOL_GPL(devres_close_group);
/**
* devres_remove_group - Remove a devres group
* @dev: Device to remove group for
* @id: ID of target group, can be NULL
*
* Remove the group identified by @id. If @id is NULL, the latest
* open group is selected. Note that removing a group doesn't affect
* any other resources.
*/
void devres_remove_group(struct device *dev, void *id)
{
struct devres_group *grp;
unsigned long flags;
spin_lock_irqsave(&dev->devres_lock, flags);
grp = find_group(dev, id);
if (grp) {
list_del_init(&grp->node[0].entry);
list_del_init(&grp->node[1].entry);
devres_log(dev, &grp->node[0], "REM");
} else
WARN_ON(1);
spin_unlock_irqrestore(&dev->devres_lock, flags);
kfree(grp);
}
EXPORT_SYMBOL_GPL(devres_remove_group);
/**
* devres_release_group - Release resources in a devres group
* @dev: Device to release group for
* @id: ID of target group, can be NULL
*
* Release all resources in the group identified by @id. If @id is
* NULL, the latest open group is selected. The selected group and
* groups properly nested inside the selected group are removed.
*
* RETURNS:
* The number of released non-group resources.
*/
int devres_release_group(struct device *dev, void *id)
{
struct devres_group *grp;
unsigned long flags;
int cnt = 0;
spin_lock_irqsave(&dev->devres_lock, flags);
grp = find_group(dev, id);
if (grp) {
struct list_head *first = &grp->node[0].entry;
struct list_head *end = &dev->devres_head;
if (!list_empty(&grp->node[1].entry))
end = grp->node[1].entry.next;
cnt = release_nodes(dev, first, end, flags);
} else {
WARN_ON(1);
spin_unlock_irqrestore(&dev->devres_lock, flags);
}
return cnt;
}
EXPORT_SYMBOL_GPL(devres_release_group);
/*
* Managed kzalloc/kfree
*/
static void devm_kzalloc_release(struct device *dev, void *res)
{
/* noop */
}
static int devm_kzalloc_match(struct device *dev, void *res, void *data)
{
return res == data;
}
/**
* devm_kzalloc - Resource-managed kzalloc
* @dev: Device to allocate memory for
* @size: Allocation size
* @gfp: Allocation gfp flags
*
* Managed kzalloc. Memory allocated with this function is
* automatically freed on driver detach. Like all other devres
* resources, guaranteed alignment is unsigned long long.
*
* RETURNS:
* Pointer to allocated memory on success, NULL on failure.
*/
void * devm_kzalloc(struct device *dev, size_t size, gfp_t gfp)
{
struct devres *dr;
/* use raw alloc_dr for kmalloc caller tracing */
dr = alloc_dr(devm_kzalloc_release, size, gfp);
if (unlikely(!dr))
return NULL;
set_node_dbginfo(&dr->node, "devm_kzalloc_release", size);
devres_add(dev, dr->data);
return dr->data;
}
EXPORT_SYMBOL_GPL(devm_kzalloc);
/**
* devm_kfree - Resource-managed kfree
* @dev: Device this memory belongs to
* @p: Memory to free
*
* Free memory allocated with dev_kzalloc().
*/
void devm_kfree(struct device *dev, void *p)
{
int rc;
rc = devres_destroy(dev, devm_kzalloc_release, devm_kzalloc_match, p);
WARN_ON(rc);
}
EXPORT_SYMBOL_GPL(devm_kfree);
| gpl-2.0 |
houst0nn/android_kernel_msm | tools/perf/builtin-evlist.c | 4908 | 1127 | /*
* Builtin evlist command: Show the list of event selectors present
* in a perf.data file.
*/
#include "builtin.h"
#include "util/util.h"
#include <linux/list.h>
#include "perf.h"
#include "util/evlist.h"
#include "util/evsel.h"
#include "util/parse-events.h"
#include "util/parse-options.h"
#include "util/session.h"
static const char *input_name;
static int __cmd_evlist(void)
{
struct perf_session *session;
struct perf_evsel *pos;
session = perf_session__new(input_name, O_RDONLY, 0, false, NULL);
if (session == NULL)
return -ENOMEM;
list_for_each_entry(pos, &session->evlist->entries, node)
printf("%s\n", event_name(pos));
perf_session__delete(session);
return 0;
}
static const char * const evlist_usage[] = {
"perf evlist [<options>]",
NULL
};
static const struct option options[] = {
OPT_STRING('i', "input", &input_name, "file",
"input file name"),
OPT_END()
};
int cmd_evlist(int argc, const char **argv, const char *prefix __used)
{
argc = parse_options(argc, argv, options, evlist_usage, 0);
if (argc)
usage_with_options(evlist_usage, options);
return __cmd_evlist();
}
| gpl-2.0 |
mayli/wrapfs-latest | drivers/net/ethernet/ti/cpsw.c | 45 | 66321 | /*
* Texas Instruments Ethernet Switch Driver
*
* Copyright (C) 2012 Texas Instruments
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; 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/io.h>
#include <linux/clk.h>
#include <linux/timer.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/irqreturn.h>
#include <linux/interrupt.h>
#include <linux/if_ether.h>
#include <linux/etherdevice.h>
#include <linux/netdevice.h>
#include <linux/net_tstamp.h>
#include <linux/phy.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include <linux/of_device.h>
#include <linux/if_vlan.h>
#include <linux/pinctrl/consumer.h>
#include "cpsw.h"
#include "cpsw_ale.h"
#include "cpts.h"
#include "davinci_cpdma.h"
#define CPSW_DEBUG (NETIF_MSG_HW | NETIF_MSG_WOL | \
NETIF_MSG_DRV | NETIF_MSG_LINK | \
NETIF_MSG_IFUP | NETIF_MSG_INTR | \
NETIF_MSG_PROBE | NETIF_MSG_TIMER | \
NETIF_MSG_IFDOWN | NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR | NETIF_MSG_TX_DONE | \
NETIF_MSG_PKTDATA | NETIF_MSG_TX_QUEUED | \
NETIF_MSG_RX_STATUS)
#define cpsw_info(priv, type, format, ...) \
do { \
if (netif_msg_##type(priv) && net_ratelimit()) \
dev_info(priv->dev, format, ## __VA_ARGS__); \
} while (0)
#define cpsw_err(priv, type, format, ...) \
do { \
if (netif_msg_##type(priv) && net_ratelimit()) \
dev_err(priv->dev, format, ## __VA_ARGS__); \
} while (0)
#define cpsw_dbg(priv, type, format, ...) \
do { \
if (netif_msg_##type(priv) && net_ratelimit()) \
dev_dbg(priv->dev, format, ## __VA_ARGS__); \
} while (0)
#define cpsw_notice(priv, type, format, ...) \
do { \
if (netif_msg_##type(priv) && net_ratelimit()) \
dev_notice(priv->dev, format, ## __VA_ARGS__); \
} while (0)
#define ALE_ALL_PORTS 0x7
#define CPSW_MAJOR_VERSION(reg) (reg >> 8 & 0x7)
#define CPSW_MINOR_VERSION(reg) (reg & 0xff)
#define CPSW_RTL_VERSION(reg) ((reg >> 11) & 0x1f)
#define CPSW_VERSION_1 0x19010a
#define CPSW_VERSION_2 0x19010c
#define CPSW_VERSION_3 0x19010f
#define CPSW_VERSION_4 0x190112
#define HOST_PORT_NUM 0
#define SLIVER_SIZE 0x40
#define CPSW1_HOST_PORT_OFFSET 0x028
#define CPSW1_SLAVE_OFFSET 0x050
#define CPSW1_SLAVE_SIZE 0x040
#define CPSW1_CPDMA_OFFSET 0x100
#define CPSW1_STATERAM_OFFSET 0x200
#define CPSW1_HW_STATS 0x400
#define CPSW1_CPTS_OFFSET 0x500
#define CPSW1_ALE_OFFSET 0x600
#define CPSW1_SLIVER_OFFSET 0x700
#define CPSW2_HOST_PORT_OFFSET 0x108
#define CPSW2_SLAVE_OFFSET 0x200
#define CPSW2_SLAVE_SIZE 0x100
#define CPSW2_CPDMA_OFFSET 0x800
#define CPSW2_HW_STATS 0x900
#define CPSW2_STATERAM_OFFSET 0xa00
#define CPSW2_CPTS_OFFSET 0xc00
#define CPSW2_ALE_OFFSET 0xd00
#define CPSW2_SLIVER_OFFSET 0xd80
#define CPSW2_BD_OFFSET 0x2000
#define CPDMA_RXTHRESH 0x0c0
#define CPDMA_RXFREE 0x0e0
#define CPDMA_TXHDP 0x00
#define CPDMA_RXHDP 0x20
#define CPDMA_TXCP 0x40
#define CPDMA_RXCP 0x60
#define CPSW_POLL_WEIGHT 64
#define CPSW_MIN_PACKET_SIZE 60
#define CPSW_MAX_PACKET_SIZE (1500 + 14 + 4 + 4)
#define RX_PRIORITY_MAPPING 0x76543210
#define TX_PRIORITY_MAPPING 0x33221100
#define CPDMA_TX_PRIORITY_MAP 0x76543210
#define CPSW_VLAN_AWARE BIT(1)
#define CPSW_ALE_VLAN_AWARE 1
#define CPSW_FIFO_NORMAL_MODE (0 << 15)
#define CPSW_FIFO_DUAL_MAC_MODE (1 << 15)
#define CPSW_FIFO_RATE_LIMIT_MODE (2 << 15)
#define CPSW_INTPACEEN (0x3f << 16)
#define CPSW_INTPRESCALE_MASK (0x7FF << 0)
#define CPSW_CMINTMAX_CNT 63
#define CPSW_CMINTMIN_CNT 2
#define CPSW_CMINTMAX_INTVL (1000 / CPSW_CMINTMIN_CNT)
#define CPSW_CMINTMIN_INTVL ((1000 / CPSW_CMINTMAX_CNT) + 1)
#define cpsw_enable_irq(priv) \
do { \
u32 i; \
for (i = 0; i < priv->num_irqs; i++) \
enable_irq(priv->irqs_table[i]); \
} while (0)
#define cpsw_disable_irq(priv) \
do { \
u32 i; \
for (i = 0; i < priv->num_irqs; i++) \
disable_irq_nosync(priv->irqs_table[i]); \
} while (0)
#define cpsw_slave_index(priv) \
((priv->data.dual_emac) ? priv->emac_port : \
priv->data.active_slave)
static int debug_level;
module_param(debug_level, int, 0);
MODULE_PARM_DESC(debug_level, "cpsw debug level (NETIF_MSG bits)");
static int ale_ageout = 10;
module_param(ale_ageout, int, 0);
MODULE_PARM_DESC(ale_ageout, "cpsw ale ageout interval (seconds)");
static int rx_packet_max = CPSW_MAX_PACKET_SIZE;
module_param(rx_packet_max, int, 0);
MODULE_PARM_DESC(rx_packet_max, "maximum receive packet size (bytes)");
struct cpsw_wr_regs {
u32 id_ver;
u32 soft_reset;
u32 control;
u32 int_control;
u32 rx_thresh_en;
u32 rx_en;
u32 tx_en;
u32 misc_en;
u32 mem_allign1[8];
u32 rx_thresh_stat;
u32 rx_stat;
u32 tx_stat;
u32 misc_stat;
u32 mem_allign2[8];
u32 rx_imax;
u32 tx_imax;
};
struct cpsw_ss_regs {
u32 id_ver;
u32 control;
u32 soft_reset;
u32 stat_port_en;
u32 ptype;
u32 soft_idle;
u32 thru_rate;
u32 gap_thresh;
u32 tx_start_wds;
u32 flow_control;
u32 vlan_ltype;
u32 ts_ltype;
u32 dlr_ltype;
};
/* CPSW_PORT_V1 */
#define CPSW1_MAX_BLKS 0x00 /* Maximum FIFO Blocks */
#define CPSW1_BLK_CNT 0x04 /* FIFO Block Usage Count (Read Only) */
#define CPSW1_TX_IN_CTL 0x08 /* Transmit FIFO Control */
#define CPSW1_PORT_VLAN 0x0c /* VLAN Register */
#define CPSW1_TX_PRI_MAP 0x10 /* Tx Header Priority to Switch Pri Mapping */
#define CPSW1_TS_CTL 0x14 /* Time Sync Control */
#define CPSW1_TS_SEQ_LTYPE 0x18 /* Time Sync Sequence ID Offset and Msg Type */
#define CPSW1_TS_VLAN 0x1c /* Time Sync VLAN1 and VLAN2 */
/* CPSW_PORT_V2 */
#define CPSW2_CONTROL 0x00 /* Control Register */
#define CPSW2_MAX_BLKS 0x08 /* Maximum FIFO Blocks */
#define CPSW2_BLK_CNT 0x0c /* FIFO Block Usage Count (Read Only) */
#define CPSW2_TX_IN_CTL 0x10 /* Transmit FIFO Control */
#define CPSW2_PORT_VLAN 0x14 /* VLAN Register */
#define CPSW2_TX_PRI_MAP 0x18 /* Tx Header Priority to Switch Pri Mapping */
#define CPSW2_TS_SEQ_MTYPE 0x1c /* Time Sync Sequence ID Offset and Msg Type */
/* CPSW_PORT_V1 and V2 */
#define SA_LO 0x20 /* CPGMAC_SL Source Address Low */
#define SA_HI 0x24 /* CPGMAC_SL Source Address High */
#define SEND_PERCENT 0x28 /* Transmit Queue Send Percentages */
/* CPSW_PORT_V2 only */
#define RX_DSCP_PRI_MAP0 0x30 /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP1 0x34 /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP2 0x38 /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP3 0x3c /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP4 0x40 /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP5 0x44 /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP6 0x48 /* Rx DSCP Priority to Rx Packet Mapping */
#define RX_DSCP_PRI_MAP7 0x4c /* Rx DSCP Priority to Rx Packet Mapping */
/* Bit definitions for the CPSW2_CONTROL register */
#define PASS_PRI_TAGGED (1<<24) /* Pass Priority Tagged */
#define VLAN_LTYPE2_EN (1<<21) /* VLAN LTYPE 2 enable */
#define VLAN_LTYPE1_EN (1<<20) /* VLAN LTYPE 1 enable */
#define DSCP_PRI_EN (1<<16) /* DSCP Priority Enable */
#define TS_320 (1<<14) /* Time Sync Dest Port 320 enable */
#define TS_319 (1<<13) /* Time Sync Dest Port 319 enable */
#define TS_132 (1<<12) /* Time Sync Dest IP Addr 132 enable */
#define TS_131 (1<<11) /* Time Sync Dest IP Addr 131 enable */
#define TS_130 (1<<10) /* Time Sync Dest IP Addr 130 enable */
#define TS_129 (1<<9) /* Time Sync Dest IP Addr 129 enable */
#define TS_TTL_NONZERO (1<<8) /* Time Sync Time To Live Non-zero enable */
#define TS_ANNEX_F_EN (1<<6) /* Time Sync Annex F enable */
#define TS_ANNEX_D_EN (1<<4) /* Time Sync Annex D enable */
#define TS_LTYPE2_EN (1<<3) /* Time Sync LTYPE 2 enable */
#define TS_LTYPE1_EN (1<<2) /* Time Sync LTYPE 1 enable */
#define TS_TX_EN (1<<1) /* Time Sync Transmit Enable */
#define TS_RX_EN (1<<0) /* Time Sync Receive Enable */
#define CTRL_V2_TS_BITS \
(TS_320 | TS_319 | TS_132 | TS_131 | TS_130 | TS_129 |\
TS_TTL_NONZERO | TS_ANNEX_D_EN | TS_LTYPE1_EN)
#define CTRL_V2_ALL_TS_MASK (CTRL_V2_TS_BITS | TS_TX_EN | TS_RX_EN)
#define CTRL_V2_TX_TS_BITS (CTRL_V2_TS_BITS | TS_TX_EN)
#define CTRL_V2_RX_TS_BITS (CTRL_V2_TS_BITS | TS_RX_EN)
#define CTRL_V3_TS_BITS \
(TS_320 | TS_319 | TS_132 | TS_131 | TS_130 | TS_129 |\
TS_TTL_NONZERO | TS_ANNEX_F_EN | TS_ANNEX_D_EN |\
TS_LTYPE1_EN)
#define CTRL_V3_ALL_TS_MASK (CTRL_V3_TS_BITS | TS_TX_EN | TS_RX_EN)
#define CTRL_V3_TX_TS_BITS (CTRL_V3_TS_BITS | TS_TX_EN)
#define CTRL_V3_RX_TS_BITS (CTRL_V3_TS_BITS | TS_RX_EN)
/* Bit definitions for the CPSW2_TS_SEQ_MTYPE register */
#define TS_SEQ_ID_OFFSET_SHIFT (16) /* Time Sync Sequence ID Offset */
#define TS_SEQ_ID_OFFSET_MASK (0x3f)
#define TS_MSG_TYPE_EN_SHIFT (0) /* Time Sync Message Type Enable */
#define TS_MSG_TYPE_EN_MASK (0xffff)
/* The PTP event messages - Sync, Delay_Req, Pdelay_Req, and Pdelay_Resp. */
#define EVENT_MSG_BITS ((1<<0) | (1<<1) | (1<<2) | (1<<3))
/* Bit definitions for the CPSW1_TS_CTL register */
#define CPSW_V1_TS_RX_EN BIT(0)
#define CPSW_V1_TS_TX_EN BIT(4)
#define CPSW_V1_MSG_TYPE_OFS 16
/* Bit definitions for the CPSW1_TS_SEQ_LTYPE register */
#define CPSW_V1_SEQ_ID_OFS_SHIFT 16
struct cpsw_host_regs {
u32 max_blks;
u32 blk_cnt;
u32 tx_in_ctl;
u32 port_vlan;
u32 tx_pri_map;
u32 cpdma_tx_pri_map;
u32 cpdma_rx_chan_map;
};
struct cpsw_sliver_regs {
u32 id_ver;
u32 mac_control;
u32 mac_status;
u32 soft_reset;
u32 rx_maxlen;
u32 __reserved_0;
u32 rx_pause;
u32 tx_pause;
u32 __reserved_1;
u32 rx_pri_map;
};
struct cpsw_hw_stats {
u32 rxgoodframes;
u32 rxbroadcastframes;
u32 rxmulticastframes;
u32 rxpauseframes;
u32 rxcrcerrors;
u32 rxaligncodeerrors;
u32 rxoversizedframes;
u32 rxjabberframes;
u32 rxundersizedframes;
u32 rxfragments;
u32 __pad_0[2];
u32 rxoctets;
u32 txgoodframes;
u32 txbroadcastframes;
u32 txmulticastframes;
u32 txpauseframes;
u32 txdeferredframes;
u32 txcollisionframes;
u32 txsinglecollframes;
u32 txmultcollframes;
u32 txexcessivecollisions;
u32 txlatecollisions;
u32 txunderrun;
u32 txcarriersenseerrors;
u32 txoctets;
u32 octetframes64;
u32 octetframes65t127;
u32 octetframes128t255;
u32 octetframes256t511;
u32 octetframes512t1023;
u32 octetframes1024tup;
u32 netoctets;
u32 rxsofoverruns;
u32 rxmofoverruns;
u32 rxdmaoverruns;
};
struct cpsw_slave {
void __iomem *regs;
struct cpsw_sliver_regs __iomem *sliver;
int slave_num;
u32 mac_control;
struct cpsw_slave_data *data;
struct phy_device *phy;
struct net_device *ndev;
u32 port_vlan;
u32 open_stat;
};
static inline u32 slave_read(struct cpsw_slave *slave, u32 offset)
{
return __raw_readl(slave->regs + offset);
}
static inline void slave_write(struct cpsw_slave *slave, u32 val, u32 offset)
{
__raw_writel(val, slave->regs + offset);
}
struct cpsw_priv {
spinlock_t lock;
struct platform_device *pdev;
struct net_device *ndev;
struct napi_struct napi;
struct device *dev;
struct cpsw_platform_data data;
struct cpsw_ss_regs __iomem *regs;
struct cpsw_wr_regs __iomem *wr_regs;
u8 __iomem *hw_stats;
struct cpsw_host_regs __iomem *host_port_regs;
u32 msg_enable;
u32 version;
u32 coal_intvl;
u32 bus_freq_mhz;
int rx_packet_max;
int host_port;
struct clk *clk;
u8 mac_addr[ETH_ALEN];
struct cpsw_slave *slaves;
struct cpdma_ctlr *dma;
struct cpdma_chan *txch, *rxch;
struct cpsw_ale *ale;
/* snapshot of IRQ numbers */
u32 irqs_table[4];
u32 num_irqs;
bool irq_enabled;
struct cpts *cpts;
u32 emac_port;
};
struct cpsw_stats {
char stat_string[ETH_GSTRING_LEN];
int type;
int sizeof_stat;
int stat_offset;
};
enum {
CPSW_STATS,
CPDMA_RX_STATS,
CPDMA_TX_STATS,
};
#define CPSW_STAT(m) CPSW_STATS, \
sizeof(((struct cpsw_hw_stats *)0)->m), \
offsetof(struct cpsw_hw_stats, m)
#define CPDMA_RX_STAT(m) CPDMA_RX_STATS, \
sizeof(((struct cpdma_chan_stats *)0)->m), \
offsetof(struct cpdma_chan_stats, m)
#define CPDMA_TX_STAT(m) CPDMA_TX_STATS, \
sizeof(((struct cpdma_chan_stats *)0)->m), \
offsetof(struct cpdma_chan_stats, m)
static const struct cpsw_stats cpsw_gstrings_stats[] = {
{ "Good Rx Frames", CPSW_STAT(rxgoodframes) },
{ "Broadcast Rx Frames", CPSW_STAT(rxbroadcastframes) },
{ "Multicast Rx Frames", CPSW_STAT(rxmulticastframes) },
{ "Pause Rx Frames", CPSW_STAT(rxpauseframes) },
{ "Rx CRC Errors", CPSW_STAT(rxcrcerrors) },
{ "Rx Align/Code Errors", CPSW_STAT(rxaligncodeerrors) },
{ "Oversize Rx Frames", CPSW_STAT(rxoversizedframes) },
{ "Rx Jabbers", CPSW_STAT(rxjabberframes) },
{ "Undersize (Short) Rx Frames", CPSW_STAT(rxundersizedframes) },
{ "Rx Fragments", CPSW_STAT(rxfragments) },
{ "Rx Octets", CPSW_STAT(rxoctets) },
{ "Good Tx Frames", CPSW_STAT(txgoodframes) },
{ "Broadcast Tx Frames", CPSW_STAT(txbroadcastframes) },
{ "Multicast Tx Frames", CPSW_STAT(txmulticastframes) },
{ "Pause Tx Frames", CPSW_STAT(txpauseframes) },
{ "Deferred Tx Frames", CPSW_STAT(txdeferredframes) },
{ "Collisions", CPSW_STAT(txcollisionframes) },
{ "Single Collision Tx Frames", CPSW_STAT(txsinglecollframes) },
{ "Multiple Collision Tx Frames", CPSW_STAT(txmultcollframes) },
{ "Excessive Collisions", CPSW_STAT(txexcessivecollisions) },
{ "Late Collisions", CPSW_STAT(txlatecollisions) },
{ "Tx Underrun", CPSW_STAT(txunderrun) },
{ "Carrier Sense Errors", CPSW_STAT(txcarriersenseerrors) },
{ "Tx Octets", CPSW_STAT(txoctets) },
{ "Rx + Tx 64 Octet Frames", CPSW_STAT(octetframes64) },
{ "Rx + Tx 65-127 Octet Frames", CPSW_STAT(octetframes65t127) },
{ "Rx + Tx 128-255 Octet Frames", CPSW_STAT(octetframes128t255) },
{ "Rx + Tx 256-511 Octet Frames", CPSW_STAT(octetframes256t511) },
{ "Rx + Tx 512-1023 Octet Frames", CPSW_STAT(octetframes512t1023) },
{ "Rx + Tx 1024-Up Octet Frames", CPSW_STAT(octetframes1024tup) },
{ "Net Octets", CPSW_STAT(netoctets) },
{ "Rx Start of Frame Overruns", CPSW_STAT(rxsofoverruns) },
{ "Rx Middle of Frame Overruns", CPSW_STAT(rxmofoverruns) },
{ "Rx DMA Overruns", CPSW_STAT(rxdmaoverruns) },
{ "Rx DMA chan: head_enqueue", CPDMA_RX_STAT(head_enqueue) },
{ "Rx DMA chan: tail_enqueue", CPDMA_RX_STAT(tail_enqueue) },
{ "Rx DMA chan: pad_enqueue", CPDMA_RX_STAT(pad_enqueue) },
{ "Rx DMA chan: misqueued", CPDMA_RX_STAT(misqueued) },
{ "Rx DMA chan: desc_alloc_fail", CPDMA_RX_STAT(desc_alloc_fail) },
{ "Rx DMA chan: pad_alloc_fail", CPDMA_RX_STAT(pad_alloc_fail) },
{ "Rx DMA chan: runt_receive_buf", CPDMA_RX_STAT(runt_receive_buff) },
{ "Rx DMA chan: runt_transmit_buf", CPDMA_RX_STAT(runt_transmit_buff) },
{ "Rx DMA chan: empty_dequeue", CPDMA_RX_STAT(empty_dequeue) },
{ "Rx DMA chan: busy_dequeue", CPDMA_RX_STAT(busy_dequeue) },
{ "Rx DMA chan: good_dequeue", CPDMA_RX_STAT(good_dequeue) },
{ "Rx DMA chan: requeue", CPDMA_RX_STAT(requeue) },
{ "Rx DMA chan: teardown_dequeue", CPDMA_RX_STAT(teardown_dequeue) },
{ "Tx DMA chan: head_enqueue", CPDMA_TX_STAT(head_enqueue) },
{ "Tx DMA chan: tail_enqueue", CPDMA_TX_STAT(tail_enqueue) },
{ "Tx DMA chan: pad_enqueue", CPDMA_TX_STAT(pad_enqueue) },
{ "Tx DMA chan: misqueued", CPDMA_TX_STAT(misqueued) },
{ "Tx DMA chan: desc_alloc_fail", CPDMA_TX_STAT(desc_alloc_fail) },
{ "Tx DMA chan: pad_alloc_fail", CPDMA_TX_STAT(pad_alloc_fail) },
{ "Tx DMA chan: runt_receive_buf", CPDMA_TX_STAT(runt_receive_buff) },
{ "Tx DMA chan: runt_transmit_buf", CPDMA_TX_STAT(runt_transmit_buff) },
{ "Tx DMA chan: empty_dequeue", CPDMA_TX_STAT(empty_dequeue) },
{ "Tx DMA chan: busy_dequeue", CPDMA_TX_STAT(busy_dequeue) },
{ "Tx DMA chan: good_dequeue", CPDMA_TX_STAT(good_dequeue) },
{ "Tx DMA chan: requeue", CPDMA_TX_STAT(requeue) },
{ "Tx DMA chan: teardown_dequeue", CPDMA_TX_STAT(teardown_dequeue) },
};
#define CPSW_STATS_LEN ARRAY_SIZE(cpsw_gstrings_stats)
#define napi_to_priv(napi) container_of(napi, struct cpsw_priv, napi)
#define for_each_slave(priv, func, arg...) \
do { \
struct cpsw_slave *slave; \
int n; \
if (priv->data.dual_emac) \
(func)((priv)->slaves + priv->emac_port, ##arg);\
else \
for (n = (priv)->data.slaves, \
slave = (priv)->slaves; \
n; n--) \
(func)(slave++, ##arg); \
} while (0)
#define cpsw_get_slave_ndev(priv, __slave_no__) \
(priv->slaves[__slave_no__].ndev)
#define cpsw_get_slave_priv(priv, __slave_no__) \
((priv->slaves[__slave_no__].ndev) ? \
netdev_priv(priv->slaves[__slave_no__].ndev) : NULL) \
#define cpsw_dual_emac_src_port_detect(status, priv, ndev, skb) \
do { \
if (!priv->data.dual_emac) \
break; \
if (CPDMA_RX_SOURCE_PORT(status) == 1) { \
ndev = cpsw_get_slave_ndev(priv, 0); \
priv = netdev_priv(ndev); \
skb->dev = ndev; \
} else if (CPDMA_RX_SOURCE_PORT(status) == 2) { \
ndev = cpsw_get_slave_ndev(priv, 1); \
priv = netdev_priv(ndev); \
skb->dev = ndev; \
} \
} while (0)
#define cpsw_add_mcast(priv, addr) \
do { \
if (priv->data.dual_emac) { \
struct cpsw_slave *slave = priv->slaves + \
priv->emac_port; \
int slave_port = cpsw_get_slave_port(priv, \
slave->slave_num); \
cpsw_ale_add_mcast(priv->ale, addr, \
1 << slave_port | 1 << priv->host_port, \
ALE_VLAN, slave->port_vlan, 0); \
} else { \
cpsw_ale_add_mcast(priv->ale, addr, \
ALE_ALL_PORTS << priv->host_port, \
0, 0, 0); \
} \
} while (0)
static inline int cpsw_get_slave_port(struct cpsw_priv *priv, u32 slave_num)
{
if (priv->host_port == 0)
return slave_num + 1;
else
return slave_num;
}
static void cpsw_set_promiscious(struct net_device *ndev, bool enable)
{
struct cpsw_priv *priv = netdev_priv(ndev);
struct cpsw_ale *ale = priv->ale;
int i;
if (priv->data.dual_emac) {
bool flag = false;
/* Enabling promiscuous mode for one interface will be
* common for both the interface as the interface shares
* the same hardware resource.
*/
for (i = 0; i < priv->data.slaves; i++)
if (priv->slaves[i].ndev->flags & IFF_PROMISC)
flag = true;
if (!enable && flag) {
enable = true;
dev_err(&ndev->dev, "promiscuity not disabled as the other interface is still in promiscuity mode\n");
}
if (enable) {
/* Enable Bypass */
cpsw_ale_control_set(ale, 0, ALE_BYPASS, 1);
dev_dbg(&ndev->dev, "promiscuity enabled\n");
} else {
/* Disable Bypass */
cpsw_ale_control_set(ale, 0, ALE_BYPASS, 0);
dev_dbg(&ndev->dev, "promiscuity disabled\n");
}
} else {
if (enable) {
unsigned long timeout = jiffies + HZ;
/* Disable Learn for all ports */
for (i = 0; i < priv->data.slaves; i++) {
cpsw_ale_control_set(ale, i,
ALE_PORT_NOLEARN, 1);
cpsw_ale_control_set(ale, i,
ALE_PORT_NO_SA_UPDATE, 1);
}
/* Clear All Untouched entries */
cpsw_ale_control_set(ale, 0, ALE_AGEOUT, 1);
do {
cpu_relax();
if (cpsw_ale_control_get(ale, 0, ALE_AGEOUT))
break;
} while (time_after(timeout, jiffies));
cpsw_ale_control_set(ale, 0, ALE_AGEOUT, 1);
/* Clear all mcast from ALE */
cpsw_ale_flush_multicast(ale, ALE_ALL_PORTS <<
priv->host_port);
/* Flood All Unicast Packets to Host port */
cpsw_ale_control_set(ale, 0, ALE_P0_UNI_FLOOD, 1);
dev_dbg(&ndev->dev, "promiscuity enabled\n");
} else {
/* Flood All Unicast Packets to Host port */
cpsw_ale_control_set(ale, 0, ALE_P0_UNI_FLOOD, 0);
/* Enable Learn for all ports */
for (i = 0; i < priv->data.slaves; i++) {
cpsw_ale_control_set(ale, i,
ALE_PORT_NOLEARN, 0);
cpsw_ale_control_set(ale, i,
ALE_PORT_NO_SA_UPDATE, 0);
}
dev_dbg(&ndev->dev, "promiscuity disabled\n");
}
}
}
static void cpsw_ndo_set_rx_mode(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
if (ndev->flags & IFF_PROMISC) {
/* Enable promiscuous mode */
cpsw_set_promiscious(ndev, true);
return;
} else {
/* Disable promiscuous mode */
cpsw_set_promiscious(ndev, false);
}
/* Clear all mcast from ALE */
cpsw_ale_flush_multicast(priv->ale, ALE_ALL_PORTS << priv->host_port);
if (!netdev_mc_empty(ndev)) {
struct netdev_hw_addr *ha;
/* program multicast address list into ALE register */
netdev_for_each_mc_addr(ha, ndev) {
cpsw_add_mcast(priv, (u8 *)ha->addr);
}
}
}
static void cpsw_intr_enable(struct cpsw_priv *priv)
{
__raw_writel(0xFF, &priv->wr_regs->tx_en);
__raw_writel(0xFF, &priv->wr_regs->rx_en);
cpdma_ctlr_int_ctrl(priv->dma, true);
return;
}
static void cpsw_intr_disable(struct cpsw_priv *priv)
{
__raw_writel(0, &priv->wr_regs->tx_en);
__raw_writel(0, &priv->wr_regs->rx_en);
cpdma_ctlr_int_ctrl(priv->dma, false);
return;
}
static void cpsw_tx_handler(void *token, int len, int status)
{
struct sk_buff *skb = token;
struct net_device *ndev = skb->dev;
struct cpsw_priv *priv = netdev_priv(ndev);
/* Check whether the queue is stopped due to stalled tx dma, if the
* queue is stopped then start the queue as we have free desc for tx
*/
if (unlikely(netif_queue_stopped(ndev)))
netif_wake_queue(ndev);
cpts_tx_timestamp(priv->cpts, skb);
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += len;
dev_kfree_skb_any(skb);
}
static void cpsw_rx_handler(void *token, int len, int status)
{
struct sk_buff *skb = token;
struct sk_buff *new_skb;
struct net_device *ndev = skb->dev;
struct cpsw_priv *priv = netdev_priv(ndev);
int ret = 0;
cpsw_dual_emac_src_port_detect(status, priv, ndev, skb);
if (unlikely(status < 0) || unlikely(!netif_running(ndev))) {
/* the interface is going down, skbs are purged */
dev_kfree_skb_any(skb);
return;
}
new_skb = netdev_alloc_skb_ip_align(ndev, priv->rx_packet_max);
if (new_skb) {
skb_put(skb, len);
cpts_rx_timestamp(priv->cpts, skb);
skb->protocol = eth_type_trans(skb, ndev);
netif_receive_skb(skb);
ndev->stats.rx_bytes += len;
ndev->stats.rx_packets++;
} else {
ndev->stats.rx_dropped++;
new_skb = skb;
}
ret = cpdma_chan_submit(priv->rxch, new_skb, new_skb->data,
skb_tailroom(new_skb), 0);
if (WARN_ON(ret < 0))
dev_kfree_skb_any(new_skb);
}
static irqreturn_t cpsw_interrupt(int irq, void *dev_id)
{
struct cpsw_priv *priv = dev_id;
cpsw_intr_disable(priv);
if (priv->irq_enabled == true) {
cpsw_disable_irq(priv);
priv->irq_enabled = false;
}
if (netif_running(priv->ndev)) {
napi_schedule(&priv->napi);
return IRQ_HANDLED;
}
priv = cpsw_get_slave_priv(priv, 1);
if (!priv)
return IRQ_NONE;
if (netif_running(priv->ndev)) {
napi_schedule(&priv->napi);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static int cpsw_poll(struct napi_struct *napi, int budget)
{
struct cpsw_priv *priv = napi_to_priv(napi);
int num_tx, num_rx;
num_tx = cpdma_chan_process(priv->txch, 128);
if (num_tx)
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_TX);
num_rx = cpdma_chan_process(priv->rxch, budget);
if (num_rx < budget) {
struct cpsw_priv *prim_cpsw;
napi_complete(napi);
cpsw_intr_enable(priv);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_RX);
prim_cpsw = cpsw_get_slave_priv(priv, 0);
if (prim_cpsw->irq_enabled == false) {
prim_cpsw->irq_enabled = true;
cpsw_enable_irq(priv);
}
}
if (num_rx || num_tx)
cpsw_dbg(priv, intr, "poll %d rx, %d tx pkts\n",
num_rx, num_tx);
return num_rx;
}
static inline void soft_reset(const char *module, void __iomem *reg)
{
unsigned long timeout = jiffies + HZ;
__raw_writel(1, reg);
do {
cpu_relax();
} while ((__raw_readl(reg) & 1) && time_after(timeout, jiffies));
WARN(__raw_readl(reg) & 1, "failed to soft-reset %s\n", module);
}
#define mac_hi(mac) (((mac)[0] << 0) | ((mac)[1] << 8) | \
((mac)[2] << 16) | ((mac)[3] << 24))
#define mac_lo(mac) (((mac)[4] << 0) | ((mac)[5] << 8))
static void cpsw_set_slave_mac(struct cpsw_slave *slave,
struct cpsw_priv *priv)
{
slave_write(slave, mac_hi(priv->mac_addr), SA_HI);
slave_write(slave, mac_lo(priv->mac_addr), SA_LO);
}
static void _cpsw_adjust_link(struct cpsw_slave *slave,
struct cpsw_priv *priv, bool *link)
{
struct phy_device *phy = slave->phy;
u32 mac_control = 0;
u32 slave_port;
if (!phy)
return;
slave_port = cpsw_get_slave_port(priv, slave->slave_num);
if (phy->link) {
mac_control = priv->data.mac_control;
/* enable forwarding */
cpsw_ale_control_set(priv->ale, slave_port,
ALE_PORT_STATE, ALE_PORT_STATE_FORWARD);
if (phy->speed == 1000)
mac_control |= BIT(7); /* GIGABITEN */
if (phy->duplex)
mac_control |= BIT(0); /* FULLDUPLEXEN */
/* set speed_in input in case RMII mode is used in 100Mbps */
if (phy->speed == 100)
mac_control |= BIT(15);
else if (phy->speed == 10)
mac_control |= BIT(18); /* In Band mode */
*link = true;
} else {
mac_control = 0;
/* disable forwarding */
cpsw_ale_control_set(priv->ale, slave_port,
ALE_PORT_STATE, ALE_PORT_STATE_DISABLE);
}
if (mac_control != slave->mac_control) {
phy_print_status(phy);
__raw_writel(mac_control, &slave->sliver->mac_control);
}
slave->mac_control = mac_control;
}
static void cpsw_adjust_link(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
bool link = false;
for_each_slave(priv, _cpsw_adjust_link, priv, &link);
if (link) {
netif_carrier_on(ndev);
if (netif_running(ndev))
netif_wake_queue(ndev);
} else {
netif_carrier_off(ndev);
netif_stop_queue(ndev);
}
}
static int cpsw_get_coalesce(struct net_device *ndev,
struct ethtool_coalesce *coal)
{
struct cpsw_priv *priv = netdev_priv(ndev);
coal->rx_coalesce_usecs = priv->coal_intvl;
return 0;
}
static int cpsw_set_coalesce(struct net_device *ndev,
struct ethtool_coalesce *coal)
{
struct cpsw_priv *priv = netdev_priv(ndev);
u32 int_ctrl;
u32 num_interrupts = 0;
u32 prescale = 0;
u32 addnl_dvdr = 1;
u32 coal_intvl = 0;
coal_intvl = coal->rx_coalesce_usecs;
int_ctrl = readl(&priv->wr_regs->int_control);
prescale = priv->bus_freq_mhz * 4;
if (!coal->rx_coalesce_usecs) {
int_ctrl &= ~(CPSW_INTPRESCALE_MASK | CPSW_INTPACEEN);
goto update_return;
}
if (coal_intvl < CPSW_CMINTMIN_INTVL)
coal_intvl = CPSW_CMINTMIN_INTVL;
if (coal_intvl > CPSW_CMINTMAX_INTVL) {
/* Interrupt pacer works with 4us Pulse, we can
* throttle further by dilating the 4us pulse.
*/
addnl_dvdr = CPSW_INTPRESCALE_MASK / prescale;
if (addnl_dvdr > 1) {
prescale *= addnl_dvdr;
if (coal_intvl > (CPSW_CMINTMAX_INTVL * addnl_dvdr))
coal_intvl = (CPSW_CMINTMAX_INTVL
* addnl_dvdr);
} else {
addnl_dvdr = 1;
coal_intvl = CPSW_CMINTMAX_INTVL;
}
}
num_interrupts = (1000 * addnl_dvdr) / coal_intvl;
writel(num_interrupts, &priv->wr_regs->rx_imax);
writel(num_interrupts, &priv->wr_regs->tx_imax);
int_ctrl |= CPSW_INTPACEEN;
int_ctrl &= (~CPSW_INTPRESCALE_MASK);
int_ctrl |= (prescale & CPSW_INTPRESCALE_MASK);
update_return:
writel(int_ctrl, &priv->wr_regs->int_control);
cpsw_notice(priv, timer, "Set coalesce to %d usecs.\n", coal_intvl);
if (priv->data.dual_emac) {
int i;
for (i = 0; i < priv->data.slaves; i++) {
priv = netdev_priv(priv->slaves[i].ndev);
priv->coal_intvl = coal_intvl;
}
} else {
priv->coal_intvl = coal_intvl;
}
return 0;
}
static int cpsw_get_sset_count(struct net_device *ndev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return CPSW_STATS_LEN;
default:
return -EOPNOTSUPP;
}
}
static void cpsw_get_strings(struct net_device *ndev, u32 stringset, u8 *data)
{
u8 *p = data;
int i;
switch (stringset) {
case ETH_SS_STATS:
for (i = 0; i < CPSW_STATS_LEN; i++) {
memcpy(p, cpsw_gstrings_stats[i].stat_string,
ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
break;
}
}
static void cpsw_get_ethtool_stats(struct net_device *ndev,
struct ethtool_stats *stats, u64 *data)
{
struct cpsw_priv *priv = netdev_priv(ndev);
struct cpdma_chan_stats rx_stats;
struct cpdma_chan_stats tx_stats;
u32 val;
u8 *p;
int i;
/* Collect Davinci CPDMA stats for Rx and Tx Channel */
cpdma_chan_get_stats(priv->rxch, &rx_stats);
cpdma_chan_get_stats(priv->txch, &tx_stats);
for (i = 0; i < CPSW_STATS_LEN; i++) {
switch (cpsw_gstrings_stats[i].type) {
case CPSW_STATS:
val = readl(priv->hw_stats +
cpsw_gstrings_stats[i].stat_offset);
data[i] = val;
break;
case CPDMA_RX_STATS:
p = (u8 *)&rx_stats +
cpsw_gstrings_stats[i].stat_offset;
data[i] = *(u32 *)p;
break;
case CPDMA_TX_STATS:
p = (u8 *)&tx_stats +
cpsw_gstrings_stats[i].stat_offset;
data[i] = *(u32 *)p;
break;
}
}
}
static int cpsw_common_res_usage_state(struct cpsw_priv *priv)
{
u32 i;
u32 usage_count = 0;
if (!priv->data.dual_emac)
return 0;
for (i = 0; i < priv->data.slaves; i++)
if (priv->slaves[i].open_stat)
usage_count++;
return usage_count;
}
static inline int cpsw_tx_packet_submit(struct net_device *ndev,
struct cpsw_priv *priv, struct sk_buff *skb)
{
if (!priv->data.dual_emac)
return cpdma_chan_submit(priv->txch, skb, skb->data,
skb->len, 0);
if (ndev == cpsw_get_slave_ndev(priv, 0))
return cpdma_chan_submit(priv->txch, skb, skb->data,
skb->len, 1);
else
return cpdma_chan_submit(priv->txch, skb, skb->data,
skb->len, 2);
}
static inline void cpsw_add_dual_emac_def_ale_entries(
struct cpsw_priv *priv, struct cpsw_slave *slave,
u32 slave_port)
{
u32 port_mask = 1 << slave_port | 1 << priv->host_port;
if (priv->version == CPSW_VERSION_1)
slave_write(slave, slave->port_vlan, CPSW1_PORT_VLAN);
else
slave_write(slave, slave->port_vlan, CPSW2_PORT_VLAN);
cpsw_ale_add_vlan(priv->ale, slave->port_vlan, port_mask,
port_mask, port_mask, 0);
cpsw_ale_add_mcast(priv->ale, priv->ndev->broadcast,
port_mask, ALE_VLAN, slave->port_vlan, 0);
cpsw_ale_add_ucast(priv->ale, priv->mac_addr,
priv->host_port, ALE_VLAN, slave->port_vlan);
}
static void soft_reset_slave(struct cpsw_slave *slave)
{
char name[32];
snprintf(name, sizeof(name), "slave-%d", slave->slave_num);
soft_reset(name, &slave->sliver->soft_reset);
}
static void cpsw_slave_open(struct cpsw_slave *slave, struct cpsw_priv *priv)
{
u32 slave_port;
soft_reset_slave(slave);
/* setup priority mapping */
__raw_writel(RX_PRIORITY_MAPPING, &slave->sliver->rx_pri_map);
switch (priv->version) {
case CPSW_VERSION_1:
slave_write(slave, TX_PRIORITY_MAPPING, CPSW1_TX_PRI_MAP);
break;
case CPSW_VERSION_2:
case CPSW_VERSION_3:
case CPSW_VERSION_4:
slave_write(slave, TX_PRIORITY_MAPPING, CPSW2_TX_PRI_MAP);
break;
}
/* setup max packet size, and mac address */
__raw_writel(priv->rx_packet_max, &slave->sliver->rx_maxlen);
cpsw_set_slave_mac(slave, priv);
slave->mac_control = 0; /* no link yet */
slave_port = cpsw_get_slave_port(priv, slave->slave_num);
if (priv->data.dual_emac)
cpsw_add_dual_emac_def_ale_entries(priv, slave, slave_port);
else
cpsw_ale_add_mcast(priv->ale, priv->ndev->broadcast,
1 << slave_port, 0, 0, ALE_MCAST_FWD_2);
slave->phy = phy_connect(priv->ndev, slave->data->phy_id,
&cpsw_adjust_link, slave->data->phy_if);
if (IS_ERR(slave->phy)) {
dev_err(priv->dev, "phy %s not found on slave %d\n",
slave->data->phy_id, slave->slave_num);
slave->phy = NULL;
} else {
dev_info(priv->dev, "phy found : id is : 0x%x\n",
slave->phy->phy_id);
phy_start(slave->phy);
/* Configure GMII_SEL register */
cpsw_phy_sel(&priv->pdev->dev, slave->phy->interface,
slave->slave_num);
}
}
static inline void cpsw_add_default_vlan(struct cpsw_priv *priv)
{
const int vlan = priv->data.default_vlan;
const int port = priv->host_port;
u32 reg;
int i;
reg = (priv->version == CPSW_VERSION_1) ? CPSW1_PORT_VLAN :
CPSW2_PORT_VLAN;
writel(vlan, &priv->host_port_regs->port_vlan);
for (i = 0; i < priv->data.slaves; i++)
slave_write(priv->slaves + i, vlan, reg);
cpsw_ale_add_vlan(priv->ale, vlan, ALE_ALL_PORTS << port,
ALE_ALL_PORTS << port, ALE_ALL_PORTS << port,
(ALE_PORT_1 | ALE_PORT_2) << port);
}
static void cpsw_init_host_port(struct cpsw_priv *priv)
{
u32 control_reg;
u32 fifo_mode;
/* soft reset the controller and initialize ale */
soft_reset("cpsw", &priv->regs->soft_reset);
cpsw_ale_start(priv->ale);
/* switch to vlan unaware mode */
cpsw_ale_control_set(priv->ale, priv->host_port, ALE_VLAN_AWARE,
CPSW_ALE_VLAN_AWARE);
control_reg = readl(&priv->regs->control);
control_reg |= CPSW_VLAN_AWARE;
writel(control_reg, &priv->regs->control);
fifo_mode = (priv->data.dual_emac) ? CPSW_FIFO_DUAL_MAC_MODE :
CPSW_FIFO_NORMAL_MODE;
writel(fifo_mode, &priv->host_port_regs->tx_in_ctl);
/* setup host port priority mapping */
__raw_writel(CPDMA_TX_PRIORITY_MAP,
&priv->host_port_regs->cpdma_tx_pri_map);
__raw_writel(0, &priv->host_port_regs->cpdma_rx_chan_map);
cpsw_ale_control_set(priv->ale, priv->host_port,
ALE_PORT_STATE, ALE_PORT_STATE_FORWARD);
if (!priv->data.dual_emac) {
cpsw_ale_add_ucast(priv->ale, priv->mac_addr, priv->host_port,
0, 0);
cpsw_ale_add_mcast(priv->ale, priv->ndev->broadcast,
1 << priv->host_port, 0, 0, ALE_MCAST_FWD_2);
}
}
static void cpsw_slave_stop(struct cpsw_slave *slave, struct cpsw_priv *priv)
{
u32 slave_port;
slave_port = cpsw_get_slave_port(priv, slave->slave_num);
if (!slave->phy)
return;
phy_stop(slave->phy);
phy_disconnect(slave->phy);
slave->phy = NULL;
cpsw_ale_control_set(priv->ale, slave_port,
ALE_PORT_STATE, ALE_PORT_STATE_DISABLE);
}
static int cpsw_ndo_open(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
struct cpsw_priv *prim_cpsw;
int i, ret;
u32 reg;
if (!cpsw_common_res_usage_state(priv))
cpsw_intr_disable(priv);
netif_carrier_off(ndev);
pm_runtime_get_sync(&priv->pdev->dev);
reg = priv->version;
dev_info(priv->dev, "initializing cpsw version %d.%d (%d)\n",
CPSW_MAJOR_VERSION(reg), CPSW_MINOR_VERSION(reg),
CPSW_RTL_VERSION(reg));
/* initialize host and slave ports */
if (!cpsw_common_res_usage_state(priv))
cpsw_init_host_port(priv);
for_each_slave(priv, cpsw_slave_open, priv);
/* Add default VLAN */
if (!priv->data.dual_emac)
cpsw_add_default_vlan(priv);
else
cpsw_ale_add_vlan(priv->ale, priv->data.default_vlan,
ALE_ALL_PORTS << priv->host_port,
ALE_ALL_PORTS << priv->host_port, 0, 0);
if (!cpsw_common_res_usage_state(priv)) {
/* setup tx dma to fixed prio and zero offset */
cpdma_control_set(priv->dma, CPDMA_TX_PRIO_FIXED, 1);
cpdma_control_set(priv->dma, CPDMA_RX_BUFFER_OFFSET, 0);
/* disable priority elevation */
__raw_writel(0, &priv->regs->ptype);
/* enable statistics collection only on all ports */
__raw_writel(0x7, &priv->regs->stat_port_en);
if (WARN_ON(!priv->data.rx_descs))
priv->data.rx_descs = 128;
for (i = 0; i < priv->data.rx_descs; i++) {
struct sk_buff *skb;
ret = -ENOMEM;
skb = __netdev_alloc_skb_ip_align(priv->ndev,
priv->rx_packet_max, GFP_KERNEL);
if (!skb)
goto err_cleanup;
ret = cpdma_chan_submit(priv->rxch, skb, skb->data,
skb_tailroom(skb), 0);
if (ret < 0) {
kfree_skb(skb);
goto err_cleanup;
}
}
/* continue even if we didn't manage to submit all
* receive descs
*/
cpsw_info(priv, ifup, "submitted %d rx descriptors\n", i);
if (cpts_register(&priv->pdev->dev, priv->cpts,
priv->data.cpts_clock_mult,
priv->data.cpts_clock_shift))
dev_err(priv->dev, "error registering cpts device\n");
}
/* Enable Interrupt pacing if configured */
if (priv->coal_intvl != 0) {
struct ethtool_coalesce coal;
coal.rx_coalesce_usecs = (priv->coal_intvl << 4);
cpsw_set_coalesce(ndev, &coal);
}
napi_enable(&priv->napi);
cpdma_ctlr_start(priv->dma);
cpsw_intr_enable(priv);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_RX);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_TX);
prim_cpsw = cpsw_get_slave_priv(priv, 0);
if (prim_cpsw->irq_enabled == false) {
if ((priv == prim_cpsw) || !netif_running(prim_cpsw->ndev)) {
prim_cpsw->irq_enabled = true;
cpsw_enable_irq(prim_cpsw);
}
}
if (priv->data.dual_emac)
priv->slaves[priv->emac_port].open_stat = true;
return 0;
err_cleanup:
cpdma_ctlr_stop(priv->dma);
for_each_slave(priv, cpsw_slave_stop, priv);
pm_runtime_put_sync(&priv->pdev->dev);
netif_carrier_off(priv->ndev);
return ret;
}
static int cpsw_ndo_stop(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
cpsw_info(priv, ifdown, "shutting down cpsw device\n");
netif_stop_queue(priv->ndev);
napi_disable(&priv->napi);
netif_carrier_off(priv->ndev);
if (cpsw_common_res_usage_state(priv) <= 1) {
cpts_unregister(priv->cpts);
cpsw_intr_disable(priv);
cpdma_ctlr_int_ctrl(priv->dma, false);
cpdma_ctlr_stop(priv->dma);
cpsw_ale_stop(priv->ale);
}
for_each_slave(priv, cpsw_slave_stop, priv);
pm_runtime_put_sync(&priv->pdev->dev);
if (priv->data.dual_emac)
priv->slaves[priv->emac_port].open_stat = false;
return 0;
}
static netdev_tx_t cpsw_ndo_start_xmit(struct sk_buff *skb,
struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
int ret;
ndev->trans_start = jiffies;
if (skb_padto(skb, CPSW_MIN_PACKET_SIZE)) {
cpsw_err(priv, tx_err, "packet pad failed\n");
ndev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
if (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP &&
priv->cpts->tx_enable)
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
skb_tx_timestamp(skb);
ret = cpsw_tx_packet_submit(ndev, priv, skb);
if (unlikely(ret != 0)) {
cpsw_err(priv, tx_err, "desc submit failed\n");
goto fail;
}
/* If there is no more tx desc left free then we need to
* tell the kernel to stop sending us tx frames.
*/
if (unlikely(!cpdma_check_free_tx_desc(priv->txch)))
netif_stop_queue(ndev);
return NETDEV_TX_OK;
fail:
ndev->stats.tx_dropped++;
netif_stop_queue(ndev);
return NETDEV_TX_BUSY;
}
#ifdef CONFIG_TI_CPTS
static void cpsw_hwtstamp_v1(struct cpsw_priv *priv)
{
struct cpsw_slave *slave = &priv->slaves[priv->data.active_slave];
u32 ts_en, seq_id;
if (!priv->cpts->tx_enable && !priv->cpts->rx_enable) {
slave_write(slave, 0, CPSW1_TS_CTL);
return;
}
seq_id = (30 << CPSW_V1_SEQ_ID_OFS_SHIFT) | ETH_P_1588;
ts_en = EVENT_MSG_BITS << CPSW_V1_MSG_TYPE_OFS;
if (priv->cpts->tx_enable)
ts_en |= CPSW_V1_TS_TX_EN;
if (priv->cpts->rx_enable)
ts_en |= CPSW_V1_TS_RX_EN;
slave_write(slave, ts_en, CPSW1_TS_CTL);
slave_write(slave, seq_id, CPSW1_TS_SEQ_LTYPE);
}
static void cpsw_hwtstamp_v2(struct cpsw_priv *priv)
{
struct cpsw_slave *slave;
u32 ctrl, mtype;
if (priv->data.dual_emac)
slave = &priv->slaves[priv->emac_port];
else
slave = &priv->slaves[priv->data.active_slave];
ctrl = slave_read(slave, CPSW2_CONTROL);
switch (priv->version) {
case CPSW_VERSION_2:
ctrl &= ~CTRL_V2_ALL_TS_MASK;
if (priv->cpts->tx_enable)
ctrl |= CTRL_V2_TX_TS_BITS;
if (priv->cpts->rx_enable)
ctrl |= CTRL_V2_RX_TS_BITS;
break;
case CPSW_VERSION_3:
default:
ctrl &= ~CTRL_V3_ALL_TS_MASK;
if (priv->cpts->tx_enable)
ctrl |= CTRL_V3_TX_TS_BITS;
if (priv->cpts->rx_enable)
ctrl |= CTRL_V3_RX_TS_BITS;
break;
}
mtype = (30 << TS_SEQ_ID_OFFSET_SHIFT) | EVENT_MSG_BITS;
slave_write(slave, mtype, CPSW2_TS_SEQ_MTYPE);
slave_write(slave, ctrl, CPSW2_CONTROL);
__raw_writel(ETH_P_1588, &priv->regs->ts_ltype);
}
static int cpsw_hwtstamp_set(struct net_device *dev, struct ifreq *ifr)
{
struct cpsw_priv *priv = netdev_priv(dev);
struct cpts *cpts = priv->cpts;
struct hwtstamp_config cfg;
if (priv->version != CPSW_VERSION_1 &&
priv->version != CPSW_VERSION_2 &&
priv->version != CPSW_VERSION_3)
return -EOPNOTSUPP;
if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
return -EFAULT;
/* reserved for future extensions */
if (cfg.flags)
return -EINVAL;
if (cfg.tx_type != HWTSTAMP_TX_OFF && cfg.tx_type != HWTSTAMP_TX_ON)
return -ERANGE;
switch (cfg.rx_filter) {
case HWTSTAMP_FILTER_NONE:
cpts->rx_enable = 0;
break;
case HWTSTAMP_FILTER_ALL:
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
return -ERANGE;
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
case HWTSTAMP_FILTER_PTP_V2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
cpts->rx_enable = 1;
cfg.rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT;
break;
default:
return -ERANGE;
}
cpts->tx_enable = cfg.tx_type == HWTSTAMP_TX_ON;
switch (priv->version) {
case CPSW_VERSION_1:
cpsw_hwtstamp_v1(priv);
break;
case CPSW_VERSION_2:
case CPSW_VERSION_3:
cpsw_hwtstamp_v2(priv);
break;
default:
WARN_ON(1);
}
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
static int cpsw_hwtstamp_get(struct net_device *dev, struct ifreq *ifr)
{
struct cpsw_priv *priv = netdev_priv(dev);
struct cpts *cpts = priv->cpts;
struct hwtstamp_config cfg;
if (priv->version != CPSW_VERSION_1 &&
priv->version != CPSW_VERSION_2 &&
priv->version != CPSW_VERSION_3)
return -EOPNOTSUPP;
cfg.flags = 0;
cfg.tx_type = cpts->tx_enable ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF;
cfg.rx_filter = (cpts->rx_enable ?
HWTSTAMP_FILTER_PTP_V2_EVENT : HWTSTAMP_FILTER_NONE);
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
#endif /*CONFIG_TI_CPTS*/
static int cpsw_ndo_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct cpsw_priv *priv = netdev_priv(dev);
int slave_no = cpsw_slave_index(priv);
if (!netif_running(dev))
return -EINVAL;
switch (cmd) {
#ifdef CONFIG_TI_CPTS
case SIOCSHWTSTAMP:
return cpsw_hwtstamp_set(dev, req);
case SIOCGHWTSTAMP:
return cpsw_hwtstamp_get(dev, req);
#endif
}
if (!priv->slaves[slave_no].phy)
return -EOPNOTSUPP;
return phy_mii_ioctl(priv->slaves[slave_no].phy, req, cmd);
}
static void cpsw_ndo_tx_timeout(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
cpsw_err(priv, tx_err, "transmit timeout, restarting dma\n");
ndev->stats.tx_errors++;
cpsw_intr_disable(priv);
cpdma_ctlr_int_ctrl(priv->dma, false);
cpdma_chan_stop(priv->txch);
cpdma_chan_start(priv->txch);
cpdma_ctlr_int_ctrl(priv->dma, true);
cpsw_intr_enable(priv);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_RX);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_TX);
}
static int cpsw_ndo_set_mac_address(struct net_device *ndev, void *p)
{
struct cpsw_priv *priv = netdev_priv(ndev);
struct sockaddr *addr = (struct sockaddr *)p;
int flags = 0;
u16 vid = 0;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
if (priv->data.dual_emac) {
vid = priv->slaves[priv->emac_port].port_vlan;
flags = ALE_VLAN;
}
cpsw_ale_del_ucast(priv->ale, priv->mac_addr, priv->host_port,
flags, vid);
cpsw_ale_add_ucast(priv->ale, addr->sa_data, priv->host_port,
flags, vid);
memcpy(priv->mac_addr, addr->sa_data, ETH_ALEN);
memcpy(ndev->dev_addr, priv->mac_addr, ETH_ALEN);
for_each_slave(priv, cpsw_set_slave_mac, priv);
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void cpsw_ndo_poll_controller(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
cpsw_intr_disable(priv);
cpdma_ctlr_int_ctrl(priv->dma, false);
cpsw_interrupt(ndev->irq, priv);
cpdma_ctlr_int_ctrl(priv->dma, true);
cpsw_intr_enable(priv);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_RX);
cpdma_ctlr_eoi(priv->dma, CPDMA_EOI_TX);
}
#endif
static inline int cpsw_add_vlan_ale_entry(struct cpsw_priv *priv,
unsigned short vid)
{
int ret;
ret = cpsw_ale_add_vlan(priv->ale, vid,
ALE_ALL_PORTS << priv->host_port,
0, ALE_ALL_PORTS << priv->host_port,
(ALE_PORT_1 | ALE_PORT_2) << priv->host_port);
if (ret != 0)
return ret;
ret = cpsw_ale_add_ucast(priv->ale, priv->mac_addr,
priv->host_port, ALE_VLAN, vid);
if (ret != 0)
goto clean_vid;
ret = cpsw_ale_add_mcast(priv->ale, priv->ndev->broadcast,
ALE_ALL_PORTS << priv->host_port,
ALE_VLAN, vid, 0);
if (ret != 0)
goto clean_vlan_ucast;
return 0;
clean_vlan_ucast:
cpsw_ale_del_ucast(priv->ale, priv->mac_addr,
priv->host_port, ALE_VLAN, vid);
clean_vid:
cpsw_ale_del_vlan(priv->ale, vid, 0);
return ret;
}
static int cpsw_ndo_vlan_rx_add_vid(struct net_device *ndev,
__be16 proto, u16 vid)
{
struct cpsw_priv *priv = netdev_priv(ndev);
if (vid == priv->data.default_vlan)
return 0;
dev_info(priv->dev, "Adding vlanid %d to vlan filter\n", vid);
return cpsw_add_vlan_ale_entry(priv, vid);
}
static int cpsw_ndo_vlan_rx_kill_vid(struct net_device *ndev,
__be16 proto, u16 vid)
{
struct cpsw_priv *priv = netdev_priv(ndev);
int ret;
if (vid == priv->data.default_vlan)
return 0;
dev_info(priv->dev, "removing vlanid %d from vlan filter\n", vid);
ret = cpsw_ale_del_vlan(priv->ale, vid, 0);
if (ret != 0)
return ret;
ret = cpsw_ale_del_ucast(priv->ale, priv->mac_addr,
priv->host_port, ALE_VLAN, vid);
if (ret != 0)
return ret;
return cpsw_ale_del_mcast(priv->ale, priv->ndev->broadcast,
0, ALE_VLAN, vid);
}
static const struct net_device_ops cpsw_netdev_ops = {
.ndo_open = cpsw_ndo_open,
.ndo_stop = cpsw_ndo_stop,
.ndo_start_xmit = cpsw_ndo_start_xmit,
.ndo_set_mac_address = cpsw_ndo_set_mac_address,
.ndo_do_ioctl = cpsw_ndo_ioctl,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = eth_change_mtu,
.ndo_tx_timeout = cpsw_ndo_tx_timeout,
.ndo_set_rx_mode = cpsw_ndo_set_rx_mode,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = cpsw_ndo_poll_controller,
#endif
.ndo_vlan_rx_add_vid = cpsw_ndo_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = cpsw_ndo_vlan_rx_kill_vid,
};
static int cpsw_get_regs_len(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
return priv->data.ale_entries * ALE_ENTRY_WORDS * sizeof(u32);
}
static void cpsw_get_regs(struct net_device *ndev,
struct ethtool_regs *regs, void *p)
{
struct cpsw_priv *priv = netdev_priv(ndev);
u32 *reg = p;
/* update CPSW IP version */
regs->version = priv->version;
cpsw_ale_dump(priv->ale, reg);
}
static void cpsw_get_drvinfo(struct net_device *ndev,
struct ethtool_drvinfo *info)
{
struct cpsw_priv *priv = netdev_priv(ndev);
strlcpy(info->driver, "cpsw", sizeof(info->driver));
strlcpy(info->version, "1.0", sizeof(info->version));
strlcpy(info->bus_info, priv->pdev->name, sizeof(info->bus_info));
info->regdump_len = cpsw_get_regs_len(ndev);
}
static u32 cpsw_get_msglevel(struct net_device *ndev)
{
struct cpsw_priv *priv = netdev_priv(ndev);
return priv->msg_enable;
}
static void cpsw_set_msglevel(struct net_device *ndev, u32 value)
{
struct cpsw_priv *priv = netdev_priv(ndev);
priv->msg_enable = value;
}
static int cpsw_get_ts_info(struct net_device *ndev,
struct ethtool_ts_info *info)
{
#ifdef CONFIG_TI_CPTS
struct cpsw_priv *priv = netdev_priv(ndev);
info->so_timestamping =
SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_TX_SOFTWARE |
SOF_TIMESTAMPING_RX_HARDWARE |
SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE |
SOF_TIMESTAMPING_RAW_HARDWARE;
info->phc_index = priv->cpts->phc_index;
info->tx_types =
(1 << HWTSTAMP_TX_OFF) |
(1 << HWTSTAMP_TX_ON);
info->rx_filters =
(1 << HWTSTAMP_FILTER_NONE) |
(1 << HWTSTAMP_FILTER_PTP_V2_EVENT);
#else
info->so_timestamping =
SOF_TIMESTAMPING_TX_SOFTWARE |
SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE;
info->phc_index = -1;
info->tx_types = 0;
info->rx_filters = 0;
#endif
return 0;
}
static int cpsw_get_settings(struct net_device *ndev,
struct ethtool_cmd *ecmd)
{
struct cpsw_priv *priv = netdev_priv(ndev);
int slave_no = cpsw_slave_index(priv);
if (priv->slaves[slave_no].phy)
return phy_ethtool_gset(priv->slaves[slave_no].phy, ecmd);
else
return -EOPNOTSUPP;
}
static int cpsw_set_settings(struct net_device *ndev, struct ethtool_cmd *ecmd)
{
struct cpsw_priv *priv = netdev_priv(ndev);
int slave_no = cpsw_slave_index(priv);
if (priv->slaves[slave_no].phy)
return phy_ethtool_sset(priv->slaves[slave_no].phy, ecmd);
else
return -EOPNOTSUPP;
}
static void cpsw_get_wol(struct net_device *ndev, struct ethtool_wolinfo *wol)
{
struct cpsw_priv *priv = netdev_priv(ndev);
int slave_no = cpsw_slave_index(priv);
wol->supported = 0;
wol->wolopts = 0;
if (priv->slaves[slave_no].phy)
phy_ethtool_get_wol(priv->slaves[slave_no].phy, wol);
}
static int cpsw_set_wol(struct net_device *ndev, struct ethtool_wolinfo *wol)
{
struct cpsw_priv *priv = netdev_priv(ndev);
int slave_no = cpsw_slave_index(priv);
if (priv->slaves[slave_no].phy)
return phy_ethtool_set_wol(priv->slaves[slave_no].phy, wol);
else
return -EOPNOTSUPP;
}
static const struct ethtool_ops cpsw_ethtool_ops = {
.get_drvinfo = cpsw_get_drvinfo,
.get_msglevel = cpsw_get_msglevel,
.set_msglevel = cpsw_set_msglevel,
.get_link = ethtool_op_get_link,
.get_ts_info = cpsw_get_ts_info,
.get_settings = cpsw_get_settings,
.set_settings = cpsw_set_settings,
.get_coalesce = cpsw_get_coalesce,
.set_coalesce = cpsw_set_coalesce,
.get_sset_count = cpsw_get_sset_count,
.get_strings = cpsw_get_strings,
.get_ethtool_stats = cpsw_get_ethtool_stats,
.get_wol = cpsw_get_wol,
.set_wol = cpsw_set_wol,
.get_regs_len = cpsw_get_regs_len,
.get_regs = cpsw_get_regs,
};
static void cpsw_slave_init(struct cpsw_slave *slave, struct cpsw_priv *priv,
u32 slave_reg_ofs, u32 sliver_reg_ofs)
{
void __iomem *regs = priv->regs;
int slave_num = slave->slave_num;
struct cpsw_slave_data *data = priv->data.slave_data + slave_num;
slave->data = data;
slave->regs = regs + slave_reg_ofs;
slave->sliver = regs + sliver_reg_ofs;
slave->port_vlan = data->dual_emac_res_vlan;
}
static int cpsw_probe_dt(struct cpsw_platform_data *data,
struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct device_node *slave_node;
int i = 0, ret;
u32 prop;
if (!node)
return -EINVAL;
if (of_property_read_u32(node, "slaves", &prop)) {
dev_err(&pdev->dev, "Missing slaves property in the DT.\n");
return -EINVAL;
}
data->slaves = prop;
if (of_property_read_u32(node, "active_slave", &prop)) {
dev_err(&pdev->dev, "Missing active_slave property in the DT.\n");
return -EINVAL;
}
data->active_slave = prop;
if (of_property_read_u32(node, "cpts_clock_mult", &prop)) {
dev_err(&pdev->dev, "Missing cpts_clock_mult property in the DT.\n");
return -EINVAL;
}
data->cpts_clock_mult = prop;
if (of_property_read_u32(node, "cpts_clock_shift", &prop)) {
dev_err(&pdev->dev, "Missing cpts_clock_shift property in the DT.\n");
return -EINVAL;
}
data->cpts_clock_shift = prop;
data->slave_data = devm_kzalloc(&pdev->dev, data->slaves
* sizeof(struct cpsw_slave_data),
GFP_KERNEL);
if (!data->slave_data)
return -ENOMEM;
if (of_property_read_u32(node, "cpdma_channels", &prop)) {
dev_err(&pdev->dev, "Missing cpdma_channels property in the DT.\n");
return -EINVAL;
}
data->channels = prop;
if (of_property_read_u32(node, "ale_entries", &prop)) {
dev_err(&pdev->dev, "Missing ale_entries property in the DT.\n");
return -EINVAL;
}
data->ale_entries = prop;
if (of_property_read_u32(node, "bd_ram_size", &prop)) {
dev_err(&pdev->dev, "Missing bd_ram_size property in the DT.\n");
return -EINVAL;
}
data->bd_ram_size = prop;
if (of_property_read_u32(node, "rx_descs", &prop)) {
dev_err(&pdev->dev, "Missing rx_descs property in the DT.\n");
return -EINVAL;
}
data->rx_descs = prop;
if (of_property_read_u32(node, "mac_control", &prop)) {
dev_err(&pdev->dev, "Missing mac_control property in the DT.\n");
return -EINVAL;
}
data->mac_control = prop;
if (of_property_read_bool(node, "dual_emac"))
data->dual_emac = 1;
/*
* Populate all the child nodes here...
*/
ret = of_platform_populate(node, NULL, NULL, &pdev->dev);
/* We do not want to force this, as in some cases may not have child */
if (ret)
dev_warn(&pdev->dev, "Doesn't have any child node\n");
for_each_child_of_node(node, slave_node) {
struct cpsw_slave_data *slave_data = data->slave_data + i;
const void *mac_addr = NULL;
u32 phyid;
int lenp;
const __be32 *parp;
struct device_node *mdio_node;
struct platform_device *mdio;
/* This is no slave child node, continue */
if (strcmp(slave_node->name, "slave"))
continue;
parp = of_get_property(slave_node, "phy_id", &lenp);
if ((parp == NULL) || (lenp != (sizeof(void *) * 2))) {
dev_err(&pdev->dev, "Missing slave[%d] phy_id property\n", i);
return -EINVAL;
}
mdio_node = of_find_node_by_phandle(be32_to_cpup(parp));
phyid = be32_to_cpup(parp+1);
mdio = of_find_device_by_node(mdio_node);
of_node_put(mdio_node);
if (!mdio) {
pr_err("Missing mdio platform device\n");
return -EINVAL;
}
snprintf(slave_data->phy_id, sizeof(slave_data->phy_id),
PHY_ID_FMT, mdio->name, phyid);
mac_addr = of_get_mac_address(slave_node);
if (mac_addr)
memcpy(slave_data->mac_addr, mac_addr, ETH_ALEN);
slave_data->phy_if = of_get_phy_mode(slave_node);
if (slave_data->phy_if < 0) {
dev_err(&pdev->dev, "Missing or malformed slave[%d] phy-mode property\n",
i);
return slave_data->phy_if;
}
if (data->dual_emac) {
if (of_property_read_u32(slave_node, "dual_emac_res_vlan",
&prop)) {
dev_err(&pdev->dev, "Missing dual_emac_res_vlan in DT.\n");
slave_data->dual_emac_res_vlan = i+1;
dev_err(&pdev->dev, "Using %d as Reserved VLAN for %d slave\n",
slave_data->dual_emac_res_vlan, i);
} else {
slave_data->dual_emac_res_vlan = prop;
}
}
i++;
if (i == data->slaves)
break;
}
return 0;
}
static int cpsw_probe_dual_emac(struct platform_device *pdev,
struct cpsw_priv *priv)
{
struct cpsw_platform_data *data = &priv->data;
struct net_device *ndev;
struct cpsw_priv *priv_sl2;
int ret = 0, i;
ndev = alloc_etherdev(sizeof(struct cpsw_priv));
if (!ndev) {
dev_err(&pdev->dev, "cpsw: error allocating net_device\n");
return -ENOMEM;
}
priv_sl2 = netdev_priv(ndev);
spin_lock_init(&priv_sl2->lock);
priv_sl2->data = *data;
priv_sl2->pdev = pdev;
priv_sl2->ndev = ndev;
priv_sl2->dev = &ndev->dev;
priv_sl2->msg_enable = netif_msg_init(debug_level, CPSW_DEBUG);
priv_sl2->rx_packet_max = max(rx_packet_max, 128);
if (is_valid_ether_addr(data->slave_data[1].mac_addr)) {
memcpy(priv_sl2->mac_addr, data->slave_data[1].mac_addr,
ETH_ALEN);
dev_info(&pdev->dev, "cpsw: Detected MACID = %pM\n", priv_sl2->mac_addr);
} else {
random_ether_addr(priv_sl2->mac_addr);
dev_info(&pdev->dev, "cpsw: Random MACID = %pM\n", priv_sl2->mac_addr);
}
memcpy(ndev->dev_addr, priv_sl2->mac_addr, ETH_ALEN);
priv_sl2->slaves = priv->slaves;
priv_sl2->clk = priv->clk;
priv_sl2->coal_intvl = 0;
priv_sl2->bus_freq_mhz = priv->bus_freq_mhz;
priv_sl2->regs = priv->regs;
priv_sl2->host_port = priv->host_port;
priv_sl2->host_port_regs = priv->host_port_regs;
priv_sl2->wr_regs = priv->wr_regs;
priv_sl2->hw_stats = priv->hw_stats;
priv_sl2->dma = priv->dma;
priv_sl2->txch = priv->txch;
priv_sl2->rxch = priv->rxch;
priv_sl2->ale = priv->ale;
priv_sl2->emac_port = 1;
priv->slaves[1].ndev = ndev;
priv_sl2->cpts = priv->cpts;
priv_sl2->version = priv->version;
for (i = 0; i < priv->num_irqs; i++) {
priv_sl2->irqs_table[i] = priv->irqs_table[i];
priv_sl2->num_irqs = priv->num_irqs;
}
ndev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
ndev->netdev_ops = &cpsw_netdev_ops;
ndev->ethtool_ops = &cpsw_ethtool_ops;
netif_napi_add(ndev, &priv_sl2->napi, cpsw_poll, CPSW_POLL_WEIGHT);
/* register the network device */
SET_NETDEV_DEV(ndev, &pdev->dev);
ret = register_netdev(ndev);
if (ret) {
dev_err(&pdev->dev, "cpsw: error registering net device\n");
free_netdev(ndev);
ret = -ENODEV;
}
return ret;
}
static int cpsw_probe(struct platform_device *pdev)
{
struct cpsw_platform_data *data;
struct net_device *ndev;
struct cpsw_priv *priv;
struct cpdma_params dma_params;
struct cpsw_ale_params ale_params;
void __iomem *ss_regs;
struct resource *res, *ss_res;
u32 slave_offset, sliver_offset, slave_size;
int ret = 0, i, k = 0;
ndev = alloc_etherdev(sizeof(struct cpsw_priv));
if (!ndev) {
dev_err(&pdev->dev, "error allocating net_device\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, ndev);
priv = netdev_priv(ndev);
spin_lock_init(&priv->lock);
priv->pdev = pdev;
priv->ndev = ndev;
priv->dev = &ndev->dev;
priv->msg_enable = netif_msg_init(debug_level, CPSW_DEBUG);
priv->rx_packet_max = max(rx_packet_max, 128);
priv->cpts = devm_kzalloc(&pdev->dev, sizeof(struct cpts), GFP_KERNEL);
priv->irq_enabled = true;
if (!priv->cpts) {
dev_err(&pdev->dev, "error allocating cpts\n");
goto clean_ndev_ret;
}
/*
* This may be required here for child devices.
*/
pm_runtime_enable(&pdev->dev);
/* Select default pin state */
pinctrl_pm_select_default_state(&pdev->dev);
if (cpsw_probe_dt(&priv->data, pdev)) {
dev_err(&pdev->dev, "cpsw: platform data missing\n");
ret = -ENODEV;
goto clean_runtime_disable_ret;
}
data = &priv->data;
if (is_valid_ether_addr(data->slave_data[0].mac_addr)) {
memcpy(priv->mac_addr, data->slave_data[0].mac_addr, ETH_ALEN);
dev_info(&pdev->dev, "Detected MACID = %pM\n", priv->mac_addr);
} else {
eth_random_addr(priv->mac_addr);
dev_info(&pdev->dev, "Random MACID = %pM\n", priv->mac_addr);
}
memcpy(ndev->dev_addr, priv->mac_addr, ETH_ALEN);
priv->slaves = devm_kzalloc(&pdev->dev,
sizeof(struct cpsw_slave) * data->slaves,
GFP_KERNEL);
if (!priv->slaves) {
ret = -ENOMEM;
goto clean_runtime_disable_ret;
}
for (i = 0; i < data->slaves; i++)
priv->slaves[i].slave_num = i;
priv->slaves[0].ndev = ndev;
priv->emac_port = 0;
priv->clk = devm_clk_get(&pdev->dev, "fck");
if (IS_ERR(priv->clk)) {
dev_err(priv->dev, "fck is not found\n");
ret = -ENODEV;
goto clean_runtime_disable_ret;
}
priv->coal_intvl = 0;
priv->bus_freq_mhz = clk_get_rate(priv->clk) / 1000000;
ss_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ss_regs = devm_ioremap_resource(&pdev->dev, ss_res);
if (IS_ERR(ss_regs)) {
ret = PTR_ERR(ss_regs);
goto clean_runtime_disable_ret;
}
priv->regs = ss_regs;
priv->host_port = HOST_PORT_NUM;
/* Need to enable clocks with runtime PM api to access module
* registers
*/
pm_runtime_get_sync(&pdev->dev);
priv->version = readl(&priv->regs->id_ver);
pm_runtime_put_sync(&pdev->dev);
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
priv->wr_regs = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(priv->wr_regs)) {
ret = PTR_ERR(priv->wr_regs);
goto clean_runtime_disable_ret;
}
memset(&dma_params, 0, sizeof(dma_params));
memset(&ale_params, 0, sizeof(ale_params));
switch (priv->version) {
case CPSW_VERSION_1:
priv->host_port_regs = ss_regs + CPSW1_HOST_PORT_OFFSET;
priv->cpts->reg = ss_regs + CPSW1_CPTS_OFFSET;
priv->hw_stats = ss_regs + CPSW1_HW_STATS;
dma_params.dmaregs = ss_regs + CPSW1_CPDMA_OFFSET;
dma_params.txhdp = ss_regs + CPSW1_STATERAM_OFFSET;
ale_params.ale_regs = ss_regs + CPSW1_ALE_OFFSET;
slave_offset = CPSW1_SLAVE_OFFSET;
slave_size = CPSW1_SLAVE_SIZE;
sliver_offset = CPSW1_SLIVER_OFFSET;
dma_params.desc_mem_phys = 0;
break;
case CPSW_VERSION_2:
case CPSW_VERSION_3:
case CPSW_VERSION_4:
priv->host_port_regs = ss_regs + CPSW2_HOST_PORT_OFFSET;
priv->cpts->reg = ss_regs + CPSW2_CPTS_OFFSET;
priv->hw_stats = ss_regs + CPSW2_HW_STATS;
dma_params.dmaregs = ss_regs + CPSW2_CPDMA_OFFSET;
dma_params.txhdp = ss_regs + CPSW2_STATERAM_OFFSET;
ale_params.ale_regs = ss_regs + CPSW2_ALE_OFFSET;
slave_offset = CPSW2_SLAVE_OFFSET;
slave_size = CPSW2_SLAVE_SIZE;
sliver_offset = CPSW2_SLIVER_OFFSET;
dma_params.desc_mem_phys =
(u32 __force) ss_res->start + CPSW2_BD_OFFSET;
break;
default:
dev_err(priv->dev, "unknown version 0x%08x\n", priv->version);
ret = -ENODEV;
goto clean_runtime_disable_ret;
}
for (i = 0; i < priv->data.slaves; i++) {
struct cpsw_slave *slave = &priv->slaves[i];
cpsw_slave_init(slave, priv, slave_offset, sliver_offset);
slave_offset += slave_size;
sliver_offset += SLIVER_SIZE;
}
dma_params.dev = &pdev->dev;
dma_params.rxthresh = dma_params.dmaregs + CPDMA_RXTHRESH;
dma_params.rxfree = dma_params.dmaregs + CPDMA_RXFREE;
dma_params.rxhdp = dma_params.txhdp + CPDMA_RXHDP;
dma_params.txcp = dma_params.txhdp + CPDMA_TXCP;
dma_params.rxcp = dma_params.txhdp + CPDMA_RXCP;
dma_params.num_chan = data->channels;
dma_params.has_soft_reset = true;
dma_params.min_packet_size = CPSW_MIN_PACKET_SIZE;
dma_params.desc_mem_size = data->bd_ram_size;
dma_params.desc_align = 16;
dma_params.has_ext_regs = true;
dma_params.desc_hw_addr = dma_params.desc_mem_phys;
priv->dma = cpdma_ctlr_create(&dma_params);
if (!priv->dma) {
dev_err(priv->dev, "error initializing dma\n");
ret = -ENOMEM;
goto clean_runtime_disable_ret;
}
priv->txch = cpdma_chan_create(priv->dma, tx_chan_num(0),
cpsw_tx_handler);
priv->rxch = cpdma_chan_create(priv->dma, rx_chan_num(0),
cpsw_rx_handler);
if (WARN_ON(!priv->txch || !priv->rxch)) {
dev_err(priv->dev, "error initializing dma channels\n");
ret = -ENOMEM;
goto clean_dma_ret;
}
ale_params.dev = &ndev->dev;
ale_params.ale_ageout = ale_ageout;
ale_params.ale_entries = data->ale_entries;
ale_params.ale_ports = data->slaves;
priv->ale = cpsw_ale_create(&ale_params);
if (!priv->ale) {
dev_err(priv->dev, "error initializing ale engine\n");
ret = -ENODEV;
goto clean_dma_ret;
}
ndev->irq = platform_get_irq(pdev, 0);
if (ndev->irq < 0) {
dev_err(priv->dev, "error getting irq resource\n");
ret = -ENOENT;
goto clean_ale_ret;
}
while ((res = platform_get_resource(priv->pdev, IORESOURCE_IRQ, k))) {
for (i = res->start; i <= res->end; i++) {
if (devm_request_irq(&pdev->dev, i, cpsw_interrupt, 0,
dev_name(&pdev->dev), priv)) {
dev_err(priv->dev, "error attaching irq\n");
goto clean_ale_ret;
}
priv->irqs_table[k] = i;
priv->num_irqs = k + 1;
}
k++;
}
ndev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
ndev->netdev_ops = &cpsw_netdev_ops;
ndev->ethtool_ops = &cpsw_ethtool_ops;
netif_napi_add(ndev, &priv->napi, cpsw_poll, CPSW_POLL_WEIGHT);
/* register the network device */
SET_NETDEV_DEV(ndev, &pdev->dev);
ret = register_netdev(ndev);
if (ret) {
dev_err(priv->dev, "error registering net device\n");
ret = -ENODEV;
goto clean_ale_ret;
}
cpsw_notice(priv, probe, "initialized device (regs %pa, irq %d)\n",
&ss_res->start, ndev->irq);
if (priv->data.dual_emac) {
ret = cpsw_probe_dual_emac(pdev, priv);
if (ret) {
cpsw_err(priv, probe, "error probe slave 2 emac interface\n");
goto clean_ale_ret;
}
}
return 0;
clean_ale_ret:
cpsw_ale_destroy(priv->ale);
clean_dma_ret:
cpdma_chan_destroy(priv->txch);
cpdma_chan_destroy(priv->rxch);
cpdma_ctlr_destroy(priv->dma);
clean_runtime_disable_ret:
pm_runtime_disable(&pdev->dev);
clean_ndev_ret:
free_netdev(priv->ndev);
return ret;
}
static int cpsw_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct cpsw_priv *priv = netdev_priv(ndev);
if (priv->data.dual_emac)
unregister_netdev(cpsw_get_slave_ndev(priv, 1));
unregister_netdev(ndev);
cpsw_ale_destroy(priv->ale);
cpdma_chan_destroy(priv->txch);
cpdma_chan_destroy(priv->rxch);
cpdma_ctlr_destroy(priv->dma);
pm_runtime_disable(&pdev->dev);
if (priv->data.dual_emac)
free_netdev(cpsw_get_slave_ndev(priv, 1));
free_netdev(ndev);
return 0;
}
static int cpsw_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct net_device *ndev = platform_get_drvdata(pdev);
struct cpsw_priv *priv = netdev_priv(ndev);
if (netif_running(ndev))
cpsw_ndo_stop(ndev);
for_each_slave(priv, soft_reset_slave);
pm_runtime_put_sync(&pdev->dev);
/* Select sleep pin state */
pinctrl_pm_select_sleep_state(&pdev->dev);
return 0;
}
static int cpsw_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct net_device *ndev = platform_get_drvdata(pdev);
pm_runtime_get_sync(&pdev->dev);
/* Select default pin state */
pinctrl_pm_select_default_state(&pdev->dev);
if (netif_running(ndev))
cpsw_ndo_open(ndev);
return 0;
}
static const struct dev_pm_ops cpsw_pm_ops = {
.suspend = cpsw_suspend,
.resume = cpsw_resume,
};
static const struct of_device_id cpsw_of_mtable[] = {
{ .compatible = "ti,cpsw", },
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(of, cpsw_of_mtable);
static struct platform_driver cpsw_driver = {
.driver = {
.name = "cpsw",
.owner = THIS_MODULE,
.pm = &cpsw_pm_ops,
.of_match_table = cpsw_of_mtable,
},
.probe = cpsw_probe,
.remove = cpsw_remove,
};
static int __init cpsw_init(void)
{
return platform_driver_register(&cpsw_driver);
}
late_initcall(cpsw_init);
static void __exit cpsw_exit(void)
{
platform_driver_unregister(&cpsw_driver);
}
module_exit(cpsw_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Cyril Chemparathy <cyril@ti.com>");
MODULE_AUTHOR("Mugunthan V N <mugunthanvnm@ti.com>");
MODULE_DESCRIPTION("TI CPSW Ethernet driver");
| gpl-2.0 |
yuhc/jdk8u-dev | jdk/src/solaris/native/sun/java2d/loops/vis_FuncArray.c | 45 | 35131 | /*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include <stdlib.h>
#include <string.h>
#include <sys/utsname.h>
#include "GraphicsPrimitiveMgr.h"
#include "java2d_Mlib.h"
typedef struct {
AnyFunc *func_c;
AnyFunc *func_vis;
} AnyFunc_pair;
#define DEF_FUNC(x) \
void x(); \
void ADD_SUFF(x)();
#define ADD_FUNC(x) \
{ & x, & ADD_SUFF(x) }
/***************************************************************/
DEF_FUNC(AnyByteDrawGlyphList)
DEF_FUNC(AnyByteDrawGlyphListXor)
DEF_FUNC(AnyByteIsomorphicCopy)
DEF_FUNC(AnyByteIsomorphicScaleCopy)
DEF_FUNC(AnyByteIsomorphicXorCopy)
DEF_FUNC(AnyByteSetLine)
DEF_FUNC(AnyByteSetRect)
DEF_FUNC(AnyByteSetSpans)
DEF_FUNC(AnyByteSetParallelogram)
DEF_FUNC(AnyByteXorLine)
DEF_FUNC(AnyByteXorRect)
DEF_FUNC(AnyByteXorSpans)
DEF_FUNC(AnyShortDrawGlyphList)
DEF_FUNC(AnyShortDrawGlyphListXor)
DEF_FUNC(AnyShortIsomorphicCopy)
DEF_FUNC(AnyShortIsomorphicScaleCopy)
DEF_FUNC(AnyShortIsomorphicXorCopy)
DEF_FUNC(AnyShortSetLine)
DEF_FUNC(AnyShortSetRect)
DEF_FUNC(AnyShortSetSpans)
DEF_FUNC(AnyShortSetParallelogram)
DEF_FUNC(AnyShortXorLine)
DEF_FUNC(AnyShortXorRect)
DEF_FUNC(AnyShortXorSpans)
DEF_FUNC(Any3ByteDrawGlyphList)
DEF_FUNC(Any3ByteDrawGlyphListXor)
DEF_FUNC(Any3ByteIsomorphicCopy)
DEF_FUNC(Any3ByteIsomorphicScaleCopy)
DEF_FUNC(Any3ByteIsomorphicXorCopy)
DEF_FUNC(Any3ByteSetLine)
DEF_FUNC(Any3ByteSetRect)
DEF_FUNC(Any3ByteSetSpans)
DEF_FUNC(Any3ByteSetParallelogram)
DEF_FUNC(Any3ByteXorLine)
DEF_FUNC(Any3ByteXorRect)
DEF_FUNC(Any3ByteXorSpans)
DEF_FUNC(Any4ByteDrawGlyphList)
DEF_FUNC(Any4ByteDrawGlyphListXor)
DEF_FUNC(Any4ByteIsomorphicCopy)
DEF_FUNC(Any4ByteIsomorphicScaleCopy)
DEF_FUNC(Any4ByteIsomorphicXorCopy)
DEF_FUNC(Any4ByteSetLine)
DEF_FUNC(Any4ByteSetRect)
DEF_FUNC(Any4ByteSetSpans)
DEF_FUNC(Any4ByteSetParallelogram)
DEF_FUNC(Any4ByteXorLine)
DEF_FUNC(Any4ByteXorRect)
DEF_FUNC(Any4ByteXorSpans)
DEF_FUNC(AnyIntDrawGlyphList)
DEF_FUNC(AnyIntDrawGlyphListXor)
DEF_FUNC(AnyIntIsomorphicCopy)
DEF_FUNC(AnyIntIsomorphicScaleCopy)
DEF_FUNC(AnyIntIsomorphicXorCopy)
DEF_FUNC(AnyIntSetLine)
DEF_FUNC(AnyIntSetRect)
DEF_FUNC(AnyIntSetSpans)
DEF_FUNC(AnyIntSetParallelogram)
DEF_FUNC(AnyIntXorLine)
DEF_FUNC(AnyIntXorRect)
DEF_FUNC(AnyIntXorSpans)
DEF_FUNC(ByteGrayAlphaMaskFill)
DEF_FUNC(ByteGrayDrawGlyphListAA)
DEF_FUNC(ByteGraySrcMaskFill)
DEF_FUNC(ByteGraySrcOverMaskFill)
DEF_FUNC(ByteGrayToIntArgbConvert)
DEF_FUNC(ByteGrayToIntArgbScaleConvert)
DEF_FUNC(ByteIndexedBmToByteGrayScaleXparOver)
DEF_FUNC(ByteIndexedBmToByteGrayXparBgCopy)
DEF_FUNC(ByteIndexedBmToByteGrayXparOver)
DEF_FUNC(ByteIndexedToByteGrayConvert)
DEF_FUNC(ByteIndexedToByteGrayScaleConvert)
DEF_FUNC(Index12GrayToByteGrayConvert)
DEF_FUNC(Index12GrayToByteGrayScaleConvert)
DEF_FUNC(Index8GrayToByteGrayConvert)
DEF_FUNC(Index8GrayToByteGrayScaleConvert)
DEF_FUNC(IntArgbBmToByteGrayScaleXparOver)
DEF_FUNC(IntArgbBmToByteGrayXparBgCopy)
DEF_FUNC(IntArgbBmToByteGrayXparOver)
DEF_FUNC(IntArgbToByteGrayAlphaMaskBlit)
DEF_FUNC(IntArgbToByteGrayConvert)
DEF_FUNC(IntArgbToByteGrayScaleConvert)
DEF_FUNC(IntArgbToByteGraySrcOverMaskBlit)
DEF_FUNC(IntArgbToByteGrayXorBlit)
DEF_FUNC(IntRgbToByteGrayAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToByteGrayConvert)
DEF_FUNC(ThreeByteBgrToByteGrayScaleConvert)
DEF_FUNC(UshortGrayToByteGrayConvert)
DEF_FUNC(UshortGrayToByteGrayScaleConvert)
DEF_FUNC(ByteGrayToUshortGrayConvert)
DEF_FUNC(ByteGrayToUshortGrayScaleConvert)
DEF_FUNC(ByteIndexedBmToUshortGrayScaleXparOver)
DEF_FUNC(ByteIndexedBmToUshortGrayXparBgCopy)
DEF_FUNC(ByteIndexedBmToUshortGrayXparOver)
DEF_FUNC(ByteIndexedToUshortGrayConvert)
DEF_FUNC(ByteIndexedToUshortGrayScaleConvert)
DEF_FUNC(IntArgbBmToUshortGrayScaleXparOver)
DEF_FUNC(IntArgbToUshortGrayAlphaMaskBlit)
DEF_FUNC(IntArgbToUshortGrayConvert)
DEF_FUNC(IntArgbToUshortGrayScaleConvert)
DEF_FUNC(IntArgbToUshortGraySrcOverMaskBlit)
DEF_FUNC(IntArgbToUshortGrayXorBlit)
DEF_FUNC(IntRgbToUshortGrayAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToUshortGrayConvert)
DEF_FUNC(ThreeByteBgrToUshortGrayScaleConvert)
DEF_FUNC(UshortGrayAlphaMaskFill)
DEF_FUNC(UshortGrayDrawGlyphListAA)
DEF_FUNC(UshortGraySrcMaskFill)
DEF_FUNC(UshortGraySrcOverMaskFill)
DEF_FUNC(UshortGrayToIntArgbConvert)
DEF_FUNC(UshortGrayToIntArgbScaleConvert)
DEF_FUNC(ByteGrayToByteIndexedConvert)
DEF_FUNC(ByteGrayToByteIndexedScaleConvert)
DEF_FUNC(ByteIndexedAlphaMaskFill)
DEF_FUNC(ByteIndexedBmToByteIndexedScaleXparOver)
DEF_FUNC(ByteIndexedBmToByteIndexedXparBgCopy)
DEF_FUNC(ByteIndexedBmToByteIndexedXparOver)
DEF_FUNC(ByteIndexedDrawGlyphListAA)
DEF_FUNC(ByteIndexedToByteIndexedConvert)
DEF_FUNC(ByteIndexedToByteIndexedScaleConvert)
DEF_FUNC(Index12GrayToByteIndexedConvert)
DEF_FUNC(Index12GrayToByteIndexedScaleConvert)
DEF_FUNC(IntArgbBmToByteIndexedScaleXparOver)
DEF_FUNC(IntArgbBmToByteIndexedXparBgCopy)
DEF_FUNC(IntArgbBmToByteIndexedXparOver)
DEF_FUNC(IntArgbToByteIndexedAlphaMaskBlit)
DEF_FUNC(IntArgbToByteIndexedConvert)
DEF_FUNC(IntArgbToByteIndexedScaleConvert)
DEF_FUNC(IntArgbToByteIndexedXorBlit)
DEF_FUNC(IntRgbToByteIndexedAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToByteIndexedConvert)
DEF_FUNC(ThreeByteBgrToByteIndexedScaleConvert)
DEF_FUNC(ByteGrayToFourByteAbgrConvert)
DEF_FUNC(ByteGrayToFourByteAbgrScaleConvert)
DEF_FUNC(ByteIndexedBmToFourByteAbgrScaleXparOver)
DEF_FUNC(ByteIndexedBmToFourByteAbgrXparBgCopy)
DEF_FUNC(ByteIndexedBmToFourByteAbgrXparOver)
DEF_FUNC(ByteIndexedToFourByteAbgrConvert)
DEF_FUNC(ByteIndexedToFourByteAbgrScaleConvert)
DEF_FUNC(FourByteAbgrAlphaMaskFill)
DEF_FUNC(FourByteAbgrDrawGlyphListAA)
DEF_FUNC(FourByteAbgrSrcMaskFill)
DEF_FUNC(FourByteAbgrSrcOverMaskFill)
DEF_FUNC(FourByteAbgrToIntArgbConvert)
DEF_FUNC(FourByteAbgrToIntArgbScaleConvert)
DEF_FUNC(IntArgbBmToFourByteAbgrScaleXparOver)
DEF_FUNC(IntArgbToFourByteAbgrAlphaMaskBlit)
DEF_FUNC(IntArgbToFourByteAbgrConvert)
DEF_FUNC(IntArgbToFourByteAbgrScaleConvert)
DEF_FUNC(IntArgbToFourByteAbgrSrcOverMaskBlit)
DEF_FUNC(IntArgbToFourByteAbgrXorBlit)
DEF_FUNC(IntRgbToFourByteAbgrAlphaMaskBlit)
DEF_FUNC(IntRgbToFourByteAbgrConvert)
DEF_FUNC(IntRgbToFourByteAbgrScaleConvert)
DEF_FUNC(ThreeByteBgrToFourByteAbgrConvert)
DEF_FUNC(ThreeByteBgrToFourByteAbgrScaleConvert)
DEF_FUNC(ByteGrayToFourByteAbgrPreConvert)
DEF_FUNC(ByteGrayToFourByteAbgrPreScaleConvert)
DEF_FUNC(ByteIndexedBmToFourByteAbgrPreScaleXparOver)
DEF_FUNC(ByteIndexedBmToFourByteAbgrPreXparBgCopy)
DEF_FUNC(ByteIndexedBmToFourByteAbgrPreXparOver)
DEF_FUNC(ByteIndexedToFourByteAbgrPreConvert)
DEF_FUNC(ByteIndexedToFourByteAbgrPreScaleConvert)
DEF_FUNC(FourByteAbgrPreAlphaMaskFill)
DEF_FUNC(FourByteAbgrPreDrawGlyphListAA)
DEF_FUNC(FourByteAbgrPreSrcMaskFill)
DEF_FUNC(FourByteAbgrPreSrcOverMaskFill)
DEF_FUNC(FourByteAbgrPreToIntArgbConvert)
DEF_FUNC(FourByteAbgrPreToIntArgbScaleConvert)
DEF_FUNC(IntArgbBmToFourByteAbgrPreScaleXparOver)
DEF_FUNC(IntArgbToFourByteAbgrPreAlphaMaskBlit)
DEF_FUNC(IntArgbToFourByteAbgrPreConvert)
DEF_FUNC(IntArgbToFourByteAbgrPreScaleConvert)
DEF_FUNC(IntArgbToFourByteAbgrPreSrcOverMaskBlit)
DEF_FUNC(IntArgbToFourByteAbgrPreXorBlit)
DEF_FUNC(IntRgbToFourByteAbgrPreAlphaMaskBlit)
DEF_FUNC(IntRgbToFourByteAbgrPreConvert)
DEF_FUNC(IntRgbToFourByteAbgrPreScaleConvert)
DEF_FUNC(ThreeByteBgrToFourByteAbgrPreConvert)
DEF_FUNC(ThreeByteBgrToFourByteAbgrPreScaleConvert)
DEF_FUNC(ByteIndexedBmToIntArgbScaleXparOver)
DEF_FUNC(ByteIndexedBmToIntArgbXparBgCopy)
DEF_FUNC(ByteIndexedBmToIntArgbXparOver)
DEF_FUNC(ByteIndexedToIntArgbConvert)
DEF_FUNC(ByteIndexedToIntArgbScaleConvert)
DEF_FUNC(Index12GrayToIntArgbConvert)
DEF_FUNC(IntArgbAlphaMaskFill)
DEF_FUNC(IntArgbBmToIntArgbScaleXparOver)
DEF_FUNC(IntArgbDrawGlyphListAA)
DEF_FUNC(IntArgbSrcMaskFill)
DEF_FUNC(IntArgbSrcOverMaskFill)
DEF_FUNC(IntArgbToIntArgbAlphaMaskBlit)
DEF_FUNC(IntArgbToIntArgbSrcOverMaskBlit)
DEF_FUNC(IntArgbToIntArgbXorBlit)
DEF_FUNC(IntRgbToIntArgbAlphaMaskBlit)
DEF_FUNC(ByteIndexedBmToIntArgbBmScaleXparOver)
DEF_FUNC(ByteIndexedBmToIntArgbBmXparBgCopy)
DEF_FUNC(ByteIndexedBmToIntArgbBmXparOver)
DEF_FUNC(ByteIndexedToIntArgbBmConvert)
DEF_FUNC(ByteIndexedToIntArgbBmScaleConvert)
DEF_FUNC(IntArgbBmAlphaMaskFill)
DEF_FUNC(IntArgbBmDrawGlyphListAA)
DEF_FUNC(IntArgbBmToIntArgbConvert)
DEF_FUNC(IntArgbToIntArgbBmAlphaMaskBlit)
DEF_FUNC(IntArgbToIntArgbBmConvert)
DEF_FUNC(IntArgbToIntArgbBmScaleConvert)
DEF_FUNC(IntArgbToIntArgbBmXorBlit)
DEF_FUNC(ByteGrayToIntArgbPreConvert)
DEF_FUNC(ByteGrayToIntArgbPreScaleConvert)
DEF_FUNC(ByteIndexedBmToIntArgbPreScaleXparOver)
DEF_FUNC(ByteIndexedBmToIntArgbPreXparBgCopy)
DEF_FUNC(ByteIndexedBmToIntArgbPreXparOver)
DEF_FUNC(ByteIndexedToIntArgbPreConvert)
DEF_FUNC(ByteIndexedToIntArgbPreScaleConvert)
DEF_FUNC(IntArgbPreAlphaMaskFill)
DEF_FUNC(IntArgbPreDrawGlyphListAA)
DEF_FUNC(IntArgbPreSrcMaskFill)
DEF_FUNC(IntArgbPreSrcOverMaskFill)
DEF_FUNC(IntArgbPreToIntArgbConvert)
DEF_FUNC(IntArgbPreToIntArgbScaleConvert)
DEF_FUNC(IntArgbToIntArgbPreAlphaMaskBlit)
DEF_FUNC(IntArgbToIntArgbPreConvert)
DEF_FUNC(IntArgbToIntArgbPreScaleConvert)
DEF_FUNC(IntArgbToIntArgbPreSrcOverMaskBlit)
DEF_FUNC(IntArgbToIntArgbPreXorBlit)
DEF_FUNC(IntRgbToIntArgbPreAlphaMaskBlit)
DEF_FUNC(IntRgbToIntArgbPreConvert)
DEF_FUNC(IntRgbToIntArgbPreScaleConvert)
DEF_FUNC(ThreeByteBgrToIntArgbPreConvert)
DEF_FUNC(ThreeByteBgrToIntArgbPreScaleConvert)
DEF_FUNC(ByteIndexedBmToIntBgrScaleXparOver)
DEF_FUNC(ByteIndexedBmToIntBgrXparBgCopy)
DEF_FUNC(ByteIndexedBmToIntBgrXparOver)
DEF_FUNC(ByteIndexedToIntBgrConvert)
DEF_FUNC(ByteIndexedToIntBgrScaleConvert)
DEF_FUNC(IntArgbBmToIntBgrScaleXparOver)
DEF_FUNC(IntArgbBmToIntBgrXparBgCopy)
DEF_FUNC(IntArgbBmToIntBgrXparOver)
DEF_FUNC(IntArgbToIntBgrAlphaMaskBlit)
DEF_FUNC(IntArgbToIntBgrConvert)
DEF_FUNC(IntArgbToIntBgrScaleConvert)
DEF_FUNC(IntArgbToIntBgrSrcOverMaskBlit)
DEF_FUNC(IntArgbToIntBgrXorBlit)
DEF_FUNC(IntBgrAlphaMaskFill)
DEF_FUNC(IntBgrDrawGlyphListAA)
DEF_FUNC(IntBgrSrcMaskFill)
DEF_FUNC(IntBgrSrcOverMaskFill)
DEF_FUNC(IntBgrToIntArgbConvert)
DEF_FUNC(IntBgrToIntArgbScaleConvert)
DEF_FUNC(IntBgrToIntBgrAlphaMaskBlit)
DEF_FUNC(IntRgbToIntBgrAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToIntBgrConvert)
DEF_FUNC(ThreeByteBgrToIntBgrScaleConvert)
DEF_FUNC(ByteGrayToIntRgbConvert)
DEF_FUNC(ByteGrayToIntRgbScaleConvert)
DEF_FUNC(IntArgbBmToIntRgbXparBgCopy)
DEF_FUNC(IntArgbBmToIntRgbXparOver)
DEF_FUNC(IntArgbToIntRgbAlphaMaskBlit)
DEF_FUNC(IntArgbToIntRgbSrcOverMaskBlit)
DEF_FUNC(IntArgbToIntRgbXorBlit)
DEF_FUNC(IntRgbAlphaMaskFill)
DEF_FUNC(IntRgbDrawGlyphListAA)
DEF_FUNC(IntRgbSrcMaskFill)
DEF_FUNC(IntRgbSrcOverMaskFill)
DEF_FUNC(IntRgbToIntArgbConvert)
DEF_FUNC(IntRgbToIntArgbScaleConvert)
DEF_FUNC(IntRgbToIntRgbAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToIntRgbConvert)
DEF_FUNC(ThreeByteBgrToIntRgbScaleConvert)
DEF_FUNC(ByteGrayToIntRgbxConvert)
DEF_FUNC(ByteGrayToIntRgbxScaleConvert)
DEF_FUNC(ByteIndexedBmToIntRgbxScaleXparOver)
DEF_FUNC(ByteIndexedBmToIntRgbxXparBgCopy)
DEF_FUNC(ByteIndexedBmToIntRgbxXparOver)
DEF_FUNC(ByteIndexedToIntRgbxConvert)
DEF_FUNC(ByteIndexedToIntRgbxScaleConvert)
DEF_FUNC(IntArgbBmToIntRgbxScaleXparOver)
DEF_FUNC(IntArgbToIntRgbxConvert)
DEF_FUNC(IntArgbToIntRgbxScaleConvert)
DEF_FUNC(IntArgbToIntRgbxXorBlit)
DEF_FUNC(IntRgbxDrawGlyphListAA)
DEF_FUNC(IntRgbxToIntArgbConvert)
DEF_FUNC(IntRgbxToIntArgbScaleConvert)
DEF_FUNC(ThreeByteBgrToIntRgbxConvert)
DEF_FUNC(ThreeByteBgrToIntRgbxScaleConvert)
DEF_FUNC(ByteGrayToThreeByteBgrConvert)
DEF_FUNC(ByteGrayToThreeByteBgrScaleConvert)
DEF_FUNC(ByteIndexedBmToThreeByteBgrScaleXparOver)
DEF_FUNC(ByteIndexedBmToThreeByteBgrXparBgCopy)
DEF_FUNC(ByteIndexedBmToThreeByteBgrXparOver)
DEF_FUNC(ByteIndexedToThreeByteBgrConvert)
DEF_FUNC(ByteIndexedToThreeByteBgrScaleConvert)
DEF_FUNC(IntArgbBmToThreeByteBgrScaleXparOver)
DEF_FUNC(IntArgbBmToThreeByteBgrXparBgCopy)
DEF_FUNC(IntArgbBmToThreeByteBgrXparOver)
DEF_FUNC(IntArgbToThreeByteBgrAlphaMaskBlit)
DEF_FUNC(IntArgbToThreeByteBgrConvert)
DEF_FUNC(IntArgbToThreeByteBgrScaleConvert)
DEF_FUNC(IntArgbToThreeByteBgrSrcOverMaskBlit)
DEF_FUNC(IntArgbToThreeByteBgrXorBlit)
DEF_FUNC(IntRgbToThreeByteBgrAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrAlphaMaskFill)
DEF_FUNC(ThreeByteBgrDrawGlyphListAA)
DEF_FUNC(ThreeByteBgrSrcMaskFill)
DEF_FUNC(ThreeByteBgrSrcOverMaskFill)
DEF_FUNC(ThreeByteBgrToIntArgbConvert)
DEF_FUNC(ThreeByteBgrToIntArgbScaleConvert)
DEF_FUNC(ByteGrayToIndex8GrayConvert)
DEF_FUNC(ByteGrayToIndex8GrayScaleConvert)
DEF_FUNC(ByteIndexedBmToIndex8GrayXparBgCopy)
DEF_FUNC(ByteIndexedBmToIndex8GrayXparOver)
DEF_FUNC(ByteIndexedToIndex8GrayConvert)
DEF_FUNC(ByteIndexedToIndex8GrayScaleConvert)
DEF_FUNC(Index12GrayToIndex8GrayConvert)
DEF_FUNC(Index12GrayToIndex8GrayScaleConvert)
DEF_FUNC(Index8GrayAlphaMaskFill)
DEF_FUNC(Index8GrayDrawGlyphListAA)
DEF_FUNC(Index8GraySrcOverMaskFill)
DEF_FUNC(Index8GrayToIndex8GrayConvert)
DEF_FUNC(Index8GrayToIndex8GrayScaleConvert)
DEF_FUNC(IntArgbToIndex8GrayAlphaMaskBlit)
DEF_FUNC(IntArgbToIndex8GrayConvert)
DEF_FUNC(IntArgbToIndex8GrayScaleConvert)
DEF_FUNC(IntArgbToIndex8GraySrcOverMaskBlit)
DEF_FUNC(IntArgbToIndex8GrayXorBlit)
DEF_FUNC(IntRgbToIndex8GrayAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToIndex8GrayConvert)
DEF_FUNC(ThreeByteBgrToIndex8GrayScaleConvert)
DEF_FUNC(UshortGrayToIndex8GrayScaleConvert)
DEF_FUNC(ByteGrayToIndex12GrayConvert)
DEF_FUNC(ByteGrayToIndex12GrayScaleConvert)
DEF_FUNC(ByteIndexedBmToIndex12GrayXparBgCopy)
DEF_FUNC(ByteIndexedBmToIndex12GrayXparOver)
DEF_FUNC(ByteIndexedToIndex12GrayConvert)
DEF_FUNC(ByteIndexedToIndex12GrayScaleConvert)
DEF_FUNC(Index12GrayAlphaMaskFill)
DEF_FUNC(Index12GrayDrawGlyphListAA)
DEF_FUNC(Index12GraySrcOverMaskFill)
DEF_FUNC(Index12GrayToIndex12GrayConvert)
DEF_FUNC(Index12GrayToIndex12GrayScaleConvert)
DEF_FUNC(Index12GrayToIntArgbScaleConvert)
DEF_FUNC(Index8GrayToIndex12GrayConvert)
DEF_FUNC(Index8GrayToIndex12GrayScaleConvert)
DEF_FUNC(IntArgbToIndex12GrayAlphaMaskBlit)
DEF_FUNC(IntArgbToIndex12GrayConvert)
DEF_FUNC(IntArgbToIndex12GrayScaleConvert)
DEF_FUNC(IntArgbToIndex12GraySrcOverMaskBlit)
DEF_FUNC(IntArgbToIndex12GrayXorBlit)
DEF_FUNC(IntRgbToIndex12GrayAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToIndex12GrayConvert)
DEF_FUNC(ThreeByteBgrToIndex12GrayScaleConvert)
DEF_FUNC(UshortGrayToIndex12GrayScaleConvert)
DEF_FUNC(ByteBinary1BitAlphaMaskFill)
DEF_FUNC(ByteBinary1BitDrawGlyphList)
DEF_FUNC(ByteBinary1BitDrawGlyphListAA)
DEF_FUNC(ByteBinary1BitDrawGlyphListXor)
DEF_FUNC(ByteBinary1BitSetLine)
DEF_FUNC(ByteBinary1BitSetRect)
DEF_FUNC(ByteBinary1BitSetSpans)
DEF_FUNC(ByteBinary1BitToByteBinary1BitConvert)
DEF_FUNC(ByteBinary1BitToIntArgbAlphaMaskBlit)
DEF_FUNC(ByteBinary1BitToIntArgbConvert)
DEF_FUNC(ByteBinary1BitXorLine)
DEF_FUNC(ByteBinary1BitXorRect)
DEF_FUNC(ByteBinary1BitXorSpans)
DEF_FUNC(IntArgbToByteBinary1BitAlphaMaskBlit)
DEF_FUNC(IntArgbToByteBinary1BitConvert)
DEF_FUNC(IntArgbToByteBinary1BitXorBlit)
DEF_FUNC(ByteBinary2BitAlphaMaskFill)
DEF_FUNC(ByteBinary2BitDrawGlyphList)
DEF_FUNC(ByteBinary2BitDrawGlyphListAA)
DEF_FUNC(ByteBinary2BitDrawGlyphListXor)
DEF_FUNC(ByteBinary2BitSetLine)
DEF_FUNC(ByteBinary2BitSetRect)
DEF_FUNC(ByteBinary2BitSetSpans)
DEF_FUNC(ByteBinary2BitToByteBinary2BitConvert)
DEF_FUNC(ByteBinary2BitToIntArgbAlphaMaskBlit)
DEF_FUNC(ByteBinary2BitToIntArgbConvert)
DEF_FUNC(ByteBinary2BitXorLine)
DEF_FUNC(ByteBinary2BitXorRect)
DEF_FUNC(ByteBinary2BitXorSpans)
DEF_FUNC(IntArgbToByteBinary2BitAlphaMaskBlit)
DEF_FUNC(IntArgbToByteBinary2BitConvert)
DEF_FUNC(IntArgbToByteBinary2BitXorBlit)
DEF_FUNC(ByteBinary4BitAlphaMaskFill)
DEF_FUNC(ByteBinary4BitDrawGlyphList)
DEF_FUNC(ByteBinary4BitDrawGlyphListAA)
DEF_FUNC(ByteBinary4BitDrawGlyphListXor)
DEF_FUNC(ByteBinary4BitSetLine)
DEF_FUNC(ByteBinary4BitSetRect)
DEF_FUNC(ByteBinary4BitSetSpans)
DEF_FUNC(ByteBinary4BitToByteBinary4BitConvert)
DEF_FUNC(ByteBinary4BitToIntArgbAlphaMaskBlit)
DEF_FUNC(ByteBinary4BitToIntArgbConvert)
DEF_FUNC(ByteBinary4BitXorLine)
DEF_FUNC(ByteBinary4BitXorRect)
DEF_FUNC(ByteBinary4BitXorSpans)
DEF_FUNC(IntArgbToByteBinary4BitAlphaMaskBlit)
DEF_FUNC(IntArgbToByteBinary4BitConvert)
DEF_FUNC(IntArgbToByteBinary4BitXorBlit)
DEF_FUNC(ByteGrayToUshort555RgbConvert)
DEF_FUNC(ByteGrayToUshort555RgbScaleConvert)
DEF_FUNC(ByteIndexedBmToUshort555RgbScaleXparOver)
DEF_FUNC(ByteIndexedBmToUshort555RgbXparBgCopy)
DEF_FUNC(ByteIndexedBmToUshort555RgbXparOver)
DEF_FUNC(ByteIndexedToUshort555RgbConvert)
DEF_FUNC(ByteIndexedToUshort555RgbScaleConvert)
DEF_FUNC(IntArgbBmToUshort555RgbScaleXparOver)
DEF_FUNC(IntArgbBmToUshort555RgbXparBgCopy)
DEF_FUNC(IntArgbBmToUshort555RgbXparOver)
DEF_FUNC(IntArgbToUshort555RgbAlphaMaskBlit)
DEF_FUNC(IntArgbToUshort555RgbConvert)
DEF_FUNC(IntArgbToUshort555RgbScaleConvert)
DEF_FUNC(IntArgbToUshort555RgbSrcOverMaskBlit)
DEF_FUNC(IntArgbToUshort555RgbXorBlit)
DEF_FUNC(IntRgbToUshort555RgbAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToUshort555RgbConvert)
DEF_FUNC(ThreeByteBgrToUshort555RgbScaleConvert)
DEF_FUNC(Ushort555RgbAlphaMaskFill)
DEF_FUNC(Ushort555RgbDrawGlyphListAA)
DEF_FUNC(Ushort555RgbSrcMaskFill)
DEF_FUNC(Ushort555RgbSrcOverMaskFill)
DEF_FUNC(Ushort555RgbToIntArgbConvert)
DEF_FUNC(Ushort555RgbToIntArgbScaleConvert)
DEF_FUNC(ByteGrayToUshort555RgbxConvert)
DEF_FUNC(ByteGrayToUshort555RgbxScaleConvert)
DEF_FUNC(ByteIndexedBmToUshort555RgbxScaleXparOver)
DEF_FUNC(ByteIndexedBmToUshort555RgbxXparBgCopy)
DEF_FUNC(ByteIndexedBmToUshort555RgbxXparOver)
DEF_FUNC(ByteIndexedToUshort555RgbxConvert)
DEF_FUNC(ByteIndexedToUshort555RgbxScaleConvert)
DEF_FUNC(IntArgbBmToUshort555RgbxScaleXparOver)
DEF_FUNC(IntArgbToUshort555RgbxConvert)
DEF_FUNC(IntArgbToUshort555RgbxScaleConvert)
DEF_FUNC(IntArgbToUshort555RgbxXorBlit)
DEF_FUNC(ThreeByteBgrToUshort555RgbxConvert)
DEF_FUNC(ThreeByteBgrToUshort555RgbxScaleConvert)
DEF_FUNC(Ushort555RgbxDrawGlyphListAA)
DEF_FUNC(Ushort555RgbxToIntArgbConvert)
DEF_FUNC(Ushort555RgbxToIntArgbScaleConvert)
DEF_FUNC(ByteGrayToUshort565RgbConvert)
DEF_FUNC(ByteGrayToUshort565RgbScaleConvert)
DEF_FUNC(ByteIndexedBmToUshort565RgbScaleXparOver)
DEF_FUNC(ByteIndexedBmToUshort565RgbXparBgCopy)
DEF_FUNC(ByteIndexedBmToUshort565RgbXparOver)
DEF_FUNC(ByteIndexedToUshort565RgbConvert)
DEF_FUNC(ByteIndexedToUshort565RgbScaleConvert)
DEF_FUNC(IntArgbBmToUshort565RgbScaleXparOver)
DEF_FUNC(IntArgbBmToUshort565RgbXparBgCopy)
DEF_FUNC(IntArgbBmToUshort565RgbXparOver)
DEF_FUNC(IntArgbToUshort565RgbAlphaMaskBlit)
DEF_FUNC(IntArgbToUshort565RgbConvert)
DEF_FUNC(IntArgbToUshort565RgbScaleConvert)
DEF_FUNC(IntArgbToUshort565RgbSrcOverMaskBlit)
DEF_FUNC(IntArgbToUshort565RgbXorBlit)
DEF_FUNC(IntRgbToUshort565RgbAlphaMaskBlit)
DEF_FUNC(ThreeByteBgrToUshort565RgbConvert)
DEF_FUNC(ThreeByteBgrToUshort565RgbScaleConvert)
DEF_FUNC(Ushort565RgbAlphaMaskFill)
DEF_FUNC(Ushort565RgbDrawGlyphListAA)
DEF_FUNC(Ushort565RgbSrcMaskFill)
DEF_FUNC(Ushort565RgbSrcOverMaskFill)
DEF_FUNC(Ushort565RgbToIntArgbConvert)
DEF_FUNC(Ushort565RgbToIntArgbScaleConvert)
/***************************************************************/
static AnyFunc_pair vis_func_pair_array[] = {
ADD_FUNC(AnyByteDrawGlyphList),
ADD_FUNC(AnyByteDrawGlyphListXor),
ADD_FUNC(AnyByteIsomorphicCopy),
ADD_FUNC(AnyByteIsomorphicScaleCopy),
ADD_FUNC(AnyByteIsomorphicXorCopy),
ADD_FUNC(AnyByteSetLine),
ADD_FUNC(AnyByteSetRect),
ADD_FUNC(AnyByteSetSpans),
ADD_FUNC(AnyByteSetParallelogram),
ADD_FUNC(AnyByteXorLine),
ADD_FUNC(AnyByteXorRect),
ADD_FUNC(AnyByteXorSpans),
ADD_FUNC(AnyShortDrawGlyphList),
ADD_FUNC(AnyShortDrawGlyphListXor),
ADD_FUNC(AnyShortIsomorphicCopy),
ADD_FUNC(AnyShortIsomorphicScaleCopy),
ADD_FUNC(AnyShortIsomorphicXorCopy),
ADD_FUNC(AnyShortSetLine),
ADD_FUNC(AnyShortSetRect),
ADD_FUNC(AnyShortSetSpans),
ADD_FUNC(AnyShortSetParallelogram),
ADD_FUNC(AnyShortXorLine),
ADD_FUNC(AnyShortXorRect),
ADD_FUNC(AnyShortXorSpans),
ADD_FUNC(Any3ByteIsomorphicCopy),
ADD_FUNC(Any3ByteIsomorphicScaleCopy),
ADD_FUNC(Any3ByteIsomorphicXorCopy),
ADD_FUNC(Any3ByteSetLine),
ADD_FUNC(Any3ByteSetRect),
ADD_FUNC(Any3ByteSetSpans),
ADD_FUNC(Any3ByteSetParallelogram),
ADD_FUNC(Any3ByteXorLine),
ADD_FUNC(Any3ByteXorRect),
ADD_FUNC(Any3ByteXorSpans),
ADD_FUNC(Any4ByteDrawGlyphList),
ADD_FUNC(Any4ByteDrawGlyphListXor),
ADD_FUNC(Any4ByteIsomorphicCopy),
ADD_FUNC(Any4ByteIsomorphicScaleCopy),
ADD_FUNC(Any4ByteIsomorphicXorCopy),
ADD_FUNC(Any4ByteSetLine),
ADD_FUNC(Any4ByteSetRect),
ADD_FUNC(Any4ByteSetSpans),
ADD_FUNC(Any4ByteSetParallelogram),
ADD_FUNC(Any4ByteXorLine),
ADD_FUNC(Any4ByteXorRect),
ADD_FUNC(Any4ByteXorSpans),
ADD_FUNC(AnyIntDrawGlyphList),
ADD_FUNC(AnyIntDrawGlyphListXor),
ADD_FUNC(AnyIntIsomorphicCopy),
ADD_FUNC(AnyIntIsomorphicScaleCopy),
ADD_FUNC(AnyIntIsomorphicXorCopy),
ADD_FUNC(AnyIntSetLine),
ADD_FUNC(AnyIntSetRect),
ADD_FUNC(AnyIntSetSpans),
ADD_FUNC(AnyIntSetParallelogram),
ADD_FUNC(AnyIntXorLine),
ADD_FUNC(AnyIntXorRect),
ADD_FUNC(AnyIntXorSpans),
ADD_FUNC(ByteGrayAlphaMaskFill),
ADD_FUNC(ByteGrayDrawGlyphListAA),
ADD_FUNC(ByteGraySrcMaskFill),
ADD_FUNC(ByteGraySrcOverMaskFill),
ADD_FUNC(ByteGrayToIntArgbConvert),
ADD_FUNC(ByteGrayToIntArgbScaleConvert),
ADD_FUNC(ByteIndexedBmToByteGrayScaleXparOver),
ADD_FUNC(ByteIndexedBmToByteGrayXparBgCopy),
ADD_FUNC(ByteIndexedBmToByteGrayXparOver),
ADD_FUNC(ByteIndexedToByteGrayConvert),
ADD_FUNC(ByteIndexedToByteGrayScaleConvert),
ADD_FUNC(Index12GrayToByteGrayConvert),
ADD_FUNC(Index12GrayToByteGrayScaleConvert),
ADD_FUNC(Index8GrayToByteGrayConvert),
ADD_FUNC(Index8GrayToByteGrayScaleConvert),
ADD_FUNC(IntArgbBmToByteGrayScaleXparOver),
ADD_FUNC(IntArgbBmToByteGrayXparBgCopy),
ADD_FUNC(IntArgbBmToByteGrayXparOver),
ADD_FUNC(IntArgbToByteGrayAlphaMaskBlit),
ADD_FUNC(IntArgbToByteGrayConvert),
ADD_FUNC(IntArgbToByteGrayScaleConvert),
ADD_FUNC(IntArgbToByteGraySrcOverMaskBlit),
ADD_FUNC(IntArgbToByteGrayXorBlit),
ADD_FUNC(IntRgbToByteGrayAlphaMaskBlit),
ADD_FUNC(ThreeByteBgrToByteGrayConvert),
ADD_FUNC(ThreeByteBgrToByteGrayScaleConvert),
ADD_FUNC(UshortGrayToByteGrayConvert),
ADD_FUNC(UshortGrayToByteGrayScaleConvert),
ADD_FUNC(ByteGrayToUshortGrayConvert),
ADD_FUNC(ByteGrayToUshortGrayScaleConvert),
ADD_FUNC(ByteIndexedBmToUshortGrayScaleXparOver),
ADD_FUNC(ByteIndexedBmToUshortGrayXparBgCopy),
ADD_FUNC(ByteIndexedBmToUshortGrayXparOver),
ADD_FUNC(ByteIndexedToUshortGrayConvert),
ADD_FUNC(ByteIndexedToUshortGrayScaleConvert),
ADD_FUNC(IntArgbBmToUshortGrayScaleXparOver),
ADD_FUNC(IntArgbToUshortGrayConvert),
ADD_FUNC(IntArgbToUshortGrayScaleConvert),
ADD_FUNC(ThreeByteBgrToUshortGrayConvert),
ADD_FUNC(ThreeByteBgrToUshortGrayScaleConvert),
ADD_FUNC(UshortGrayToIntArgbConvert),
ADD_FUNC(UshortGrayToIntArgbScaleConvert),
ADD_FUNC(ByteGrayToByteIndexedConvert),
ADD_FUNC(ByteGrayToByteIndexedScaleConvert),
ADD_FUNC(ByteIndexedBmToByteIndexedScaleXparOver),
ADD_FUNC(ByteIndexedBmToByteIndexedXparBgCopy),
ADD_FUNC(ByteIndexedBmToByteIndexedXparOver),
ADD_FUNC(ByteIndexedToByteIndexedConvert),
ADD_FUNC(ByteIndexedToByteIndexedScaleConvert),
ADD_FUNC(Index12GrayToByteIndexedConvert),
ADD_FUNC(Index12GrayToByteIndexedScaleConvert),
ADD_FUNC(IntArgbBmToByteIndexedScaleXparOver),
ADD_FUNC(IntArgbBmToByteIndexedXparBgCopy),
ADD_FUNC(IntArgbBmToByteIndexedXparOver),
ADD_FUNC(IntArgbToByteIndexedConvert),
ADD_FUNC(IntArgbToByteIndexedScaleConvert),
ADD_FUNC(IntArgbToByteIndexedXorBlit),
ADD_FUNC(ThreeByteBgrToByteIndexedConvert),
ADD_FUNC(ThreeByteBgrToByteIndexedScaleConvert),
ADD_FUNC(ByteGrayToFourByteAbgrConvert),
ADD_FUNC(ByteGrayToFourByteAbgrScaleConvert),
ADD_FUNC(ByteIndexedBmToFourByteAbgrScaleXparOver),
ADD_FUNC(ByteIndexedBmToFourByteAbgrXparBgCopy),
ADD_FUNC(ByteIndexedBmToFourByteAbgrXparOver),
ADD_FUNC(ByteIndexedToFourByteAbgrConvert),
ADD_FUNC(ByteIndexedToFourByteAbgrScaleConvert),
ADD_FUNC(FourByteAbgrAlphaMaskFill),
ADD_FUNC(FourByteAbgrDrawGlyphListAA),
ADD_FUNC(FourByteAbgrSrcMaskFill),
ADD_FUNC(FourByteAbgrSrcOverMaskFill),
ADD_FUNC(FourByteAbgrToIntArgbConvert),
ADD_FUNC(FourByteAbgrToIntArgbScaleConvert),
ADD_FUNC(IntArgbBmToFourByteAbgrScaleXparOver),
ADD_FUNC(IntArgbToFourByteAbgrAlphaMaskBlit),
ADD_FUNC(IntArgbToFourByteAbgrConvert),
ADD_FUNC(IntArgbToFourByteAbgrScaleConvert),
ADD_FUNC(IntArgbToFourByteAbgrSrcOverMaskBlit),
ADD_FUNC(IntArgbToFourByteAbgrXorBlit),
ADD_FUNC(IntRgbToFourByteAbgrAlphaMaskBlit),
ADD_FUNC(IntRgbToFourByteAbgrConvert),
ADD_FUNC(IntRgbToFourByteAbgrScaleConvert),
ADD_FUNC(ThreeByteBgrToFourByteAbgrConvert),
ADD_FUNC(ThreeByteBgrToFourByteAbgrScaleConvert),
ADD_FUNC(ByteGrayToFourByteAbgrPreConvert),
ADD_FUNC(ByteGrayToFourByteAbgrPreScaleConvert),
ADD_FUNC(ByteIndexedBmToFourByteAbgrPreScaleXparOver),
ADD_FUNC(ByteIndexedBmToFourByteAbgrPreXparBgCopy),
ADD_FUNC(ByteIndexedBmToFourByteAbgrPreXparOver),
ADD_FUNC(ByteIndexedToFourByteAbgrPreConvert),
ADD_FUNC(ByteIndexedToFourByteAbgrPreScaleConvert),
ADD_FUNC(FourByteAbgrPreAlphaMaskFill),
ADD_FUNC(FourByteAbgrPreDrawGlyphListAA),
ADD_FUNC(FourByteAbgrPreSrcMaskFill),
ADD_FUNC(FourByteAbgrPreSrcOverMaskFill),
ADD_FUNC(FourByteAbgrPreToIntArgbConvert),
ADD_FUNC(FourByteAbgrPreToIntArgbScaleConvert),
ADD_FUNC(IntArgbBmToFourByteAbgrPreScaleXparOver),
ADD_FUNC(IntArgbToFourByteAbgrPreAlphaMaskBlit),
ADD_FUNC(IntArgbToFourByteAbgrPreConvert),
ADD_FUNC(IntArgbToFourByteAbgrPreScaleConvert),
ADD_FUNC(IntArgbToFourByteAbgrPreSrcOverMaskBlit),
ADD_FUNC(IntArgbToFourByteAbgrPreXorBlit),
ADD_FUNC(IntRgbToFourByteAbgrPreAlphaMaskBlit),
ADD_FUNC(IntRgbToFourByteAbgrPreConvert),
ADD_FUNC(IntRgbToFourByteAbgrPreScaleConvert),
ADD_FUNC(ThreeByteBgrToFourByteAbgrPreConvert),
ADD_FUNC(ThreeByteBgrToFourByteAbgrPreScaleConvert),
ADD_FUNC(ByteIndexedBmToIntArgbScaleXparOver),
ADD_FUNC(ByteIndexedBmToIntArgbXparBgCopy),
ADD_FUNC(ByteIndexedBmToIntArgbXparOver),
ADD_FUNC(ByteIndexedToIntArgbConvert),
ADD_FUNC(ByteIndexedToIntArgbScaleConvert),
ADD_FUNC(Index12GrayToIntArgbConvert),
ADD_FUNC(IntArgbAlphaMaskFill),
ADD_FUNC(IntArgbBmToIntArgbScaleXparOver),
ADD_FUNC(IntArgbDrawGlyphListAA),
ADD_FUNC(IntArgbSrcMaskFill),
ADD_FUNC(IntArgbSrcOverMaskFill),
ADD_FUNC(IntArgbToIntArgbAlphaMaskBlit),
ADD_FUNC(IntArgbToIntArgbSrcOverMaskBlit),
ADD_FUNC(IntArgbToIntArgbXorBlit),
ADD_FUNC(IntRgbToIntArgbAlphaMaskBlit),
ADD_FUNC(ByteIndexedBmToIntArgbBmScaleXparOver),
ADD_FUNC(ByteIndexedBmToIntArgbBmXparBgCopy),
ADD_FUNC(ByteIndexedBmToIntArgbBmXparOver),
ADD_FUNC(ByteIndexedToIntArgbBmConvert),
ADD_FUNC(ByteIndexedToIntArgbBmScaleConvert),
ADD_FUNC(IntArgbBmDrawGlyphListAA),
ADD_FUNC(IntArgbBmToIntArgbConvert),
ADD_FUNC(IntArgbToIntArgbBmConvert),
ADD_FUNC(IntArgbToIntArgbBmScaleConvert),
ADD_FUNC(IntArgbToIntArgbBmXorBlit),
ADD_FUNC(ByteGrayToIntArgbPreConvert),
ADD_FUNC(ByteGrayToIntArgbPreScaleConvert),
ADD_FUNC(ByteIndexedBmToIntArgbPreScaleXparOver),
ADD_FUNC(ByteIndexedBmToIntArgbPreXparBgCopy),
ADD_FUNC(ByteIndexedBmToIntArgbPreXparOver),
ADD_FUNC(ByteIndexedToIntArgbPreConvert),
ADD_FUNC(ByteIndexedToIntArgbPreScaleConvert),
ADD_FUNC(IntArgbPreAlphaMaskFill),
ADD_FUNC(IntArgbPreDrawGlyphListAA),
ADD_FUNC(IntArgbPreSrcMaskFill),
ADD_FUNC(IntArgbPreSrcOverMaskFill),
ADD_FUNC(IntArgbPreToIntArgbConvert),
ADD_FUNC(IntArgbPreToIntArgbScaleConvert),
ADD_FUNC(IntArgbToIntArgbPreAlphaMaskBlit),
ADD_FUNC(IntArgbToIntArgbPreConvert),
ADD_FUNC(IntArgbToIntArgbPreScaleConvert),
ADD_FUNC(IntArgbToIntArgbPreSrcOverMaskBlit),
ADD_FUNC(IntArgbToIntArgbPreXorBlit),
ADD_FUNC(IntRgbToIntArgbPreAlphaMaskBlit),
ADD_FUNC(IntRgbToIntArgbPreConvert),
ADD_FUNC(IntRgbToIntArgbPreScaleConvert),
ADD_FUNC(ThreeByteBgrToIntArgbPreConvert),
ADD_FUNC(ThreeByteBgrToIntArgbPreScaleConvert),
ADD_FUNC(ByteIndexedBmToIntBgrScaleXparOver),
ADD_FUNC(ByteIndexedBmToIntBgrXparBgCopy),
ADD_FUNC(ByteIndexedBmToIntBgrXparOver),
ADD_FUNC(ByteIndexedToIntBgrConvert),
ADD_FUNC(ByteIndexedToIntBgrScaleConvert),
ADD_FUNC(IntArgbBmToIntBgrScaleXparOver),
ADD_FUNC(IntArgbBmToIntBgrXparBgCopy),
ADD_FUNC(IntArgbBmToIntBgrXparOver),
ADD_FUNC(IntArgbToIntBgrAlphaMaskBlit),
ADD_FUNC(IntArgbToIntBgrConvert),
ADD_FUNC(IntArgbToIntBgrScaleConvert),
ADD_FUNC(IntArgbToIntBgrSrcOverMaskBlit),
ADD_FUNC(IntArgbToIntBgrXorBlit),
ADD_FUNC(IntBgrAlphaMaskFill),
ADD_FUNC(IntBgrDrawGlyphListAA),
ADD_FUNC(IntBgrSrcMaskFill),
ADD_FUNC(IntBgrSrcOverMaskFill),
ADD_FUNC(IntBgrToIntArgbConvert),
ADD_FUNC(IntBgrToIntArgbScaleConvert),
ADD_FUNC(IntBgrToIntBgrAlphaMaskBlit),
ADD_FUNC(IntRgbToIntBgrAlphaMaskBlit),
ADD_FUNC(ThreeByteBgrToIntBgrConvert),
ADD_FUNC(ThreeByteBgrToIntBgrScaleConvert),
ADD_FUNC(ByteGrayToIntRgbConvert),
ADD_FUNC(ByteGrayToIntRgbScaleConvert),
ADD_FUNC(IntArgbBmToIntRgbXparBgCopy),
ADD_FUNC(IntArgbBmToIntRgbXparOver),
ADD_FUNC(IntArgbToIntRgbAlphaMaskBlit),
ADD_FUNC(IntArgbToIntRgbSrcOverMaskBlit),
ADD_FUNC(IntArgbToIntRgbXorBlit),
ADD_FUNC(IntRgbAlphaMaskFill),
ADD_FUNC(IntRgbDrawGlyphListAA),
ADD_FUNC(IntRgbSrcMaskFill),
ADD_FUNC(IntRgbSrcOverMaskFill),
ADD_FUNC(IntRgbToIntArgbConvert),
ADD_FUNC(IntRgbToIntArgbScaleConvert),
ADD_FUNC(IntRgbToIntRgbAlphaMaskBlit),
ADD_FUNC(ThreeByteBgrToIntRgbConvert),
ADD_FUNC(ThreeByteBgrToIntRgbScaleConvert),
ADD_FUNC(ByteGrayToIntRgbxConvert),
ADD_FUNC(ByteGrayToIntRgbxScaleConvert),
ADD_FUNC(ByteIndexedBmToIntRgbxScaleXparOver),
ADD_FUNC(ByteIndexedBmToIntRgbxXparBgCopy),
ADD_FUNC(ByteIndexedBmToIntRgbxXparOver),
ADD_FUNC(ByteIndexedToIntRgbxConvert),
ADD_FUNC(ByteIndexedToIntRgbxScaleConvert),
ADD_FUNC(IntArgbBmToIntRgbxScaleXparOver),
ADD_FUNC(IntArgbToIntRgbxConvert),
ADD_FUNC(IntArgbToIntRgbxScaleConvert),
ADD_FUNC(IntArgbToIntRgbxXorBlit),
ADD_FUNC(IntRgbxDrawGlyphListAA),
ADD_FUNC(IntRgbxToIntArgbConvert),
ADD_FUNC(IntRgbxToIntArgbScaleConvert),
ADD_FUNC(ThreeByteBgrToIntRgbxConvert),
ADD_FUNC(ThreeByteBgrToIntRgbxScaleConvert),
ADD_FUNC(ThreeByteBgrAlphaMaskFill),
ADD_FUNC(ThreeByteBgrSrcMaskFill),
ADD_FUNC(ThreeByteBgrSrcOverMaskFill),
ADD_FUNC(ThreeByteBgrToIntArgbConvert),
ADD_FUNC(ThreeByteBgrToIntArgbScaleConvert),
};
/***************************************************************/
#define NUM_VIS_FUNCS sizeof(vis_func_pair_array)/sizeof(AnyFunc_pair)
/***************************************************************/
#define HASH_SIZE 1024 /* must be power of 2 and > number of functions */
#define PTR_SHIFT ((sizeof(void*) == 4) ? 2 : 3)
#define HASH_FUNC(x) (((jint)(x) >> PTR_SHIFT) & (HASH_SIZE - 1))
#define NEXT_INDEX(j) ((j + 1) & (HASH_SIZE - 1))
static AnyFunc* hash_table[HASH_SIZE];
static AnyFunc* hash_table_vis[HASH_SIZE];
/***************************************************************/
static int initialized;
static int usevis = JNI_TRUE;
#if defined(__linux__) || defined(MACOSX)
# define ULTRA_CHIP "sparc64"
#else
# define ULTRA_CHIP "sun4u"
#endif
extern TransformInterpFunc *pBilinearFunc;
extern TransformInterpFunc *pBicubicFunc;
extern TransformInterpFunc vis_BilinearBlend;
extern TransformInterpFunc vis_BicubicBlend;
/*
* This function returns a pointer to the VIS accelerated version
* of the indicated C function if it exists and if the conditions
* are correct to use the VIS functions.
*/
AnyFunc* MapAccelFunction(AnyFunc *func_c)
{
jint i, j;
if (!initialized) {
struct utsname name;
/*
* Only use the vis loops if the environment variable is set.
* Find out the machine name. If it is an SUN ultra, we
* can use the vis library
*/
if (uname(&name) < 0 || strcmp(name.machine, ULTRA_CHIP) != 0) {
usevis = JNI_FALSE;
} else {
char *vis_env = getenv("J2D_USE_VIS_LOOPS");
if (vis_env != 0) {
switch (*vis_env) {
case 'T':
fprintf(stderr, "VIS loops enabled\n");
case 't':
usevis = JNI_TRUE;
break;
case 'F':
fprintf(stderr, "VIS loops disabled\n");
case 'f':
usevis = JNI_FALSE;
break;
default:
fprintf(stderr, "VIS loops %s by default\n",
usevis ? "enabled" : "disabled");
break;
}
}
}
initialized = 1;
if (usevis) {
/* fill hash table */
memset(hash_table, 0, sizeof(hash_table));
for (i = 0; i < NUM_VIS_FUNCS; i++) {
AnyFunc* func = vis_func_pair_array[i].func_c;
j = HASH_FUNC(func);
while (hash_table[j] != NULL) {
j = NEXT_INDEX(j);
}
hash_table[j] = func;
hash_table_vis[j] = vis_func_pair_array[i].func_vis;
}
pBilinearFunc = vis_BilinearBlend;
pBicubicFunc = vis_BicubicBlend;
}
}
if (!usevis) {
return func_c;
}
j = HASH_FUNC(func_c);
while (hash_table[j] != NULL) {
if (hash_table[j] == func_c) {
return hash_table_vis[j];
}
j = NEXT_INDEX(j);
}
return func_c;
}
/***************************************************************/
| gpl-2.0 |
Kalafina/papercrop | luabind-0.9/test/test_null_pointer.cpp | 45 | 1607 | // Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#include "test.hpp"
#include <luabind/luabind.hpp>
struct A : counted_type<A>
{
A* f() { return 0; }
};
A* return_pointer()
{
return 0;
}
COUNTER_GUARD(A);
void test_main(lua_State* L)
{
using namespace luabind;
module(L)
[
class_<A>("A")
.def(constructor<>())
.def("f", &A::f),
def("return_pointer", &return_pointer)
];
DOSTRING(L,
"e = return_pointer()\n"
"assert(e == nil)");
DOSTRING(L,
"a = A()\n"
"e = a:f()\n"
"assert(e == nil)");
}
| gpl-2.0 |
wfarnsworth/utrace-beagle | drivers/net/cxgb4/t4_hw.c | 45 | 88856 | /*
* This file is part of the Chelsio T4 Ethernet driver for Linux.
*
* Copyright (c) 2003-2010 Chelsio Communications, 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/init.h>
#include <linux/delay.h>
#include "cxgb4.h"
#include "t4_regs.h"
#include "t4fw_api.h"
/**
* t4_wait_op_done_val - wait until an operation is completed
* @adapter: the adapter performing the operation
* @reg: the register to check for completion
* @mask: a single-bit field within @reg that indicates completion
* @polarity: the value of the field when the operation is completed
* @attempts: number of check iterations
* @delay: delay in usecs between iterations
* @valp: where to store the value of the register at completion time
*
* Wait until an operation is completed by checking a bit in a register
* up to @attempts times. If @valp is not NULL the value of the register
* at the time it indicated completion is stored there. Returns 0 if the
* operation completes and -EAGAIN otherwise.
*/
static int t4_wait_op_done_val(struct adapter *adapter, int reg, u32 mask,
int polarity, int attempts, int delay, u32 *valp)
{
while (1) {
u32 val = t4_read_reg(adapter, reg);
if (!!(val & mask) == polarity) {
if (valp)
*valp = val;
return 0;
}
if (--attempts == 0)
return -EAGAIN;
if (delay)
udelay(delay);
}
}
static inline int t4_wait_op_done(struct adapter *adapter, int reg, u32 mask,
int polarity, int attempts, int delay)
{
return t4_wait_op_done_val(adapter, reg, mask, polarity, attempts,
delay, NULL);
}
/**
* t4_set_reg_field - set a register field to a value
* @adapter: the adapter to program
* @addr: the register address
* @mask: specifies the portion of the register to modify
* @val: the new value for the register field
*
* Sets a register field specified by the supplied mask to the
* given value.
*/
void t4_set_reg_field(struct adapter *adapter, unsigned int addr, u32 mask,
u32 val)
{
u32 v = t4_read_reg(adapter, addr) & ~mask;
t4_write_reg(adapter, addr, v | val);
(void) t4_read_reg(adapter, addr); /* flush */
}
/**
* t4_read_indirect - read indirectly addressed registers
* @adap: the adapter
* @addr_reg: register holding the indirect address
* @data_reg: register holding the value of the indirect register
* @vals: where the read register values are stored
* @nregs: how many indirect registers to read
* @start_idx: index of first indirect register to read
*
* Reads registers that are accessed indirectly through an address/data
* register pair.
*/
static void t4_read_indirect(struct adapter *adap, unsigned int addr_reg,
unsigned int data_reg, u32 *vals,
unsigned int nregs, unsigned int start_idx)
{
while (nregs--) {
t4_write_reg(adap, addr_reg, start_idx);
*vals++ = t4_read_reg(adap, data_reg);
start_idx++;
}
}
/*
* Get the reply to a mailbox command and store it in @rpl in big-endian order.
*/
static void get_mbox_rpl(struct adapter *adap, __be64 *rpl, int nflit,
u32 mbox_addr)
{
for ( ; nflit; nflit--, mbox_addr += 8)
*rpl++ = cpu_to_be64(t4_read_reg64(adap, mbox_addr));
}
/*
* Handle a FW assertion reported in a mailbox.
*/
static void fw_asrt(struct adapter *adap, u32 mbox_addr)
{
struct fw_debug_cmd asrt;
get_mbox_rpl(adap, (__be64 *)&asrt, sizeof(asrt) / 8, mbox_addr);
dev_alert(adap->pdev_dev,
"FW assertion at %.16s:%u, val0 %#x, val1 %#x\n",
asrt.u.assert.filename_0_7, ntohl(asrt.u.assert.line),
ntohl(asrt.u.assert.x), ntohl(asrt.u.assert.y));
}
static void dump_mbox(struct adapter *adap, int mbox, u32 data_reg)
{
dev_err(adap->pdev_dev,
"mbox %d: %llx %llx %llx %llx %llx %llx %llx %llx\n", mbox,
(unsigned long long)t4_read_reg64(adap, data_reg),
(unsigned long long)t4_read_reg64(adap, data_reg + 8),
(unsigned long long)t4_read_reg64(adap, data_reg + 16),
(unsigned long long)t4_read_reg64(adap, data_reg + 24),
(unsigned long long)t4_read_reg64(adap, data_reg + 32),
(unsigned long long)t4_read_reg64(adap, data_reg + 40),
(unsigned long long)t4_read_reg64(adap, data_reg + 48),
(unsigned long long)t4_read_reg64(adap, data_reg + 56));
}
/**
* t4_wr_mbox_meat - send a command to FW through the given mailbox
* @adap: the adapter
* @mbox: index of the mailbox to use
* @cmd: the command to write
* @size: command length in bytes
* @rpl: where to optionally store the reply
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Sends the given command to FW through the selected mailbox and waits
* for the FW to execute the command. If @rpl is not %NULL it is used to
* store the FW's reply to the command. The command and its optional
* reply are of the same length. FW can take up to %FW_CMD_MAX_TIMEOUT ms
* to respond. @sleep_ok determines whether we may sleep while awaiting
* the response. If sleeping is allowed we use progressive backoff
* otherwise we spin.
*
* The return value is 0 on success or a negative errno on failure. A
* failure can happen either because we are not able to execute the
* command or FW executes it but signals an error. In the latter case
* the return value is the error code indicated by FW (negated).
*/
int t4_wr_mbox_meat(struct adapter *adap, int mbox, const void *cmd, int size,
void *rpl, bool sleep_ok)
{
static int delay[] = {
1, 1, 3, 5, 10, 10, 20, 50, 100, 200
};
u32 v;
u64 res;
int i, ms, delay_idx;
const __be64 *p = cmd;
u32 data_reg = PF_REG(mbox, CIM_PF_MAILBOX_DATA);
u32 ctl_reg = PF_REG(mbox, CIM_PF_MAILBOX_CTRL);
if ((size & 15) || size > MBOX_LEN)
return -EINVAL;
/*
* If the device is off-line, as in EEH, commands will time out.
* Fail them early so we don't waste time waiting.
*/
if (adap->pdev->error_state != pci_channel_io_normal)
return -EIO;
v = MBOWNER_GET(t4_read_reg(adap, ctl_reg));
for (i = 0; v == MBOX_OWNER_NONE && i < 3; i++)
v = MBOWNER_GET(t4_read_reg(adap, ctl_reg));
if (v != MBOX_OWNER_DRV)
return v ? -EBUSY : -ETIMEDOUT;
for (i = 0; i < size; i += 8)
t4_write_reg64(adap, data_reg + i, be64_to_cpu(*p++));
t4_write_reg(adap, ctl_reg, MBMSGVALID | MBOWNER(MBOX_OWNER_FW));
t4_read_reg(adap, ctl_reg); /* flush write */
delay_idx = 0;
ms = delay[0];
for (i = 0; i < FW_CMD_MAX_TIMEOUT; i += ms) {
if (sleep_ok) {
ms = delay[delay_idx]; /* last element may repeat */
if (delay_idx < ARRAY_SIZE(delay) - 1)
delay_idx++;
msleep(ms);
} else
mdelay(ms);
v = t4_read_reg(adap, ctl_reg);
if (MBOWNER_GET(v) == MBOX_OWNER_DRV) {
if (!(v & MBMSGVALID)) {
t4_write_reg(adap, ctl_reg, 0);
continue;
}
res = t4_read_reg64(adap, data_reg);
if (FW_CMD_OP_GET(res >> 32) == FW_DEBUG_CMD) {
fw_asrt(adap, data_reg);
res = FW_CMD_RETVAL(EIO);
} else if (rpl)
get_mbox_rpl(adap, rpl, size / 8, data_reg);
if (FW_CMD_RETVAL_GET((int)res))
dump_mbox(adap, mbox, data_reg);
t4_write_reg(adap, ctl_reg, 0);
return -FW_CMD_RETVAL_GET((int)res);
}
}
dump_mbox(adap, mbox, data_reg);
dev_err(adap->pdev_dev, "command %#x in mailbox %d timed out\n",
*(const u8 *)cmd, mbox);
return -ETIMEDOUT;
}
/**
* t4_mc_read - read from MC through backdoor accesses
* @adap: the adapter
* @addr: address of first byte requested
* @data: 64 bytes of data containing the requested address
* @ecc: where to store the corresponding 64-bit ECC word
*
* Read 64 bytes of data from MC starting at a 64-byte-aligned address
* that covers the requested address @addr. If @parity is not %NULL it
* is assigned the 64-bit ECC word for the read data.
*/
int t4_mc_read(struct adapter *adap, u32 addr, __be32 *data, u64 *ecc)
{
int i;
if (t4_read_reg(adap, MC_BIST_CMD) & START_BIST)
return -EBUSY;
t4_write_reg(adap, MC_BIST_CMD_ADDR, addr & ~0x3fU);
t4_write_reg(adap, MC_BIST_CMD_LEN, 64);
t4_write_reg(adap, MC_BIST_DATA_PATTERN, 0xc);
t4_write_reg(adap, MC_BIST_CMD, BIST_OPCODE(1) | START_BIST |
BIST_CMD_GAP(1));
i = t4_wait_op_done(adap, MC_BIST_CMD, START_BIST, 0, 10, 1);
if (i)
return i;
#define MC_DATA(i) MC_BIST_STATUS_REG(MC_BIST_STATUS_RDATA, i)
for (i = 15; i >= 0; i--)
*data++ = htonl(t4_read_reg(adap, MC_DATA(i)));
if (ecc)
*ecc = t4_read_reg64(adap, MC_DATA(16));
#undef MC_DATA
return 0;
}
/**
* t4_edc_read - read from EDC through backdoor accesses
* @adap: the adapter
* @idx: which EDC to access
* @addr: address of first byte requested
* @data: 64 bytes of data containing the requested address
* @ecc: where to store the corresponding 64-bit ECC word
*
* Read 64 bytes of data from EDC starting at a 64-byte-aligned address
* that covers the requested address @addr. If @parity is not %NULL it
* is assigned the 64-bit ECC word for the read data.
*/
int t4_edc_read(struct adapter *adap, int idx, u32 addr, __be32 *data, u64 *ecc)
{
int i;
idx *= EDC_STRIDE;
if (t4_read_reg(adap, EDC_BIST_CMD + idx) & START_BIST)
return -EBUSY;
t4_write_reg(adap, EDC_BIST_CMD_ADDR + idx, addr & ~0x3fU);
t4_write_reg(adap, EDC_BIST_CMD_LEN + idx, 64);
t4_write_reg(adap, EDC_BIST_DATA_PATTERN + idx, 0xc);
t4_write_reg(adap, EDC_BIST_CMD + idx,
BIST_OPCODE(1) | BIST_CMD_GAP(1) | START_BIST);
i = t4_wait_op_done(adap, EDC_BIST_CMD + idx, START_BIST, 0, 10, 1);
if (i)
return i;
#define EDC_DATA(i) (EDC_BIST_STATUS_REG(EDC_BIST_STATUS_RDATA, i) + idx)
for (i = 15; i >= 0; i--)
*data++ = htonl(t4_read_reg(adap, EDC_DATA(i)));
if (ecc)
*ecc = t4_read_reg64(adap, EDC_DATA(16));
#undef EDC_DATA
return 0;
}
/*
* Partial EEPROM Vital Product Data structure. Includes only the ID and
* VPD-R header.
*/
struct t4_vpd_hdr {
u8 id_tag;
u8 id_len[2];
u8 id_data[ID_LEN];
u8 vpdr_tag;
u8 vpdr_len[2];
};
#define EEPROM_STAT_ADDR 0x7bfc
#define VPD_BASE 0
#define VPD_LEN 512
/**
* t4_seeprom_wp - enable/disable EEPROM write protection
* @adapter: the adapter
* @enable: whether to enable or disable write protection
*
* Enables or disables write protection on the serial EEPROM.
*/
int t4_seeprom_wp(struct adapter *adapter, bool enable)
{
unsigned int v = enable ? 0xc : 0;
int ret = pci_write_vpd(adapter->pdev, EEPROM_STAT_ADDR, 4, &v);
return ret < 0 ? ret : 0;
}
/**
* get_vpd_params - read VPD parameters from VPD EEPROM
* @adapter: adapter to read
* @p: where to store the parameters
*
* Reads card parameters stored in VPD EEPROM.
*/
static int get_vpd_params(struct adapter *adapter, struct vpd_params *p)
{
int i, ret;
int ec, sn, v2;
u8 vpd[VPD_LEN], csum;
unsigned int vpdr_len;
const struct t4_vpd_hdr *v;
ret = pci_read_vpd(adapter->pdev, VPD_BASE, sizeof(vpd), vpd);
if (ret < 0)
return ret;
v = (const struct t4_vpd_hdr *)vpd;
vpdr_len = pci_vpd_lrdt_size(&v->vpdr_tag);
if (vpdr_len + sizeof(struct t4_vpd_hdr) > VPD_LEN) {
dev_err(adapter->pdev_dev, "bad VPD-R length %u\n", vpdr_len);
return -EINVAL;
}
#define FIND_VPD_KW(var, name) do { \
var = pci_vpd_find_info_keyword(&v->id_tag, sizeof(struct t4_vpd_hdr), \
vpdr_len, name); \
if (var < 0) { \
dev_err(adapter->pdev_dev, "missing VPD keyword " name "\n"); \
return -EINVAL; \
} \
var += PCI_VPD_INFO_FLD_HDR_SIZE; \
} while (0)
FIND_VPD_KW(i, "RV");
for (csum = 0; i >= 0; i--)
csum += vpd[i];
if (csum) {
dev_err(adapter->pdev_dev,
"corrupted VPD EEPROM, actual csum %u\n", csum);
return -EINVAL;
}
FIND_VPD_KW(ec, "EC");
FIND_VPD_KW(sn, "SN");
FIND_VPD_KW(v2, "V2");
#undef FIND_VPD_KW
p->cclk = simple_strtoul(vpd + v2, NULL, 10);
memcpy(p->id, v->id_data, ID_LEN);
strim(p->id);
memcpy(p->ec, vpd + ec, EC_LEN);
strim(p->ec);
i = pci_vpd_info_field_size(vpd + sn - PCI_VPD_INFO_FLD_HDR_SIZE);
memcpy(p->sn, vpd + sn, min(i, SERNUM_LEN));
strim(p->sn);
return 0;
}
/* serial flash and firmware constants */
enum {
SF_ATTEMPTS = 10, /* max retries for SF operations */
/* flash command opcodes */
SF_PROG_PAGE = 2, /* program page */
SF_WR_DISABLE = 4, /* disable writes */
SF_RD_STATUS = 5, /* read status register */
SF_WR_ENABLE = 6, /* enable writes */
SF_RD_DATA_FAST = 0xb, /* read flash */
SF_RD_ID = 0x9f, /* read ID */
SF_ERASE_SECTOR = 0xd8, /* erase sector */
FW_MAX_SIZE = 512 * 1024,
};
/**
* sf1_read - read data from the serial flash
* @adapter: the adapter
* @byte_cnt: number of bytes to read
* @cont: whether another operation will be chained
* @lock: whether to lock SF for PL access only
* @valp: where to store the read data
*
* Reads up to 4 bytes of data from the serial flash. The location of
* the read needs to be specified prior to calling this by issuing the
* appropriate commands to the serial flash.
*/
static int sf1_read(struct adapter *adapter, unsigned int byte_cnt, int cont,
int lock, u32 *valp)
{
int ret;
if (!byte_cnt || byte_cnt > 4)
return -EINVAL;
if (t4_read_reg(adapter, SF_OP) & BUSY)
return -EBUSY;
cont = cont ? SF_CONT : 0;
lock = lock ? SF_LOCK : 0;
t4_write_reg(adapter, SF_OP, lock | cont | BYTECNT(byte_cnt - 1));
ret = t4_wait_op_done(adapter, SF_OP, BUSY, 0, SF_ATTEMPTS, 5);
if (!ret)
*valp = t4_read_reg(adapter, SF_DATA);
return ret;
}
/**
* sf1_write - write data to the serial flash
* @adapter: the adapter
* @byte_cnt: number of bytes to write
* @cont: whether another operation will be chained
* @lock: whether to lock SF for PL access only
* @val: value to write
*
* Writes up to 4 bytes of data to the serial flash. The location of
* the write needs to be specified prior to calling this by issuing the
* appropriate commands to the serial flash.
*/
static int sf1_write(struct adapter *adapter, unsigned int byte_cnt, int cont,
int lock, u32 val)
{
if (!byte_cnt || byte_cnt > 4)
return -EINVAL;
if (t4_read_reg(adapter, SF_OP) & BUSY)
return -EBUSY;
cont = cont ? SF_CONT : 0;
lock = lock ? SF_LOCK : 0;
t4_write_reg(adapter, SF_DATA, val);
t4_write_reg(adapter, SF_OP, lock |
cont | BYTECNT(byte_cnt - 1) | OP_WR);
return t4_wait_op_done(adapter, SF_OP, BUSY, 0, SF_ATTEMPTS, 5);
}
/**
* flash_wait_op - wait for a flash operation to complete
* @adapter: the adapter
* @attempts: max number of polls of the status register
* @delay: delay between polls in ms
*
* Wait for a flash operation to complete by polling the status register.
*/
static int flash_wait_op(struct adapter *adapter, int attempts, int delay)
{
int ret;
u32 status;
while (1) {
if ((ret = sf1_write(adapter, 1, 1, 1, SF_RD_STATUS)) != 0 ||
(ret = sf1_read(adapter, 1, 0, 1, &status)) != 0)
return ret;
if (!(status & 1))
return 0;
if (--attempts == 0)
return -EAGAIN;
if (delay)
msleep(delay);
}
}
/**
* t4_read_flash - read words from serial flash
* @adapter: the adapter
* @addr: the start address for the read
* @nwords: how many 32-bit words to read
* @data: where to store the read data
* @byte_oriented: whether to store data as bytes or as words
*
* Read the specified number of 32-bit words from the serial flash.
* If @byte_oriented is set the read data is stored as a byte array
* (i.e., big-endian), otherwise as 32-bit words in the platform's
* natural endianess.
*/
static int t4_read_flash(struct adapter *adapter, unsigned int addr,
unsigned int nwords, u32 *data, int byte_oriented)
{
int ret;
if (addr + nwords * sizeof(u32) > adapter->params.sf_size || (addr & 3))
return -EINVAL;
addr = swab32(addr) | SF_RD_DATA_FAST;
if ((ret = sf1_write(adapter, 4, 1, 0, addr)) != 0 ||
(ret = sf1_read(adapter, 1, 1, 0, data)) != 0)
return ret;
for ( ; nwords; nwords--, data++) {
ret = sf1_read(adapter, 4, nwords > 1, nwords == 1, data);
if (nwords == 1)
t4_write_reg(adapter, SF_OP, 0); /* unlock SF */
if (ret)
return ret;
if (byte_oriented)
*data = htonl(*data);
}
return 0;
}
/**
* t4_write_flash - write up to a page of data to the serial flash
* @adapter: the adapter
* @addr: the start address to write
* @n: length of data to write in bytes
* @data: the data to write
*
* Writes up to a page of data (256 bytes) to the serial flash starting
* at the given address. All the data must be written to the same page.
*/
static int t4_write_flash(struct adapter *adapter, unsigned int addr,
unsigned int n, const u8 *data)
{
int ret;
u32 buf[64];
unsigned int i, c, left, val, offset = addr & 0xff;
if (addr >= adapter->params.sf_size || offset + n > SF_PAGE_SIZE)
return -EINVAL;
val = swab32(addr) | SF_PROG_PAGE;
if ((ret = sf1_write(adapter, 1, 0, 1, SF_WR_ENABLE)) != 0 ||
(ret = sf1_write(adapter, 4, 1, 1, val)) != 0)
goto unlock;
for (left = n; left; left -= c) {
c = min(left, 4U);
for (val = 0, i = 0; i < c; ++i)
val = (val << 8) + *data++;
ret = sf1_write(adapter, c, c != left, 1, val);
if (ret)
goto unlock;
}
ret = flash_wait_op(adapter, 8, 1);
if (ret)
goto unlock;
t4_write_reg(adapter, SF_OP, 0); /* unlock SF */
/* Read the page to verify the write succeeded */
ret = t4_read_flash(adapter, addr & ~0xff, ARRAY_SIZE(buf), buf, 1);
if (ret)
return ret;
if (memcmp(data - n, (u8 *)buf + offset, n)) {
dev_err(adapter->pdev_dev,
"failed to correctly write the flash page at %#x\n",
addr);
return -EIO;
}
return 0;
unlock:
t4_write_reg(adapter, SF_OP, 0); /* unlock SF */
return ret;
}
/**
* get_fw_version - read the firmware version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the FW version from flash.
*/
static int get_fw_version(struct adapter *adapter, u32 *vers)
{
return t4_read_flash(adapter, adapter->params.sf_fw_start +
offsetof(struct fw_hdr, fw_ver), 1, vers, 0);
}
/**
* get_tp_version - read the TP microcode version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the TP microcode version from flash.
*/
static int get_tp_version(struct adapter *adapter, u32 *vers)
{
return t4_read_flash(adapter, adapter->params.sf_fw_start +
offsetof(struct fw_hdr, tp_microcode_ver),
1, vers, 0);
}
/**
* t4_check_fw_version - check if the FW is compatible with this driver
* @adapter: the adapter
*
* Checks if an adapter's FW is compatible with the driver. Returns 0
* if there's exact match, a negative error if the version could not be
* read or there's a major version mismatch, and a positive value if the
* expected major version is found but there's a minor version mismatch.
*/
int t4_check_fw_version(struct adapter *adapter)
{
u32 api_vers[2];
int ret, major, minor, micro;
ret = get_fw_version(adapter, &adapter->params.fw_vers);
if (!ret)
ret = get_tp_version(adapter, &adapter->params.tp_vers);
if (!ret)
ret = t4_read_flash(adapter, adapter->params.sf_fw_start +
offsetof(struct fw_hdr, intfver_nic),
2, api_vers, 1);
if (ret)
return ret;
major = FW_HDR_FW_VER_MAJOR_GET(adapter->params.fw_vers);
minor = FW_HDR_FW_VER_MINOR_GET(adapter->params.fw_vers);
micro = FW_HDR_FW_VER_MICRO_GET(adapter->params.fw_vers);
memcpy(adapter->params.api_vers, api_vers,
sizeof(adapter->params.api_vers));
if (major != FW_VERSION_MAJOR) { /* major mismatch - fail */
dev_err(adapter->pdev_dev,
"card FW has major version %u, driver wants %u\n",
major, FW_VERSION_MAJOR);
return -EINVAL;
}
if (minor == FW_VERSION_MINOR && micro == FW_VERSION_MICRO)
return 0; /* perfect match */
/* Minor/micro version mismatch. Report it but often it's OK. */
return 1;
}
/**
* t4_flash_erase_sectors - erase a range of flash sectors
* @adapter: the adapter
* @start: the first sector to erase
* @end: the last sector to erase
*
* Erases the sectors in the given inclusive range.
*/
static int t4_flash_erase_sectors(struct adapter *adapter, int start, int end)
{
int ret = 0;
while (start <= end) {
if ((ret = sf1_write(adapter, 1, 0, 1, SF_WR_ENABLE)) != 0 ||
(ret = sf1_write(adapter, 4, 0, 1,
SF_ERASE_SECTOR | (start << 8))) != 0 ||
(ret = flash_wait_op(adapter, 14, 500)) != 0) {
dev_err(adapter->pdev_dev,
"erase of flash sector %d failed, error %d\n",
start, ret);
break;
}
start++;
}
t4_write_reg(adapter, SF_OP, 0); /* unlock SF */
return ret;
}
/**
* t4_load_fw - download firmware
* @adap: the adapter
* @fw_data: the firmware image to write
* @size: image size
*
* Write the supplied firmware image to the card's serial flash.
*/
int t4_load_fw(struct adapter *adap, const u8 *fw_data, unsigned int size)
{
u32 csum;
int ret, addr;
unsigned int i;
u8 first_page[SF_PAGE_SIZE];
const u32 *p = (const u32 *)fw_data;
const struct fw_hdr *hdr = (const struct fw_hdr *)fw_data;
unsigned int sf_sec_size = adap->params.sf_size / adap->params.sf_nsec;
unsigned int fw_img_start = adap->params.sf_fw_start;
unsigned int fw_start_sec = fw_img_start / sf_sec_size;
if (!size) {
dev_err(adap->pdev_dev, "FW image has no data\n");
return -EINVAL;
}
if (size & 511) {
dev_err(adap->pdev_dev,
"FW image size not multiple of 512 bytes\n");
return -EINVAL;
}
if (ntohs(hdr->len512) * 512 != size) {
dev_err(adap->pdev_dev,
"FW image size differs from size in FW header\n");
return -EINVAL;
}
if (size > FW_MAX_SIZE) {
dev_err(adap->pdev_dev, "FW image too large, max is %u bytes\n",
FW_MAX_SIZE);
return -EFBIG;
}
for (csum = 0, i = 0; i < size / sizeof(csum); i++)
csum += ntohl(p[i]);
if (csum != 0xffffffff) {
dev_err(adap->pdev_dev,
"corrupted firmware image, checksum %#x\n", csum);
return -EINVAL;
}
i = DIV_ROUND_UP(size, sf_sec_size); /* # of sectors spanned */
ret = t4_flash_erase_sectors(adap, fw_start_sec, fw_start_sec + i - 1);
if (ret)
goto out;
/*
* We write the correct version at the end so the driver can see a bad
* version if the FW write fails. Start by writing a copy of the
* first page with a bad version.
*/
memcpy(first_page, fw_data, SF_PAGE_SIZE);
((struct fw_hdr *)first_page)->fw_ver = htonl(0xffffffff);
ret = t4_write_flash(adap, fw_img_start, SF_PAGE_SIZE, first_page);
if (ret)
goto out;
addr = fw_img_start;
for (size -= SF_PAGE_SIZE; size; size -= SF_PAGE_SIZE) {
addr += SF_PAGE_SIZE;
fw_data += SF_PAGE_SIZE;
ret = t4_write_flash(adap, addr, SF_PAGE_SIZE, fw_data);
if (ret)
goto out;
}
ret = t4_write_flash(adap,
fw_img_start + offsetof(struct fw_hdr, fw_ver),
sizeof(hdr->fw_ver), (const u8 *)&hdr->fw_ver);
out:
if (ret)
dev_err(adap->pdev_dev, "firmware download failed, error %d\n",
ret);
return ret;
}
#define ADVERT_MASK (FW_PORT_CAP_SPEED_100M | FW_PORT_CAP_SPEED_1G |\
FW_PORT_CAP_SPEED_10G | FW_PORT_CAP_ANEG)
/**
* t4_link_start - apply link configuration to MAC/PHY
* @phy: the PHY to setup
* @mac: the MAC to setup
* @lc: the requested link configuration
*
* Set up a port's MAC and PHY according to a desired link configuration.
* - If the PHY can auto-negotiate first decide what to advertise, then
* enable/disable auto-negotiation as desired, and reset.
* - If the PHY does not auto-negotiate just reset it.
* - If auto-negotiation is off set the MAC to the proper speed/duplex/FC,
* otherwise do it later based on the outcome of auto-negotiation.
*/
int t4_link_start(struct adapter *adap, unsigned int mbox, unsigned int port,
struct link_config *lc)
{
struct fw_port_cmd c;
unsigned int fc = 0, mdi = FW_PORT_MDI(FW_PORT_MDI_AUTO);
lc->link_ok = 0;
if (lc->requested_fc & PAUSE_RX)
fc |= FW_PORT_CAP_FC_RX;
if (lc->requested_fc & PAUSE_TX)
fc |= FW_PORT_CAP_FC_TX;
memset(&c, 0, sizeof(c));
c.op_to_portid = htonl(FW_CMD_OP(FW_PORT_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_PORT_CMD_PORTID(port));
c.action_to_len16 = htonl(FW_PORT_CMD_ACTION(FW_PORT_ACTION_L1_CFG) |
FW_LEN16(c));
if (!(lc->supported & FW_PORT_CAP_ANEG)) {
c.u.l1cfg.rcap = htonl((lc->supported & ADVERT_MASK) | fc);
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
} else if (lc->autoneg == AUTONEG_DISABLE) {
c.u.l1cfg.rcap = htonl(lc->requested_speed | fc | mdi);
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
} else
c.u.l1cfg.rcap = htonl(lc->advertising | fc | mdi);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_restart_aneg - restart autonegotiation
* @adap: the adapter
* @mbox: mbox to use for the FW command
* @port: the port id
*
* Restarts autonegotiation for the selected port.
*/
int t4_restart_aneg(struct adapter *adap, unsigned int mbox, unsigned int port)
{
struct fw_port_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_portid = htonl(FW_CMD_OP(FW_PORT_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_PORT_CMD_PORTID(port));
c.action_to_len16 = htonl(FW_PORT_CMD_ACTION(FW_PORT_ACTION_L1_CFG) |
FW_LEN16(c));
c.u.l1cfg.rcap = htonl(FW_PORT_CAP_ANEG);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
struct intr_info {
unsigned int mask; /* bits to check in interrupt status */
const char *msg; /* message to print or NULL */
short stat_idx; /* stat counter to increment or -1 */
unsigned short fatal; /* whether the condition reported is fatal */
};
/**
* t4_handle_intr_status - table driven interrupt handler
* @adapter: the adapter that generated the interrupt
* @reg: the interrupt status register to process
* @acts: table of interrupt actions
*
* A table driven interrupt handler that applies a set of masks to an
* interrupt status word and performs the corresponding actions if the
* interrupts described by the mask have occured. The actions include
* optionally emitting a warning or alert message. The table is terminated
* by an entry specifying mask 0. Returns the number of fatal interrupt
* conditions.
*/
static int t4_handle_intr_status(struct adapter *adapter, unsigned int reg,
const struct intr_info *acts)
{
int fatal = 0;
unsigned int mask = 0;
unsigned int status = t4_read_reg(adapter, reg);
for ( ; acts->mask; ++acts) {
if (!(status & acts->mask))
continue;
if (acts->fatal) {
fatal++;
dev_alert(adapter->pdev_dev, "%s (0x%x)\n", acts->msg,
status & acts->mask);
} else if (acts->msg && printk_ratelimit())
dev_warn(adapter->pdev_dev, "%s (0x%x)\n", acts->msg,
status & acts->mask);
mask |= acts->mask;
}
status &= mask;
if (status) /* clear processed interrupts */
t4_write_reg(adapter, reg, status);
return fatal;
}
/*
* Interrupt handler for the PCIE module.
*/
static void pcie_intr_handler(struct adapter *adapter)
{
static struct intr_info sysbus_intr_info[] = {
{ RNPP, "RXNP array parity error", -1, 1 },
{ RPCP, "RXPC array parity error", -1, 1 },
{ RCIP, "RXCIF array parity error", -1, 1 },
{ RCCP, "Rx completions control array parity error", -1, 1 },
{ RFTP, "RXFT array parity error", -1, 1 },
{ 0 }
};
static struct intr_info pcie_port_intr_info[] = {
{ TPCP, "TXPC array parity error", -1, 1 },
{ TNPP, "TXNP array parity error", -1, 1 },
{ TFTP, "TXFT array parity error", -1, 1 },
{ TCAP, "TXCA array parity error", -1, 1 },
{ TCIP, "TXCIF array parity error", -1, 1 },
{ RCAP, "RXCA array parity error", -1, 1 },
{ OTDD, "outbound request TLP discarded", -1, 1 },
{ RDPE, "Rx data parity error", -1, 1 },
{ TDUE, "Tx uncorrectable data error", -1, 1 },
{ 0 }
};
static struct intr_info pcie_intr_info[] = {
{ MSIADDRLPERR, "MSI AddrL parity error", -1, 1 },
{ MSIADDRHPERR, "MSI AddrH parity error", -1, 1 },
{ MSIDATAPERR, "MSI data parity error", -1, 1 },
{ MSIXADDRLPERR, "MSI-X AddrL parity error", -1, 1 },
{ MSIXADDRHPERR, "MSI-X AddrH parity error", -1, 1 },
{ MSIXDATAPERR, "MSI-X data parity error", -1, 1 },
{ MSIXDIPERR, "MSI-X DI parity error", -1, 1 },
{ PIOCPLPERR, "PCI PIO completion FIFO parity error", -1, 1 },
{ PIOREQPERR, "PCI PIO request FIFO parity error", -1, 1 },
{ TARTAGPERR, "PCI PCI target tag FIFO parity error", -1, 1 },
{ CCNTPERR, "PCI CMD channel count parity error", -1, 1 },
{ CREQPERR, "PCI CMD channel request parity error", -1, 1 },
{ CRSPPERR, "PCI CMD channel response parity error", -1, 1 },
{ DCNTPERR, "PCI DMA channel count parity error", -1, 1 },
{ DREQPERR, "PCI DMA channel request parity error", -1, 1 },
{ DRSPPERR, "PCI DMA channel response parity error", -1, 1 },
{ HCNTPERR, "PCI HMA channel count parity error", -1, 1 },
{ HREQPERR, "PCI HMA channel request parity error", -1, 1 },
{ HRSPPERR, "PCI HMA channel response parity error", -1, 1 },
{ CFGSNPPERR, "PCI config snoop FIFO parity error", -1, 1 },
{ FIDPERR, "PCI FID parity error", -1, 1 },
{ INTXCLRPERR, "PCI INTx clear parity error", -1, 1 },
{ MATAGPERR, "PCI MA tag parity error", -1, 1 },
{ PIOTAGPERR, "PCI PIO tag parity error", -1, 1 },
{ RXCPLPERR, "PCI Rx completion parity error", -1, 1 },
{ RXWRPERR, "PCI Rx write parity error", -1, 1 },
{ RPLPERR, "PCI replay buffer parity error", -1, 1 },
{ PCIESINT, "PCI core secondary fault", -1, 1 },
{ PCIEPINT, "PCI core primary fault", -1, 1 },
{ UNXSPLCPLERR, "PCI unexpected split completion error", -1, 0 },
{ 0 }
};
int fat;
fat = t4_handle_intr_status(adapter,
PCIE_CORE_UTL_SYSTEM_BUS_AGENT_STATUS,
sysbus_intr_info) +
t4_handle_intr_status(adapter,
PCIE_CORE_UTL_PCI_EXPRESS_PORT_STATUS,
pcie_port_intr_info) +
t4_handle_intr_status(adapter, PCIE_INT_CAUSE, pcie_intr_info);
if (fat)
t4_fatal_err(adapter);
}
/*
* TP interrupt handler.
*/
static void tp_intr_handler(struct adapter *adapter)
{
static struct intr_info tp_intr_info[] = {
{ 0x3fffffff, "TP parity error", -1, 1 },
{ FLMTXFLSTEMPTY, "TP out of Tx pages", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, TP_INT_CAUSE, tp_intr_info))
t4_fatal_err(adapter);
}
/*
* SGE interrupt handler.
*/
static void sge_intr_handler(struct adapter *adapter)
{
u64 v;
static struct intr_info sge_intr_info[] = {
{ ERR_CPL_EXCEED_IQE_SIZE,
"SGE received CPL exceeding IQE size", -1, 1 },
{ ERR_INVALID_CIDX_INC,
"SGE GTS CIDX increment too large", -1, 0 },
{ ERR_CPL_OPCODE_0, "SGE received 0-length CPL", -1, 0 },
{ ERR_DROPPED_DB, "SGE doorbell dropped", -1, 0 },
{ ERR_DATA_CPL_ON_HIGH_QID1 | ERR_DATA_CPL_ON_HIGH_QID0,
"SGE IQID > 1023 received CPL for FL", -1, 0 },
{ ERR_BAD_DB_PIDX3, "SGE DBP 3 pidx increment too large", -1,
0 },
{ ERR_BAD_DB_PIDX2, "SGE DBP 2 pidx increment too large", -1,
0 },
{ ERR_BAD_DB_PIDX1, "SGE DBP 1 pidx increment too large", -1,
0 },
{ ERR_BAD_DB_PIDX0, "SGE DBP 0 pidx increment too large", -1,
0 },
{ ERR_ING_CTXT_PRIO,
"SGE too many priority ingress contexts", -1, 0 },
{ ERR_EGR_CTXT_PRIO,
"SGE too many priority egress contexts", -1, 0 },
{ INGRESS_SIZE_ERR, "SGE illegal ingress QID", -1, 0 },
{ EGRESS_SIZE_ERR, "SGE illegal egress QID", -1, 0 },
{ 0 }
};
v = (u64)t4_read_reg(adapter, SGE_INT_CAUSE1) |
((u64)t4_read_reg(adapter, SGE_INT_CAUSE2) << 32);
if (v) {
dev_alert(adapter->pdev_dev, "SGE parity error (%#llx)\n",
(unsigned long long)v);
t4_write_reg(adapter, SGE_INT_CAUSE1, v);
t4_write_reg(adapter, SGE_INT_CAUSE2, v >> 32);
}
if (t4_handle_intr_status(adapter, SGE_INT_CAUSE3, sge_intr_info) ||
v != 0)
t4_fatal_err(adapter);
}
/*
* CIM interrupt handler.
*/
static void cim_intr_handler(struct adapter *adapter)
{
static struct intr_info cim_intr_info[] = {
{ PREFDROPINT, "CIM control register prefetch drop", -1, 1 },
{ OBQPARERR, "CIM OBQ parity error", -1, 1 },
{ IBQPARERR, "CIM IBQ parity error", -1, 1 },
{ MBUPPARERR, "CIM mailbox uP parity error", -1, 1 },
{ MBHOSTPARERR, "CIM mailbox host parity error", -1, 1 },
{ TIEQINPARERRINT, "CIM TIEQ outgoing parity error", -1, 1 },
{ TIEQOUTPARERRINT, "CIM TIEQ incoming parity error", -1, 1 },
{ 0 }
};
static struct intr_info cim_upintr_info[] = {
{ RSVDSPACEINT, "CIM reserved space access", -1, 1 },
{ ILLTRANSINT, "CIM illegal transaction", -1, 1 },
{ ILLWRINT, "CIM illegal write", -1, 1 },
{ ILLRDINT, "CIM illegal read", -1, 1 },
{ ILLRDBEINT, "CIM illegal read BE", -1, 1 },
{ ILLWRBEINT, "CIM illegal write BE", -1, 1 },
{ SGLRDBOOTINT, "CIM single read from boot space", -1, 1 },
{ SGLWRBOOTINT, "CIM single write to boot space", -1, 1 },
{ BLKWRBOOTINT, "CIM block write to boot space", -1, 1 },
{ SGLRDFLASHINT, "CIM single read from flash space", -1, 1 },
{ SGLWRFLASHINT, "CIM single write to flash space", -1, 1 },
{ BLKWRFLASHINT, "CIM block write to flash space", -1, 1 },
{ SGLRDEEPROMINT, "CIM single EEPROM read", -1, 1 },
{ SGLWREEPROMINT, "CIM single EEPROM write", -1, 1 },
{ BLKRDEEPROMINT, "CIM block EEPROM read", -1, 1 },
{ BLKWREEPROMINT, "CIM block EEPROM write", -1, 1 },
{ SGLRDCTLINT , "CIM single read from CTL space", -1, 1 },
{ SGLWRCTLINT , "CIM single write to CTL space", -1, 1 },
{ BLKRDCTLINT , "CIM block read from CTL space", -1, 1 },
{ BLKWRCTLINT , "CIM block write to CTL space", -1, 1 },
{ SGLRDPLINT , "CIM single read from PL space", -1, 1 },
{ SGLWRPLINT , "CIM single write to PL space", -1, 1 },
{ BLKRDPLINT , "CIM block read from PL space", -1, 1 },
{ BLKWRPLINT , "CIM block write to PL space", -1, 1 },
{ REQOVRLOOKUPINT , "CIM request FIFO overwrite", -1, 1 },
{ RSPOVRLOOKUPINT , "CIM response FIFO overwrite", -1, 1 },
{ TIMEOUTINT , "CIM PIF timeout", -1, 1 },
{ TIMEOUTMAINT , "CIM PIF MA timeout", -1, 1 },
{ 0 }
};
int fat;
fat = t4_handle_intr_status(adapter, CIM_HOST_INT_CAUSE,
cim_intr_info) +
t4_handle_intr_status(adapter, CIM_HOST_UPACC_INT_CAUSE,
cim_upintr_info);
if (fat)
t4_fatal_err(adapter);
}
/*
* ULP RX interrupt handler.
*/
static void ulprx_intr_handler(struct adapter *adapter)
{
static struct intr_info ulprx_intr_info[] = {
{ 0x1800000, "ULPRX context error", -1, 1 },
{ 0x7fffff, "ULPRX parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, ULP_RX_INT_CAUSE, ulprx_intr_info))
t4_fatal_err(adapter);
}
/*
* ULP TX interrupt handler.
*/
static void ulptx_intr_handler(struct adapter *adapter)
{
static struct intr_info ulptx_intr_info[] = {
{ PBL_BOUND_ERR_CH3, "ULPTX channel 3 PBL out of bounds", -1,
0 },
{ PBL_BOUND_ERR_CH2, "ULPTX channel 2 PBL out of bounds", -1,
0 },
{ PBL_BOUND_ERR_CH1, "ULPTX channel 1 PBL out of bounds", -1,
0 },
{ PBL_BOUND_ERR_CH0, "ULPTX channel 0 PBL out of bounds", -1,
0 },
{ 0xfffffff, "ULPTX parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, ULP_TX_INT_CAUSE, ulptx_intr_info))
t4_fatal_err(adapter);
}
/*
* PM TX interrupt handler.
*/
static void pmtx_intr_handler(struct adapter *adapter)
{
static struct intr_info pmtx_intr_info[] = {
{ PCMD_LEN_OVFL0, "PMTX channel 0 pcmd too large", -1, 1 },
{ PCMD_LEN_OVFL1, "PMTX channel 1 pcmd too large", -1, 1 },
{ PCMD_LEN_OVFL2, "PMTX channel 2 pcmd too large", -1, 1 },
{ ZERO_C_CMD_ERROR, "PMTX 0-length pcmd", -1, 1 },
{ PMTX_FRAMING_ERROR, "PMTX framing error", -1, 1 },
{ OESPI_PAR_ERROR, "PMTX oespi parity error", -1, 1 },
{ DB_OPTIONS_PAR_ERROR, "PMTX db_options parity error", -1, 1 },
{ ICSPI_PAR_ERROR, "PMTX icspi parity error", -1, 1 },
{ C_PCMD_PAR_ERROR, "PMTX c_pcmd parity error", -1, 1},
{ 0 }
};
if (t4_handle_intr_status(adapter, PM_TX_INT_CAUSE, pmtx_intr_info))
t4_fatal_err(adapter);
}
/*
* PM RX interrupt handler.
*/
static void pmrx_intr_handler(struct adapter *adapter)
{
static struct intr_info pmrx_intr_info[] = {
{ ZERO_E_CMD_ERROR, "PMRX 0-length pcmd", -1, 1 },
{ PMRX_FRAMING_ERROR, "PMRX framing error", -1, 1 },
{ OCSPI_PAR_ERROR, "PMRX ocspi parity error", -1, 1 },
{ DB_OPTIONS_PAR_ERROR, "PMRX db_options parity error", -1, 1 },
{ IESPI_PAR_ERROR, "PMRX iespi parity error", -1, 1 },
{ E_PCMD_PAR_ERROR, "PMRX e_pcmd parity error", -1, 1},
{ 0 }
};
if (t4_handle_intr_status(adapter, PM_RX_INT_CAUSE, pmrx_intr_info))
t4_fatal_err(adapter);
}
/*
* CPL switch interrupt handler.
*/
static void cplsw_intr_handler(struct adapter *adapter)
{
static struct intr_info cplsw_intr_info[] = {
{ CIM_OP_MAP_PERR, "CPLSW CIM op_map parity error", -1, 1 },
{ CIM_OVFL_ERROR, "CPLSW CIM overflow", -1, 1 },
{ TP_FRAMING_ERROR, "CPLSW TP framing error", -1, 1 },
{ SGE_FRAMING_ERROR, "CPLSW SGE framing error", -1, 1 },
{ CIM_FRAMING_ERROR, "CPLSW CIM framing error", -1, 1 },
{ ZERO_SWITCH_ERROR, "CPLSW no-switch error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, CPL_INTR_CAUSE, cplsw_intr_info))
t4_fatal_err(adapter);
}
/*
* LE interrupt handler.
*/
static void le_intr_handler(struct adapter *adap)
{
static struct intr_info le_intr_info[] = {
{ LIPMISS, "LE LIP miss", -1, 0 },
{ LIP0, "LE 0 LIP error", -1, 0 },
{ PARITYERR, "LE parity error", -1, 1 },
{ UNKNOWNCMD, "LE unknown command", -1, 1 },
{ REQQPARERR, "LE request queue parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, LE_DB_INT_CAUSE, le_intr_info))
t4_fatal_err(adap);
}
/*
* MPS interrupt handler.
*/
static void mps_intr_handler(struct adapter *adapter)
{
static struct intr_info mps_rx_intr_info[] = {
{ 0xffffff, "MPS Rx parity error", -1, 1 },
{ 0 }
};
static struct intr_info mps_tx_intr_info[] = {
{ TPFIFO, "MPS Tx TP FIFO parity error", -1, 1 },
{ NCSIFIFO, "MPS Tx NC-SI FIFO parity error", -1, 1 },
{ TXDATAFIFO, "MPS Tx data FIFO parity error", -1, 1 },
{ TXDESCFIFO, "MPS Tx desc FIFO parity error", -1, 1 },
{ BUBBLE, "MPS Tx underflow", -1, 1 },
{ SECNTERR, "MPS Tx SOP/EOP error", -1, 1 },
{ FRMERR, "MPS Tx framing error", -1, 1 },
{ 0 }
};
static struct intr_info mps_trc_intr_info[] = {
{ FILTMEM, "MPS TRC filter parity error", -1, 1 },
{ PKTFIFO, "MPS TRC packet FIFO parity error", -1, 1 },
{ MISCPERR, "MPS TRC misc parity error", -1, 1 },
{ 0 }
};
static struct intr_info mps_stat_sram_intr_info[] = {
{ 0x1fffff, "MPS statistics SRAM parity error", -1, 1 },
{ 0 }
};
static struct intr_info mps_stat_tx_intr_info[] = {
{ 0xfffff, "MPS statistics Tx FIFO parity error", -1, 1 },
{ 0 }
};
static struct intr_info mps_stat_rx_intr_info[] = {
{ 0xffffff, "MPS statistics Rx FIFO parity error", -1, 1 },
{ 0 }
};
static struct intr_info mps_cls_intr_info[] = {
{ MATCHSRAM, "MPS match SRAM parity error", -1, 1 },
{ MATCHTCAM, "MPS match TCAM parity error", -1, 1 },
{ HASHSRAM, "MPS hash SRAM parity error", -1, 1 },
{ 0 }
};
int fat;
fat = t4_handle_intr_status(adapter, MPS_RX_PERR_INT_CAUSE,
mps_rx_intr_info) +
t4_handle_intr_status(adapter, MPS_TX_INT_CAUSE,
mps_tx_intr_info) +
t4_handle_intr_status(adapter, MPS_TRC_INT_CAUSE,
mps_trc_intr_info) +
t4_handle_intr_status(adapter, MPS_STAT_PERR_INT_CAUSE_SRAM,
mps_stat_sram_intr_info) +
t4_handle_intr_status(adapter, MPS_STAT_PERR_INT_CAUSE_TX_FIFO,
mps_stat_tx_intr_info) +
t4_handle_intr_status(adapter, MPS_STAT_PERR_INT_CAUSE_RX_FIFO,
mps_stat_rx_intr_info) +
t4_handle_intr_status(adapter, MPS_CLS_INT_CAUSE,
mps_cls_intr_info);
t4_write_reg(adapter, MPS_INT_CAUSE, CLSINT | TRCINT |
RXINT | TXINT | STATINT);
t4_read_reg(adapter, MPS_INT_CAUSE); /* flush */
if (fat)
t4_fatal_err(adapter);
}
#define MEM_INT_MASK (PERR_INT_CAUSE | ECC_CE_INT_CAUSE | ECC_UE_INT_CAUSE)
/*
* EDC/MC interrupt handler.
*/
static void mem_intr_handler(struct adapter *adapter, int idx)
{
static const char name[3][5] = { "EDC0", "EDC1", "MC" };
unsigned int addr, cnt_addr, v;
if (idx <= MEM_EDC1) {
addr = EDC_REG(EDC_INT_CAUSE, idx);
cnt_addr = EDC_REG(EDC_ECC_STATUS, idx);
} else {
addr = MC_INT_CAUSE;
cnt_addr = MC_ECC_STATUS;
}
v = t4_read_reg(adapter, addr) & MEM_INT_MASK;
if (v & PERR_INT_CAUSE)
dev_alert(adapter->pdev_dev, "%s FIFO parity error\n",
name[idx]);
if (v & ECC_CE_INT_CAUSE) {
u32 cnt = ECC_CECNT_GET(t4_read_reg(adapter, cnt_addr));
t4_write_reg(adapter, cnt_addr, ECC_CECNT_MASK);
if (printk_ratelimit())
dev_warn(adapter->pdev_dev,
"%u %s correctable ECC data error%s\n",
cnt, name[idx], cnt > 1 ? "s" : "");
}
if (v & ECC_UE_INT_CAUSE)
dev_alert(adapter->pdev_dev,
"%s uncorrectable ECC data error\n", name[idx]);
t4_write_reg(adapter, addr, v);
if (v & (PERR_INT_CAUSE | ECC_UE_INT_CAUSE))
t4_fatal_err(adapter);
}
/*
* MA interrupt handler.
*/
static void ma_intr_handler(struct adapter *adap)
{
u32 v, status = t4_read_reg(adap, MA_INT_CAUSE);
if (status & MEM_PERR_INT_CAUSE)
dev_alert(adap->pdev_dev,
"MA parity error, parity status %#x\n",
t4_read_reg(adap, MA_PARITY_ERROR_STATUS));
if (status & MEM_WRAP_INT_CAUSE) {
v = t4_read_reg(adap, MA_INT_WRAP_STATUS);
dev_alert(adap->pdev_dev, "MA address wrap-around error by "
"client %u to address %#x\n",
MEM_WRAP_CLIENT_NUM_GET(v),
MEM_WRAP_ADDRESS_GET(v) << 4);
}
t4_write_reg(adap, MA_INT_CAUSE, status);
t4_fatal_err(adap);
}
/*
* SMB interrupt handler.
*/
static void smb_intr_handler(struct adapter *adap)
{
static struct intr_info smb_intr_info[] = {
{ MSTTXFIFOPARINT, "SMB master Tx FIFO parity error", -1, 1 },
{ MSTRXFIFOPARINT, "SMB master Rx FIFO parity error", -1, 1 },
{ SLVFIFOPARINT, "SMB slave FIFO parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, SMB_INT_CAUSE, smb_intr_info))
t4_fatal_err(adap);
}
/*
* NC-SI interrupt handler.
*/
static void ncsi_intr_handler(struct adapter *adap)
{
static struct intr_info ncsi_intr_info[] = {
{ CIM_DM_PRTY_ERR, "NC-SI CIM parity error", -1, 1 },
{ MPS_DM_PRTY_ERR, "NC-SI MPS parity error", -1, 1 },
{ TXFIFO_PRTY_ERR, "NC-SI Tx FIFO parity error", -1, 1 },
{ RXFIFO_PRTY_ERR, "NC-SI Rx FIFO parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, NCSI_INT_CAUSE, ncsi_intr_info))
t4_fatal_err(adap);
}
/*
* XGMAC interrupt handler.
*/
static void xgmac_intr_handler(struct adapter *adap, int port)
{
u32 v = t4_read_reg(adap, PORT_REG(port, XGMAC_PORT_INT_CAUSE));
v &= TXFIFO_PRTY_ERR | RXFIFO_PRTY_ERR;
if (!v)
return;
if (v & TXFIFO_PRTY_ERR)
dev_alert(adap->pdev_dev, "XGMAC %d Tx FIFO parity error\n",
port);
if (v & RXFIFO_PRTY_ERR)
dev_alert(adap->pdev_dev, "XGMAC %d Rx FIFO parity error\n",
port);
t4_write_reg(adap, PORT_REG(port, XGMAC_PORT_INT_CAUSE), v);
t4_fatal_err(adap);
}
/*
* PL interrupt handler.
*/
static void pl_intr_handler(struct adapter *adap)
{
static struct intr_info pl_intr_info[] = {
{ FATALPERR, "T4 fatal parity error", -1, 1 },
{ PERRVFID, "PL VFID_MAP parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, PL_PL_INT_CAUSE, pl_intr_info))
t4_fatal_err(adap);
}
#define PF_INTR_MASK (PFSW)
#define GLBL_INTR_MASK (CIM | MPS | PL | PCIE | MC | EDC0 | \
EDC1 | LE | TP | MA | PM_TX | PM_RX | ULP_RX | \
CPL_SWITCH | SGE | ULP_TX)
/**
* t4_slow_intr_handler - control path interrupt handler
* @adapter: the adapter
*
* T4 interrupt handler for non-data global interrupt events, e.g., errors.
* The designation 'slow' is because it involves register reads, while
* data interrupts typically don't involve any MMIOs.
*/
int t4_slow_intr_handler(struct adapter *adapter)
{
u32 cause = t4_read_reg(adapter, PL_INT_CAUSE);
if (!(cause & GLBL_INTR_MASK))
return 0;
if (cause & CIM)
cim_intr_handler(adapter);
if (cause & MPS)
mps_intr_handler(adapter);
if (cause & NCSI)
ncsi_intr_handler(adapter);
if (cause & PL)
pl_intr_handler(adapter);
if (cause & SMB)
smb_intr_handler(adapter);
if (cause & XGMAC0)
xgmac_intr_handler(adapter, 0);
if (cause & XGMAC1)
xgmac_intr_handler(adapter, 1);
if (cause & XGMAC_KR0)
xgmac_intr_handler(adapter, 2);
if (cause & XGMAC_KR1)
xgmac_intr_handler(adapter, 3);
if (cause & PCIE)
pcie_intr_handler(adapter);
if (cause & MC)
mem_intr_handler(adapter, MEM_MC);
if (cause & EDC0)
mem_intr_handler(adapter, MEM_EDC0);
if (cause & EDC1)
mem_intr_handler(adapter, MEM_EDC1);
if (cause & LE)
le_intr_handler(adapter);
if (cause & TP)
tp_intr_handler(adapter);
if (cause & MA)
ma_intr_handler(adapter);
if (cause & PM_TX)
pmtx_intr_handler(adapter);
if (cause & PM_RX)
pmrx_intr_handler(adapter);
if (cause & ULP_RX)
ulprx_intr_handler(adapter);
if (cause & CPL_SWITCH)
cplsw_intr_handler(adapter);
if (cause & SGE)
sge_intr_handler(adapter);
if (cause & ULP_TX)
ulptx_intr_handler(adapter);
/* Clear the interrupts just processed for which we are the master. */
t4_write_reg(adapter, PL_INT_CAUSE, cause & GLBL_INTR_MASK);
(void) t4_read_reg(adapter, PL_INT_CAUSE); /* flush */
return 1;
}
/**
* t4_intr_enable - enable interrupts
* @adapter: the adapter whose interrupts should be enabled
*
* Enable PF-specific interrupts for the calling function and the top-level
* interrupt concentrator for global interrupts. Interrupts are already
* enabled at each module, here we just enable the roots of the interrupt
* hierarchies.
*
* Note: this function should be called only when the driver manages
* non PF-specific interrupts from the various HW modules. Only one PCI
* function at a time should be doing this.
*/
void t4_intr_enable(struct adapter *adapter)
{
u32 pf = SOURCEPF_GET(t4_read_reg(adapter, PL_WHOAMI));
t4_write_reg(adapter, SGE_INT_ENABLE3, ERR_CPL_EXCEED_IQE_SIZE |
ERR_INVALID_CIDX_INC | ERR_CPL_OPCODE_0 |
ERR_DROPPED_DB | ERR_DATA_CPL_ON_HIGH_QID1 |
ERR_DATA_CPL_ON_HIGH_QID0 | ERR_BAD_DB_PIDX3 |
ERR_BAD_DB_PIDX2 | ERR_BAD_DB_PIDX1 |
ERR_BAD_DB_PIDX0 | ERR_ING_CTXT_PRIO |
ERR_EGR_CTXT_PRIO | INGRESS_SIZE_ERR |
EGRESS_SIZE_ERR);
t4_write_reg(adapter, MYPF_REG(PL_PF_INT_ENABLE), PF_INTR_MASK);
t4_set_reg_field(adapter, PL_INT_MAP0, 0, 1 << pf);
}
/**
* t4_intr_disable - disable interrupts
* @adapter: the adapter whose interrupts should be disabled
*
* Disable interrupts. We only disable the top-level interrupt
* concentrators. The caller must be a PCI function managing global
* interrupts.
*/
void t4_intr_disable(struct adapter *adapter)
{
u32 pf = SOURCEPF_GET(t4_read_reg(adapter, PL_WHOAMI));
t4_write_reg(adapter, MYPF_REG(PL_PF_INT_ENABLE), 0);
t4_set_reg_field(adapter, PL_INT_MAP0, 1 << pf, 0);
}
/**
* hash_mac_addr - return the hash value of a MAC address
* @addr: the 48-bit Ethernet MAC address
*
* Hashes a MAC address according to the hash function used by HW inexact
* (hash) address matching.
*/
static int hash_mac_addr(const u8 *addr)
{
u32 a = ((u32)addr[0] << 16) | ((u32)addr[1] << 8) | addr[2];
u32 b = ((u32)addr[3] << 16) | ((u32)addr[4] << 8) | addr[5];
a ^= b;
a ^= (a >> 12);
a ^= (a >> 6);
return a & 0x3f;
}
/**
* t4_config_rss_range - configure a portion of the RSS mapping table
* @adapter: the adapter
* @mbox: mbox to use for the FW command
* @viid: virtual interface whose RSS subtable is to be written
* @start: start entry in the table to write
* @n: how many table entries to write
* @rspq: values for the response queue lookup table
* @nrspq: number of values in @rspq
*
* Programs the selected part of the VI's RSS mapping table with the
* provided values. If @nrspq < @n the supplied values are used repeatedly
* until the full table range is populated.
*
* The caller must ensure the values in @rspq are in the range allowed for
* @viid.
*/
int t4_config_rss_range(struct adapter *adapter, int mbox, unsigned int viid,
int start, int n, const u16 *rspq, unsigned int nrspq)
{
int ret;
const u16 *rsp = rspq;
const u16 *rsp_end = rspq + nrspq;
struct fw_rss_ind_tbl_cmd cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_viid = htonl(FW_CMD_OP(FW_RSS_IND_TBL_CMD) |
FW_CMD_REQUEST | FW_CMD_WRITE |
FW_RSS_IND_TBL_CMD_VIID(viid));
cmd.retval_len16 = htonl(FW_LEN16(cmd));
/* each fw_rss_ind_tbl_cmd takes up to 32 entries */
while (n > 0) {
int nq = min(n, 32);
__be32 *qp = &cmd.iq0_to_iq2;
cmd.niqid = htons(nq);
cmd.startidx = htons(start);
start += nq;
n -= nq;
while (nq > 0) {
unsigned int v;
v = FW_RSS_IND_TBL_CMD_IQ0(*rsp);
if (++rsp >= rsp_end)
rsp = rspq;
v |= FW_RSS_IND_TBL_CMD_IQ1(*rsp);
if (++rsp >= rsp_end)
rsp = rspq;
v |= FW_RSS_IND_TBL_CMD_IQ2(*rsp);
if (++rsp >= rsp_end)
rsp = rspq;
*qp++ = htonl(v);
nq -= 3;
}
ret = t4_wr_mbox(adapter, mbox, &cmd, sizeof(cmd), NULL);
if (ret)
return ret;
}
return 0;
}
/**
* t4_config_glbl_rss - configure the global RSS mode
* @adapter: the adapter
* @mbox: mbox to use for the FW command
* @mode: global RSS mode
* @flags: mode-specific flags
*
* Sets the global RSS mode.
*/
int t4_config_glbl_rss(struct adapter *adapter, int mbox, unsigned int mode,
unsigned int flags)
{
struct fw_rss_glb_config_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_write = htonl(FW_CMD_OP(FW_RSS_GLB_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_WRITE);
c.retval_len16 = htonl(FW_LEN16(c));
if (mode == FW_RSS_GLB_CONFIG_CMD_MODE_MANUAL) {
c.u.manual.mode_pkd = htonl(FW_RSS_GLB_CONFIG_CMD_MODE(mode));
} else if (mode == FW_RSS_GLB_CONFIG_CMD_MODE_BASICVIRTUAL) {
c.u.basicvirtual.mode_pkd =
htonl(FW_RSS_GLB_CONFIG_CMD_MODE(mode));
c.u.basicvirtual.synmapen_to_hashtoeplitz = htonl(flags);
} else
return -EINVAL;
return t4_wr_mbox(adapter, mbox, &c, sizeof(c), NULL);
}
/**
* t4_tp_get_tcp_stats - read TP's TCP MIB counters
* @adap: the adapter
* @v4: holds the TCP/IP counter values
* @v6: holds the TCP/IPv6 counter values
*
* Returns the values of TP's TCP/IP and TCP/IPv6 MIB counters.
* Either @v4 or @v6 may be %NULL to skip the corresponding stats.
*/
void t4_tp_get_tcp_stats(struct adapter *adap, struct tp_tcp_stats *v4,
struct tp_tcp_stats *v6)
{
u32 val[TP_MIB_TCP_RXT_SEG_LO - TP_MIB_TCP_OUT_RST + 1];
#define STAT_IDX(x) ((TP_MIB_TCP_##x) - TP_MIB_TCP_OUT_RST)
#define STAT(x) val[STAT_IDX(x)]
#define STAT64(x) (((u64)STAT(x##_HI) << 32) | STAT(x##_LO))
if (v4) {
t4_read_indirect(adap, TP_MIB_INDEX, TP_MIB_DATA, val,
ARRAY_SIZE(val), TP_MIB_TCP_OUT_RST);
v4->tcpOutRsts = STAT(OUT_RST);
v4->tcpInSegs = STAT64(IN_SEG);
v4->tcpOutSegs = STAT64(OUT_SEG);
v4->tcpRetransSegs = STAT64(RXT_SEG);
}
if (v6) {
t4_read_indirect(adap, TP_MIB_INDEX, TP_MIB_DATA, val,
ARRAY_SIZE(val), TP_MIB_TCP_V6OUT_RST);
v6->tcpOutRsts = STAT(OUT_RST);
v6->tcpInSegs = STAT64(IN_SEG);
v6->tcpOutSegs = STAT64(OUT_SEG);
v6->tcpRetransSegs = STAT64(RXT_SEG);
}
#undef STAT64
#undef STAT
#undef STAT_IDX
}
/**
* t4_read_mtu_tbl - returns the values in the HW path MTU table
* @adap: the adapter
* @mtus: where to store the MTU values
* @mtu_log: where to store the MTU base-2 log (may be %NULL)
*
* Reads the HW path MTU table.
*/
void t4_read_mtu_tbl(struct adapter *adap, u16 *mtus, u8 *mtu_log)
{
u32 v;
int i;
for (i = 0; i < NMTUS; ++i) {
t4_write_reg(adap, TP_MTU_TABLE,
MTUINDEX(0xff) | MTUVALUE(i));
v = t4_read_reg(adap, TP_MTU_TABLE);
mtus[i] = MTUVALUE_GET(v);
if (mtu_log)
mtu_log[i] = MTUWIDTH_GET(v);
}
}
/**
* init_cong_ctrl - initialize congestion control parameters
* @a: the alpha values for congestion control
* @b: the beta values for congestion control
*
* Initialize the congestion control parameters.
*/
static void __devinit init_cong_ctrl(unsigned short *a, unsigned short *b)
{
a[0] = a[1] = a[2] = a[3] = a[4] = a[5] = a[6] = a[7] = a[8] = 1;
a[9] = 2;
a[10] = 3;
a[11] = 4;
a[12] = 5;
a[13] = 6;
a[14] = 7;
a[15] = 8;
a[16] = 9;
a[17] = 10;
a[18] = 14;
a[19] = 17;
a[20] = 21;
a[21] = 25;
a[22] = 30;
a[23] = 35;
a[24] = 45;
a[25] = 60;
a[26] = 80;
a[27] = 100;
a[28] = 200;
a[29] = 300;
a[30] = 400;
a[31] = 500;
b[0] = b[1] = b[2] = b[3] = b[4] = b[5] = b[6] = b[7] = b[8] = 0;
b[9] = b[10] = 1;
b[11] = b[12] = 2;
b[13] = b[14] = b[15] = b[16] = 3;
b[17] = b[18] = b[19] = b[20] = b[21] = 4;
b[22] = b[23] = b[24] = b[25] = b[26] = b[27] = 5;
b[28] = b[29] = 6;
b[30] = b[31] = 7;
}
/* The minimum additive increment value for the congestion control table */
#define CC_MIN_INCR 2U
/**
* t4_load_mtus - write the MTU and congestion control HW tables
* @adap: the adapter
* @mtus: the values for the MTU table
* @alpha: the values for the congestion control alpha parameter
* @beta: the values for the congestion control beta parameter
*
* Write the HW MTU table with the supplied MTUs and the high-speed
* congestion control table with the supplied alpha, beta, and MTUs.
* We write the two tables together because the additive increments
* depend on the MTUs.
*/
void t4_load_mtus(struct adapter *adap, const unsigned short *mtus,
const unsigned short *alpha, const unsigned short *beta)
{
static const unsigned int avg_pkts[NCCTRL_WIN] = {
2, 6, 10, 14, 20, 28, 40, 56, 80, 112, 160, 224, 320, 448, 640,
896, 1281, 1792, 2560, 3584, 5120, 7168, 10240, 14336, 20480,
28672, 40960, 57344, 81920, 114688, 163840, 229376
};
unsigned int i, w;
for (i = 0; i < NMTUS; ++i) {
unsigned int mtu = mtus[i];
unsigned int log2 = fls(mtu);
if (!(mtu & ((1 << log2) >> 2))) /* round */
log2--;
t4_write_reg(adap, TP_MTU_TABLE, MTUINDEX(i) |
MTUWIDTH(log2) | MTUVALUE(mtu));
for (w = 0; w < NCCTRL_WIN; ++w) {
unsigned int inc;
inc = max(((mtu - 40) * alpha[w]) / avg_pkts[w],
CC_MIN_INCR);
t4_write_reg(adap, TP_CCTRL_TABLE, (i << 21) |
(w << 16) | (beta[w] << 13) | inc);
}
}
}
/**
* get_mps_bg_map - return the buffer groups associated with a port
* @adap: the adapter
* @idx: the port index
*
* Returns a bitmap indicating which MPS buffer groups are associated
* with the given port. Bit i is set if buffer group i is used by the
* port.
*/
static unsigned int get_mps_bg_map(struct adapter *adap, int idx)
{
u32 n = NUMPORTS_GET(t4_read_reg(adap, MPS_CMN_CTL));
if (n == 0)
return idx == 0 ? 0xf : 0;
if (n == 1)
return idx < 2 ? (3 << (2 * idx)) : 0;
return 1 << idx;
}
/**
* t4_get_port_stats - collect port statistics
* @adap: the adapter
* @idx: the port index
* @p: the stats structure to fill
*
* Collect statistics related to the given port from HW.
*/
void t4_get_port_stats(struct adapter *adap, int idx, struct port_stats *p)
{
u32 bgmap = get_mps_bg_map(adap, idx);
#define GET_STAT(name) \
t4_read_reg64(adap, PORT_REG(idx, MPS_PORT_STAT_##name##_L))
#define GET_STAT_COM(name) t4_read_reg64(adap, MPS_STAT_##name##_L)
p->tx_octets = GET_STAT(TX_PORT_BYTES);
p->tx_frames = GET_STAT(TX_PORT_FRAMES);
p->tx_bcast_frames = GET_STAT(TX_PORT_BCAST);
p->tx_mcast_frames = GET_STAT(TX_PORT_MCAST);
p->tx_ucast_frames = GET_STAT(TX_PORT_UCAST);
p->tx_error_frames = GET_STAT(TX_PORT_ERROR);
p->tx_frames_64 = GET_STAT(TX_PORT_64B);
p->tx_frames_65_127 = GET_STAT(TX_PORT_65B_127B);
p->tx_frames_128_255 = GET_STAT(TX_PORT_128B_255B);
p->tx_frames_256_511 = GET_STAT(TX_PORT_256B_511B);
p->tx_frames_512_1023 = GET_STAT(TX_PORT_512B_1023B);
p->tx_frames_1024_1518 = GET_STAT(TX_PORT_1024B_1518B);
p->tx_frames_1519_max = GET_STAT(TX_PORT_1519B_MAX);
p->tx_drop = GET_STAT(TX_PORT_DROP);
p->tx_pause = GET_STAT(TX_PORT_PAUSE);
p->tx_ppp0 = GET_STAT(TX_PORT_PPP0);
p->tx_ppp1 = GET_STAT(TX_PORT_PPP1);
p->tx_ppp2 = GET_STAT(TX_PORT_PPP2);
p->tx_ppp3 = GET_STAT(TX_PORT_PPP3);
p->tx_ppp4 = GET_STAT(TX_PORT_PPP4);
p->tx_ppp5 = GET_STAT(TX_PORT_PPP5);
p->tx_ppp6 = GET_STAT(TX_PORT_PPP6);
p->tx_ppp7 = GET_STAT(TX_PORT_PPP7);
p->rx_octets = GET_STAT(RX_PORT_BYTES);
p->rx_frames = GET_STAT(RX_PORT_FRAMES);
p->rx_bcast_frames = GET_STAT(RX_PORT_BCAST);
p->rx_mcast_frames = GET_STAT(RX_PORT_MCAST);
p->rx_ucast_frames = GET_STAT(RX_PORT_UCAST);
p->rx_too_long = GET_STAT(RX_PORT_MTU_ERROR);
p->rx_jabber = GET_STAT(RX_PORT_MTU_CRC_ERROR);
p->rx_fcs_err = GET_STAT(RX_PORT_CRC_ERROR);
p->rx_len_err = GET_STAT(RX_PORT_LEN_ERROR);
p->rx_symbol_err = GET_STAT(RX_PORT_SYM_ERROR);
p->rx_runt = GET_STAT(RX_PORT_LESS_64B);
p->rx_frames_64 = GET_STAT(RX_PORT_64B);
p->rx_frames_65_127 = GET_STAT(RX_PORT_65B_127B);
p->rx_frames_128_255 = GET_STAT(RX_PORT_128B_255B);
p->rx_frames_256_511 = GET_STAT(RX_PORT_256B_511B);
p->rx_frames_512_1023 = GET_STAT(RX_PORT_512B_1023B);
p->rx_frames_1024_1518 = GET_STAT(RX_PORT_1024B_1518B);
p->rx_frames_1519_max = GET_STAT(RX_PORT_1519B_MAX);
p->rx_pause = GET_STAT(RX_PORT_PAUSE);
p->rx_ppp0 = GET_STAT(RX_PORT_PPP0);
p->rx_ppp1 = GET_STAT(RX_PORT_PPP1);
p->rx_ppp2 = GET_STAT(RX_PORT_PPP2);
p->rx_ppp3 = GET_STAT(RX_PORT_PPP3);
p->rx_ppp4 = GET_STAT(RX_PORT_PPP4);
p->rx_ppp5 = GET_STAT(RX_PORT_PPP5);
p->rx_ppp6 = GET_STAT(RX_PORT_PPP6);
p->rx_ppp7 = GET_STAT(RX_PORT_PPP7);
p->rx_ovflow0 = (bgmap & 1) ? GET_STAT_COM(RX_BG_0_MAC_DROP_FRAME) : 0;
p->rx_ovflow1 = (bgmap & 2) ? GET_STAT_COM(RX_BG_1_MAC_DROP_FRAME) : 0;
p->rx_ovflow2 = (bgmap & 4) ? GET_STAT_COM(RX_BG_2_MAC_DROP_FRAME) : 0;
p->rx_ovflow3 = (bgmap & 8) ? GET_STAT_COM(RX_BG_3_MAC_DROP_FRAME) : 0;
p->rx_trunc0 = (bgmap & 1) ? GET_STAT_COM(RX_BG_0_MAC_TRUNC_FRAME) : 0;
p->rx_trunc1 = (bgmap & 2) ? GET_STAT_COM(RX_BG_1_MAC_TRUNC_FRAME) : 0;
p->rx_trunc2 = (bgmap & 4) ? GET_STAT_COM(RX_BG_2_MAC_TRUNC_FRAME) : 0;
p->rx_trunc3 = (bgmap & 8) ? GET_STAT_COM(RX_BG_3_MAC_TRUNC_FRAME) : 0;
#undef GET_STAT
#undef GET_STAT_COM
}
/**
* t4_wol_magic_enable - enable/disable magic packet WoL
* @adap: the adapter
* @port: the physical port index
* @addr: MAC address expected in magic packets, %NULL to disable
*
* Enables/disables magic packet wake-on-LAN for the selected port.
*/
void t4_wol_magic_enable(struct adapter *adap, unsigned int port,
const u8 *addr)
{
if (addr) {
t4_write_reg(adap, PORT_REG(port, XGMAC_PORT_MAGIC_MACID_LO),
(addr[2] << 24) | (addr[3] << 16) |
(addr[4] << 8) | addr[5]);
t4_write_reg(adap, PORT_REG(port, XGMAC_PORT_MAGIC_MACID_HI),
(addr[0] << 8) | addr[1]);
}
t4_set_reg_field(adap, PORT_REG(port, XGMAC_PORT_CFG2), MAGICEN,
addr ? MAGICEN : 0);
}
/**
* t4_wol_pat_enable - enable/disable pattern-based WoL
* @adap: the adapter
* @port: the physical port index
* @map: bitmap of which HW pattern filters to set
* @mask0: byte mask for bytes 0-63 of a packet
* @mask1: byte mask for bytes 64-127 of a packet
* @crc: Ethernet CRC for selected bytes
* @enable: enable/disable switch
*
* Sets the pattern filters indicated in @map to mask out the bytes
* specified in @mask0/@mask1 in received packets and compare the CRC of
* the resulting packet against @crc. If @enable is %true pattern-based
* WoL is enabled, otherwise disabled.
*/
int t4_wol_pat_enable(struct adapter *adap, unsigned int port, unsigned int map,
u64 mask0, u64 mask1, unsigned int crc, bool enable)
{
int i;
if (!enable) {
t4_set_reg_field(adap, PORT_REG(port, XGMAC_PORT_CFG2),
PATEN, 0);
return 0;
}
if (map > 0xff)
return -EINVAL;
#define EPIO_REG(name) PORT_REG(port, XGMAC_PORT_EPIO_##name)
t4_write_reg(adap, EPIO_REG(DATA1), mask0 >> 32);
t4_write_reg(adap, EPIO_REG(DATA2), mask1);
t4_write_reg(adap, EPIO_REG(DATA3), mask1 >> 32);
for (i = 0; i < NWOL_PAT; i++, map >>= 1) {
if (!(map & 1))
continue;
/* write byte masks */
t4_write_reg(adap, EPIO_REG(DATA0), mask0);
t4_write_reg(adap, EPIO_REG(OP), ADDRESS(i) | EPIOWR);
t4_read_reg(adap, EPIO_REG(OP)); /* flush */
if (t4_read_reg(adap, EPIO_REG(OP)) & BUSY)
return -ETIMEDOUT;
/* write CRC */
t4_write_reg(adap, EPIO_REG(DATA0), crc);
t4_write_reg(adap, EPIO_REG(OP), ADDRESS(i + 32) | EPIOWR);
t4_read_reg(adap, EPIO_REG(OP)); /* flush */
if (t4_read_reg(adap, EPIO_REG(OP)) & BUSY)
return -ETIMEDOUT;
}
#undef EPIO_REG
t4_set_reg_field(adap, PORT_REG(port, XGMAC_PORT_CFG2), 0, PATEN);
return 0;
}
#define INIT_CMD(var, cmd, rd_wr) do { \
(var).op_to_write = htonl(FW_CMD_OP(FW_##cmd##_CMD) | \
FW_CMD_REQUEST | FW_CMD_##rd_wr); \
(var).retval_len16 = htonl(FW_LEN16(var)); \
} while (0)
/**
* t4_mdio_rd - read a PHY register through MDIO
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @phy_addr: the PHY address
* @mmd: the PHY MMD to access (0 for clause 22 PHYs)
* @reg: the register to read
* @valp: where to store the value
*
* Issues a FW command through the given mailbox to read a PHY register.
*/
int t4_mdio_rd(struct adapter *adap, unsigned int mbox, unsigned int phy_addr,
unsigned int mmd, unsigned int reg, u16 *valp)
{
int ret;
struct fw_ldst_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_addrspace = htonl(FW_CMD_OP(FW_LDST_CMD) | FW_CMD_REQUEST |
FW_CMD_READ | FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MDIO));
c.cycles_to_len16 = htonl(FW_LEN16(c));
c.u.mdio.paddr_mmd = htons(FW_LDST_CMD_PADDR(phy_addr) |
FW_LDST_CMD_MMD(mmd));
c.u.mdio.raddr = htons(reg);
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0)
*valp = ntohs(c.u.mdio.rval);
return ret;
}
/**
* t4_mdio_wr - write a PHY register through MDIO
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @phy_addr: the PHY address
* @mmd: the PHY MMD to access (0 for clause 22 PHYs)
* @reg: the register to write
* @valp: value to write
*
* Issues a FW command through the given mailbox to write a PHY register.
*/
int t4_mdio_wr(struct adapter *adap, unsigned int mbox, unsigned int phy_addr,
unsigned int mmd, unsigned int reg, u16 val)
{
struct fw_ldst_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_addrspace = htonl(FW_CMD_OP(FW_LDST_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MDIO));
c.cycles_to_len16 = htonl(FW_LEN16(c));
c.u.mdio.paddr_mmd = htons(FW_LDST_CMD_PADDR(phy_addr) |
FW_LDST_CMD_MMD(mmd));
c.u.mdio.raddr = htons(reg);
c.u.mdio.rval = htons(val);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_fw_hello - establish communication with FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @evt_mbox: mailbox to receive async FW events
* @master: specifies the caller's willingness to be the device master
* @state: returns the current device state
*
* Issues a command to establish communication with FW.
*/
int t4_fw_hello(struct adapter *adap, unsigned int mbox, unsigned int evt_mbox,
enum dev_master master, enum dev_state *state)
{
int ret;
struct fw_hello_cmd c;
INIT_CMD(c, HELLO, WRITE);
c.err_to_mbasyncnot = htonl(
FW_HELLO_CMD_MASTERDIS(master == MASTER_CANT) |
FW_HELLO_CMD_MASTERFORCE(master == MASTER_MUST) |
FW_HELLO_CMD_MBMASTER(master == MASTER_MUST ? mbox : 0xff) |
FW_HELLO_CMD_MBASYNCNOT(evt_mbox));
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0 && state) {
u32 v = ntohl(c.err_to_mbasyncnot);
if (v & FW_HELLO_CMD_INIT)
*state = DEV_STATE_INIT;
else if (v & FW_HELLO_CMD_ERR)
*state = DEV_STATE_ERR;
else
*state = DEV_STATE_UNINIT;
}
return ret;
}
/**
* t4_fw_bye - end communication with FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
*
* Issues a command to terminate communication with FW.
*/
int t4_fw_bye(struct adapter *adap, unsigned int mbox)
{
struct fw_bye_cmd c;
INIT_CMD(c, BYE, WRITE);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_init_cmd - ask FW to initialize the device
* @adap: the adapter
* @mbox: mailbox to use for the FW command
*
* Issues a command to FW to partially initialize the device. This
* performs initialization that generally doesn't depend on user input.
*/
int t4_early_init(struct adapter *adap, unsigned int mbox)
{
struct fw_initialize_cmd c;
INIT_CMD(c, INITIALIZE, WRITE);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_fw_reset - issue a reset to FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @reset: specifies the type of reset to perform
*
* Issues a reset command of the specified type to FW.
*/
int t4_fw_reset(struct adapter *adap, unsigned int mbox, int reset)
{
struct fw_reset_cmd c;
INIT_CMD(c, RESET, WRITE);
c.val = htonl(reset);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_query_params - query FW or device parameters
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF
* @vf: the VF
* @nparams: the number of parameters
* @params: the parameter names
* @val: the parameter values
*
* Reads the value of FW or device parameters. Up to 7 parameters can be
* queried at once.
*/
int t4_query_params(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int nparams, const u32 *params,
u32 *val)
{
int i, ret;
struct fw_params_cmd c;
__be32 *p = &c.param[0].mnem;
if (nparams > 7)
return -EINVAL;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_PARAMS_CMD) | FW_CMD_REQUEST |
FW_CMD_READ | FW_PARAMS_CMD_PFN(pf) |
FW_PARAMS_CMD_VFN(vf));
c.retval_len16 = htonl(FW_LEN16(c));
for (i = 0; i < nparams; i++, p += 2)
*p = htonl(*params++);
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0)
for (i = 0, p = &c.param[0].val; i < nparams; i++, p += 2)
*val++ = ntohl(*p);
return ret;
}
/**
* t4_set_params - sets FW or device parameters
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF
* @vf: the VF
* @nparams: the number of parameters
* @params: the parameter names
* @val: the parameter values
*
* Sets the value of FW or device parameters. Up to 7 parameters can be
* specified at once.
*/
int t4_set_params(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int nparams, const u32 *params,
const u32 *val)
{
struct fw_params_cmd c;
__be32 *p = &c.param[0].mnem;
if (nparams > 7)
return -EINVAL;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_PARAMS_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_PARAMS_CMD_PFN(pf) |
FW_PARAMS_CMD_VFN(vf));
c.retval_len16 = htonl(FW_LEN16(c));
while (nparams--) {
*p++ = htonl(*params++);
*p++ = htonl(*val++);
}
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_cfg_pfvf - configure PF/VF resource limits
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF being configured
* @vf: the VF being configured
* @txq: the max number of egress queues
* @txq_eth_ctrl: the max number of egress Ethernet or control queues
* @rxqi: the max number of interrupt-capable ingress queues
* @rxq: the max number of interruptless ingress queues
* @tc: the PCI traffic class
* @vi: the max number of virtual interfaces
* @cmask: the channel access rights mask for the PF/VF
* @pmask: the port access rights mask for the PF/VF
* @nexact: the maximum number of exact MPS filters
* @rcaps: read capabilities
* @wxcaps: write/execute capabilities
*
* Configures resource limits and capabilities for a physical or virtual
* function.
*/
int t4_cfg_pfvf(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int txq, unsigned int txq_eth_ctrl,
unsigned int rxqi, unsigned int rxq, unsigned int tc,
unsigned int vi, unsigned int cmask, unsigned int pmask,
unsigned int nexact, unsigned int rcaps, unsigned int wxcaps)
{
struct fw_pfvf_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_PFVF_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_PFVF_CMD_PFN(pf) |
FW_PFVF_CMD_VFN(vf));
c.retval_len16 = htonl(FW_LEN16(c));
c.niqflint_niq = htonl(FW_PFVF_CMD_NIQFLINT(rxqi) |
FW_PFVF_CMD_NIQ(rxq));
c.type_to_neq = htonl(FW_PFVF_CMD_CMASK(cmask) |
FW_PFVF_CMD_PMASK(pmask) |
FW_PFVF_CMD_NEQ(txq));
c.tc_to_nexactf = htonl(FW_PFVF_CMD_TC(tc) | FW_PFVF_CMD_NVI(vi) |
FW_PFVF_CMD_NEXACTF(nexact));
c.r_caps_to_nethctrl = htonl(FW_PFVF_CMD_R_CAPS(rcaps) |
FW_PFVF_CMD_WX_CAPS(wxcaps) |
FW_PFVF_CMD_NETHCTRL(txq_eth_ctrl));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_alloc_vi - allocate a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @port: physical port associated with the VI
* @pf: the PF owning the VI
* @vf: the VF owning the VI
* @nmac: number of MAC addresses needed (1 to 5)
* @mac: the MAC addresses of the VI
* @rss_size: size of RSS table slice associated with this VI
*
* Allocates a virtual interface for the given physical port. If @mac is
* not %NULL it contains the MAC addresses of the VI as assigned by FW.
* @mac should be large enough to hold @nmac Ethernet addresses, they are
* stored consecutively so the space needed is @nmac * 6 bytes.
* Returns a negative error number or the non-negative VI id.
*/
int t4_alloc_vi(struct adapter *adap, unsigned int mbox, unsigned int port,
unsigned int pf, unsigned int vf, unsigned int nmac, u8 *mac,
unsigned int *rss_size)
{
int ret;
struct fw_vi_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_VI_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_CMD_EXEC |
FW_VI_CMD_PFN(pf) | FW_VI_CMD_VFN(vf));
c.alloc_to_len16 = htonl(FW_VI_CMD_ALLOC | FW_LEN16(c));
c.portid_pkd = FW_VI_CMD_PORTID(port);
c.nmac = nmac - 1;
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret)
return ret;
if (mac) {
memcpy(mac, c.mac, sizeof(c.mac));
switch (nmac) {
case 5:
memcpy(mac + 24, c.nmac3, sizeof(c.nmac3));
case 4:
memcpy(mac + 18, c.nmac2, sizeof(c.nmac2));
case 3:
memcpy(mac + 12, c.nmac1, sizeof(c.nmac1));
case 2:
memcpy(mac + 6, c.nmac0, sizeof(c.nmac0));
}
}
if (rss_size)
*rss_size = FW_VI_CMD_RSSSIZE_GET(ntohs(c.rsssize_pkd));
return FW_VI_CMD_VIID_GET(ntohs(c.type_viid));
}
/**
* t4_set_rxmode - set Rx properties of a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @mtu: the new MTU or -1
* @promisc: 1 to enable promiscuous mode, 0 to disable it, -1 no change
* @all_multi: 1 to enable all-multi mode, 0 to disable it, -1 no change
* @bcast: 1 to enable broadcast Rx, 0 to disable it, -1 no change
* @vlanex: 1 to enable HW VLAN extraction, 0 to disable it, -1 no change
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Sets Rx properties of a virtual interface.
*/
int t4_set_rxmode(struct adapter *adap, unsigned int mbox, unsigned int viid,
int mtu, int promisc, int all_multi, int bcast, int vlanex,
bool sleep_ok)
{
struct fw_vi_rxmode_cmd c;
/* convert to FW values */
if (mtu < 0)
mtu = FW_RXMODE_MTU_NO_CHG;
if (promisc < 0)
promisc = FW_VI_RXMODE_CMD_PROMISCEN_MASK;
if (all_multi < 0)
all_multi = FW_VI_RXMODE_CMD_ALLMULTIEN_MASK;
if (bcast < 0)
bcast = FW_VI_RXMODE_CMD_BROADCASTEN_MASK;
if (vlanex < 0)
vlanex = FW_VI_RXMODE_CMD_VLANEXEN_MASK;
memset(&c, 0, sizeof(c));
c.op_to_viid = htonl(FW_CMD_OP(FW_VI_RXMODE_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_VI_RXMODE_CMD_VIID(viid));
c.retval_len16 = htonl(FW_LEN16(c));
c.mtu_to_vlanexen = htonl(FW_VI_RXMODE_CMD_MTU(mtu) |
FW_VI_RXMODE_CMD_PROMISCEN(promisc) |
FW_VI_RXMODE_CMD_ALLMULTIEN(all_multi) |
FW_VI_RXMODE_CMD_BROADCASTEN(bcast) |
FW_VI_RXMODE_CMD_VLANEXEN(vlanex));
return t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), NULL, sleep_ok);
}
/**
* t4_alloc_mac_filt - allocates exact-match filters for MAC addresses
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @free: if true any existing filters for this VI id are first removed
* @naddr: the number of MAC addresses to allocate filters for (up to 7)
* @addr: the MAC address(es)
* @idx: where to store the index of each allocated filter
* @hash: pointer to hash address filter bitmap
* @sleep_ok: call is allowed to sleep
*
* Allocates an exact-match filter for each of the supplied addresses and
* sets it to the corresponding address. If @idx is not %NULL it should
* have at least @naddr entries, each of which will be set to the index of
* the filter allocated for the corresponding MAC address. If a filter
* could not be allocated for an address its index is set to 0xffff.
* If @hash is not %NULL addresses that fail to allocate an exact filter
* are hashed and update the hash filter bitmap pointed at by @hash.
*
* Returns a negative error number or the number of filters allocated.
*/
int t4_alloc_mac_filt(struct adapter *adap, unsigned int mbox,
unsigned int viid, bool free, unsigned int naddr,
const u8 **addr, u16 *idx, u64 *hash, bool sleep_ok)
{
int i, ret;
struct fw_vi_mac_cmd c;
struct fw_vi_mac_exact *p;
if (naddr > 7)
return -EINVAL;
memset(&c, 0, sizeof(c));
c.op_to_viid = htonl(FW_CMD_OP(FW_VI_MAC_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | (free ? FW_CMD_EXEC : 0) |
FW_VI_MAC_CMD_VIID(viid));
c.freemacs_to_len16 = htonl(FW_VI_MAC_CMD_FREEMACS(free) |
FW_CMD_LEN16((naddr + 2) / 2));
for (i = 0, p = c.u.exact; i < naddr; i++, p++) {
p->valid_to_idx = htons(FW_VI_MAC_CMD_VALID |
FW_VI_MAC_CMD_IDX(FW_VI_MAC_ADD_MAC));
memcpy(p->macaddr, addr[i], sizeof(p->macaddr));
}
ret = t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), &c, sleep_ok);
if (ret)
return ret;
for (i = 0, p = c.u.exact; i < naddr; i++, p++) {
u16 index = FW_VI_MAC_CMD_IDX_GET(ntohs(p->valid_to_idx));
if (idx)
idx[i] = index >= NEXACT_MAC ? 0xffff : index;
if (index < NEXACT_MAC)
ret++;
else if (hash)
*hash |= (1ULL << hash_mac_addr(addr[i]));
}
return ret;
}
/**
* t4_change_mac - modifies the exact-match filter for a MAC address
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @idx: index of existing filter for old value of MAC address, or -1
* @addr: the new MAC address value
* @persist: whether a new MAC allocation should be persistent
* @add_smt: if true also add the address to the HW SMT
*
* Modifies an exact-match filter and sets it to the new MAC address.
* Note that in general it is not possible to modify the value of a given
* filter so the generic way to modify an address filter is to free the one
* being used by the old address value and allocate a new filter for the
* new address value. @idx can be -1 if the address is a new addition.
*
* Returns a negative error number or the index of the filter with the new
* MAC value.
*/
int t4_change_mac(struct adapter *adap, unsigned int mbox, unsigned int viid,
int idx, const u8 *addr, bool persist, bool add_smt)
{
int ret, mode;
struct fw_vi_mac_cmd c;
struct fw_vi_mac_exact *p = c.u.exact;
if (idx < 0) /* new allocation */
idx = persist ? FW_VI_MAC_ADD_PERSIST_MAC : FW_VI_MAC_ADD_MAC;
mode = add_smt ? FW_VI_MAC_SMT_AND_MPSTCAM : FW_VI_MAC_MPS_TCAM_ENTRY;
memset(&c, 0, sizeof(c));
c.op_to_viid = htonl(FW_CMD_OP(FW_VI_MAC_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_VI_MAC_CMD_VIID(viid));
c.freemacs_to_len16 = htonl(FW_CMD_LEN16(1));
p->valid_to_idx = htons(FW_VI_MAC_CMD_VALID |
FW_VI_MAC_CMD_SMAC_RESULT(mode) |
FW_VI_MAC_CMD_IDX(idx));
memcpy(p->macaddr, addr, sizeof(p->macaddr));
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0) {
ret = FW_VI_MAC_CMD_IDX_GET(ntohs(p->valid_to_idx));
if (ret >= NEXACT_MAC)
ret = -ENOMEM;
}
return ret;
}
/**
* t4_set_addr_hash - program the MAC inexact-match hash filter
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @ucast: whether the hash filter should also match unicast addresses
* @vec: the value to be written to the hash filter
* @sleep_ok: call is allowed to sleep
*
* Sets the 64-bit inexact-match hash filter for a virtual interface.
*/
int t4_set_addr_hash(struct adapter *adap, unsigned int mbox, unsigned int viid,
bool ucast, u64 vec, bool sleep_ok)
{
struct fw_vi_mac_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_viid = htonl(FW_CMD_OP(FW_VI_MAC_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_VI_ENABLE_CMD_VIID(viid));
c.freemacs_to_len16 = htonl(FW_VI_MAC_CMD_HASHVECEN |
FW_VI_MAC_CMD_HASHUNIEN(ucast) |
FW_CMD_LEN16(1));
c.u.hash.hashvec = cpu_to_be64(vec);
return t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), NULL, sleep_ok);
}
/**
* t4_enable_vi - enable/disable a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @rx_en: 1=enable Rx, 0=disable Rx
* @tx_en: 1=enable Tx, 0=disable Tx
*
* Enables/disables a virtual interface.
*/
int t4_enable_vi(struct adapter *adap, unsigned int mbox, unsigned int viid,
bool rx_en, bool tx_en)
{
struct fw_vi_enable_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_viid = htonl(FW_CMD_OP(FW_VI_ENABLE_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_VI_ENABLE_CMD_VIID(viid));
c.ien_to_len16 = htonl(FW_VI_ENABLE_CMD_IEN(rx_en) |
FW_VI_ENABLE_CMD_EEN(tx_en) | FW_LEN16(c));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_identify_port - identify a VI's port by blinking its LED
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @nblinks: how many times to blink LED at 2.5 Hz
*
* Identifies a VI's port by blinking its LED.
*/
int t4_identify_port(struct adapter *adap, unsigned int mbox, unsigned int viid,
unsigned int nblinks)
{
struct fw_vi_enable_cmd c;
c.op_to_viid = htonl(FW_CMD_OP(FW_VI_ENABLE_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_VI_ENABLE_CMD_VIID(viid));
c.ien_to_len16 = htonl(FW_VI_ENABLE_CMD_LED | FW_LEN16(c));
c.blinkdur = htons(nblinks);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_iq_free - free an ingress queue and its FLs
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queues
* @vf: the VF owning the queues
* @iqtype: the ingress queue type
* @iqid: ingress queue id
* @fl0id: FL0 queue id or 0xffff if no attached FL0
* @fl1id: FL1 queue id or 0xffff if no attached FL1
*
* Frees an ingress queue and its associated FLs, if any.
*/
int t4_iq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int iqtype, unsigned int iqid,
unsigned int fl0id, unsigned int fl1id)
{
struct fw_iq_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_IQ_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_IQ_CMD_PFN(pf) |
FW_IQ_CMD_VFN(vf));
c.alloc_to_len16 = htonl(FW_IQ_CMD_FREE | FW_LEN16(c));
c.type_to_iqandstindex = htonl(FW_IQ_CMD_TYPE(iqtype));
c.iqid = htons(iqid);
c.fl0id = htons(fl0id);
c.fl1id = htons(fl1id);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_eth_eq_free - free an Ethernet egress queue
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queue
* @vf: the VF owning the queue
* @eqid: egress queue id
*
* Frees an Ethernet egress queue.
*/
int t4_eth_eq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int eqid)
{
struct fw_eq_eth_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_ETH_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_EQ_ETH_CMD_PFN(pf) |
FW_EQ_ETH_CMD_VFN(vf));
c.alloc_to_len16 = htonl(FW_EQ_ETH_CMD_FREE | FW_LEN16(c));
c.eqid_pkd = htonl(FW_EQ_ETH_CMD_EQID(eqid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_ctrl_eq_free - free a control egress queue
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queue
* @vf: the VF owning the queue
* @eqid: egress queue id
*
* Frees a control egress queue.
*/
int t4_ctrl_eq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int eqid)
{
struct fw_eq_ctrl_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_CTRL_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_EQ_CTRL_CMD_PFN(pf) |
FW_EQ_CTRL_CMD_VFN(vf));
c.alloc_to_len16 = htonl(FW_EQ_CTRL_CMD_FREE | FW_LEN16(c));
c.cmpliqid_eqid = htonl(FW_EQ_CTRL_CMD_EQID(eqid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_ofld_eq_free - free an offload egress queue
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queue
* @vf: the VF owning the queue
* @eqid: egress queue id
*
* Frees a control egress queue.
*/
int t4_ofld_eq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int eqid)
{
struct fw_eq_ofld_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_OFLD_CMD) | FW_CMD_REQUEST |
FW_CMD_EXEC | FW_EQ_OFLD_CMD_PFN(pf) |
FW_EQ_OFLD_CMD_VFN(vf));
c.alloc_to_len16 = htonl(FW_EQ_OFLD_CMD_FREE | FW_LEN16(c));
c.eqid_pkd = htonl(FW_EQ_OFLD_CMD_EQID(eqid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_handle_fw_rpl - process a FW reply message
* @adap: the adapter
* @rpl: start of the FW message
*
* Processes a FW message, such as link state change messages.
*/
int t4_handle_fw_rpl(struct adapter *adap, const __be64 *rpl)
{
u8 opcode = *(const u8 *)rpl;
if (opcode == FW_PORT_CMD) { /* link/module state change message */
int speed = 0, fc = 0;
const struct fw_port_cmd *p = (void *)rpl;
int chan = FW_PORT_CMD_PORTID_GET(ntohl(p->op_to_portid));
int port = adap->chan_map[chan];
struct port_info *pi = adap2pinfo(adap, port);
struct link_config *lc = &pi->link_cfg;
u32 stat = ntohl(p->u.info.lstatus_to_modtype);
int link_ok = (stat & FW_PORT_CMD_LSTATUS) != 0;
u32 mod = FW_PORT_CMD_MODTYPE_GET(stat);
if (stat & FW_PORT_CMD_RXPAUSE)
fc |= PAUSE_RX;
if (stat & FW_PORT_CMD_TXPAUSE)
fc |= PAUSE_TX;
if (stat & FW_PORT_CMD_LSPEED(FW_PORT_CAP_SPEED_100M))
speed = SPEED_100;
else if (stat & FW_PORT_CMD_LSPEED(FW_PORT_CAP_SPEED_1G))
speed = SPEED_1000;
else if (stat & FW_PORT_CMD_LSPEED(FW_PORT_CAP_SPEED_10G))
speed = SPEED_10000;
if (link_ok != lc->link_ok || speed != lc->speed ||
fc != lc->fc) { /* something changed */
lc->link_ok = link_ok;
lc->speed = speed;
lc->fc = fc;
t4_os_link_changed(adap, port, link_ok);
}
if (mod != pi->mod_type) {
pi->mod_type = mod;
t4_os_portmod_changed(adap, port);
}
}
return 0;
}
static void __devinit get_pci_mode(struct adapter *adapter,
struct pci_params *p)
{
u16 val;
u32 pcie_cap = pci_pcie_cap(adapter->pdev);
if (pcie_cap) {
pci_read_config_word(adapter->pdev, pcie_cap + PCI_EXP_LNKSTA,
&val);
p->speed = val & PCI_EXP_LNKSTA_CLS;
p->width = (val & PCI_EXP_LNKSTA_NLW) >> 4;
}
}
/**
* init_link_config - initialize a link's SW state
* @lc: structure holding the link state
* @caps: link capabilities
*
* Initializes the SW state maintained for each link, including the link's
* capabilities and default speed/flow-control/autonegotiation settings.
*/
static void __devinit init_link_config(struct link_config *lc,
unsigned int caps)
{
lc->supported = caps;
lc->requested_speed = 0;
lc->speed = 0;
lc->requested_fc = lc->fc = PAUSE_RX | PAUSE_TX;
if (lc->supported & FW_PORT_CAP_ANEG) {
lc->advertising = lc->supported & ADVERT_MASK;
lc->autoneg = AUTONEG_ENABLE;
lc->requested_fc |= PAUSE_AUTONEG;
} else {
lc->advertising = 0;
lc->autoneg = AUTONEG_DISABLE;
}
}
int t4_wait_dev_ready(struct adapter *adap)
{
if (t4_read_reg(adap, PL_WHOAMI) != 0xffffffff)
return 0;
msleep(500);
return t4_read_reg(adap, PL_WHOAMI) != 0xffffffff ? 0 : -EIO;
}
static int __devinit get_flash_params(struct adapter *adap)
{
int ret;
u32 info;
ret = sf1_write(adap, 1, 1, 0, SF_RD_ID);
if (!ret)
ret = sf1_read(adap, 3, 0, 1, &info);
t4_write_reg(adap, SF_OP, 0); /* unlock SF */
if (ret)
return ret;
if ((info & 0xff) != 0x20) /* not a Numonix flash */
return -EINVAL;
info >>= 16; /* log2 of size */
if (info >= 0x14 && info < 0x18)
adap->params.sf_nsec = 1 << (info - 16);
else if (info == 0x18)
adap->params.sf_nsec = 64;
else
return -EINVAL;
adap->params.sf_size = 1 << info;
adap->params.sf_fw_start =
t4_read_reg(adap, CIM_BOOT_CFG) & BOOTADDR_MASK;
return 0;
}
/**
* t4_prep_adapter - prepare SW and HW for operation
* @adapter: the adapter
* @reset: if true perform a HW reset
*
* Initialize adapter SW state for the various HW modules, set initial
* values for some adapter tunables, take PHYs out of reset, and
* initialize the MDIO interface.
*/
int __devinit t4_prep_adapter(struct adapter *adapter)
{
int ret;
ret = t4_wait_dev_ready(adapter);
if (ret < 0)
return ret;
get_pci_mode(adapter, &adapter->params.pci);
adapter->params.rev = t4_read_reg(adapter, PL_REV);
ret = get_flash_params(adapter);
if (ret < 0) {
dev_err(adapter->pdev_dev, "error %d identifying flash\n", ret);
return ret;
}
ret = get_vpd_params(adapter, &adapter->params.vpd);
if (ret < 0)
return ret;
init_cong_ctrl(adapter->params.a_wnd, adapter->params.b_wnd);
/*
* Default port for debugging in case we can't reach FW.
*/
adapter->params.nports = 1;
adapter->params.portvec = 1;
return 0;
}
int __devinit t4_port_init(struct adapter *adap, int mbox, int pf, int vf)
{
u8 addr[6];
int ret, i, j = 0;
struct fw_port_cmd c;
struct fw_rss_vi_config_cmd rvc;
memset(&c, 0, sizeof(c));
memset(&rvc, 0, sizeof(rvc));
for_each_port(adap, i) {
unsigned int rss_size;
struct port_info *p = adap2pinfo(adap, i);
while ((adap->params.portvec & (1 << j)) == 0)
j++;
c.op_to_portid = htonl(FW_CMD_OP(FW_PORT_CMD) |
FW_CMD_REQUEST | FW_CMD_READ |
FW_PORT_CMD_PORTID(j));
c.action_to_len16 = htonl(
FW_PORT_CMD_ACTION(FW_PORT_ACTION_GET_PORT_INFO) |
FW_LEN16(c));
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret)
return ret;
ret = t4_alloc_vi(adap, mbox, j, pf, vf, 1, addr, &rss_size);
if (ret < 0)
return ret;
p->viid = ret;
p->tx_chan = j;
p->lport = j;
p->rss_size = rss_size;
memcpy(adap->port[i]->dev_addr, addr, ETH_ALEN);
memcpy(adap->port[i]->perm_addr, addr, ETH_ALEN);
adap->port[i]->dev_id = j;
ret = ntohl(c.u.info.lstatus_to_modtype);
p->mdio_addr = (ret & FW_PORT_CMD_MDIOCAP) ?
FW_PORT_CMD_MDIOADDR_GET(ret) : -1;
p->port_type = FW_PORT_CMD_PTYPE_GET(ret);
p->mod_type = FW_PORT_MOD_TYPE_NA;
rvc.op_to_viid = htonl(FW_CMD_OP(FW_RSS_VI_CONFIG_CMD) |
FW_CMD_REQUEST | FW_CMD_READ |
FW_RSS_VI_CONFIG_CMD_VIID(p->viid));
rvc.retval_len16 = htonl(FW_LEN16(rvc));
ret = t4_wr_mbox(adap, mbox, &rvc, sizeof(rvc), &rvc);
if (ret)
return ret;
p->rss_mode = ntohl(rvc.u.basicvirtual.defaultq_to_udpen);
init_link_config(&p->link_cfg, ntohs(c.u.info.pcap));
j++;
}
return 0;
}
| gpl-2.0 |
Cpasjuste/android_kernel_lg_p990 | fs/ext4/xattr.c | 301 | 42979 | /*
* linux/fs/ext4/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* Fix by Harrison Xing <harrison@mountainviewdata.com>.
* Ext4 code with a lot of help from Eric Jarman <ejarman@acm.org>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <luka.renko@hermes.si>.
* xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
* Red Hat Inc.
* ea-in-inode support by Alex Tomas <alex@clusterfs.com> aka bzzz
* and Andreas Gruenbacher <agruen@suse.de>.
*/
/*
* Extended attributes are stored directly in inodes (on file systems with
* inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
* field contains the block number if an inode uses an additional block. All
* attributes must fit in the inode and one additional block. Blocks that
* contain the identical set of attributes may be shared among several inodes.
* Identical blocks are detected by keeping a cache of blocks that have
* recently been accessed.
*
* The attributes in inodes and on blocks have a different header; the entries
* are stored in the same format:
*
* +------------------+
* | header |
* | entry 1 | |
* | entry 2 | | growing downwards
* | entry 3 | v
* | four null bytes |
* | . . . |
* | value 1 | ^
* | value 3 | | growing upwards
* | value 2 | |
* +------------------+
*
* The header is followed by multiple entry descriptors. In disk blocks, the
* entry descriptors are kept sorted. In inodes, they are unsorted. The
* attribute values are aligned to the end of the block in no specific order.
*
* Locking strategy
* ----------------
* EXT4_I(inode)->i_file_acl is protected by EXT4_I(inode)->xattr_sem.
* EA blocks are only changed if they are exclusive to an inode, so
* holding xattr_sem also means that nothing but the EA block's reference
* count can change. Multiple writers to the same block are synchronized
* by the buffer lock.
*/
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include <linux/rwsem.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
#define BHDR(bh) ((struct ext4_xattr_header *)((bh)->b_data))
#define ENTRY(ptr) ((struct ext4_xattr_entry *)(ptr))
#define BFIRST(bh) ENTRY(BHDR(bh)+1)
#define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
#ifdef EXT4_XATTR_DEBUG
# define ea_idebug(inode, f...) do { \
printk(KERN_DEBUG "inode %s:%lu: ", \
inode->i_sb->s_id, inode->i_ino); \
printk(f); \
printk("\n"); \
} while (0)
# define ea_bdebug(bh, f...) do { \
char b[BDEVNAME_SIZE]; \
printk(KERN_DEBUG "block %s:%lu: ", \
bdevname(bh->b_bdev, b), \
(unsigned long) bh->b_blocknr); \
printk(f); \
printk("\n"); \
} while (0)
#else
# define ea_idebug(f...)
# define ea_bdebug(f...)
#endif
static void ext4_xattr_cache_insert(struct buffer_head *);
static struct buffer_head *ext4_xattr_cache_find(struct inode *,
struct ext4_xattr_header *,
struct mb_cache_entry **);
static void ext4_xattr_rehash(struct ext4_xattr_header *,
struct ext4_xattr_entry *);
static int ext4_xattr_list(struct inode *inode, char *buffer,
size_t buffer_size);
static struct mb_cache *ext4_xattr_cache;
static struct xattr_handler *ext4_xattr_handler_map[] = {
[EXT4_XATTR_INDEX_USER] = &ext4_xattr_user_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS] = &ext4_xattr_acl_access_handler,
[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &ext4_xattr_acl_default_handler,
#endif
[EXT4_XATTR_INDEX_TRUSTED] = &ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_SECURITY
[EXT4_XATTR_INDEX_SECURITY] = &ext4_xattr_security_handler,
#endif
};
struct xattr_handler *ext4_xattr_handlers[] = {
&ext4_xattr_user_handler,
&ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
&ext4_xattr_acl_access_handler,
&ext4_xattr_acl_default_handler,
#endif
#ifdef CONFIG_EXT4_FS_SECURITY
&ext4_xattr_security_handler,
#endif
NULL
};
static inline struct xattr_handler *
ext4_xattr_handler(int name_index)
{
struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
handler = ext4_xattr_handler_map[name_index];
return handler;
}
/*
* Inode operation listxattr()
*
* dentry->d_inode->i_mutex: don't care
*/
ssize_t
ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext4_xattr_list(dentry->d_inode, buffer, size);
}
static int
ext4_xattr_check_names(struct ext4_xattr_entry *entry, void *end)
{
while (!IS_LAST_ENTRY(entry)) {
struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(entry);
if ((void *)next >= end)
return -EIO;
entry = next;
}
return 0;
}
static inline int
ext4_xattr_check_block(struct buffer_head *bh)
{
int error;
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1))
return -EIO;
error = ext4_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size);
return error;
}
static inline int
ext4_xattr_check_entry(struct ext4_xattr_entry *entry, size_t size)
{
size_t value_size = le32_to_cpu(entry->e_value_size);
if (entry->e_value_block != 0 || value_size > size ||
le16_to_cpu(entry->e_value_offs) + value_size > size)
return -EIO;
return 0;
}
static int
ext4_xattr_find_entry(struct ext4_xattr_entry **pentry, int name_index,
const char *name, size_t size, int sorted)
{
struct ext4_xattr_entry *entry;
size_t name_len;
int cmp = 1;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
entry = *pentry;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
if (cmp <= 0 && (sorted || cmp == 0))
break;
}
*pentry = entry;
if (!cmp && ext4_xattr_check_entry(entry, size))
return -EIO;
return cmp ? -ENODATA : 0;
}
static int
ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_entry *entry;
size_t size;
int error;
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
error = -ENODATA;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %u", EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(bh)) {
bad_block: ext4_error(inode->i_sb, __func__,
"inode %lu: bad block %llu", inode->i_ino,
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext4_xattr_cache_insert(bh);
entry = BFIRST(bh);
error = ext4_xattr_find_entry(&entry, name_index, name, bh->b_size, 1);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
return error;
}
static int
ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR))
return -ENODATA;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = ext4_xattr_check_names(entry, end);
if (error)
goto cleanup;
error = ext4_xattr_find_entry(&entry, name_index, name,
end - (void *)entry, 0);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, (void *)IFIRST(header) +
le16_to_cpu(entry->e_value_offs), size);
}
error = size;
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext4_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
down_read(&EXT4_I(inode)->xattr_sem);
error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = ext4_xattr_block_get(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
ext4_xattr_list_entries(struct inode *inode, struct ext4_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
struct xattr_handler *handler =
ext4_xattr_handler(entry->e_name_index);
if (handler) {
size_t size = handler->list(inode, buffer, rest,
entry->e_name,
entry->e_name_len);
if (buffer) {
if (size > rest)
return -ERANGE;
buffer += size;
}
rest -= size;
}
}
return buffer_size - rest;
}
static int
ext4_xattr_block_list(struct inode *inode, char *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
int error;
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %u", EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(bh)) {
ext4_error(inode->i_sb, __func__,
"inode %lu: bad block %llu", inode->i_ino,
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext4_xattr_cache_insert(bh);
error = ext4_xattr_list_entries(inode, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
ext4_xattr_ibody_list(struct inode *inode, char *buffer, size_t buffer_size)
{
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR))
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = ext4_xattr_check_names(IFIRST(header), end);
if (error)
goto cleanup;
error = ext4_xattr_list_entries(inode, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_list()
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
static int
ext4_xattr_list(struct inode *inode, char *buffer, size_t buffer_size)
{
int i_error, b_error;
down_read(&EXT4_I(inode)->xattr_sem);
i_error = ext4_xattr_ibody_list(inode, buffer, buffer_size);
if (i_error < 0) {
b_error = 0;
} else {
if (buffer) {
buffer += i_error;
buffer_size -= i_error;
}
b_error = ext4_xattr_block_list(inode, buffer, buffer_size);
if (b_error < 0)
i_error = 0;
}
up_read(&EXT4_I(inode)->xattr_sem);
return i_error + b_error;
}
/*
* If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext4_xattr_update_super_block(handle_t *handle,
struct super_block *sb)
{
if (EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR))
return;
if (ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh) == 0) {
EXT4_SET_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR);
sb->s_dirt = 1;
ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement
* it; otherwise free the block.
*/
static void
ext4_xattr_release_block(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
struct mb_cache_entry *ce = NULL;
int error = 0;
ce = mb_cache_entry_get(ext4_xattr_cache, bh->b_bdev, bh->b_blocknr);
error = ext4_journal_get_write_access(handle, bh);
if (error)
goto out;
lock_buffer(bh);
if (BHDR(bh)->h_refcount == cpu_to_le32(1)) {
ea_bdebug(bh, "refcount now=0; freeing");
if (ce)
mb_cache_entry_free(ce);
ext4_free_blocks(handle, inode, bh->b_blocknr, 1, 1);
get_bh(bh);
ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
error = ext4_handle_dirty_metadata(handle, inode, bh);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
vfs_dq_free_block(inode, 1);
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
if (ce)
mb_cache_entry_release(ce);
}
unlock_buffer(bh);
out:
ext4_std_error(inode->i_sb, error);
return;
}
/*
* Find the available free space for EAs. This also returns the total number of
* bytes used by EA entries.
*/
static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
size_t *min_offs, void *base, int *total)
{
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
*total += EXT4_XATTR_LEN(last->e_name_len);
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < *min_offs)
*min_offs = offs;
}
}
return (*min_offs - ((void *)last - base) - sizeof(__u32));
}
struct ext4_xattr_info {
int name_index;
const char *name;
const void *value;
size_t value_len;
};
struct ext4_xattr_search {
struct ext4_xattr_entry *first;
void *base;
void *end;
struct ext4_xattr_entry *here;
int not_found;
};
static int
ext4_xattr_set_entry(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
{
struct ext4_xattr_entry *last;
size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found) {
if (!s->here->e_value_block && s->here->e_value_size) {
size_t size = le32_to_cpu(s->here->e_value_size);
free += EXT4_XATTR_SIZE(size);
}
free += EXT4_XATTR_LEN(name_len);
}
if (i->value) {
if (free < EXT4_XATTR_SIZE(i->value_len) ||
free < EXT4_XATTR_LEN(name_len) +
EXT4_XATTR_SIZE(i->value_len))
return -ENOSPC;
}
if (i->value && s->not_found) {
/* Insert the new name. */
size_t size = EXT4_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
memmove((void *)s->here + size, s->here, rest);
memset(s->here, 0, size);
s->here->e_name_index = i->name_index;
s->here->e_name_len = name_len;
memcpy(s->here->e_name, i->name, name_len);
} else {
if (!s->here->e_value_block && s->here->e_value_size) {
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(s->here->e_value_offs);
void *val = s->base + offs;
size_t size = EXT4_XATTR_SIZE(
le32_to_cpu(s->here->e_value_size));
if (i->value && size == EXT4_XATTR_SIZE(i->value_len)) {
/* The old and the new value have the same
size. Just replace. */
s->here->e_value_size =
cpu_to_le32(i->value_len);
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear pad bytes. */
memcpy(val, i->value, i->value_len);
return 0;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
s->here->e_value_size = 0;
s->here->e_value_offs = 0;
min_offs += size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_block &&
last->e_value_size && o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove the old name. */
size_t size = EXT4_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(s->here, (void *)s->here + size,
(void *)last - (void *)s->here + sizeof(__u32));
memset(last, 0, size);
}
}
if (i->value) {
/* Insert the new value. */
s->here->e_value_size = cpu_to_le32(i->value_len);
if (i->value_len) {
size_t size = EXT4_XATTR_SIZE(i->value_len);
void *val = s->base + min_offs - size;
s->here->e_value_offs = cpu_to_le16(min_offs - size);
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, i->value, i->value_len);
}
}
return 0;
}
struct ext4_xattr_block_find {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
int error;
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
i->name_index, i->name, i->value, (long)i->value_len);
if (EXT4_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = sb_bread(sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bs->bh)
goto cleanup;
ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
atomic_read(&(bs->bh->b_count)),
le32_to_cpu(BHDR(bs->bh)->h_refcount));
if (ext4_xattr_check_block(bs->bh)) {
ext4_error(sb, __func__,
"inode %lu: bad block %llu", inode->i_ino,
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* Find the named attribute. */
bs->s.base = BHDR(bs->bh);
bs->s.first = BFIRST(bs->bh);
bs->s.end = bs->bh->b_data + bs->bh->b_size;
bs->s.here = bs->s.first;
error = ext4_xattr_find_entry(&bs->s.here, i->name_index,
i->name, bs->bh->b_size, 1);
if (error && error != -ENODATA)
goto cleanup;
bs->s.not_found = error;
}
error = 0;
cleanup:
return error;
}
static int
ext4_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
#define header(x) ((struct ext4_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext4_xattr_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
error = ext4_journal_get_write_access(handle, bs->bh);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
if (ce) {
mb_cache_entry_free(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "modifying in-place");
error = ext4_xattr_set_entry(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
ext4_xattr_cache_insert(bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EIO)
goto bad_block;
if (!error)
error = ext4_handle_dirty_metadata(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
jbd2_journal_release_buffer(handle, bs->bh);
if (ce) {
mb_cache_entry_release(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "cloning");
s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
/* assert(header == s->base) */
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = ext4_xattr_set_entry(i, s);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = ext4_xattr_cache_find(inode, header(s->base), &ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
/* The old block is released after updating
the inode. */
error = -EDQUOT;
if (vfs_dq_alloc_block(inode, 1))
goto cleanup;
error = ext4_journal_get_write_access(handle,
new_bh);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "reusing; refcount now=%d",
le32_to_cpu(BHDR(new_bh)->h_refcount));
unlock_buffer(new_bh);
error = ext4_handle_dirty_metadata(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
mb_cache_entry_release(ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext4_fsblk_t goal, block;
goal = ext4_group_first_block_no(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
block = ext4_new_meta_blocks(handle, inode,
goal, NULL, &error);
if (error)
goto cleanup;
if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
ea_idebug(inode, "creating block %d", block);
new_bh = sb_getblk(sb, block);
if (!new_bh) {
getblk_failed:
ext4_free_blocks(handle, inode, block, 1, 1);
error = -EIO;
goto cleanup;
}
lock_buffer(new_bh);
error = ext4_journal_get_create_access(handle, new_bh);
if (error) {
unlock_buffer(new_bh);
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext4_xattr_cache_insert(new_bh);
error = ext4_handle_dirty_metadata(handle,
inode, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
ext4_xattr_release_block(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
mb_cache_entry_release(ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
vfs_dq_free_block(inode, 1);
goto cleanup;
bad_block:
ext4_error(inode->i_sb, __func__,
"inode %lu: bad block %llu", inode->i_ino,
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
struct ext4_xattr_ibody_find {
struct ext4_xattr_search s;
struct ext4_iloc iloc;
};
static int
ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
raw_inode = ext4_raw_inode(&is->iloc);
header = IHDR(inode, raw_inode);
is->s.base = is->s.first = IFIRST(header);
is->s.here = is->s.first;
is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
if (EXT4_I(inode)->i_state & EXT4_STATE_XATTR) {
error = ext4_xattr_check_names(IFIRST(header), is->s.end);
if (error)
return error;
/* Find the named attribute. */
error = ext4_xattr_find_entry(&is->s.here, i->name_index,
i->name, is->s.end -
(void *)is->s.base, 0);
if (error && error != -ENODATA)
return error;
is->s.not_found = error;
}
return 0;
}
static int
ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = ext4_xattr_set_entry(i, s);
if (error)
return error;
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
EXT4_I(inode)->i_state |= EXT4_STATE_XATTR;
} else {
header->h_magic = cpu_to_le32(0);
EXT4_I(inode)->i_state &= ~EXT4_STATE_XATTR;
}
return 0;
}
/*
* ext4_xattr_set_handle()
*
* Create, replace or remove an extended attribute for this inode. Buffer
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
const char *name, const void *value, size_t value_len,
int flags)
{
struct ext4_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
};
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_block_find bs = {
.s = { .not_found = -ENODATA, },
};
unsigned long no_expand;
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
down_write(&EXT4_I(inode)->xattr_sem);
no_expand = EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND;
EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
error = ext4_get_inode_loc(inode, &is.iloc);
if (error)
goto cleanup;
error = ext4_journal_get_write_access(handle, is.iloc.bh);
if (error)
goto cleanup;
if (EXT4_I(inode)->i_state & EXT4_STATE_NEW) {
struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
EXT4_I(inode)->i_state &= ~EXT4_STATE_NEW;
}
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
if (is.s.not_found && bs.s.not_found) {
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (!value)
goto cleanup;
} else {
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
}
if (!value) {
if (!is.s.not_found)
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else {
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
}
error = ext4_xattr_block_set(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = ext4_xattr_ibody_set(handle, inode, &i,
&is);
}
}
}
if (!error) {
ext4_xattr_update_super_block(handle, inode->i_sb);
inode->i_ctime = ext4_current_time(inode);
if (!value)
EXT4_I(inode)->i_state &= ~EXT4_STATE_NO_EXPAND;
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
/*
* The bh is consumed by ext4_mark_iloc_dirty, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
if (no_expand == 0)
EXT4_I(inode)->i_state &= ~EXT4_STATE_NO_EXPAND;
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_set()
*
* Like ext4_xattr_set_handle, but start from an inode. This extended
* attribute modification is a filesystem transaction by itself.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
handle_t *handle;
int error, retries = 0;
retry:
handle = ext4_journal_start(inode, EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = ext4_xattr_set_handle(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
return error;
}
/*
* Shift the EA entries in the inode to create space for the increased
* i_extra_isize.
*/
static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
/*
* Expand an inode by new_extra_isize bytes when EAs are present.
* Returns 0 on success or negative error number on failure.
*/
int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry, *last, *first;
struct buffer_head *bh = NULL;
struct ext4_xattr_ibody_find *is = NULL;
struct ext4_xattr_block_find *bs = NULL;
char *buffer = NULL, *b_entry_name = NULL;
size_t min_offs, free;
int total_ino, total_blk;
void *base, *start, *end;
int extra_isize = 0, error = 0, tried_min_extra_isize = 0;
int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
down_write(&EXT4_I(inode)->xattr_sem);
retry:
if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) {
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
}
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
/*
* Check if enough free space is available in the inode to shift the
* entries ahead by new_extra_isize.
*/
base = start = entry;
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
min_offs = end - base;
last = entry;
total_ino = sizeof(struct ext4_xattr_ibody_header);
free = ext4_xattr_free_space(last, &min_offs, base, &total_ino);
if (free >= new_extra_isize) {
entry = IFIRST(header);
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
(void *)header, total_ino,
inode->i_sb->s_blocksize);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
error = 0;
goto cleanup;
}
/*
* Enough free space isn't available in the inode, check if
* EA block can hold new_extra_isize bytes.
*/
if (EXT4_I(inode)->i_file_acl) {
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
if (ext4_xattr_check_block(bh)) {
ext4_error(inode->i_sb, __func__,
"inode %lu: bad block %llu", inode->i_ino,
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
base = BHDR(bh);
first = BFIRST(bh);
end = bh->b_data + bh->b_size;
min_offs = end - base;
free = ext4_xattr_free_space(first, &min_offs, base,
&total_blk);
if (free < new_extra_isize) {
if (!tried_min_extra_isize && s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
} else {
free = inode->i_sb->s_blocksize;
}
while (new_extra_isize > 0) {
size_t offs, size, entry_size;
struct ext4_xattr_entry *small_entry = NULL;
struct ext4_xattr_info i = {
.value = NULL,
.value_len = 0,
};
unsigned int total_size; /* EA entry size + value size */
unsigned int shift_bytes; /* No. of bytes to shift EAs by? */
unsigned int min_total_size = ~0U;
is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
if (!is || !bs) {
error = -ENOMEM;
goto cleanup;
}
is->s.not_found = -ENODATA;
bs->s.not_found = -ENODATA;
is->iloc.bh = NULL;
bs->bh = NULL;
last = IFIRST(header);
/* Find the entry best suited to be pushed into EA block */
entry = NULL;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
total_size =
EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
EXT4_XATTR_LEN(last->e_name_len);
if (total_size <= free && total_size < min_total_size) {
if (total_size < new_extra_isize) {
small_entry = last;
} else {
entry = last;
min_total_size = total_size;
}
}
}
if (entry == NULL) {
if (small_entry) {
entry = small_entry;
} else {
if (!tried_min_extra_isize &&
s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
goto retry;
}
error = -1;
goto cleanup;
}
}
offs = le16_to_cpu(entry->e_value_offs);
size = le32_to_cpu(entry->e_value_size);
entry_size = EXT4_XATTR_LEN(entry->e_name_len);
i.name_index = entry->e_name_index,
buffer = kmalloc(EXT4_XATTR_SIZE(size), GFP_NOFS);
b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
if (!buffer || !b_entry_name) {
error = -ENOMEM;
goto cleanup;
}
/* Save the entry name and the entry value */
memcpy(buffer, (void *)IFIRST(header) + offs,
EXT4_XATTR_SIZE(size));
memcpy(b_entry_name, entry->e_name, entry->e_name_len);
b_entry_name[entry->e_name_len] = '\0';
i.name = b_entry_name;
error = ext4_get_inode_loc(inode, &is->iloc);
if (error)
goto cleanup;
error = ext4_xattr_ibody_find(inode, &i, is);
if (error)
goto cleanup;
/* Remove the chosen entry from the inode */
error = ext4_xattr_ibody_set(handle, inode, &i, is);
entry = IFIRST(header);
if (entry_size + EXT4_XATTR_SIZE(size) >= new_extra_isize)
shift_bytes = new_extra_isize;
else
shift_bytes = entry_size + size;
/* Adjust the offsets and shift the remaining entries ahead */
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize -
shift_bytes, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + extra_isize + shift_bytes,
(void *)header, total_ino - entry_size,
inode->i_sb->s_blocksize);
extra_isize += shift_bytes;
new_extra_isize -= shift_bytes;
EXT4_I(inode)->i_extra_isize = extra_isize;
i.name = b_entry_name;
i.value = buffer;
i.value_len = size;
error = ext4_xattr_block_find(inode, &i, bs);
if (error)
goto cleanup;
/* Add entry which was removed from the inode into the block */
error = ext4_xattr_block_set(handle, inode, &i, bs);
if (error)
goto cleanup;
kfree(b_entry_name);
kfree(buffer);
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
}
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
cleanup:
kfree(b_entry_name);
kfree(buffer);
if (is)
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_delete_inode()
*
* Free extended attribute resources associated with this inode. This
* is called immediately before an inode is freed. We have exclusive
* access to the inode.
*/
void
ext4_xattr_delete_inode(handle_t *handle, struct inode *inode)
{
struct buffer_head *bh = NULL;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh) {
ext4_error(inode->i_sb, __func__,
"inode %lu: block %llu read error", inode->i_ino,
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
ext4_error(inode->i_sb, __func__,
"inode %lu: bad block %llu", inode->i_ino,
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
ext4_xattr_release_block(handle, inode, bh);
EXT4_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* ext4_xattr_put_super()
*
* This is called when a file system is unmounted.
*/
void
ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* ext4_xattr_cache_insert()
*
* Create a new entry in the extended attribute cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static void
ext4_xattr_cache_insert(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext4_xattr_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, &hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
mb_cache_entry_release(ce);
}
}
/*
* ext4_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext4_xattr_cmp(struct ext4_xattr_header *header1,
struct ext4_xattr_header *header2)
{
struct ext4_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EIO;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT4_XATTR_NEXT(entry1);
entry2 = EXT4_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* ext4_xattr_cache_find()
*
* Find an identical extended attribute block.
*
* Returns a pointer to the block found, or NULL if such a block was
* not found or an error occurred.
*/
static struct buffer_head *
ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext4_xattr_cache, 0,
inode->i_sb->s_bdev, hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext4_error(inode->i_sb, __func__,
"inode %lu: block %lu read error",
inode->i_ino, (unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, 0, inode->i_sb->s_bdev, hash);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* ext4_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static inline void ext4_xattr_hash_entry(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
__u32 hash = 0;
char *name = entry->e_name;
int n;
for (n = 0; n < entry->e_name_len; n++) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
*name++;
}
if (entry->e_value_block == 0 && entry->e_value_size != 0) {
__le32 *value = (__le32 *)((char *)header +
le16_to_cpu(entry->e_value_offs));
for (n = (le32_to_cpu(entry->e_value_size) +
EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n--) {
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
}
entry->e_hash = cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext4_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext4_xattr_rehash(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
struct ext4_xattr_entry *here;
__u32 hash = 0;
ext4_xattr_hash_entry(header, entry);
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT4_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
int __init
init_ext4_xattr(void)
{
ext4_xattr_cache = mb_cache_create("ext4_xattr", NULL,
sizeof(struct mb_cache_entry) +
sizeof(((struct mb_cache_entry *) 0)->e_indexes[0]), 1, 6);
if (!ext4_xattr_cache)
return -ENOMEM;
return 0;
}
void
exit_ext4_xattr(void)
{
if (ext4_xattr_cache)
mb_cache_destroy(ext4_xattr_cache);
ext4_xattr_cache = NULL;
}
| gpl-2.0 |
Starship-Android/starship_kernel_moto_shamu | drivers/net/veth.c | 301 | 10216 | /*
* drivers/net/veth.c
*
* Copyright (C) 2007 OpenVZ http://openvz.org, SWsoft Inc
*
* Author: Pavel Emelianov <xemul@openvz.org>
* Ethtool interface from: Eric W. Biederman <ebiederm@xmission.com>
*
*/
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <linux/ethtool.h>
#include <linux/etherdevice.h>
#include <linux/u64_stats_sync.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <linux/veth.h>
#include <linux/module.h>
#define DRV_NAME "veth"
#define DRV_VERSION "1.0"
#define MIN_MTU 68 /* Min L3 MTU */
#define MAX_MTU 65535 /* Max L3 MTU (arbitrary) */
struct pcpu_vstats {
u64 packets;
u64 bytes;
struct u64_stats_sync syncp;
};
struct veth_priv {
struct net_device __rcu *peer;
atomic64_t dropped;
};
/*
* ethtool interface
*/
static struct {
const char string[ETH_GSTRING_LEN];
} ethtool_stats_keys[] = {
{ "peer_ifindex" },
};
static int veth_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
cmd->supported = 0;
cmd->advertising = 0;
ethtool_cmd_speed_set(cmd, SPEED_10000);
cmd->duplex = DUPLEX_FULL;
cmd->port = PORT_TP;
cmd->phy_address = 0;
cmd->transceiver = XCVR_INTERNAL;
cmd->autoneg = AUTONEG_DISABLE;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static void veth_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
}
static void veth_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
{
switch(stringset) {
case ETH_SS_STATS:
memcpy(buf, ðtool_stats_keys, sizeof(ethtool_stats_keys));
break;
}
}
static int veth_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(ethtool_stats_keys);
default:
return -EOPNOTSUPP;
}
}
static void veth_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 *data)
{
struct veth_priv *priv = netdev_priv(dev);
struct net_device *peer = rtnl_dereference(priv->peer);
data[0] = peer ? peer->ifindex : 0;
}
static const struct ethtool_ops veth_ethtool_ops = {
.get_settings = veth_get_settings,
.get_drvinfo = veth_get_drvinfo,
.get_link = ethtool_op_get_link,
.get_strings = veth_get_strings,
.get_sset_count = veth_get_sset_count,
.get_ethtool_stats = veth_get_ethtool_stats,
};
static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct veth_priv *priv = netdev_priv(dev);
struct net_device *rcv;
int length = skb->len;
rcu_read_lock();
rcv = rcu_dereference(priv->peer);
if (unlikely(!rcv)) {
kfree_skb(skb);
goto drop;
}
if (likely(dev_forward_skb(rcv, skb) == NET_RX_SUCCESS)) {
struct pcpu_vstats *stats = this_cpu_ptr(dev->vstats);
u64_stats_update_begin(&stats->syncp);
stats->bytes += length;
stats->packets++;
u64_stats_update_end(&stats->syncp);
} else {
drop:
atomic64_inc(&priv->dropped);
}
rcu_read_unlock();
return NETDEV_TX_OK;
}
/*
* general routines
*/
static u64 veth_stats_one(struct pcpu_vstats *result, struct net_device *dev)
{
struct veth_priv *priv = netdev_priv(dev);
int cpu;
result->packets = 0;
result->bytes = 0;
for_each_possible_cpu(cpu) {
struct pcpu_vstats *stats = per_cpu_ptr(dev->vstats, cpu);
u64 packets, bytes;
unsigned int start;
do {
start = u64_stats_fetch_begin_bh(&stats->syncp);
packets = stats->packets;
bytes = stats->bytes;
} while (u64_stats_fetch_retry_bh(&stats->syncp, start));
result->packets += packets;
result->bytes += bytes;
}
return atomic64_read(&priv->dropped);
}
static struct rtnl_link_stats64 *veth_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *tot)
{
struct veth_priv *priv = netdev_priv(dev);
struct net_device *peer;
struct pcpu_vstats one;
tot->tx_dropped = veth_stats_one(&one, dev);
tot->tx_bytes = one.bytes;
tot->tx_packets = one.packets;
rcu_read_lock();
peer = rcu_dereference(priv->peer);
if (peer) {
tot->rx_dropped = veth_stats_one(&one, peer);
tot->rx_bytes = one.bytes;
tot->rx_packets = one.packets;
}
rcu_read_unlock();
return tot;
}
static int veth_open(struct net_device *dev)
{
struct veth_priv *priv = netdev_priv(dev);
struct net_device *peer = rtnl_dereference(priv->peer);
if (!peer)
return -ENOTCONN;
if (peer->flags & IFF_UP) {
netif_carrier_on(dev);
netif_carrier_on(peer);
}
return 0;
}
static int veth_close(struct net_device *dev)
{
struct veth_priv *priv = netdev_priv(dev);
struct net_device *peer = rtnl_dereference(priv->peer);
netif_carrier_off(dev);
if (peer)
netif_carrier_off(peer);
return 0;
}
static int is_valid_veth_mtu(int new_mtu)
{
return new_mtu >= MIN_MTU && new_mtu <= MAX_MTU;
}
static int veth_change_mtu(struct net_device *dev, int new_mtu)
{
if (!is_valid_veth_mtu(new_mtu))
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
static int veth_dev_init(struct net_device *dev)
{
dev->vstats = alloc_percpu(struct pcpu_vstats);
if (!dev->vstats)
return -ENOMEM;
return 0;
}
static void veth_dev_free(struct net_device *dev)
{
free_percpu(dev->vstats);
free_netdev(dev);
}
static const struct net_device_ops veth_netdev_ops = {
.ndo_init = veth_dev_init,
.ndo_open = veth_open,
.ndo_stop = veth_close,
.ndo_start_xmit = veth_xmit,
.ndo_change_mtu = veth_change_mtu,
.ndo_get_stats64 = veth_get_stats64,
.ndo_set_mac_address = eth_mac_addr,
};
#define VETH_FEATURES (NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_ALL_TSO | \
NETIF_F_HW_CSUM | NETIF_F_RXCSUM | NETIF_F_HIGHDMA | \
NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX | \
NETIF_F_HW_VLAN_STAG_TX | NETIF_F_HW_VLAN_STAG_RX )
static void veth_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
dev->netdev_ops = &veth_netdev_ops;
dev->ethtool_ops = &veth_ethtool_ops;
dev->features |= NETIF_F_LLTX;
dev->features |= VETH_FEATURES;
dev->destructor = veth_dev_free;
dev->hw_features = VETH_FEATURES;
}
/*
* netlink interface
*/
static int veth_validate(struct nlattr *tb[], struct nlattr *data[])
{
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
if (tb[IFLA_MTU]) {
if (!is_valid_veth_mtu(nla_get_u32(tb[IFLA_MTU])))
return -EINVAL;
}
return 0;
}
static struct rtnl_link_ops veth_link_ops;
static int veth_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[])
{
int err;
struct net_device *peer;
struct veth_priv *priv;
char ifname[IFNAMSIZ];
struct nlattr *peer_tb[IFLA_MAX + 1], **tbp;
struct ifinfomsg *ifmp;
struct net *net;
/*
* create and register peer first
*/
if (data != NULL && data[VETH_INFO_PEER] != NULL) {
struct nlattr *nla_peer;
nla_peer = data[VETH_INFO_PEER];
ifmp = nla_data(nla_peer);
err = nla_parse(peer_tb, IFLA_MAX,
nla_data(nla_peer) + sizeof(struct ifinfomsg),
nla_len(nla_peer) - sizeof(struct ifinfomsg),
ifla_policy);
if (err < 0)
return err;
err = veth_validate(peer_tb, NULL);
if (err < 0)
return err;
tbp = peer_tb;
} else {
ifmp = NULL;
tbp = tb;
}
if (tbp[IFLA_IFNAME])
nla_strlcpy(ifname, tbp[IFLA_IFNAME], IFNAMSIZ);
else
snprintf(ifname, IFNAMSIZ, DRV_NAME "%%d");
net = rtnl_link_get_net(src_net, tbp);
if (IS_ERR(net))
return PTR_ERR(net);
peer = rtnl_create_link(net, ifname, &veth_link_ops, tbp);
if (IS_ERR(peer)) {
put_net(net);
return PTR_ERR(peer);
}
if (tbp[IFLA_ADDRESS] == NULL)
eth_hw_addr_random(peer);
if (ifmp && (dev->ifindex != 0))
peer->ifindex = ifmp->ifi_index;
err = register_netdevice(peer);
put_net(net);
net = NULL;
if (err < 0)
goto err_register_peer;
netif_carrier_off(peer);
err = rtnl_configure_link(peer, ifmp);
if (err < 0)
goto err_configure_peer;
/*
* register dev last
*
* note, that since we've registered new device the dev's name
* should be re-allocated
*/
if (tb[IFLA_ADDRESS] == NULL)
eth_hw_addr_random(dev);
if (tb[IFLA_IFNAME])
nla_strlcpy(dev->name, tb[IFLA_IFNAME], IFNAMSIZ);
else
snprintf(dev->name, IFNAMSIZ, DRV_NAME "%%d");
if (strchr(dev->name, '%')) {
err = dev_alloc_name(dev, dev->name);
if (err < 0)
goto err_alloc_name;
}
err = register_netdevice(dev);
if (err < 0)
goto err_register_dev;
netif_carrier_off(dev);
/*
* tie the deviced together
*/
priv = netdev_priv(dev);
rcu_assign_pointer(priv->peer, peer);
priv = netdev_priv(peer);
rcu_assign_pointer(priv->peer, dev);
return 0;
err_register_dev:
/* nothing to do */
err_alloc_name:
err_configure_peer:
unregister_netdevice(peer);
return err;
err_register_peer:
free_netdev(peer);
return err;
}
static void veth_dellink(struct net_device *dev, struct list_head *head)
{
struct veth_priv *priv;
struct net_device *peer;
priv = netdev_priv(dev);
peer = rtnl_dereference(priv->peer);
/* Note : dellink() is called from default_device_exit_batch(),
* before a rcu_synchronize() point. The devices are guaranteed
* not being freed before one RCU grace period.
*/
RCU_INIT_POINTER(priv->peer, NULL);
unregister_netdevice_queue(dev, head);
if (peer) {
priv = netdev_priv(peer);
RCU_INIT_POINTER(priv->peer, NULL);
unregister_netdevice_queue(peer, head);
}
}
static const struct nla_policy veth_policy[VETH_INFO_MAX + 1] = {
[VETH_INFO_PEER] = { .len = sizeof(struct ifinfomsg) },
};
static struct rtnl_link_ops veth_link_ops = {
.kind = DRV_NAME,
.priv_size = sizeof(struct veth_priv),
.setup = veth_setup,
.validate = veth_validate,
.newlink = veth_newlink,
.dellink = veth_dellink,
.policy = veth_policy,
.maxtype = VETH_INFO_MAX,
};
/*
* init/fini
*/
static __init int veth_init(void)
{
return rtnl_link_register(&veth_link_ops);
}
static __exit void veth_exit(void)
{
rtnl_link_unregister(&veth_link_ops);
}
module_init(veth_init);
module_exit(veth_exit);
MODULE_DESCRIPTION("Virtual Ethernet Tunnel");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS_RTNL_LINK(DRV_NAME);
| gpl-2.0 |
cwyy/kernel | drivers/s390/cio/crw.c | 557 | 4007 | /*
* Channel report handling code
*
* Copyright IBM Corp. 2000,2009
* Author(s): Ingo Adlung <adlung@de.ibm.com>,
* Martin Schwidefsky <schwidefsky@de.ibm.com>,
* Cornelia Huck <cornelia.huck@de.ibm.com>,
* Heiko Carstens <heiko.carstens@de.ibm.com>,
*/
#include <linux/semaphore.h>
#include <linux/mutex.h>
#include <linux/kthread.h>
#include <linux/init.h>
#include <asm/crw.h>
static struct semaphore crw_semaphore;
static DEFINE_MUTEX(crw_handler_mutex);
static crw_handler_t crw_handlers[NR_RSCS];
/**
* crw_register_handler() - register a channel report word handler
* @rsc: reporting source code to handle
* @handler: handler to be registered
*
* Returns %0 on success and a negative error value otherwise.
*/
int crw_register_handler(int rsc, crw_handler_t handler)
{
int rc = 0;
if ((rsc < 0) || (rsc >= NR_RSCS))
return -EINVAL;
mutex_lock(&crw_handler_mutex);
if (crw_handlers[rsc])
rc = -EBUSY;
else
crw_handlers[rsc] = handler;
mutex_unlock(&crw_handler_mutex);
return rc;
}
/**
* crw_unregister_handler() - unregister a channel report word handler
* @rsc: reporting source code to handle
*/
void crw_unregister_handler(int rsc)
{
if ((rsc < 0) || (rsc >= NR_RSCS))
return;
mutex_lock(&crw_handler_mutex);
crw_handlers[rsc] = NULL;
mutex_unlock(&crw_handler_mutex);
}
/*
* Retrieve CRWs and call function to handle event.
*/
static int crw_collect_info(void *unused)
{
struct crw crw[2];
int ccode;
unsigned int chain;
int ignore;
repeat:
ignore = down_interruptible(&crw_semaphore);
chain = 0;
while (1) {
crw_handler_t handler;
if (unlikely(chain > 1)) {
struct crw tmp_crw;
printk(KERN_WARNING"%s: Code does not support more "
"than two chained crws; please report to "
"linux390@de.ibm.com!\n", __func__);
ccode = stcrw(&tmp_crw);
printk(KERN_WARNING"%s: crw reports slct=%d, oflw=%d, "
"chn=%d, rsc=%X, anc=%d, erc=%X, rsid=%X\n",
__func__, tmp_crw.slct, tmp_crw.oflw,
tmp_crw.chn, tmp_crw.rsc, tmp_crw.anc,
tmp_crw.erc, tmp_crw.rsid);
printk(KERN_WARNING"%s: This was crw number %x in the "
"chain\n", __func__, chain);
if (ccode != 0)
break;
chain = tmp_crw.chn ? chain + 1 : 0;
continue;
}
ccode = stcrw(&crw[chain]);
if (ccode != 0)
break;
printk(KERN_DEBUG "crw_info : CRW reports slct=%d, oflw=%d, "
"chn=%d, rsc=%X, anc=%d, erc=%X, rsid=%X\n",
crw[chain].slct, crw[chain].oflw, crw[chain].chn,
crw[chain].rsc, crw[chain].anc, crw[chain].erc,
crw[chain].rsid);
/* Check for overflows. */
if (crw[chain].oflw) {
int i;
pr_debug("%s: crw overflow detected!\n", __func__);
mutex_lock(&crw_handler_mutex);
for (i = 0; i < NR_RSCS; i++) {
if (crw_handlers[i])
crw_handlers[i](NULL, NULL, 1);
}
mutex_unlock(&crw_handler_mutex);
chain = 0;
continue;
}
if (crw[0].chn && !chain) {
chain++;
continue;
}
mutex_lock(&crw_handler_mutex);
handler = crw_handlers[crw[chain].rsc];
if (handler)
handler(&crw[0], chain ? &crw[1] : NULL, 0);
mutex_unlock(&crw_handler_mutex);
/* chain is always 0 or 1 here. */
chain = crw[chain].chn ? chain + 1 : 0;
}
goto repeat;
return 0;
}
void crw_handle_channel_report(void)
{
up(&crw_semaphore);
}
/*
* Separate initcall needed for semaphore initialization since
* crw_handle_channel_report might be called before crw_machine_check_init.
*/
static int __init crw_init_semaphore(void)
{
init_MUTEX_LOCKED(&crw_semaphore);
return 0;
}
pure_initcall(crw_init_semaphore);
/*
* Machine checks for the channel subsystem must be enabled
* after the channel subsystem is initialized
*/
static int __init crw_machine_check_init(void)
{
struct task_struct *task;
task = kthread_run(crw_collect_info, NULL, "kmcheck");
if (IS_ERR(task))
return PTR_ERR(task);
ctl_set_bit(14, 28); /* enable channel report MCH */
return 0;
}
device_initcall(crw_machine_check_init);
| gpl-2.0 |
andyjhf/mini2440-linux-2.6.32.2 | drivers/net/can/sja1000/ems_pci.c | 557 | 10340 | /*
* Copyright (C) 2007 Wolfgang Grandegger <wg@grandegger.com>
* Copyright (C) 2008 Markus Plessing <plessing@ems-wuensche.com>
* Copyright (C) 2008 Sebastian Haas <haas@ems-wuensche.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the version 2 of the GNU General Public License
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include <linux/io.h>
#include "sja1000.h"
#define DRV_NAME "ems_pci"
MODULE_AUTHOR("Sebastian Haas <haas@ems-wuenche.com>");
MODULE_DESCRIPTION("Socket-CAN driver for EMS CPC-PCI/PCIe/104P CAN cards");
MODULE_SUPPORTED_DEVICE("EMS CPC-PCI/PCIe/104P CAN card");
MODULE_LICENSE("GPL v2");
#define EMS_PCI_V1_MAX_CHAN 2
#define EMS_PCI_V2_MAX_CHAN 4
#define EMS_PCI_MAX_CHAN EMS_PCI_V2_MAX_CHAN
struct ems_pci_card {
int version;
int channels;
struct pci_dev *pci_dev;
struct net_device *net_dev[EMS_PCI_MAX_CHAN];
void __iomem *conf_addr;
void __iomem *base_addr;
};
#define EMS_PCI_CAN_CLOCK (16000000 / 2)
/*
* Register definitions and descriptions are from LinCAN 0.3.3.
*
* PSB4610 PITA-2 bridge control registers
*/
#define PITA2_ICR 0x00 /* Interrupt Control Register */
#define PITA2_ICR_INT0 0x00000002 /* [RC] INT0 Active/Clear */
#define PITA2_ICR_INT0_EN 0x00020000 /* [RW] Enable INT0 */
#define PITA2_MISC 0x1c /* Miscellaneous Register */
#define PITA2_MISC_CONFIG 0x04000000 /* Multiplexed parallel interface */
/*
* Register definitions for the PLX 9030
*/
#define PLX_ICSR 0x4c /* Interrupt Control/Status register */
#define PLX_ICSR_LINTI1_ENA 0x0001 /* LINTi1 Enable */
#define PLX_ICSR_PCIINT_ENA 0x0040 /* PCI Interrupt Enable */
#define PLX_ICSR_LINTI1_CLR 0x0400 /* Local Edge Triggerable Interrupt Clear */
#define PLX_ICSR_ENA_CLR (PLX_ICSR_LINTI1_ENA | PLX_ICSR_PCIINT_ENA | \
PLX_ICSR_LINTI1_CLR)
/*
* The board configuration is probably following:
* RX1 is connected to ground.
* TX1 is not connected.
* CLKO is not connected.
* Setting the OCR register to 0xDA is a good idea.
* This means normal output mode, push-pull and the correct polarity.
*/
#define EMS_PCI_OCR (OCR_TX0_PUSHPULL | OCR_TX1_PUSHPULL)
/*
* In the CDR register, you should set CBP to 1.
* You will probably also want to set the clock divider value to 7
* (meaning direct oscillator output) because the second SJA1000 chip
* is driven by the first one CLKOUT output.
*/
#define EMS_PCI_CDR (CDR_CBP | CDR_CLKOUT_MASK)
#define EMS_PCI_V1_BASE_BAR 1
#define EMS_PCI_V1_CONF_SIZE 4096 /* size of PITA control area */
#define EMS_PCI_V2_BASE_BAR 2
#define EMS_PCI_V2_CONF_SIZE 128 /* size of PLX control area */
#define EMS_PCI_CAN_BASE_OFFSET 0x400 /* offset where the controllers starts */
#define EMS_PCI_CAN_CTRL_SIZE 0x200 /* memory size for each controller */
#define EMS_PCI_BASE_SIZE 4096 /* size of controller area */
static struct pci_device_id ems_pci_tbl[] = {
/* CPC-PCI v1 */
{PCI_VENDOR_ID_SIEMENS, 0x2104, PCI_ANY_ID, PCI_ANY_ID,},
/* CPC-PCI v2 */
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9030, PCI_VENDOR_ID_PLX, 0x4000},
/* CPC-104P v2 */
{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9030, PCI_VENDOR_ID_PLX, 0x4002},
{0,}
};
MODULE_DEVICE_TABLE(pci, ems_pci_tbl);
/*
* Helper to read internal registers from card logic (not CAN)
*/
static u8 ems_pci_v1_readb(struct ems_pci_card *card, unsigned int port)
{
return readb(card->base_addr + (port * 4));
}
static u8 ems_pci_v1_read_reg(const struct sja1000_priv *priv, int port)
{
return readb(priv->reg_base + (port * 4));
}
static void ems_pci_v1_write_reg(const struct sja1000_priv *priv,
int port, u8 val)
{
writeb(val, priv->reg_base + (port * 4));
}
static void ems_pci_v1_post_irq(const struct sja1000_priv *priv)
{
struct ems_pci_card *card = (struct ems_pci_card *)priv->priv;
/* reset int flag of pita */
writel(PITA2_ICR_INT0_EN | PITA2_ICR_INT0,
card->conf_addr + PITA2_ICR);
}
static u8 ems_pci_v2_read_reg(const struct sja1000_priv *priv, int port)
{
return readb(priv->reg_base + port);
}
static void ems_pci_v2_write_reg(const struct sja1000_priv *priv,
int port, u8 val)
{
writeb(val, priv->reg_base + port);
}
static void ems_pci_v2_post_irq(const struct sja1000_priv *priv)
{
struct ems_pci_card *card = (struct ems_pci_card *)priv->priv;
writel(PLX_ICSR_ENA_CLR, card->conf_addr + PLX_ICSR);
}
/*
* Check if a CAN controller is present at the specified location
* by trying to set 'em into the PeliCAN mode
*/
static inline int ems_pci_check_chan(const struct sja1000_priv *priv)
{
unsigned char res;
/* Make sure SJA1000 is in reset mode */
priv->write_reg(priv, REG_MOD, 1);
priv->write_reg(priv, REG_CDR, CDR_PELICAN);
/* read reset-values */
res = priv->read_reg(priv, REG_CDR);
if (res == CDR_PELICAN)
return 1;
return 0;
}
static void ems_pci_del_card(struct pci_dev *pdev)
{
struct ems_pci_card *card = pci_get_drvdata(pdev);
struct net_device *dev;
int i = 0;
for (i = 0; i < card->channels; i++) {
dev = card->net_dev[i];
if (!dev)
continue;
dev_info(&pdev->dev, "Removing %s.\n", dev->name);
unregister_sja1000dev(dev);
free_sja1000dev(dev);
}
if (card->base_addr != NULL)
pci_iounmap(card->pci_dev, card->base_addr);
if (card->conf_addr != NULL)
pci_iounmap(card->pci_dev, card->conf_addr);
kfree(card);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
static void ems_pci_card_reset(struct ems_pci_card *card)
{
/* Request board reset */
writeb(0, card->base_addr);
}
/*
* Probe PCI device for EMS CAN signature and register each available
* CAN channel to SJA1000 Socket-CAN subsystem.
*/
static int __devinit ems_pci_add_card(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct sja1000_priv *priv;
struct net_device *dev;
struct ems_pci_card *card;
int max_chan, conf_size, base_bar;
int err, i;
/* Enabling PCI device */
if (pci_enable_device(pdev) < 0) {
dev_err(&pdev->dev, "Enabling PCI device failed\n");
return -ENODEV;
}
/* Allocating card structures to hold addresses, ... */
card = kzalloc(sizeof(struct ems_pci_card), GFP_KERNEL);
if (card == NULL) {
dev_err(&pdev->dev, "Unable to allocate memory\n");
pci_disable_device(pdev);
return -ENOMEM;
}
pci_set_drvdata(pdev, card);
card->pci_dev = pdev;
card->channels = 0;
if (pdev->vendor == PCI_VENDOR_ID_PLX) {
card->version = 2; /* CPC-PCI v2 */
max_chan = EMS_PCI_V2_MAX_CHAN;
base_bar = EMS_PCI_V2_BASE_BAR;
conf_size = EMS_PCI_V2_CONF_SIZE;
} else {
card->version = 1; /* CPC-PCI v1 */
max_chan = EMS_PCI_V1_MAX_CHAN;
base_bar = EMS_PCI_V1_BASE_BAR;
conf_size = EMS_PCI_V1_CONF_SIZE;
}
/* Remap configuration space and controller memory area */
card->conf_addr = pci_iomap(pdev, 0, conf_size);
if (card->conf_addr == NULL) {
err = -ENOMEM;
goto failure_cleanup;
}
card->base_addr = pci_iomap(pdev, base_bar, EMS_PCI_BASE_SIZE);
if (card->base_addr == NULL) {
err = -ENOMEM;
goto failure_cleanup;
}
if (card->version == 1) {
/* Configure PITA-2 parallel interface (enable MUX) */
writel(PITA2_MISC_CONFIG, card->conf_addr + PITA2_MISC);
/* Check for unique EMS CAN signature */
if (ems_pci_v1_readb(card, 0) != 0x55 ||
ems_pci_v1_readb(card, 1) != 0xAA ||
ems_pci_v1_readb(card, 2) != 0x01 ||
ems_pci_v1_readb(card, 3) != 0xCB ||
ems_pci_v1_readb(card, 4) != 0x11) {
dev_err(&pdev->dev,
"Not EMS Dr. Thomas Wuensche interface\n");
err = -ENODEV;
goto failure_cleanup;
}
}
ems_pci_card_reset(card);
/* Detect available channels */
for (i = 0; i < max_chan; i++) {
dev = alloc_sja1000dev(0);
if (dev == NULL) {
err = -ENOMEM;
goto failure_cleanup;
}
card->net_dev[i] = dev;
priv = netdev_priv(dev);
priv->priv = card;
priv->irq_flags = IRQF_SHARED;
dev->irq = pdev->irq;
priv->reg_base = card->base_addr + EMS_PCI_CAN_BASE_OFFSET
+ (i * EMS_PCI_CAN_CTRL_SIZE);
if (card->version == 1) {
priv->read_reg = ems_pci_v1_read_reg;
priv->write_reg = ems_pci_v1_write_reg;
priv->post_irq = ems_pci_v1_post_irq;
} else {
priv->read_reg = ems_pci_v2_read_reg;
priv->write_reg = ems_pci_v2_write_reg;
priv->post_irq = ems_pci_v2_post_irq;
}
/* Check if channel is present */
if (ems_pci_check_chan(priv)) {
priv->can.clock.freq = EMS_PCI_CAN_CLOCK;
priv->ocr = EMS_PCI_OCR;
priv->cdr = EMS_PCI_CDR;
SET_NETDEV_DEV(dev, &pdev->dev);
if (card->version == 1)
/* reset int flag of pita */
writel(PITA2_ICR_INT0_EN | PITA2_ICR_INT0,
card->conf_addr + PITA2_ICR);
else
/* enable IRQ in PLX 9030 */
writel(PLX_ICSR_ENA_CLR,
card->conf_addr + PLX_ICSR);
/* Register SJA1000 device */
err = register_sja1000dev(dev);
if (err) {
dev_err(&pdev->dev, "Registering device failed "
"(err=%d)\n", err);
free_sja1000dev(dev);
goto failure_cleanup;
}
card->channels++;
dev_info(&pdev->dev, "Channel #%d at 0x%p, irq %d\n",
i + 1, priv->reg_base, dev->irq);
} else {
free_sja1000dev(dev);
}
}
return 0;
failure_cleanup:
dev_err(&pdev->dev, "Error: %d. Cleaning Up.\n", err);
ems_pci_del_card(pdev);
return err;
}
static struct pci_driver ems_pci_driver = {
.name = DRV_NAME,
.id_table = ems_pci_tbl,
.probe = ems_pci_add_card,
.remove = ems_pci_del_card,
};
static int __init ems_pci_init(void)
{
return pci_register_driver(&ems_pci_driver);
}
static void __exit ems_pci_exit(void)
{
pci_unregister_driver(&ems_pci_driver);
}
module_init(ems_pci_init);
module_exit(ems_pci_exit);
| gpl-2.0 |
yangxiaohua1977/sound-linux-4.5.7 | drivers/staging/nvec/nvec_paz00.c | 813 | 2241 | /*
* nvec_paz00: OEM specific driver for Compal PAZ00 based devices
*
* Copyright (C) 2011 The AC100 Kernel Team <ac100@lists.launchpad.net>
*
* Authors: Ilya Petrov <ilya.muromec@gmail.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/leds.h>
#include <linux/platform_device.h>
#include "nvec.h"
#define to_nvec_led(led_cdev) \
container_of(led_cdev, struct nvec_led, cdev)
#define NVEC_LED_REQ {'\x0d', '\x10', '\x45', '\x10', '\x00'}
#define NVEC_LED_MAX 8
struct nvec_led {
struct led_classdev cdev;
struct nvec_chip *nvec;
};
static void nvec_led_brightness_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct nvec_led *led = to_nvec_led(led_cdev);
unsigned char buf[] = NVEC_LED_REQ;
buf[4] = value;
nvec_write_async(led->nvec, buf, sizeof(buf));
led->cdev.brightness = value;
}
static int nvec_paz00_probe(struct platform_device *pdev)
{
struct nvec_chip *nvec = dev_get_drvdata(pdev->dev.parent);
struct nvec_led *led;
int ret = 0;
led = devm_kzalloc(&pdev->dev, sizeof(*led), GFP_KERNEL);
if (!led)
return -ENOMEM;
led->cdev.max_brightness = NVEC_LED_MAX;
led->cdev.brightness_set = nvec_led_brightness_set;
led->cdev.name = "paz00-led";
led->cdev.flags |= LED_CORE_SUSPENDRESUME;
led->nvec = nvec;
platform_set_drvdata(pdev, led);
ret = led_classdev_register(&pdev->dev, &led->cdev);
if (ret < 0)
return ret;
/* to expose the default value to userspace */
led->cdev.brightness = 0;
return 0;
}
static int nvec_paz00_remove(struct platform_device *pdev)
{
struct nvec_led *led = platform_get_drvdata(pdev);
led_classdev_unregister(&led->cdev);
return 0;
}
static struct platform_driver nvec_paz00_driver = {
.probe = nvec_paz00_probe,
.remove = nvec_paz00_remove,
.driver = {
.name = "nvec-paz00",
},
};
module_platform_driver(nvec_paz00_driver);
MODULE_AUTHOR("Ilya Petrov <ilya.muromec@gmail.com>");
MODULE_DESCRIPTION("Tegra NVEC PAZ00 driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:nvec-paz00");
| gpl-2.0 |
shobhitka/linux-kernel | drivers/s390/block/dasd_fba.c | 813 | 17894 | /*
* Author(s)......: Holger Smolinski <Holger.Smolinski@de.ibm.com>
* Bugreports.to..: <Linux390@de.ibm.com>
* Copyright IBM Corp. 1999, 2009
*/
#define KMSG_COMPONENT "dasd-fba"
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <asm/debug.h>
#include <linux/slab.h>
#include <linux/hdreg.h> /* HDIO_GETGEO */
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/init.h>
#include <asm/idals.h>
#include <asm/ebcdic.h>
#include <asm/io.h>
#include <asm/ccwdev.h>
#include "dasd_int.h"
#include "dasd_fba.h"
#ifdef PRINTK_HEADER
#undef PRINTK_HEADER
#endif /* PRINTK_HEADER */
#define PRINTK_HEADER "dasd(fba):"
#define FBA_DEFAULT_RETRIES 32
#define DASD_FBA_CCW_WRITE 0x41
#define DASD_FBA_CCW_READ 0x42
#define DASD_FBA_CCW_LOCATE 0x43
#define DASD_FBA_CCW_DEFINE_EXTENT 0x63
MODULE_LICENSE("GPL");
static struct dasd_discipline dasd_fba_discipline;
struct dasd_fba_private {
struct dasd_fba_characteristics rdc_data;
};
static struct ccw_device_id dasd_fba_ids[] = {
{ CCW_DEVICE_DEVTYPE (0x6310, 0, 0x9336, 0), .driver_info = 0x1},
{ CCW_DEVICE_DEVTYPE (0x3880, 0, 0x3370, 0), .driver_info = 0x2},
{ /* end of list */ },
};
MODULE_DEVICE_TABLE(ccw, dasd_fba_ids);
static struct ccw_driver dasd_fba_driver; /* see below */
static int
dasd_fba_probe(struct ccw_device *cdev)
{
return dasd_generic_probe(cdev, &dasd_fba_discipline);
}
static int
dasd_fba_set_online(struct ccw_device *cdev)
{
return dasd_generic_set_online(cdev, &dasd_fba_discipline);
}
static struct ccw_driver dasd_fba_driver = {
.driver = {
.name = "dasd-fba",
.owner = THIS_MODULE,
},
.ids = dasd_fba_ids,
.probe = dasd_fba_probe,
.remove = dasd_generic_remove,
.set_offline = dasd_generic_set_offline,
.set_online = dasd_fba_set_online,
.notify = dasd_generic_notify,
.path_event = dasd_generic_path_event,
.freeze = dasd_generic_pm_freeze,
.thaw = dasd_generic_restore_device,
.restore = dasd_generic_restore_device,
.int_class = IRQIO_DAS,
};
static void
define_extent(struct ccw1 * ccw, struct DE_fba_data *data, int rw,
int blksize, int beg, int nr)
{
ccw->cmd_code = DASD_FBA_CCW_DEFINE_EXTENT;
ccw->flags = 0;
ccw->count = 16;
ccw->cda = (__u32) __pa(data);
memset(data, 0, sizeof (struct DE_fba_data));
if (rw == WRITE)
(data->mask).perm = 0x0;
else if (rw == READ)
(data->mask).perm = 0x1;
else
data->mask.perm = 0x2;
data->blk_size = blksize;
data->ext_loc = beg;
data->ext_end = nr - 1;
}
static void
locate_record(struct ccw1 * ccw, struct LO_fba_data *data, int rw,
int block_nr, int block_ct)
{
ccw->cmd_code = DASD_FBA_CCW_LOCATE;
ccw->flags = 0;
ccw->count = 8;
ccw->cda = (__u32) __pa(data);
memset(data, 0, sizeof (struct LO_fba_data));
if (rw == WRITE)
data->operation.cmd = 0x5;
else if (rw == READ)
data->operation.cmd = 0x6;
else
data->operation.cmd = 0x8;
data->blk_nr = block_nr;
data->blk_ct = block_ct;
}
static int
dasd_fba_check_characteristics(struct dasd_device *device)
{
struct dasd_block *block;
struct dasd_fba_private *private;
struct ccw_device *cdev = device->cdev;
int rc;
int readonly;
private = (struct dasd_fba_private *) device->private;
if (!private) {
private = kzalloc(sizeof(*private), GFP_KERNEL | GFP_DMA);
if (!private) {
dev_warn(&device->cdev->dev,
"Allocating memory for private DASD "
"data failed\n");
return -ENOMEM;
}
device->private = (void *) private;
} else {
memset(private, 0, sizeof(*private));
}
block = dasd_alloc_block();
if (IS_ERR(block)) {
DBF_EVENT_DEVID(DBF_WARNING, cdev, "%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 */
rc = dasd_generic_read_dev_chars(device, DASD_FBA_MAGIC,
&private->rdc_data, 32);
if (rc) {
DBF_EVENT_DEVID(DBF_WARNING, cdev, "Read device "
"characteristics returned error %d", rc);
device->block = NULL;
dasd_free_block(block);
device->private = NULL;
kfree(private);
return rc;
}
device->default_expires = DASD_EXPIRES;
device->default_retries = FBA_DEFAULT_RETRIES;
device->path_data.opm = LPM_ANYPATH;
readonly = dasd_device_is_ro(device);
if (readonly)
set_bit(DASD_FLAG_DEVICE_RO, &device->flags);
dev_info(&device->cdev->dev,
"New FBA DASD %04X/%02X (CU %04X/%02X) with %d MB "
"and %d B/blk%s\n",
cdev->id.dev_type,
cdev->id.dev_model,
cdev->id.cu_type,
cdev->id.cu_model,
((private->rdc_data.blk_bdsa *
(private->rdc_data.blk_size >> 9)) >> 11),
private->rdc_data.blk_size,
readonly ? ", read-only device" : "");
return 0;
}
static int dasd_fba_do_analysis(struct dasd_block *block)
{
struct dasd_fba_private *private;
int sb, rc;
private = (struct dasd_fba_private *) block->base->private;
rc = dasd_check_blocksize(private->rdc_data.blk_size);
if (rc) {
DBF_DEV_EVENT(DBF_WARNING, block->base, "unknown blocksize %d",
private->rdc_data.blk_size);
return rc;
}
block->blocks = private->rdc_data.blk_bdsa;
block->bp_block = private->rdc_data.blk_size;
block->s2b_shift = 0; /* bits to shift 512 to get a block */
for (sb = 512; sb < private->rdc_data.blk_size; sb = sb << 1)
block->s2b_shift++;
return 0;
}
static int dasd_fba_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_fba_erp_action(struct dasd_ccw_req * cqr)
{
return dasd_default_erp_action;
}
static dasd_erp_fn_t
dasd_fba_erp_postaction(struct dasd_ccw_req * cqr)
{
if (cqr->function == dasd_default_erp_action)
return dasd_default_erp_postaction;
DBF_DEV_EVENT(DBF_WARNING, cqr->startdev, "unknown ERP action %p",
cqr->function);
return NULL;
}
static void dasd_fba_check_for_device_change(struct dasd_device *device,
struct dasd_ccw_req *cqr,
struct irb *irb)
{
char mask;
/* first of all check for state change pending interrupt */
mask = DEV_STAT_ATTENTION | DEV_STAT_DEV_END | DEV_STAT_UNIT_EXCEP;
if ((irb->scsw.cmd.dstat & mask) == mask)
dasd_generic_handle_state_change(device);
};
static struct dasd_ccw_req *dasd_fba_build_cp(struct dasd_device * memdev,
struct dasd_block *block,
struct request *req)
{
struct dasd_fba_private *private;
unsigned long *idaws;
struct LO_fba_data *LO_data;
struct dasd_ccw_req *cqr;
struct ccw1 *ccw;
struct req_iterator iter;
struct bio_vec bv;
char *dst;
int count, cidaw, cplength, datasize;
sector_t recid, first_rec, last_rec;
unsigned int blksize, off;
unsigned char cmd;
private = (struct dasd_fba_private *) block->base->private;
if (rq_data_dir(req) == READ) {
cmd = DASD_FBA_CCW_READ;
} else if (rq_data_dir(req) == WRITE) {
cmd = DASD_FBA_CCW_WRITE;
} 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;
cidaw = 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);
if (idal_is_needed (page_address(bv.bv_page), bv.bv_len))
cidaw += bv.bv_len / blksize;
}
/* Paranoia. */
if (count != last_rec - first_rec + 1)
return ERR_PTR(-EINVAL);
/* 1x define extent + 1x locate record + number of blocks */
cplength = 2 + count;
/* 1x define extent + 1x locate record */
datasize = sizeof(struct DE_fba_data) + sizeof(struct LO_fba_data) +
cidaw * sizeof(unsigned long);
/*
* Find out number of additional locate record ccws if the device
* can't do data chaining.
*/
if (private->rdc_data.mode.bits.data_chain == 0) {
cplength += count - 1;
datasize += (count - 1)*sizeof(struct LO_fba_data);
}
/* Allocate the ccw request. */
cqr = dasd_smalloc_request(DASD_FBA_MAGIC, cplength, datasize, memdev);
if (IS_ERR(cqr))
return cqr;
ccw = cqr->cpaddr;
/* First ccw is define extent. */
define_extent(ccw++, cqr->data, rq_data_dir(req),
block->bp_block, blk_rq_pos(req), blk_rq_sectors(req));
/* Build locate_record + read/write ccws. */
idaws = (unsigned long *) (cqr->data + sizeof(struct DE_fba_data));
LO_data = (struct LO_fba_data *) (idaws + cidaw);
/* Locate record for all blocks for smart devices. */
if (private->rdc_data.mode.bits.data_chain != 0) {
ccw[-1].flags |= CCW_FLAG_CC;
locate_record(ccw++, LO_data++, rq_data_dir(req), 0, count);
}
recid = first_rec;
rq_for_each_segment(bv, req, iter) {
dst = page_address(bv.bv_page) + bv.bv_offset;
if (dasd_page_cache) {
char *copy = kmem_cache_alloc(dasd_page_cache,
GFP_DMA | __GFP_NOWARN);
if (copy && rq_data_dir(req) == WRITE)
memcpy(copy + bv.bv_offset, dst, bv.bv_len);
if (copy)
dst = copy + bv.bv_offset;
}
for (off = 0; off < bv.bv_len; off += blksize) {
/* Locate record for stupid devices. */
if (private->rdc_data.mode.bits.data_chain == 0) {
ccw[-1].flags |= CCW_FLAG_CC;
locate_record(ccw, LO_data++,
rq_data_dir(req),
recid - first_rec, 1);
ccw->flags = CCW_FLAG_CC;
ccw++;
} else {
if (recid > first_rec)
ccw[-1].flags |= CCW_FLAG_DC;
else
ccw[-1].flags |= CCW_FLAG_CC;
}
ccw->cmd_code = cmd;
ccw->count = block->bp_block;
if (idal_is_needed(dst, blksize)) {
ccw->cda = (__u32)(addr_t) idaws;
ccw->flags = CCW_FLAG_IDA;
idaws = idal_create_words(idaws, dst, blksize);
} else {
ccw->cda = (__u32)(addr_t) dst;
ccw->flags = 0;
}
ccw++;
dst += blksize;
recid++;
}
}
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; /* default 5 minutes */
cqr->retries = memdev->default_retries;
cqr->buildclk = get_tod_clock();
cqr->status = DASD_CQR_FILLED;
return cqr;
}
static int
dasd_fba_free_cp(struct dasd_ccw_req *cqr, struct request *req)
{
struct dasd_fba_private *private;
struct ccw1 *ccw;
struct req_iterator iter;
struct bio_vec bv;
char *dst, *cda;
unsigned int blksize, off;
int status;
if (!dasd_page_cache)
goto out;
private = (struct dasd_fba_private *) cqr->block->base->private;
blksize = cqr->block->bp_block;
ccw = cqr->cpaddr;
/* Skip over define extent & locate record. */
ccw++;
if (private->rdc_data.mode.bits.data_chain != 0)
ccw++;
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) {
/* Skip locate record. */
if (private->rdc_data.mode.bits.data_chain == 0)
ccw++;
if (dst) {
if (ccw->flags & CCW_FLAG_IDA)
cda = *((char **)((addr_t) ccw->cda));
else
cda = (char *)((addr_t) ccw->cda);
if (dst != cda) {
if (rq_data_dir(req) == READ)
memcpy(dst, cda, bv.bv_len);
kmem_cache_free(dasd_page_cache,
(void *)((addr_t)cda & PAGE_MASK));
}
dst = NULL;
}
ccw++;
}
}
out:
status = cqr->status == DASD_CQR_DONE;
dasd_sfree_request(cqr, cqr->memdev);
return status;
}
static void dasd_fba_handle_terminated_request(struct dasd_ccw_req *cqr)
{
if (cqr->retries < 0)
cqr->status = DASD_CQR_FAILED;
else
cqr->status = DASD_CQR_FILLED;
};
static int
dasd_fba_fill_info(struct dasd_device * device,
struct dasd_information2_t * info)
{
info->label_block = 1;
info->FBA_layout = 1;
info->format = DASD_FORMAT_LDL;
info->characteristics_size = sizeof(struct dasd_fba_characteristics);
memcpy(info->characteristics,
&((struct dasd_fba_private *) device->private)->rdc_data,
sizeof (struct dasd_fba_characteristics));
info->confdata_size = 0;
return 0;
}
static void
dasd_fba_dump_sense_dbf(struct dasd_device *device, struct irb *irb,
char *reason)
{
u64 *sense;
sense = (u64 *) dasd_get_sense(irb);
if (sense) {
DBF_DEV_EVENT(DBF_EMERG, device,
"%s: %s %02x%02x%02x %016llx %016llx %016llx "
"%016llx", reason,
scsw_is_tm(&irb->scsw) ? "t" : "c",
scsw_cc(&irb->scsw), scsw_cstat(&irb->scsw),
scsw_dstat(&irb->scsw), sense[0], sense[1],
sense[2], sense[3]);
} else {
DBF_DEV_EVENT(DBF_EMERG, device, "%s",
"SORRY - NO VALID SENSE AVAILABLE\n");
}
}
static void
dasd_fba_dump_sense(struct dasd_device *device, struct dasd_ccw_req * req,
struct irb *irb)
{
char *page;
struct ccw1 *act, *end, *last;
int len, sl, sct, count;
page = (char *) get_zeroed_page(GFP_ATOMIC);
if (page == NULL) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"No memory to dump sense data");
return;
}
len = sprintf(page, PRINTK_HEADER
" I/O status report for device %s:\n",
dev_name(&device->cdev->dev));
len += sprintf(page + len, PRINTK_HEADER
" in req: %p CS: 0x%02X DS: 0x%02X\n", req,
irb->scsw.cmd.cstat, irb->scsw.cmd.dstat);
len += sprintf(page + len, PRINTK_HEADER
" device %s: Failing CCW: %p\n",
dev_name(&device->cdev->dev),
(void *) (addr_t) irb->scsw.cmd.cpa);
if (irb->esw.esw0.erw.cons) {
for (sl = 0; sl < 4; sl++) {
len += sprintf(page + len, PRINTK_HEADER
" Sense(hex) %2d-%2d:",
(8 * sl), ((8 * sl) + 7));
for (sct = 0; sct < 8; sct++) {
len += sprintf(page + len, " %02x",
irb->ecw[8 * sl + sct]);
}
len += sprintf(page + len, "\n");
}
} else {
len += sprintf(page + len, PRINTK_HEADER
" SORRY - NO VALID SENSE AVAILABLE\n");
}
printk(KERN_ERR "%s", page);
/* dump the Channel Program */
/* print first CCWs (maximum 8) */
act = req->cpaddr;
for (last = act; last->flags & (CCW_FLAG_CC | CCW_FLAG_DC); last++);
end = min(act + 8, last);
len = sprintf(page, PRINTK_HEADER " Related CP in req: %p\n", req);
while (act <= end) {
len += sprintf(page + len, PRINTK_HEADER
" CCW %p: %08X %08X DAT:",
act, ((int *) act)[0], ((int *) act)[1]);
for (count = 0; count < 32 && count < act->count;
count += sizeof(int))
len += sprintf(page + len, " %08X",
((int *) (addr_t) act->cda)
[(count>>2)]);
len += sprintf(page + len, "\n");
act++;
}
printk(KERN_ERR "%s", page);
/* print failing CCW area */
len = 0;
if (act < ((struct ccw1 *)(addr_t) irb->scsw.cmd.cpa) - 2) {
act = ((struct ccw1 *)(addr_t) irb->scsw.cmd.cpa) - 2;
len += sprintf(page + len, PRINTK_HEADER "......\n");
}
end = min((struct ccw1 *)(addr_t) irb->scsw.cmd.cpa + 2, last);
while (act <= end) {
len += sprintf(page + len, PRINTK_HEADER
" CCW %p: %08X %08X DAT:",
act, ((int *) act)[0], ((int *) act)[1]);
for (count = 0; count < 32 && count < act->count;
count += sizeof(int))
len += sprintf(page + len, " %08X",
((int *) (addr_t) act->cda)
[(count>>2)]);
len += sprintf(page + len, "\n");
act++;
}
/* print last CCWs */
if (act < last - 2) {
act = last - 2;
len += sprintf(page + len, PRINTK_HEADER "......\n");
}
while (act <= last) {
len += sprintf(page + len, PRINTK_HEADER
" CCW %p: %08X %08X DAT:",
act, ((int *) act)[0], ((int *) act)[1]);
for (count = 0; count < 32 && count < act->count;
count += sizeof(int))
len += sprintf(page + len, " %08X",
((int *) (addr_t) act->cda)
[(count>>2)]);
len += sprintf(page + len, "\n");
act++;
}
if (len > 0)
printk(KERN_ERR "%s", page);
free_page((unsigned long) page);
}
/*
* max_blocks is dependent on the amount of storage that is available
* in the static io buffer for each device. Currently each device has
* 8192 bytes (=2 pages). For 64 bit one dasd_mchunkt_t structure has
* 24 bytes, the struct dasd_ccw_req has 136 bytes and each block can use
* up to 16 bytes (8 for the ccw and 8 for the idal pointer). In
* addition we have one define extent ccw + 16 bytes of data and a
* locate record ccw for each block (stupid devices!) + 16 bytes of data.
* That makes:
* (8192 - 24 - 136 - 8 - 16) / 40 = 200.2 blocks at maximum.
* We want to fit two into the available memory so that we can immediately
* start the next request if one finishes off. That makes 100.1 blocks
* for one request. Give a little safety and the result is 96.
*/
static struct dasd_discipline dasd_fba_discipline = {
.owner = THIS_MODULE,
.name = "FBA ",
.ebcname = "FBA ",
.max_blocks = 96,
.check_device = dasd_fba_check_characteristics,
.do_analysis = dasd_fba_do_analysis,
.verify_path = dasd_generic_verify_path,
.fill_geometry = dasd_fba_fill_geometry,
.start_IO = dasd_start_IO,
.term_IO = dasd_term_IO,
.handle_terminated_request = dasd_fba_handle_terminated_request,
.erp_action = dasd_fba_erp_action,
.erp_postaction = dasd_fba_erp_postaction,
.check_for_device_change = dasd_fba_check_for_device_change,
.build_cp = dasd_fba_build_cp,
.free_cp = dasd_fba_free_cp,
.dump_sense = dasd_fba_dump_sense,
.dump_sense_dbf = dasd_fba_dump_sense_dbf,
.fill_info = dasd_fba_fill_info,
};
static int __init
dasd_fba_init(void)
{
int ret;
ASCEBC(dasd_fba_discipline.ebcname, 4);
ret = ccw_driver_register(&dasd_fba_driver);
if (!ret)
wait_for_device_probe();
return ret;
}
static void __exit
dasd_fba_cleanup(void)
{
ccw_driver_unregister(&dasd_fba_driver);
}
module_init(dasd_fba_init);
module_exit(dasd_fba_cleanup);
| gpl-2.0 |
jmztaylor/android_kernel_htc_m4 | drivers/net/can/flexcan.c | 1069 | 27181 | /*
* flexcan.c - FLEXCAN CAN controller driver
*
* Copyright (c) 2005-2006 Varma Electronics Oy
* Copyright (c) 2009 Sascha Hauer, Pengutronix
* Copyright (c) 2010 Marc Kleine-Budde, Pengutronix
*
* Based on code originally by Andrey Volkov <avolkov@varma-el.com>
*
* LICENCE:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/netdevice.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include <linux/can/platform/flexcan.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#define DRV_NAME "flexcan"
/* 8 for RX fifo and 2 error handling */
#define FLEXCAN_NAPI_WEIGHT (8 + 2)
/* FLEXCAN module configuration register (CANMCR) bits */
#define FLEXCAN_MCR_MDIS BIT(31)
#define FLEXCAN_MCR_FRZ BIT(30)
#define FLEXCAN_MCR_FEN BIT(29)
#define FLEXCAN_MCR_HALT BIT(28)
#define FLEXCAN_MCR_NOT_RDY BIT(27)
#define FLEXCAN_MCR_WAK_MSK BIT(26)
#define FLEXCAN_MCR_SOFTRST BIT(25)
#define FLEXCAN_MCR_FRZ_ACK BIT(24)
#define FLEXCAN_MCR_SUPV BIT(23)
#define FLEXCAN_MCR_SLF_WAK BIT(22)
#define FLEXCAN_MCR_WRN_EN BIT(21)
#define FLEXCAN_MCR_LPM_ACK BIT(20)
#define FLEXCAN_MCR_WAK_SRC BIT(19)
#define FLEXCAN_MCR_DOZE BIT(18)
#define FLEXCAN_MCR_SRX_DIS BIT(17)
#define FLEXCAN_MCR_BCC BIT(16)
#define FLEXCAN_MCR_LPRIO_EN BIT(13)
#define FLEXCAN_MCR_AEN BIT(12)
#define FLEXCAN_MCR_MAXMB(x) ((x) & 0xf)
#define FLEXCAN_MCR_IDAM_A (0 << 8)
#define FLEXCAN_MCR_IDAM_B (1 << 8)
#define FLEXCAN_MCR_IDAM_C (2 << 8)
#define FLEXCAN_MCR_IDAM_D (3 << 8)
/* FLEXCAN control register (CANCTRL) bits */
#define FLEXCAN_CTRL_PRESDIV(x) (((x) & 0xff) << 24)
#define FLEXCAN_CTRL_RJW(x) (((x) & 0x03) << 22)
#define FLEXCAN_CTRL_PSEG1(x) (((x) & 0x07) << 19)
#define FLEXCAN_CTRL_PSEG2(x) (((x) & 0x07) << 16)
#define FLEXCAN_CTRL_BOFF_MSK BIT(15)
#define FLEXCAN_CTRL_ERR_MSK BIT(14)
#define FLEXCAN_CTRL_CLK_SRC BIT(13)
#define FLEXCAN_CTRL_LPB BIT(12)
#define FLEXCAN_CTRL_TWRN_MSK BIT(11)
#define FLEXCAN_CTRL_RWRN_MSK BIT(10)
#define FLEXCAN_CTRL_SMP BIT(7)
#define FLEXCAN_CTRL_BOFF_REC BIT(6)
#define FLEXCAN_CTRL_TSYN BIT(5)
#define FLEXCAN_CTRL_LBUF BIT(4)
#define FLEXCAN_CTRL_LOM BIT(3)
#define FLEXCAN_CTRL_PROPSEG(x) ((x) & 0x07)
#define FLEXCAN_CTRL_ERR_BUS (FLEXCAN_CTRL_ERR_MSK)
#define FLEXCAN_CTRL_ERR_STATE \
(FLEXCAN_CTRL_TWRN_MSK | FLEXCAN_CTRL_RWRN_MSK | \
FLEXCAN_CTRL_BOFF_MSK)
#define FLEXCAN_CTRL_ERR_ALL \
(FLEXCAN_CTRL_ERR_BUS | FLEXCAN_CTRL_ERR_STATE)
/* FLEXCAN error and status register (ESR) bits */
#define FLEXCAN_ESR_TWRN_INT BIT(17)
#define FLEXCAN_ESR_RWRN_INT BIT(16)
#define FLEXCAN_ESR_BIT1_ERR BIT(15)
#define FLEXCAN_ESR_BIT0_ERR BIT(14)
#define FLEXCAN_ESR_ACK_ERR BIT(13)
#define FLEXCAN_ESR_CRC_ERR BIT(12)
#define FLEXCAN_ESR_FRM_ERR BIT(11)
#define FLEXCAN_ESR_STF_ERR BIT(10)
#define FLEXCAN_ESR_TX_WRN BIT(9)
#define FLEXCAN_ESR_RX_WRN BIT(8)
#define FLEXCAN_ESR_IDLE BIT(7)
#define FLEXCAN_ESR_TXRX BIT(6)
#define FLEXCAN_EST_FLT_CONF_SHIFT (4)
#define FLEXCAN_ESR_FLT_CONF_MASK (0x3 << FLEXCAN_EST_FLT_CONF_SHIFT)
#define FLEXCAN_ESR_FLT_CONF_ACTIVE (0x0 << FLEXCAN_EST_FLT_CONF_SHIFT)
#define FLEXCAN_ESR_FLT_CONF_PASSIVE (0x1 << FLEXCAN_EST_FLT_CONF_SHIFT)
#define FLEXCAN_ESR_BOFF_INT BIT(2)
#define FLEXCAN_ESR_ERR_INT BIT(1)
#define FLEXCAN_ESR_WAK_INT BIT(0)
#define FLEXCAN_ESR_ERR_BUS \
(FLEXCAN_ESR_BIT1_ERR | FLEXCAN_ESR_BIT0_ERR | \
FLEXCAN_ESR_ACK_ERR | FLEXCAN_ESR_CRC_ERR | \
FLEXCAN_ESR_FRM_ERR | FLEXCAN_ESR_STF_ERR)
#define FLEXCAN_ESR_ERR_STATE \
(FLEXCAN_ESR_TWRN_INT | FLEXCAN_ESR_RWRN_INT | FLEXCAN_ESR_BOFF_INT)
#define FLEXCAN_ESR_ERR_ALL \
(FLEXCAN_ESR_ERR_BUS | FLEXCAN_ESR_ERR_STATE)
#define FLEXCAN_ESR_ALL_INT \
(FLEXCAN_ESR_TWRN_INT | FLEXCAN_ESR_RWRN_INT | \
FLEXCAN_ESR_BOFF_INT | FLEXCAN_ESR_ERR_INT)
/* FLEXCAN interrupt flag register (IFLAG) bits */
#define FLEXCAN_TX_BUF_ID 8
#define FLEXCAN_IFLAG_BUF(x) BIT(x)
#define FLEXCAN_IFLAG_RX_FIFO_OVERFLOW BIT(7)
#define FLEXCAN_IFLAG_RX_FIFO_WARN BIT(6)
#define FLEXCAN_IFLAG_RX_FIFO_AVAILABLE BIT(5)
#define FLEXCAN_IFLAG_DEFAULT \
(FLEXCAN_IFLAG_RX_FIFO_OVERFLOW | FLEXCAN_IFLAG_RX_FIFO_AVAILABLE | \
FLEXCAN_IFLAG_BUF(FLEXCAN_TX_BUF_ID))
/* FLEXCAN message buffers */
#define FLEXCAN_MB_CNT_CODE(x) (((x) & 0xf) << 24)
#define FLEXCAN_MB_CNT_SRR BIT(22)
#define FLEXCAN_MB_CNT_IDE BIT(21)
#define FLEXCAN_MB_CNT_RTR BIT(20)
#define FLEXCAN_MB_CNT_LENGTH(x) (((x) & 0xf) << 16)
#define FLEXCAN_MB_CNT_TIMESTAMP(x) ((x) & 0xffff)
#define FLEXCAN_MB_CODE_MASK (0xf0ffffff)
/* Structure of the message buffer */
struct flexcan_mb {
u32 can_ctrl;
u32 can_id;
u32 data[2];
};
/* Structure of the hardware registers */
struct flexcan_regs {
u32 mcr; /* 0x00 */
u32 ctrl; /* 0x04 */
u32 timer; /* 0x08 */
u32 _reserved1; /* 0x0c */
u32 rxgmask; /* 0x10 */
u32 rx14mask; /* 0x14 */
u32 rx15mask; /* 0x18 */
u32 ecr; /* 0x1c */
u32 esr; /* 0x20 */
u32 imask2; /* 0x24 */
u32 imask1; /* 0x28 */
u32 iflag2; /* 0x2c */
u32 iflag1; /* 0x30 */
u32 _reserved2[19];
struct flexcan_mb cantxfg[64];
};
struct flexcan_priv {
struct can_priv can;
struct net_device *dev;
struct napi_struct napi;
void __iomem *base;
u32 reg_esr;
u32 reg_ctrl_default;
struct clk *clk;
struct flexcan_platform_data *pdata;
};
static struct can_bittiming_const flexcan_bittiming_const = {
.name = DRV_NAME,
.tseg1_min = 4,
.tseg1_max = 16,
.tseg2_min = 2,
.tseg2_max = 8,
.sjw_max = 4,
.brp_min = 1,
.brp_max = 256,
.brp_inc = 1,
};
/*
* Abstract off the read/write for arm versus ppc.
*/
#if defined(__BIG_ENDIAN)
static inline u32 flexcan_read(void __iomem *addr)
{
return in_be32(addr);
}
static inline void flexcan_write(u32 val, void __iomem *addr)
{
out_be32(addr, val);
}
#else
static inline u32 flexcan_read(void __iomem *addr)
{
return readl(addr);
}
static inline void flexcan_write(u32 val, void __iomem *addr)
{
writel(val, addr);
}
#endif
/*
* Swtich transceiver on or off
*/
static void flexcan_transceiver_switch(const struct flexcan_priv *priv, int on)
{
if (priv->pdata && priv->pdata->transceiver_switch)
priv->pdata->transceiver_switch(on);
}
static inline int flexcan_has_and_handle_berr(const struct flexcan_priv *priv,
u32 reg_esr)
{
return (priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
(reg_esr & FLEXCAN_ESR_ERR_BUS);
}
static inline void flexcan_chip_enable(struct flexcan_priv *priv)
{
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
reg = flexcan_read(®s->mcr);
reg &= ~FLEXCAN_MCR_MDIS;
flexcan_write(reg, ®s->mcr);
udelay(10);
}
static inline void flexcan_chip_disable(struct flexcan_priv *priv)
{
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
reg = flexcan_read(®s->mcr);
reg |= FLEXCAN_MCR_MDIS;
flexcan_write(reg, ®s->mcr);
}
static int flexcan_get_berr_counter(const struct net_device *dev,
struct can_berr_counter *bec)
{
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg = flexcan_read(®s->ecr);
bec->txerr = (reg >> 0) & 0xff;
bec->rxerr = (reg >> 8) & 0xff;
return 0;
}
static int flexcan_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
struct can_frame *cf = (struct can_frame *)skb->data;
u32 can_id;
u32 ctrl = FLEXCAN_MB_CNT_CODE(0xc) | (cf->can_dlc << 16);
if (can_dropped_invalid_skb(dev, skb))
return NETDEV_TX_OK;
netif_stop_queue(dev);
if (cf->can_id & CAN_EFF_FLAG) {
can_id = cf->can_id & CAN_EFF_MASK;
ctrl |= FLEXCAN_MB_CNT_IDE | FLEXCAN_MB_CNT_SRR;
} else {
can_id = (cf->can_id & CAN_SFF_MASK) << 18;
}
if (cf->can_id & CAN_RTR_FLAG)
ctrl |= FLEXCAN_MB_CNT_RTR;
if (cf->can_dlc > 0) {
u32 data = be32_to_cpup((__be32 *)&cf->data[0]);
flexcan_write(data, ®s->cantxfg[FLEXCAN_TX_BUF_ID].data[0]);
}
if (cf->can_dlc > 3) {
u32 data = be32_to_cpup((__be32 *)&cf->data[4]);
flexcan_write(data, ®s->cantxfg[FLEXCAN_TX_BUF_ID].data[1]);
}
can_put_echo_skb(skb, dev, 0);
flexcan_write(can_id, ®s->cantxfg[FLEXCAN_TX_BUF_ID].can_id);
flexcan_write(ctrl, ®s->cantxfg[FLEXCAN_TX_BUF_ID].can_ctrl);
return NETDEV_TX_OK;
}
static void do_bus_err(struct net_device *dev,
struct can_frame *cf, u32 reg_esr)
{
struct flexcan_priv *priv = netdev_priv(dev);
int rx_errors = 0, tx_errors = 0;
cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
if (reg_esr & FLEXCAN_ESR_BIT1_ERR) {
netdev_dbg(dev, "BIT1_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_BIT1;
tx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_BIT0_ERR) {
netdev_dbg(dev, "BIT0_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_BIT0;
tx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_ACK_ERR) {
netdev_dbg(dev, "ACK_ERR irq\n");
cf->can_id |= CAN_ERR_ACK;
cf->data[3] |= CAN_ERR_PROT_LOC_ACK;
tx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_CRC_ERR) {
netdev_dbg(dev, "CRC_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_BIT;
cf->data[3] |= CAN_ERR_PROT_LOC_CRC_SEQ;
rx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_FRM_ERR) {
netdev_dbg(dev, "FRM_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_FORM;
rx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_STF_ERR) {
netdev_dbg(dev, "STF_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_STUFF;
rx_errors = 1;
}
priv->can.can_stats.bus_error++;
if (rx_errors)
dev->stats.rx_errors++;
if (tx_errors)
dev->stats.tx_errors++;
}
static int flexcan_poll_bus_err(struct net_device *dev, u32 reg_esr)
{
struct sk_buff *skb;
struct can_frame *cf;
skb = alloc_can_err_skb(dev, &cf);
if (unlikely(!skb))
return 0;
do_bus_err(dev, cf, reg_esr);
netif_receive_skb(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += cf->can_dlc;
return 1;
}
static void do_state(struct net_device *dev,
struct can_frame *cf, enum can_state new_state)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct can_berr_counter bec;
flexcan_get_berr_counter(dev, &bec);
switch (priv->can.state) {
case CAN_STATE_ERROR_ACTIVE:
/*
* from: ERROR_ACTIVE
* to : ERROR_WARNING, ERROR_PASSIVE, BUS_OFF
* => : there was a warning int
*/
if (new_state >= CAN_STATE_ERROR_WARNING &&
new_state <= CAN_STATE_BUS_OFF) {
netdev_dbg(dev, "Error Warning IRQ\n");
priv->can.can_stats.error_warning++;
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = (bec.txerr > bec.rxerr) ?
CAN_ERR_CRTL_TX_WARNING :
CAN_ERR_CRTL_RX_WARNING;
}
case CAN_STATE_ERROR_WARNING: /* fallthrough */
/*
* from: ERROR_ACTIVE, ERROR_WARNING
* to : ERROR_PASSIVE, BUS_OFF
* => : error passive int
*/
if (new_state >= CAN_STATE_ERROR_PASSIVE &&
new_state <= CAN_STATE_BUS_OFF) {
netdev_dbg(dev, "Error Passive IRQ\n");
priv->can.can_stats.error_passive++;
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = (bec.txerr > bec.rxerr) ?
CAN_ERR_CRTL_TX_PASSIVE :
CAN_ERR_CRTL_RX_PASSIVE;
}
break;
case CAN_STATE_BUS_OFF:
netdev_err(dev, "BUG! "
"hardware recovered automatically from BUS_OFF\n");
break;
default:
break;
}
/* process state changes depending on the new state */
switch (new_state) {
case CAN_STATE_ERROR_ACTIVE:
netdev_dbg(dev, "Error Active\n");
cf->can_id |= CAN_ERR_PROT;
cf->data[2] = CAN_ERR_PROT_ACTIVE;
break;
case CAN_STATE_BUS_OFF:
cf->can_id |= CAN_ERR_BUSOFF;
can_bus_off(dev);
break;
default:
break;
}
}
static int flexcan_poll_state(struct net_device *dev, u32 reg_esr)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct sk_buff *skb;
struct can_frame *cf;
enum can_state new_state;
int flt;
flt = reg_esr & FLEXCAN_ESR_FLT_CONF_MASK;
if (likely(flt == FLEXCAN_ESR_FLT_CONF_ACTIVE)) {
if (likely(!(reg_esr & (FLEXCAN_ESR_TX_WRN |
FLEXCAN_ESR_RX_WRN))))
new_state = CAN_STATE_ERROR_ACTIVE;
else
new_state = CAN_STATE_ERROR_WARNING;
} else if (unlikely(flt == FLEXCAN_ESR_FLT_CONF_PASSIVE))
new_state = CAN_STATE_ERROR_PASSIVE;
else
new_state = CAN_STATE_BUS_OFF;
/* state hasn't changed */
if (likely(new_state == priv->can.state))
return 0;
skb = alloc_can_err_skb(dev, &cf);
if (unlikely(!skb))
return 0;
do_state(dev, cf, new_state);
priv->can.state = new_state;
netif_receive_skb(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += cf->can_dlc;
return 1;
}
static void flexcan_read_fifo(const struct net_device *dev,
struct can_frame *cf)
{
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
struct flexcan_mb __iomem *mb = ®s->cantxfg[0];
u32 reg_ctrl, reg_id;
reg_ctrl = flexcan_read(&mb->can_ctrl);
reg_id = flexcan_read(&mb->can_id);
if (reg_ctrl & FLEXCAN_MB_CNT_IDE)
cf->can_id = ((reg_id >> 0) & CAN_EFF_MASK) | CAN_EFF_FLAG;
else
cf->can_id = (reg_id >> 18) & CAN_SFF_MASK;
if (reg_ctrl & FLEXCAN_MB_CNT_RTR)
cf->can_id |= CAN_RTR_FLAG;
cf->can_dlc = get_can_dlc((reg_ctrl >> 16) & 0xf);
*(__be32 *)(cf->data + 0) = cpu_to_be32(flexcan_read(&mb->data[0]));
*(__be32 *)(cf->data + 4) = cpu_to_be32(flexcan_read(&mb->data[1]));
/* mark as read */
flexcan_write(FLEXCAN_IFLAG_RX_FIFO_AVAILABLE, ®s->iflag1);
flexcan_read(®s->timer);
}
static int flexcan_read_frame(struct net_device *dev)
{
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
skb = alloc_can_skb(dev, &cf);
if (unlikely(!skb)) {
stats->rx_dropped++;
return 0;
}
flexcan_read_fifo(dev, cf);
netif_receive_skb(skb);
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
return 1;
}
static int flexcan_poll(struct napi_struct *napi, int quota)
{
struct net_device *dev = napi->dev;
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg_iflag1, reg_esr;
int work_done = 0;
/*
* The error bits are cleared on read,
* use saved value from irq handler.
*/
reg_esr = flexcan_read(®s->esr) | priv->reg_esr;
/* handle state changes */
work_done += flexcan_poll_state(dev, reg_esr);
/* handle RX-FIFO */
reg_iflag1 = flexcan_read(®s->iflag1);
while (reg_iflag1 & FLEXCAN_IFLAG_RX_FIFO_AVAILABLE &&
work_done < quota) {
work_done += flexcan_read_frame(dev);
reg_iflag1 = flexcan_read(®s->iflag1);
}
/* report bus errors */
if (flexcan_has_and_handle_berr(priv, reg_esr) && work_done < quota)
work_done += flexcan_poll_bus_err(dev, reg_esr);
if (work_done < quota) {
napi_complete(napi);
/* enable IRQs */
flexcan_write(FLEXCAN_IFLAG_DEFAULT, ®s->imask1);
flexcan_write(priv->reg_ctrl_default, ®s->ctrl);
}
return work_done;
}
static irqreturn_t flexcan_irq(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct net_device_stats *stats = &dev->stats;
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg_iflag1, reg_esr;
reg_iflag1 = flexcan_read(®s->iflag1);
reg_esr = flexcan_read(®s->esr);
/* ACK all bus error and state change IRQ sources */
if (reg_esr & FLEXCAN_ESR_ALL_INT)
flexcan_write(reg_esr & FLEXCAN_ESR_ALL_INT, ®s->esr);
/*
* schedule NAPI in case of:
* - rx IRQ
* - state change IRQ
* - bus error IRQ and bus error reporting is activated
*/
if ((reg_iflag1 & FLEXCAN_IFLAG_RX_FIFO_AVAILABLE) ||
(reg_esr & FLEXCAN_ESR_ERR_STATE) ||
flexcan_has_and_handle_berr(priv, reg_esr)) {
/*
* The error bits are cleared on read,
* save them for later use.
*/
priv->reg_esr = reg_esr & FLEXCAN_ESR_ERR_BUS;
flexcan_write(FLEXCAN_IFLAG_DEFAULT &
~FLEXCAN_IFLAG_RX_FIFO_AVAILABLE, ®s->imask1);
flexcan_write(priv->reg_ctrl_default & ~FLEXCAN_CTRL_ERR_ALL,
®s->ctrl);
napi_schedule(&priv->napi);
}
/* FIFO overflow */
if (reg_iflag1 & FLEXCAN_IFLAG_RX_FIFO_OVERFLOW) {
flexcan_write(FLEXCAN_IFLAG_RX_FIFO_OVERFLOW, ®s->iflag1);
dev->stats.rx_over_errors++;
dev->stats.rx_errors++;
}
/* transmission complete interrupt */
if (reg_iflag1 & (1 << FLEXCAN_TX_BUF_ID)) {
stats->tx_bytes += can_get_echo_skb(dev, 0);
stats->tx_packets++;
flexcan_write((1 << FLEXCAN_TX_BUF_ID), ®s->iflag1);
netif_wake_queue(dev);
}
return IRQ_HANDLED;
}
static void flexcan_set_bittiming(struct net_device *dev)
{
const struct flexcan_priv *priv = netdev_priv(dev);
const struct can_bittiming *bt = &priv->can.bittiming;
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
reg = flexcan_read(®s->ctrl);
reg &= ~(FLEXCAN_CTRL_PRESDIV(0xff) |
FLEXCAN_CTRL_RJW(0x3) |
FLEXCAN_CTRL_PSEG1(0x7) |
FLEXCAN_CTRL_PSEG2(0x7) |
FLEXCAN_CTRL_PROPSEG(0x7) |
FLEXCAN_CTRL_LPB |
FLEXCAN_CTRL_SMP |
FLEXCAN_CTRL_LOM);
reg |= FLEXCAN_CTRL_PRESDIV(bt->brp - 1) |
FLEXCAN_CTRL_PSEG1(bt->phase_seg1 - 1) |
FLEXCAN_CTRL_PSEG2(bt->phase_seg2 - 1) |
FLEXCAN_CTRL_RJW(bt->sjw - 1) |
FLEXCAN_CTRL_PROPSEG(bt->prop_seg - 1);
if (priv->can.ctrlmode & CAN_CTRLMODE_LOOPBACK)
reg |= FLEXCAN_CTRL_LPB;
if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
reg |= FLEXCAN_CTRL_LOM;
if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
reg |= FLEXCAN_CTRL_SMP;
netdev_info(dev, "writing ctrl=0x%08x\n", reg);
flexcan_write(reg, ®s->ctrl);
/* print chip status */
netdev_dbg(dev, "%s: mcr=0x%08x ctrl=0x%08x\n", __func__,
flexcan_read(®s->mcr), flexcan_read(®s->ctrl));
}
/*
* flexcan_chip_start
*
* this functions is entered with clocks enabled
*
*/
static int flexcan_chip_start(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
unsigned int i;
int err;
u32 reg_mcr, reg_ctrl;
/* enable module */
flexcan_chip_enable(priv);
/* soft reset */
flexcan_write(FLEXCAN_MCR_SOFTRST, ®s->mcr);
udelay(10);
reg_mcr = flexcan_read(®s->mcr);
if (reg_mcr & FLEXCAN_MCR_SOFTRST) {
netdev_err(dev, "Failed to softreset can module (mcr=0x%08x)\n",
reg_mcr);
err = -ENODEV;
goto out;
}
flexcan_set_bittiming(dev);
/*
* MCR
*
* enable freeze
* enable fifo
* halt now
* only supervisor access
* enable warning int
* choose format C
* disable local echo
*
*/
reg_mcr = flexcan_read(®s->mcr);
reg_mcr |= FLEXCAN_MCR_FRZ | FLEXCAN_MCR_FEN | FLEXCAN_MCR_HALT |
FLEXCAN_MCR_SUPV | FLEXCAN_MCR_WRN_EN |
FLEXCAN_MCR_IDAM_C | FLEXCAN_MCR_SRX_DIS;
netdev_dbg(dev, "%s: writing mcr=0x%08x", __func__, reg_mcr);
flexcan_write(reg_mcr, ®s->mcr);
/*
* CTRL
*
* disable timer sync feature
*
* disable auto busoff recovery
* transmit lowest buffer first
*
* enable tx and rx warning interrupt
* enable bus off interrupt
* (== FLEXCAN_CTRL_ERR_STATE)
*
* _note_: we enable the "error interrupt"
* (FLEXCAN_CTRL_ERR_MSK), too. Otherwise we don't get any
* warning or bus passive interrupts.
*/
reg_ctrl = flexcan_read(®s->ctrl);
reg_ctrl &= ~FLEXCAN_CTRL_TSYN;
reg_ctrl |= FLEXCAN_CTRL_BOFF_REC | FLEXCAN_CTRL_LBUF |
FLEXCAN_CTRL_ERR_STATE | FLEXCAN_CTRL_ERR_MSK;
/* save for later use */
priv->reg_ctrl_default = reg_ctrl;
netdev_dbg(dev, "%s: writing ctrl=0x%08x", __func__, reg_ctrl);
flexcan_write(reg_ctrl, ®s->ctrl);
for (i = 0; i < ARRAY_SIZE(regs->cantxfg); i++) {
flexcan_write(0, ®s->cantxfg[i].can_ctrl);
flexcan_write(0, ®s->cantxfg[i].can_id);
flexcan_write(0, ®s->cantxfg[i].data[0]);
flexcan_write(0, ®s->cantxfg[i].data[1]);
/* put MB into rx queue */
flexcan_write(FLEXCAN_MB_CNT_CODE(0x4),
®s->cantxfg[i].can_ctrl);
}
/* acceptance mask/acceptance code (accept everything) */
flexcan_write(0x0, ®s->rxgmask);
flexcan_write(0x0, ®s->rx14mask);
flexcan_write(0x0, ®s->rx15mask);
flexcan_transceiver_switch(priv, 1);
/* synchronize with the can bus */
reg_mcr = flexcan_read(®s->mcr);
reg_mcr &= ~FLEXCAN_MCR_HALT;
flexcan_write(reg_mcr, ®s->mcr);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
/* enable FIFO interrupts */
flexcan_write(FLEXCAN_IFLAG_DEFAULT, ®s->imask1);
/* print chip status */
netdev_dbg(dev, "%s: reading mcr=0x%08x ctrl=0x%08x\n", __func__,
flexcan_read(®s->mcr), flexcan_read(®s->ctrl));
return 0;
out:
flexcan_chip_disable(priv);
return err;
}
/*
* flexcan_chip_stop
*
* this functions is entered with clocks enabled
*
*/
static void flexcan_chip_stop(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
/* Disable all interrupts */
flexcan_write(0, ®s->imask1);
/* Disable + halt module */
reg = flexcan_read(®s->mcr);
reg |= FLEXCAN_MCR_MDIS | FLEXCAN_MCR_HALT;
flexcan_write(reg, ®s->mcr);
flexcan_transceiver_switch(priv, 0);
priv->can.state = CAN_STATE_STOPPED;
return;
}
static int flexcan_open(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
int err;
clk_prepare_enable(priv->clk);
err = open_candev(dev);
if (err)
goto out;
err = request_irq(dev->irq, flexcan_irq, IRQF_SHARED, dev->name, dev);
if (err)
goto out_close;
/* start chip and queuing */
err = flexcan_chip_start(dev);
if (err)
goto out_close;
napi_enable(&priv->napi);
netif_start_queue(dev);
return 0;
out_close:
close_candev(dev);
out:
clk_disable_unprepare(priv->clk);
return err;
}
static int flexcan_close(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
netif_stop_queue(dev);
napi_disable(&priv->napi);
flexcan_chip_stop(dev);
free_irq(dev->irq, dev);
clk_disable_unprepare(priv->clk);
close_candev(dev);
return 0;
}
static int flexcan_set_mode(struct net_device *dev, enum can_mode mode)
{
int err;
switch (mode) {
case CAN_MODE_START:
err = flexcan_chip_start(dev);
if (err)
return err;
netif_wake_queue(dev);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static const struct net_device_ops flexcan_netdev_ops = {
.ndo_open = flexcan_open,
.ndo_stop = flexcan_close,
.ndo_start_xmit = flexcan_start_xmit,
};
static int __devinit register_flexcandev(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg, err;
clk_prepare_enable(priv->clk);
/* select "bus clock", chip must be disabled */
flexcan_chip_disable(priv);
reg = flexcan_read(®s->ctrl);
reg |= FLEXCAN_CTRL_CLK_SRC;
flexcan_write(reg, ®s->ctrl);
flexcan_chip_enable(priv);
/* set freeze, halt and activate FIFO, restrict register access */
reg = flexcan_read(®s->mcr);
reg |= FLEXCAN_MCR_FRZ | FLEXCAN_MCR_HALT |
FLEXCAN_MCR_FEN | FLEXCAN_MCR_SUPV;
flexcan_write(reg, ®s->mcr);
/*
* Currently we only support newer versions of this core
* featuring a RX FIFO. Older cores found on some Coldfire
* derivates are not yet supported.
*/
reg = flexcan_read(®s->mcr);
if (!(reg & FLEXCAN_MCR_FEN)) {
netdev_err(dev, "Could not enable RX FIFO, unsupported core\n");
err = -ENODEV;
goto out;
}
err = register_candev(dev);
out:
/* disable core and turn off clocks */
flexcan_chip_disable(priv);
clk_disable_unprepare(priv->clk);
return err;
}
static void __devexit unregister_flexcandev(struct net_device *dev)
{
unregister_candev(dev);
}
static int __devinit flexcan_probe(struct platform_device *pdev)
{
struct net_device *dev;
struct flexcan_priv *priv;
struct resource *mem;
struct clk *clk = NULL;
void __iomem *base;
resource_size_t mem_size;
int err, irq;
u32 clock_freq = 0;
if (pdev->dev.of_node) {
const __be32 *clock_freq_p;
clock_freq_p = of_get_property(pdev->dev.of_node,
"clock-frequency", NULL);
if (clock_freq_p)
clock_freq = be32_to_cpup(clock_freq_p);
}
if (!clock_freq) {
clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "no clock defined\n");
err = PTR_ERR(clk);
goto failed_clock;
}
clock_freq = clk_get_rate(clk);
}
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (!mem || irq <= 0) {
err = -ENODEV;
goto failed_get;
}
mem_size = resource_size(mem);
if (!request_mem_region(mem->start, mem_size, pdev->name)) {
err = -EBUSY;
goto failed_get;
}
base = ioremap(mem->start, mem_size);
if (!base) {
err = -ENOMEM;
goto failed_map;
}
dev = alloc_candev(sizeof(struct flexcan_priv), 1);
if (!dev) {
err = -ENOMEM;
goto failed_alloc;
}
dev->netdev_ops = &flexcan_netdev_ops;
dev->irq = irq;
dev->flags |= IFF_ECHO;
priv = netdev_priv(dev);
priv->can.clock.freq = clock_freq;
priv->can.bittiming_const = &flexcan_bittiming_const;
priv->can.do_set_mode = flexcan_set_mode;
priv->can.do_get_berr_counter = flexcan_get_berr_counter;
priv->can.ctrlmode_supported = CAN_CTRLMODE_LOOPBACK |
CAN_CTRLMODE_LISTENONLY | CAN_CTRLMODE_3_SAMPLES |
CAN_CTRLMODE_BERR_REPORTING;
priv->base = base;
priv->dev = dev;
priv->clk = clk;
priv->pdata = pdev->dev.platform_data;
netif_napi_add(dev, &priv->napi, flexcan_poll, FLEXCAN_NAPI_WEIGHT);
dev_set_drvdata(&pdev->dev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
err = register_flexcandev(dev);
if (err) {
dev_err(&pdev->dev, "registering netdev failed\n");
goto failed_register;
}
dev_info(&pdev->dev, "device registered (reg_base=%p, irq=%d)\n",
priv->base, dev->irq);
return 0;
failed_register:
free_candev(dev);
failed_alloc:
iounmap(base);
failed_map:
release_mem_region(mem->start, mem_size);
failed_get:
if (clk)
clk_put(clk);
failed_clock:
return err;
}
static int __devexit flexcan_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct flexcan_priv *priv = netdev_priv(dev);
struct resource *mem;
unregister_flexcandev(dev);
platform_set_drvdata(pdev, NULL);
iounmap(priv->base);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, resource_size(mem));
if (priv->clk)
clk_put(priv->clk);
free_candev(dev);
return 0;
}
static struct of_device_id flexcan_of_match[] = {
{
.compatible = "fsl,p1010-flexcan",
},
{},
};
static struct platform_driver flexcan_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = flexcan_of_match,
},
.probe = flexcan_probe,
.remove = __devexit_p(flexcan_remove),
};
module_platform_driver(flexcan_driver);
MODULE_AUTHOR("Sascha Hauer <kernel@pengutronix.de>, "
"Marc Kleine-Budde <kernel@pengutronix.de>");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("CAN port driver for flexcan based chip");
| gpl-2.0 |
Galaxy-J5/android_kernel_samsung_j5nlte | fs/proc/array.c | 1325 | 18866 | /*
* linux/fs/proc/array.c
*
* Copyright (C) 1992 by Linus Torvalds
* based on ideas by Darren Senn
*
* Fixes:
* Michael. K. Johnson: stat,statm extensions.
* <johnsonm@stolaf.edu>
*
* Pauline Middelink : Made cmdline,envline only break at '\0's, to
* make sure SET_PROCTITLE works. Also removed
* bad '!' which forced address recalculation for
* EVERY character on the current page.
* <middelin@polyware.iaf.nl>
*
* Danny ter Haar : added cpuinfo
* <dth@cistron.nl>
*
* Alessandro Rubini : profile extension.
* <rubini@ipvvis.unipv.it>
*
* Jeff Tranter : added BogoMips field to cpuinfo
* <Jeff_Tranter@Mitel.COM>
*
* Bruno Haible : remove 4K limit for the maps file
* <haible@ma2s2.mathematik.uni-karlsruhe.de>
*
* Yves Arrouye : remove removal of trailing spaces in get_array.
* <Yves.Arrouye@marin.fdn.fr>
*
* Jerome Forissier : added per-CPU time information to /proc/stat
* and /proc/<pid>/cpu extension
* <forissier@isia.cma.fr>
* - Incorporation and non-SMP safe operation
* of forissier patch in 2.1.78 by
* Hans Marcus <crowbar@concepts.nl>
*
* aeb@cwi.nl : /proc/partitions
*
*
* Alan Cox : security fixes.
* <alan@lxorguk.ukuu.org.uk>
*
* Al Viro : safe handling of mm_struct
*
* Gerhard Wichert : added BIGMEM support
* Siemens AG <Gerhard.Wichert@pdb.siemens.de>
*
* Al Viro & Jeff Garzik : moved most of the thing into base.c and
* : proc_misc.c. The rest may eventually go into
* : base.c too.
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/kernel_stat.h>
#include <linux/tty.h>
#include <linux/string.h>
#include <linux/mman.h>
#include <linux/proc_fs.h>
#include <linux/ioport.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/smp.h>
#include <linux/signal.h>
#include <linux/highmem.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/times.h>
#include <linux/cpuset.h>
#include <linux/rcupdate.h>
#include <linux/delayacct.h>
#include <linux/seq_file.h>
#include <linux/pid_namespace.h>
#include <linux/ptrace.h>
#include <linux/tracehook.h>
#include <linux/user_namespace.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include "internal.h"
static inline void task_name(struct seq_file *m, struct task_struct *p)
{
int i;
char *buf, *end;
char *name;
char tcomm[sizeof(p->comm)];
get_task_comm(tcomm, p);
seq_puts(m, "Name:\t");
end = m->buf + m->size;
buf = m->buf + m->count;
name = tcomm;
i = sizeof(tcomm);
while (i && (buf < end)) {
unsigned char c = *name;
name++;
i--;
*buf = c;
if (!c)
break;
if (c == '\\') {
buf++;
if (buf < end)
*buf++ = c;
continue;
}
if (c == '\n') {
*buf++ = '\\';
if (buf < end)
*buf++ = 'n';
continue;
}
buf++;
}
m->count = buf - m->buf;
seq_putc(m, '\n');
}
/*
* The task state array is a strange "bitmap" of
* reasons to sleep. Thus "running" is zero, and
* you can test for combinations of others with
* simple bit tests.
*/
static const char * const task_state_array[] = {
"R (running)", /* 0 */
"S (sleeping)", /* 1 */
"D (disk sleep)", /* 2 */
"T (stopped)", /* 4 */
"t (tracing stop)", /* 8 */
"Z (zombie)", /* 16 */
"X (dead)", /* 32 */
"x (dead)", /* 64 */
"K (wakekill)", /* 128 */
"W (waking)", /* 256 */
"P (parked)", /* 512 */
};
static inline const char *get_task_state(struct task_struct *tsk)
{
unsigned int state = (tsk->state & TASK_REPORT) | tsk->exit_state;
const char * const *p = &task_state_array[0];
BUILD_BUG_ON(1 + ilog2(TASK_STATE_MAX) != ARRAY_SIZE(task_state_array));
while (state) {
p++;
state >>= 1;
}
return *p;
}
static inline void task_state(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *p)
{
struct user_namespace *user_ns = seq_user_ns(m);
struct group_info *group_info;
int g;
struct fdtable *fdt = NULL;
const struct cred *cred;
pid_t ppid, tpid;
rcu_read_lock();
ppid = pid_alive(p) ?
task_tgid_nr_ns(rcu_dereference(p->real_parent), ns) : 0;
tpid = 0;
if (pid_alive(p)) {
struct task_struct *tracer = ptrace_parent(p);
if (tracer)
tpid = task_pid_nr_ns(tracer, ns);
}
cred = get_task_cred(p);
seq_printf(m,
"State:\t%s\n"
"Tgid:\t%d\n"
"Pid:\t%d\n"
"PPid:\t%d\n"
"TracerPid:\t%d\n"
"Uid:\t%d\t%d\t%d\t%d\n"
"Gid:\t%d\t%d\t%d\t%d\n",
get_task_state(p),
task_tgid_nr_ns(p, ns),
pid_nr_ns(pid, ns),
ppid, tpid,
from_kuid_munged(user_ns, cred->uid),
from_kuid_munged(user_ns, cred->euid),
from_kuid_munged(user_ns, cred->suid),
from_kuid_munged(user_ns, cred->fsuid),
from_kgid_munged(user_ns, cred->gid),
from_kgid_munged(user_ns, cred->egid),
from_kgid_munged(user_ns, cred->sgid),
from_kgid_munged(user_ns, cred->fsgid));
task_lock(p);
if (p->files)
fdt = files_fdtable(p->files);
seq_printf(m,
"FDSize:\t%d\n"
"Groups:\t",
fdt ? fdt->max_fds : 0);
rcu_read_unlock();
group_info = cred->group_info;
task_unlock(p);
for (g = 0; g < group_info->ngroups; g++)
seq_printf(m, "%d ",
from_kgid_munged(user_ns, GROUP_AT(group_info, g)));
put_cred(cred);
seq_putc(m, '\n');
}
void render_sigset_t(struct seq_file *m, const char *header,
sigset_t *set)
{
int i;
seq_puts(m, header);
i = _NSIG;
do {
int x = 0;
i -= 4;
if (sigismember(set, i+1)) x |= 1;
if (sigismember(set, i+2)) x |= 2;
if (sigismember(set, i+3)) x |= 4;
if (sigismember(set, i+4)) x |= 8;
seq_printf(m, "%x", x);
} while (i >= 4);
seq_putc(m, '\n');
}
static void collect_sigign_sigcatch(struct task_struct *p, sigset_t *ign,
sigset_t *catch)
{
struct k_sigaction *k;
int i;
k = p->sighand->action;
for (i = 1; i <= _NSIG; ++i, ++k) {
if (k->sa.sa_handler == SIG_IGN)
sigaddset(ign, i);
else if (k->sa.sa_handler != SIG_DFL)
sigaddset(catch, i);
}
}
static inline void task_sig(struct seq_file *m, struct task_struct *p)
{
unsigned long flags;
sigset_t pending, shpending, blocked, ignored, caught;
int num_threads = 0;
unsigned long qsize = 0;
unsigned long qlim = 0;
sigemptyset(&pending);
sigemptyset(&shpending);
sigemptyset(&blocked);
sigemptyset(&ignored);
sigemptyset(&caught);
if (lock_task_sighand(p, &flags)) {
pending = p->pending.signal;
shpending = p->signal->shared_pending.signal;
blocked = p->blocked;
collect_sigign_sigcatch(p, &ignored, &caught);
num_threads = get_nr_threads(p);
rcu_read_lock(); /* FIXME: is this correct? */
qsize = atomic_read(&__task_cred(p)->user->sigpending);
rcu_read_unlock();
qlim = task_rlimit(p, RLIMIT_SIGPENDING);
unlock_task_sighand(p, &flags);
}
seq_printf(m, "Threads:\t%d\n", num_threads);
seq_printf(m, "SigQ:\t%lu/%lu\n", qsize, qlim);
/* render them all */
render_sigset_t(m, "SigPnd:\t", &pending);
render_sigset_t(m, "ShdPnd:\t", &shpending);
render_sigset_t(m, "SigBlk:\t", &blocked);
render_sigset_t(m, "SigIgn:\t", &ignored);
render_sigset_t(m, "SigCgt:\t", &caught);
}
static void render_cap_t(struct seq_file *m, const char *header,
kernel_cap_t *a)
{
unsigned __capi;
seq_puts(m, header);
CAP_FOR_EACH_U32(__capi) {
seq_printf(m, "%08x",
a->cap[(_KERNEL_CAPABILITY_U32S-1) - __capi]);
}
seq_putc(m, '\n');
}
/* Remove non-existent capabilities */
#define NORM_CAPS(v) (v.cap[CAP_TO_INDEX(CAP_LAST_CAP)] &= \
CAP_TO_MASK(CAP_LAST_CAP + 1) - 1)
static inline void task_cap(struct seq_file *m, struct task_struct *p)
{
const struct cred *cred;
kernel_cap_t cap_inheritable, cap_permitted, cap_effective, cap_bset;
rcu_read_lock();
cred = __task_cred(p);
cap_inheritable = cred->cap_inheritable;
cap_permitted = cred->cap_permitted;
cap_effective = cred->cap_effective;
cap_bset = cred->cap_bset;
rcu_read_unlock();
NORM_CAPS(cap_inheritable);
NORM_CAPS(cap_permitted);
NORM_CAPS(cap_effective);
NORM_CAPS(cap_bset);
render_cap_t(m, "CapInh:\t", &cap_inheritable);
render_cap_t(m, "CapPrm:\t", &cap_permitted);
render_cap_t(m, "CapEff:\t", &cap_effective);
render_cap_t(m, "CapBnd:\t", &cap_bset);
}
static inline void task_seccomp(struct seq_file *m, struct task_struct *p)
{
#ifdef CONFIG_SECCOMP
seq_printf(m, "Seccomp:\t%d\n", p->seccomp.mode);
#endif
}
static inline void task_context_switch_counts(struct seq_file *m,
struct task_struct *p)
{
seq_printf(m, "voluntary_ctxt_switches:\t%lu\n"
"nonvoluntary_ctxt_switches:\t%lu\n",
p->nvcsw,
p->nivcsw);
}
static void task_cpus_allowed(struct seq_file *m, struct task_struct *task)
{
seq_puts(m, "Cpus_allowed:\t");
seq_cpumask(m, &task->cpus_allowed);
seq_putc(m, '\n');
seq_puts(m, "Cpus_allowed_list:\t");
seq_cpumask_list(m, &task->cpus_allowed);
seq_putc(m, '\n');
}
int proc_pid_status(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
struct mm_struct *mm = get_task_mm(task);
task_name(m, task);
task_state(m, ns, pid, task);
if (mm) {
task_mem(m, mm);
mmput(mm);
}
task_sig(m, task);
task_cap(m, task);
task_seccomp(m, task);
task_cpus_allowed(m, task);
cpuset_task_status_allowed(m, task);
task_context_switch_counts(m, task);
return 0;
}
static int do_task_stat(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task, int whole)
{
unsigned long vsize, eip, esp, wchan = ~0UL;
int priority, nice;
int tty_pgrp = -1, tty_nr = 0;
sigset_t sigign, sigcatch;
char state;
pid_t ppid = 0, pgid = -1, sid = -1;
int num_threads = 0;
int permitted;
struct mm_struct *mm;
unsigned long long start_time;
unsigned long cmin_flt = 0, cmaj_flt = 0;
unsigned long min_flt = 0, maj_flt = 0;
cputime_t cutime, cstime, utime, stime;
cputime_t cgtime, gtime;
unsigned long rsslim = 0;
char tcomm[sizeof(task->comm)];
unsigned long flags;
state = *get_task_state(task);
vsize = eip = esp = 0;
permitted = ptrace_may_access(task, PTRACE_MODE_READ | PTRACE_MODE_NOAUDIT);
mm = get_task_mm(task);
if (mm) {
vsize = task_vsize(mm);
if (permitted) {
eip = KSTK_EIP(task);
esp = KSTK_ESP(task);
}
}
get_task_comm(tcomm, task);
sigemptyset(&sigign);
sigemptyset(&sigcatch);
cutime = cstime = utime = stime = 0;
cgtime = gtime = 0;
if (lock_task_sighand(task, &flags)) {
struct signal_struct *sig = task->signal;
if (sig->tty) {
struct pid *pgrp = tty_get_pgrp(sig->tty);
tty_pgrp = pid_nr_ns(pgrp, ns);
put_pid(pgrp);
tty_nr = new_encode_dev(tty_devnum(sig->tty));
}
num_threads = get_nr_threads(task);
collect_sigign_sigcatch(task, &sigign, &sigcatch);
cmin_flt = sig->cmin_flt;
cmaj_flt = sig->cmaj_flt;
cutime = sig->cutime;
cstime = sig->cstime;
cgtime = sig->cgtime;
rsslim = ACCESS_ONCE(sig->rlim[RLIMIT_RSS].rlim_cur);
/* add up live thread stats at the group level */
if (whole) {
struct task_struct *t = task;
do {
min_flt += t->min_flt;
maj_flt += t->maj_flt;
gtime += task_gtime(t);
t = next_thread(t);
} while (t != task);
min_flt += sig->min_flt;
maj_flt += sig->maj_flt;
thread_group_cputime_adjusted(task, &utime, &stime);
gtime += sig->gtime;
}
sid = task_session_nr_ns(task, ns);
ppid = task_tgid_nr_ns(task->real_parent, ns);
pgid = task_pgrp_nr_ns(task, ns);
unlock_task_sighand(task, &flags);
}
if (permitted && (!whole || num_threads < 2))
wchan = get_wchan(task);
if (!whole) {
min_flt = task->min_flt;
maj_flt = task->maj_flt;
task_cputime_adjusted(task, &utime, &stime);
gtime = task_gtime(task);
}
/* scale priority and nice values from timeslices to -20..20 */
/* to make it look like a "normal" Unix priority/nice value */
priority = task_prio(task);
nice = task_nice(task);
/* Temporary variable needed for gcc-2.96 */
/* convert timespec -> nsec*/
start_time =
(unsigned long long)task->real_start_time.tv_sec * NSEC_PER_SEC
+ task->real_start_time.tv_nsec;
/* convert nsec -> ticks */
start_time = nsec_to_clock_t(start_time);
seq_printf(m, "%d (%s) %c", pid_nr_ns(pid, ns), tcomm, state);
seq_put_decimal_ll(m, ' ', ppid);
seq_put_decimal_ll(m, ' ', pgid);
seq_put_decimal_ll(m, ' ', sid);
seq_put_decimal_ll(m, ' ', tty_nr);
seq_put_decimal_ll(m, ' ', tty_pgrp);
seq_put_decimal_ull(m, ' ', task->flags);
seq_put_decimal_ull(m, ' ', min_flt);
seq_put_decimal_ull(m, ' ', cmin_flt);
seq_put_decimal_ull(m, ' ', maj_flt);
seq_put_decimal_ull(m, ' ', cmaj_flt);
seq_put_decimal_ull(m, ' ', cputime_to_clock_t(utime));
seq_put_decimal_ull(m, ' ', cputime_to_clock_t(stime));
seq_put_decimal_ll(m, ' ', cputime_to_clock_t(cutime));
seq_put_decimal_ll(m, ' ', cputime_to_clock_t(cstime));
seq_put_decimal_ll(m, ' ', priority);
seq_put_decimal_ll(m, ' ', nice);
seq_put_decimal_ll(m, ' ', num_threads);
seq_put_decimal_ull(m, ' ', 0);
seq_put_decimal_ull(m, ' ', start_time);
seq_put_decimal_ull(m, ' ', vsize);
seq_put_decimal_ull(m, ' ', mm ? get_mm_rss(mm) : 0);
seq_put_decimal_ull(m, ' ', rsslim);
seq_put_decimal_ull(m, ' ', mm ? (permitted ? mm->start_code : 1) : 0);
seq_put_decimal_ull(m, ' ', mm ? (permitted ? mm->end_code : 1) : 0);
seq_put_decimal_ull(m, ' ', (permitted && mm) ? mm->start_stack : 0);
seq_put_decimal_ull(m, ' ', esp);
seq_put_decimal_ull(m, ' ', eip);
/* The signal information here is obsolete.
* It must be decimal for Linux 2.0 compatibility.
* Use /proc/#/status for real-time signals.
*/
seq_put_decimal_ull(m, ' ', task->pending.signal.sig[0] & 0x7fffffffUL);
seq_put_decimal_ull(m, ' ', task->blocked.sig[0] & 0x7fffffffUL);
seq_put_decimal_ull(m, ' ', sigign.sig[0] & 0x7fffffffUL);
seq_put_decimal_ull(m, ' ', sigcatch.sig[0] & 0x7fffffffUL);
seq_put_decimal_ull(m, ' ', wchan);
seq_put_decimal_ull(m, ' ', 0);
seq_put_decimal_ull(m, ' ', 0);
seq_put_decimal_ll(m, ' ', task->exit_signal);
seq_put_decimal_ll(m, ' ', task_cpu(task));
seq_put_decimal_ull(m, ' ', task->rt_priority);
seq_put_decimal_ull(m, ' ', task->policy);
seq_put_decimal_ull(m, ' ', delayacct_blkio_ticks(task));
seq_put_decimal_ull(m, ' ', cputime_to_clock_t(gtime));
seq_put_decimal_ll(m, ' ', cputime_to_clock_t(cgtime));
if (mm && permitted) {
seq_put_decimal_ull(m, ' ', mm->start_data);
seq_put_decimal_ull(m, ' ', mm->end_data);
seq_put_decimal_ull(m, ' ', mm->start_brk);
seq_put_decimal_ull(m, ' ', mm->arg_start);
seq_put_decimal_ull(m, ' ', mm->arg_end);
seq_put_decimal_ull(m, ' ', mm->env_start);
seq_put_decimal_ull(m, ' ', mm->env_end);
} else
seq_printf(m, " 0 0 0 0 0 0 0");
if (permitted)
seq_put_decimal_ll(m, ' ', task->exit_code);
else
seq_put_decimal_ll(m, ' ', 0);
seq_putc(m, '\n');
if (mm)
mmput(mm);
return 0;
}
int proc_tid_stat(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
return do_task_stat(m, ns, pid, task, 0);
}
int proc_tgid_stat(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
return do_task_stat(m, ns, pid, task, 1);
}
int proc_pid_statm(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
unsigned long size = 0, resident = 0, shared = 0, text = 0, data = 0;
struct mm_struct *mm = get_task_mm(task);
if (mm) {
size = task_statm(mm, &shared, &text, &data, &resident);
mmput(mm);
}
/*
* For quick read, open code by putting numbers directly
* expected format is
* seq_printf(m, "%lu %lu %lu %lu 0 %lu 0\n",
* size, resident, shared, text, data);
*/
seq_put_decimal_ull(m, 0, size);
seq_put_decimal_ull(m, ' ', resident);
seq_put_decimal_ull(m, ' ', shared);
seq_put_decimal_ull(m, ' ', text);
seq_put_decimal_ull(m, ' ', 0);
seq_put_decimal_ull(m, ' ', data);
seq_put_decimal_ull(m, ' ', 0);
seq_putc(m, '\n');
return 0;
}
#ifdef CONFIG_CHECKPOINT_RESTORE
static struct pid *
get_children_pid(struct inode *inode, struct pid *pid_prev, loff_t pos)
{
struct task_struct *start, *task;
struct pid *pid = NULL;
read_lock(&tasklist_lock);
start = pid_task(proc_pid(inode), PIDTYPE_PID);
if (!start)
goto out;
/*
* Lets try to continue searching first, this gives
* us significant speedup on children-rich processes.
*/
if (pid_prev) {
task = pid_task(pid_prev, PIDTYPE_PID);
if (task && task->real_parent == start &&
!(list_empty(&task->sibling))) {
if (list_is_last(&task->sibling, &start->children))
goto out;
task = list_first_entry(&task->sibling,
struct task_struct, sibling);
pid = get_pid(task_pid(task));
goto out;
}
}
/*
* Slow search case.
*
* We might miss some children here if children
* are exited while we were not holding the lock,
* but it was never promised to be accurate that
* much.
*
* "Just suppose that the parent sleeps, but N children
* exit after we printed their tids. Now the slow paths
* skips N extra children, we miss N tasks." (c)
*
* So one need to stop or freeze the leader and all
* its children to get a precise result.
*/
list_for_each_entry(task, &start->children, sibling) {
if (pos-- == 0) {
pid = get_pid(task_pid(task));
break;
}
}
out:
read_unlock(&tasklist_lock);
return pid;
}
static int children_seq_show(struct seq_file *seq, void *v)
{
struct inode *inode = seq->private;
pid_t pid;
pid = pid_nr_ns(v, inode->i_sb->s_fs_info);
return seq_printf(seq, "%d ", pid);
}
static void *children_seq_start(struct seq_file *seq, loff_t *pos)
{
return get_children_pid(seq->private, NULL, *pos);
}
static void *children_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct pid *pid;
pid = get_children_pid(seq->private, v, *pos + 1);
put_pid(v);
++*pos;
return pid;
}
static void children_seq_stop(struct seq_file *seq, void *v)
{
put_pid(v);
}
static const struct seq_operations children_seq_ops = {
.start = children_seq_start,
.next = children_seq_next,
.stop = children_seq_stop,
.show = children_seq_show,
};
static int children_seq_open(struct inode *inode, struct file *file)
{
struct seq_file *m;
int ret;
ret = seq_open(file, &children_seq_ops);
if (ret)
return ret;
m = file->private_data;
m->private = inode;
return ret;
}
int children_seq_release(struct inode *inode, struct file *file)
{
seq_release(inode, file);
return 0;
}
const struct file_operations proc_tid_children_operations = {
.open = children_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = children_seq_release,
};
#endif /* CONFIG_CHECKPOINT_RESTORE */
| gpl-2.0 |
google-code-export/bricked | drivers/gpu/drm/drm_encoder_slave.c | 1325 | 3690 | /*
* Copyright (C) 2009 Francisco Jerez.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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 "drm_encoder_slave.h"
/**
* drm_i2c_encoder_init - Initialize an I2C slave encoder
* @dev: DRM device.
* @encoder: Encoder to be attached to the I2C device. You aren't
* required to have called drm_encoder_init() before.
* @adap: I2C adapter that will be used to communicate with
* the device.
* @info: Information that will be used to create the I2C device.
* Required fields are @addr and @type.
*
* Create an I2C device on the specified bus (the module containing its
* driver is transparently loaded) and attach it to the specified
* &drm_encoder_slave. The @slave_funcs field will be initialized with
* the hooks provided by the slave driver.
*
* Returns 0 on success or a negative errno on failure, in particular,
* -ENODEV is returned when no matching driver is found.
*/
int drm_i2c_encoder_init(struct drm_device *dev,
struct drm_encoder_slave *encoder,
struct i2c_adapter *adap,
const struct i2c_board_info *info)
{
char modalias[sizeof(I2C_MODULE_PREFIX)
+ I2C_NAME_SIZE];
struct module *module = NULL;
struct i2c_client *client;
struct drm_i2c_encoder_driver *encoder_drv;
int err = 0;
snprintf(modalias, sizeof(modalias),
"%s%s", I2C_MODULE_PREFIX, info->type);
request_module(modalias);
client = i2c_new_device(adap, info);
if (!client) {
err = -ENOMEM;
goto fail;
}
if (!client->driver) {
err = -ENODEV;
goto fail_unregister;
}
module = client->driver->driver.owner;
if (!try_module_get(module)) {
err = -ENODEV;
goto fail_unregister;
}
encoder->bus_priv = client;
encoder_drv = to_drm_i2c_encoder_driver(client->driver);
err = encoder_drv->encoder_init(client, dev, encoder);
if (err)
goto fail_unregister;
return 0;
fail_unregister:
i2c_unregister_device(client);
module_put(module);
fail:
return err;
}
EXPORT_SYMBOL(drm_i2c_encoder_init);
/**
* drm_i2c_encoder_destroy - Unregister the I2C device backing an encoder
* @drm_encoder: Encoder to be unregistered.
*
* This should be called from the @destroy method of an I2C slave
* encoder driver once I2C access is no longer needed.
*/
void drm_i2c_encoder_destroy(struct drm_encoder *drm_encoder)
{
struct drm_encoder_slave *encoder = to_encoder_slave(drm_encoder);
struct i2c_client *client = drm_i2c_encoder_get_client(drm_encoder);
struct module *module = client->driver->driver.owner;
i2c_unregister_device(client);
encoder->bus_priv = NULL;
module_put(module);
}
EXPORT_SYMBOL(drm_i2c_encoder_destroy);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.