repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
AospPlus/android_kernel_x86 | drivers/s390/char/tape_char.c | 1566 | 11629 | /*
* character device frontend for tape device driver
*
* S390 and zSeries version
* Copyright IBM Corp. 2001, 2006
* Author(s): Carsten Otte <cotte@de.ibm.com>
* Michael Holzheu <holzheu@de.ibm.com>
* Tuan Ngo-Anh <ngoanh@de.ibm.com>
* Martin Schwidefsky <schwidefsky@de.ibm.com>
*/
#define KMSG_COMPONENT "tape"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/mtio.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#define TAPE_DBF_AREA tape_core_dbf
#include "tape.h"
#include "tape_std.h"
#include "tape_class.h"
#define TAPECHAR_MAJOR 0 /* get dynamic major */
/*
* file operation structure for tape character frontend
*/
static ssize_t tapechar_read(struct file *, char __user *, size_t, loff_t *);
static ssize_t tapechar_write(struct file *, const char __user *, size_t, loff_t *);
static int tapechar_open(struct inode *,struct file *);
static int tapechar_release(struct inode *,struct file *);
static long tapechar_ioctl(struct file *, unsigned int, unsigned long);
#ifdef CONFIG_COMPAT
static long tapechar_compat_ioctl(struct file *, unsigned int, unsigned long);
#endif
static const struct file_operations tape_fops =
{
.owner = THIS_MODULE,
.read = tapechar_read,
.write = tapechar_write,
.unlocked_ioctl = tapechar_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = tapechar_compat_ioctl,
#endif
.open = tapechar_open,
.release = tapechar_release,
.llseek = no_llseek,
};
static int tapechar_major = TAPECHAR_MAJOR;
/*
* This function is called for every new tapedevice
*/
int
tapechar_setup_device(struct tape_device * device)
{
char device_name[20];
sprintf(device_name, "ntibm%i", device->first_minor / 2);
device->nt = register_tape_dev(
&device->cdev->dev,
MKDEV(tapechar_major, device->first_minor),
&tape_fops,
device_name,
"non-rewinding"
);
device_name[0] = 'r';
device->rt = register_tape_dev(
&device->cdev->dev,
MKDEV(tapechar_major, device->first_minor + 1),
&tape_fops,
device_name,
"rewinding"
);
return 0;
}
void
tapechar_cleanup_device(struct tape_device *device)
{
unregister_tape_dev(&device->cdev->dev, device->rt);
device->rt = NULL;
unregister_tape_dev(&device->cdev->dev, device->nt);
device->nt = NULL;
}
static int
tapechar_check_idalbuffer(struct tape_device *device, size_t block_size)
{
struct idal_buffer *new;
if (device->char_data.idal_buf != NULL &&
device->char_data.idal_buf->size == block_size)
return 0;
if (block_size > MAX_BLOCKSIZE) {
DBF_EVENT(3, "Invalid blocksize (%zd > %d)\n",
block_size, MAX_BLOCKSIZE);
return -EINVAL;
}
/* The current idal buffer is not correct. Allocate a new one. */
new = idal_buffer_alloc(block_size, 0);
if (IS_ERR(new))
return -ENOMEM;
if (device->char_data.idal_buf != NULL)
idal_buffer_free(device->char_data.idal_buf);
device->char_data.idal_buf = new;
return 0;
}
/*
* Tape device read function
*/
static ssize_t
tapechar_read(struct file *filp, char __user *data, size_t count, loff_t *ppos)
{
struct tape_device *device;
struct tape_request *request;
size_t block_size;
int rc;
DBF_EVENT(6, "TCHAR:read\n");
device = (struct tape_device *) filp->private_data;
/*
* If the tape isn't terminated yet, do it now. And since we then
* are at the end of the tape there wouldn't be anything to read
* anyways. So we return immediately.
*/
if(device->required_tapemarks) {
return tape_std_terminate_write(device);
}
/* Find out block size to use */
if (device->char_data.block_size != 0) {
if (count < device->char_data.block_size) {
DBF_EVENT(3, "TCHAR:read smaller than block "
"size was requested\n");
return -EINVAL;
}
block_size = device->char_data.block_size;
} else {
block_size = count;
}
rc = tapechar_check_idalbuffer(device, block_size);
if (rc)
return rc;
DBF_EVENT(6, "TCHAR:nbytes: %lx\n", block_size);
/* Let the discipline build the ccw chain. */
request = device->discipline->read_block(device, block_size);
if (IS_ERR(request))
return PTR_ERR(request);
/* Execute it. */
rc = tape_do_io(device, request);
if (rc == 0) {
rc = block_size - request->rescnt;
DBF_EVENT(6, "TCHAR:rbytes: %x\n", rc);
/* Copy data from idal buffer to user space. */
if (idal_buffer_to_user(device->char_data.idal_buf,
data, rc) != 0)
rc = -EFAULT;
}
tape_free_request(request);
return rc;
}
/*
* Tape device write function
*/
static ssize_t
tapechar_write(struct file *filp, const char __user *data, size_t count, loff_t *ppos)
{
struct tape_device *device;
struct tape_request *request;
size_t block_size;
size_t written;
int nblocks;
int i, rc;
DBF_EVENT(6, "TCHAR:write\n");
device = (struct tape_device *) filp->private_data;
/* Find out block size and number of blocks */
if (device->char_data.block_size != 0) {
if (count < device->char_data.block_size) {
DBF_EVENT(3, "TCHAR:write smaller than block "
"size was requested\n");
return -EINVAL;
}
block_size = device->char_data.block_size;
nblocks = count / block_size;
} else {
block_size = count;
nblocks = 1;
}
rc = tapechar_check_idalbuffer(device, block_size);
if (rc)
return rc;
DBF_EVENT(6,"TCHAR:nbytes: %lx\n", block_size);
DBF_EVENT(6, "TCHAR:nblocks: %x\n", nblocks);
/* Let the discipline build the ccw chain. */
request = device->discipline->write_block(device, block_size);
if (IS_ERR(request))
return PTR_ERR(request);
rc = 0;
written = 0;
for (i = 0; i < nblocks; i++) {
/* Copy data from user space to idal buffer. */
if (idal_buffer_from_user(device->char_data.idal_buf,
data, block_size)) {
rc = -EFAULT;
break;
}
rc = tape_do_io(device, request);
if (rc)
break;
DBF_EVENT(6, "TCHAR:wbytes: %lx\n",
block_size - request->rescnt);
written += block_size - request->rescnt;
if (request->rescnt != 0)
break;
data += block_size;
}
tape_free_request(request);
if (rc == -ENOSPC) {
/*
* Ok, the device has no more space. It has NOT written
* the block.
*/
if (device->discipline->process_eov)
device->discipline->process_eov(device);
if (written > 0)
rc = 0;
}
/*
* After doing a write we always need two tapemarks to correctly
* terminate the tape (one to terminate the file, the second to
* flag the end of recorded data.
* Since process_eov positions the tape in front of the written
* tapemark it doesn't hurt to write two marks again.
*/
if (!rc)
device->required_tapemarks = 2;
return rc ? rc : written;
}
/*
* Character frontend tape device open function.
*/
static int
tapechar_open (struct inode *inode, struct file *filp)
{
struct tape_device *device;
int minor, rc;
DBF_EVENT(6, "TCHAR:open: %i:%i\n",
imajor(file_inode(filp)),
iminor(file_inode(filp)));
if (imajor(file_inode(filp)) != tapechar_major)
return -ENODEV;
minor = iminor(file_inode(filp));
device = tape_find_device(minor / TAPE_MINORS_PER_DEV);
if (IS_ERR(device)) {
DBF_EVENT(3, "TCHAR:open: tape_find_device() failed\n");
return PTR_ERR(device);
}
rc = tape_open(device);
if (rc == 0) {
filp->private_data = device;
nonseekable_open(inode, filp);
} else
tape_put_device(device);
return rc;
}
/*
* Character frontend tape device release function.
*/
static int
tapechar_release(struct inode *inode, struct file *filp)
{
struct tape_device *device;
DBF_EVENT(6, "TCHAR:release: %x\n", iminor(inode));
device = (struct tape_device *) filp->private_data;
/*
* If this is the rewinding tape minor then rewind. In that case we
* write all required tapemarks. Otherwise only one to terminate the
* file.
*/
if ((iminor(inode) & 1) != 0) {
if (device->required_tapemarks)
tape_std_terminate_write(device);
tape_mtop(device, MTREW, 1);
} else {
if (device->required_tapemarks > 1) {
if (tape_mtop(device, MTWEOF, 1) == 0)
device->required_tapemarks--;
}
}
if (device->char_data.idal_buf != NULL) {
idal_buffer_free(device->char_data.idal_buf);
device->char_data.idal_buf = NULL;
}
tape_release(device);
filp->private_data = NULL;
tape_put_device(device);
return 0;
}
/*
* Tape device io controls.
*/
static int
__tapechar_ioctl(struct tape_device *device,
unsigned int no, unsigned long data)
{
int rc;
if (no == MTIOCTOP) {
struct mtop op;
if (copy_from_user(&op, (char __user *) data, sizeof(op)) != 0)
return -EFAULT;
if (op.mt_count < 0)
return -EINVAL;
/*
* Operations that change tape position should write final
* tapemarks.
*/
switch (op.mt_op) {
case MTFSF:
case MTBSF:
case MTFSR:
case MTBSR:
case MTREW:
case MTOFFL:
case MTEOM:
case MTRETEN:
case MTBSFM:
case MTFSFM:
case MTSEEK:
if (device->required_tapemarks)
tape_std_terminate_write(device);
default:
;
}
rc = tape_mtop(device, op.mt_op, op.mt_count);
if (op.mt_op == MTWEOF && rc == 0) {
if (op.mt_count > device->required_tapemarks)
device->required_tapemarks = 0;
else
device->required_tapemarks -= op.mt_count;
}
return rc;
}
if (no == MTIOCPOS) {
/* MTIOCPOS: query the tape position. */
struct mtpos pos;
rc = tape_mtop(device, MTTELL, 1);
if (rc < 0)
return rc;
pos.mt_blkno = rc;
if (copy_to_user((char __user *) data, &pos, sizeof(pos)) != 0)
return -EFAULT;
return 0;
}
if (no == MTIOCGET) {
/* MTIOCGET: query the tape drive status. */
struct mtget get;
memset(&get, 0, sizeof(get));
get.mt_type = MT_ISUNKNOWN;
get.mt_resid = 0 /* device->devstat.rescnt */;
get.mt_dsreg =
((device->char_data.block_size << MT_ST_BLKSIZE_SHIFT)
& MT_ST_BLKSIZE_MASK);
/* FIXME: mt_gstat, mt_erreg, mt_fileno */
get.mt_gstat = 0;
get.mt_erreg = 0;
get.mt_fileno = 0;
get.mt_gstat = device->tape_generic_status;
if (device->medium_state == MS_LOADED) {
rc = tape_mtop(device, MTTELL, 1);
if (rc < 0)
return rc;
if (rc == 0)
get.mt_gstat |= GMT_BOT(~0);
get.mt_blkno = rc;
}
if (copy_to_user((char __user *) data, &get, sizeof(get)) != 0)
return -EFAULT;
return 0;
}
/* Try the discipline ioctl function. */
if (device->discipline->ioctl_fn == NULL)
return -EINVAL;
return device->discipline->ioctl_fn(device, no, data);
}
static long
tapechar_ioctl(struct file *filp, unsigned int no, unsigned long data)
{
struct tape_device *device;
long rc;
DBF_EVENT(6, "TCHAR:ioct\n");
device = (struct tape_device *) filp->private_data;
mutex_lock(&device->mutex);
rc = __tapechar_ioctl(device, no, data);
mutex_unlock(&device->mutex);
return rc;
}
#ifdef CONFIG_COMPAT
static long
tapechar_compat_ioctl(struct file *filp, unsigned int no, unsigned long data)
{
struct tape_device *device = filp->private_data;
int rval = -ENOIOCTLCMD;
unsigned long argp;
/* The 'arg' argument of any ioctl function may only be used for
* pointers because of the compat pointer conversion.
* Consider this when adding new ioctls.
*/
argp = (unsigned long) compat_ptr(data);
if (device->discipline->ioctl_fn) {
mutex_lock(&device->mutex);
rval = device->discipline->ioctl_fn(device, no, argp);
mutex_unlock(&device->mutex);
if (rval == -EINVAL)
rval = -ENOIOCTLCMD;
}
return rval;
}
#endif /* CONFIG_COMPAT */
/*
* Initialize character device frontend.
*/
int
tapechar_init (void)
{
dev_t dev;
if (alloc_chrdev_region(&dev, 0, 256, "tape") != 0)
return -1;
tapechar_major = MAJOR(dev);
return 0;
}
/*
* cleanup
*/
void
tapechar_exit(void)
{
unregister_chrdev_region(MKDEV(tapechar_major, 0), 256);
}
| gpl-2.0 |
sultanqasim/android_kernel_alcatel_alto45 | drivers/media/usb/stk1160/stk1160-v4l.c | 1566 | 18223 | /*
* STK1160 driver
*
* Copyright (C) 2012 Ezequiel Garcia
* <elezegarcia--a.t--gmail.com>
*
* Based on Easycap driver by R.M. Thomas
* Copyright (C) 2010 R.M. Thomas
* <rmthomas--a.t--sciolus.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.
*
*/
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include <media/v4l2-chip-ident.h>
#include <media/videobuf2-vmalloc.h>
#include <media/saa7115.h>
#include "stk1160.h"
#include "stk1160-reg.h"
static unsigned int vidioc_debug;
module_param(vidioc_debug, int, 0644);
MODULE_PARM_DESC(vidioc_debug, "enable debug messages [vidioc]");
static bool keep_buffers;
module_param(keep_buffers, bool, 0644);
MODULE_PARM_DESC(keep_buffers, "don't release buffers upon stop streaming");
/* supported video standards */
static struct stk1160_fmt format[] = {
{
.name = "16 bpp YUY2, 4:2:2, packed",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = 16,
}
};
static void stk1160_set_std(struct stk1160 *dev)
{
int i;
static struct regval std525[] = {
/* 720x480 */
/* Frame start */
{STK116_CFSPO_STX_L, 0x0000},
{STK116_CFSPO_STX_H, 0x0000},
{STK116_CFSPO_STY_L, 0x0003},
{STK116_CFSPO_STY_H, 0x0000},
/* Frame end */
{STK116_CFEPO_ENX_L, 0x05a0},
{STK116_CFEPO_ENX_H, 0x0005},
{STK116_CFEPO_ENY_L, 0x00f3},
{STK116_CFEPO_ENY_H, 0x0000},
{0xffff, 0xffff}
};
static struct regval std625[] = {
/* 720x576 */
/* TODO: Each line of frame has some junk at the end */
/* Frame start */
{STK116_CFSPO, 0x0000},
{STK116_CFSPO+1, 0x0000},
{STK116_CFSPO+2, 0x0001},
{STK116_CFSPO+3, 0x0000},
/* Frame end */
{STK116_CFEPO, 0x05a0},
{STK116_CFEPO+1, 0x0005},
{STK116_CFEPO+2, 0x0121},
{STK116_CFEPO+3, 0x0001},
{0xffff, 0xffff}
};
if (dev->norm & V4L2_STD_525_60) {
stk1160_dbg("registers to NTSC like standard\n");
for (i = 0; std525[i].reg != 0xffff; i++)
stk1160_write_reg(dev, std525[i].reg, std525[i].val);
} else {
stk1160_dbg("registers to PAL like standard\n");
for (i = 0; std625[i].reg != 0xffff; i++)
stk1160_write_reg(dev, std625[i].reg, std625[i].val);
}
}
/*
* Set a new alternate setting.
* Returns true is dev->max_pkt_size has changed, false otherwise.
*/
static bool stk1160_set_alternate(struct stk1160 *dev)
{
int i, prev_alt = dev->alt;
unsigned int min_pkt_size;
bool new_pkt_size;
/*
* If we don't set right alternate,
* then we will get a green screen with junk.
*/
min_pkt_size = STK1160_MIN_PKT_SIZE;
for (i = 0; i < dev->num_alt; i++) {
/* stop when the selected alt setting offers enough bandwidth */
if (dev->alt_max_pkt_size[i] >= min_pkt_size) {
dev->alt = i;
break;
/*
* otherwise make sure that we end up with the maximum bandwidth
* because the min_pkt_size equation might be wrong...
*/
} else if (dev->alt_max_pkt_size[i] >
dev->alt_max_pkt_size[dev->alt])
dev->alt = i;
}
stk1160_info("setting alternate %d\n", dev->alt);
if (dev->alt != prev_alt) {
stk1160_dbg("minimum isoc packet size: %u (alt=%d)\n",
min_pkt_size, dev->alt);
stk1160_dbg("setting alt %d with wMaxPacketSize=%u\n",
dev->alt, dev->alt_max_pkt_size[dev->alt]);
usb_set_interface(dev->udev, 0, dev->alt);
}
new_pkt_size = dev->max_pkt_size != dev->alt_max_pkt_size[dev->alt];
dev->max_pkt_size = dev->alt_max_pkt_size[dev->alt];
return new_pkt_size;
}
static int stk1160_start_streaming(struct stk1160 *dev)
{
bool new_pkt_size;
int rc = 0;
int i;
/* Check device presence */
if (!dev->udev)
return -ENODEV;
if (mutex_lock_interruptible(&dev->v4l_lock))
return -ERESTARTSYS;
/*
* For some reason it is mandatory to set alternate *first*
* and only *then* initialize isoc urbs.
* Someone please explain me why ;)
*/
new_pkt_size = stk1160_set_alternate(dev);
/*
* We (re)allocate isoc urbs if:
* there is no allocated isoc urbs, OR
* a new dev->max_pkt_size is detected
*/
if (!dev->isoc_ctl.num_bufs || new_pkt_size) {
rc = stk1160_alloc_isoc(dev);
if (rc < 0)
goto out_stop_hw;
}
/* submit urbs and enables IRQ */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_KERNEL);
if (rc) {
stk1160_err("cannot submit urb[%d] (%d)\n", i, rc);
goto out_uninit;
}
}
/* Start saa711x */
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 1);
/* Start stk1160 */
stk1160_write_reg(dev, STK1160_DCTRL, 0xb3);
stk1160_write_reg(dev, STK1160_DCTRL+3, 0x00);
stk1160_dbg("streaming started\n");
mutex_unlock(&dev->v4l_lock);
return 0;
out_uninit:
stk1160_uninit_isoc(dev);
out_stop_hw:
usb_set_interface(dev->udev, 0, 0);
stk1160_clear_queue(dev);
mutex_unlock(&dev->v4l_lock);
return rc;
}
/* Must be called with v4l_lock hold */
static void stk1160_stop_hw(struct stk1160 *dev)
{
/* If the device is not physically present, there is nothing to do */
if (!dev->udev)
return;
/* set alternate 0 */
dev->alt = 0;
stk1160_info("setting alternate %d\n", dev->alt);
usb_set_interface(dev->udev, 0, 0);
/* Stop stk1160 */
stk1160_write_reg(dev, STK1160_DCTRL, 0x00);
stk1160_write_reg(dev, STK1160_DCTRL+3, 0x00);
/* Stop saa711x */
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
}
static int stk1160_stop_streaming(struct stk1160 *dev)
{
if (mutex_lock_interruptible(&dev->v4l_lock))
return -ERESTARTSYS;
stk1160_cancel_isoc(dev);
/*
* It is possible to keep buffers around using a module parameter.
* This is intended to avoid memory fragmentation.
*/
if (!keep_buffers)
stk1160_free_isoc(dev);
stk1160_stop_hw(dev);
stk1160_clear_queue(dev);
stk1160_dbg("streaming stopped\n");
mutex_unlock(&dev->v4l_lock);
return 0;
}
static struct v4l2_file_operations stk1160_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.read = vb2_fop_read,
.poll = vb2_fop_poll,
.mmap = vb2_fop_mmap,
.unlocked_ioctl = video_ioctl2,
};
/*
* vidioc ioctls
*/
static int vidioc_querycap(struct file *file,
void *priv, struct v4l2_capability *cap)
{
struct stk1160 *dev = video_drvdata(file);
strcpy(cap->driver, "stk1160");
strcpy(cap->card, "stk1160");
usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
cap->device_caps =
V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_STREAMING |
V4L2_CAP_READWRITE;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index != 0)
return -EINVAL;
strlcpy(f->description, format[f->index].name, sizeof(f->description));
f->pixelformat = format[f->index].fourcc;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct stk1160 *dev = video_drvdata(file);
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
f->fmt.pix.pixelformat = dev->fmt->fourcc;
f->fmt.pix.bytesperline = dev->width * 2;
f->fmt.pix.sizeimage = dev->height * f->fmt.pix.bytesperline;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct stk1160 *dev = video_drvdata(file);
/*
* User can't choose size at his own will,
* so we just return him the current size chosen
* at standard selection.
* TODO: Implement frame scaling?
*/
f->fmt.pix.pixelformat = dev->fmt->fourcc;
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
f->fmt.pix.bytesperline = dev->width * 2;
f->fmt.pix.sizeimage = dev->height * f->fmt.pix.bytesperline;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct stk1160 *dev = video_drvdata(file);
struct vb2_queue *q = &dev->vb_vidq;
if (vb2_is_busy(q))
return -EBUSY;
vidioc_try_fmt_vid_cap(file, priv, f);
/* We don't support any format changes */
return 0;
}
static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
{
struct stk1160 *dev = video_drvdata(file);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, querystd, norm);
return 0;
}
static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
{
struct stk1160 *dev = video_drvdata(file);
*norm = dev->norm;
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
{
struct stk1160 *dev = video_drvdata(file);
struct vb2_queue *q = &dev->vb_vidq;
if (vb2_is_busy(q))
return -EBUSY;
/* Check device presence */
if (!dev->udev)
return -ENODEV;
/* We need to set this now, before we call stk1160_set_std */
dev->norm = norm;
/* This is taken from saa7115 video decoder */
if (dev->norm & V4L2_STD_525_60) {
dev->width = 720;
dev->height = 480;
} else if (dev->norm & V4L2_STD_625_50) {
dev->width = 720;
dev->height = 576;
} else {
stk1160_err("invalid standard\n");
return -EINVAL;
}
stk1160_set_std(dev);
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std,
dev->norm);
return 0;
}
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct stk1160 *dev = video_drvdata(file);
if (i->index > STK1160_MAX_INPUT)
return -EINVAL;
/* S-Video special handling */
if (i->index == STK1160_SVIDEO_INPUT)
sprintf(i->name, "S-Video");
else
sprintf(i->name, "Composite%d", i->index);
i->type = V4L2_INPUT_TYPE_CAMERA;
i->std = dev->vdev.tvnorms;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct stk1160 *dev = video_drvdata(file);
*i = dev->ctl_input;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct stk1160 *dev = video_drvdata(file);
if (vb2_is_busy(&dev->vb_vidq))
return -EBUSY;
if (i > STK1160_MAX_INPUT)
return -EINVAL;
dev->ctl_input = i;
stk1160_select_input(dev);
return 0;
}
static int vidioc_g_chip_ident(struct file *file, void *priv,
struct v4l2_dbg_chip_ident *chip)
{
switch (chip->match.type) {
case V4L2_CHIP_MATCH_BRIDGE:
chip->ident = V4L2_IDENT_NONE;
chip->revision = 0;
return 0;
default:
return -EINVAL;
}
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int vidioc_g_register(struct file *file, void *priv,
struct v4l2_dbg_register *reg)
{
struct stk1160 *dev = video_drvdata(file);
int rc;
u8 val;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_register, reg);
return 0;
case V4L2_CHIP_MATCH_I2C_ADDR:
/* TODO: is this correct? */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_register, reg);
return 0;
default:
if (!v4l2_chip_match_host(®->match))
return -EINVAL;
}
/* Match host */
rc = stk1160_read_reg(dev, reg->reg, &val);
reg->val = val;
reg->size = 1;
return rc;
}
static int vidioc_s_register(struct file *file, void *priv,
const struct v4l2_dbg_register *reg)
{
struct stk1160 *dev = video_drvdata(file);
switch (reg->match.type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_register, reg);
return 0;
case V4L2_CHIP_MATCH_I2C_ADDR:
/* TODO: is this correct? */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_register, reg);
return 0;
default:
if (!v4l2_chip_match_host(®->match))
return -EINVAL;
}
/* Match host */
return stk1160_write_reg(dev, reg->reg, cpu_to_le16(reg->val));
}
#endif
static const struct v4l2_ioctl_ops stk1160_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_querystd = vidioc_querystd,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
/* vb2 takes care of these */
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
.vidioc_g_chip_ident = vidioc_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.vidioc_g_register = vidioc_g_register,
.vidioc_s_register = vidioc_s_register,
#endif
};
/********************************************************************/
/*
* Videobuf2 operations
*/
static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *v4l_fmt,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct stk1160 *dev = vb2_get_drv_priv(vq);
unsigned long size;
size = dev->width * dev->height * 2;
/*
* Here we can change the number of buffers being requested.
* So, we set a minimum and a maximum like this:
*/
*nbuffers = clamp_t(unsigned int, *nbuffers,
STK1160_MIN_VIDEO_BUFFERS, STK1160_MAX_VIDEO_BUFFERS);
/* This means a packed colorformat */
*nplanes = 1;
sizes[0] = size;
stk1160_info("%s: buffer count %d, each %ld bytes\n",
__func__, *nbuffers, size);
return 0;
}
static void buffer_queue(struct vb2_buffer *vb)
{
unsigned long flags;
struct stk1160 *dev = vb2_get_drv_priv(vb->vb2_queue);
struct stk1160_buffer *buf =
container_of(vb, struct stk1160_buffer, vb);
spin_lock_irqsave(&dev->buf_lock, flags);
if (!dev->udev) {
/*
* If the device is disconnected return the buffer to userspace
* directly. The next QBUF call will fail with -ENODEV.
*/
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
} else {
buf->mem = vb2_plane_vaddr(vb, 0);
buf->length = vb2_plane_size(vb, 0);
buf->bytesused = 0;
buf->pos = 0;
/*
* If buffer length is less from expected then we return
* the buffer to userspace directly.
*/
if (buf->length < dev->width * dev->height * 2)
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
else
list_add_tail(&buf->list, &dev->avail_bufs);
}
spin_unlock_irqrestore(&dev->buf_lock, flags);
}
static int start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct stk1160 *dev = vb2_get_drv_priv(vq);
return stk1160_start_streaming(dev);
}
/* abort streaming and wait for last buffer */
static int stop_streaming(struct vb2_queue *vq)
{
struct stk1160 *dev = vb2_get_drv_priv(vq);
return stk1160_stop_streaming(dev);
}
static struct vb2_ops stk1160_video_qops = {
.queue_setup = queue_setup,
.buf_queue = buffer_queue,
.start_streaming = start_streaming,
.stop_streaming = stop_streaming,
.wait_prepare = vb2_ops_wait_prepare,
.wait_finish = vb2_ops_wait_finish,
};
static struct video_device v4l_template = {
.name = "stk1160",
.tvnorms = V4L2_STD_525_60 | V4L2_STD_625_50,
.fops = &stk1160_fops,
.ioctl_ops = &stk1160_ioctl_ops,
.release = video_device_release_empty,
};
/********************************************************************/
/* Must be called with both v4l_lock and vb_queue_lock hold */
void stk1160_clear_queue(struct stk1160 *dev)
{
struct stk1160_buffer *buf;
unsigned long flags;
/* Release all active buffers */
spin_lock_irqsave(&dev->buf_lock, flags);
while (!list_empty(&dev->avail_bufs)) {
buf = list_first_entry(&dev->avail_bufs,
struct stk1160_buffer, list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
stk1160_info("buffer [%p/%d] aborted\n",
buf, buf->vb.v4l2_buf.index);
}
/* It's important to clear current buffer */
dev->isoc_ctl.buf = NULL;
spin_unlock_irqrestore(&dev->buf_lock, flags);
}
int stk1160_vb2_setup(struct stk1160 *dev)
{
int rc;
struct vb2_queue *q;
q = &dev->vb_vidq;
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct stk1160_buffer);
q->ops = &stk1160_video_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
rc = vb2_queue_init(q);
if (rc < 0)
return rc;
/* initialize video dma queue */
INIT_LIST_HEAD(&dev->avail_bufs);
return 0;
}
int stk1160_video_register(struct stk1160 *dev)
{
int rc;
/* Initialize video_device with a template structure */
dev->vdev = v4l_template;
dev->vdev.debug = vidioc_debug;
dev->vdev.queue = &dev->vb_vidq;
/*
* Provide mutexes for v4l2 core and for videobuf2 queue.
* It will be used to protect *only* v4l2 ioctls.
*/
dev->vdev.lock = &dev->v4l_lock;
dev->vdev.queue->lock = &dev->vb_queue_lock;
/* This will be used to set video_device parent */
dev->vdev.v4l2_dev = &dev->v4l2_dev;
set_bit(V4L2_FL_USE_FH_PRIO, &dev->vdev.flags);
/* NTSC is default */
dev->norm = V4L2_STD_NTSC_M;
dev->width = 720;
dev->height = 480;
/* set default format */
dev->fmt = &format[0];
stk1160_set_std(dev);
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std,
dev->norm);
video_set_drvdata(&dev->vdev, dev);
rc = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
if (rc < 0) {
stk1160_err("video_register_device failed (%d)\n", rc);
return rc;
}
v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
video_device_node_name(&dev->vdev));
return 0;
}
| gpl-2.0 |
bju2000/android_kernel_samsung_slteskt | fs/cifs/misc.c | 2078 | 17222 | /*
* fs/cifs/misc.c
*
* Copyright (C) International Business Machines Corp., 2002,2008
* Author(s): Steve French (sfrench@us.ibm.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/mempool.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
#include "smberr.h"
#include "nterr.h"
#include "cifs_unicode.h"
#ifdef CONFIG_CIFS_SMB2
#include "smb2pdu.h"
#endif
extern mempool_t *cifs_sm_req_poolp;
extern mempool_t *cifs_req_poolp;
/* The xid serves as a useful identifier for each incoming vfs request,
in a similar way to the mid which is useful to track each sent smb,
and CurrentXid can also provide a running counter (although it
will eventually wrap past zero) of the total vfs operations handled
since the cifs fs was mounted */
unsigned int
_get_xid(void)
{
unsigned int xid;
spin_lock(&GlobalMid_Lock);
GlobalTotalActiveXid++;
/* keep high water mark for number of simultaneous ops in filesystem */
if (GlobalTotalActiveXid > GlobalMaxActiveXid)
GlobalMaxActiveXid = GlobalTotalActiveXid;
if (GlobalTotalActiveXid > 65000)
cifs_dbg(FYI, "warning: more than 65000 requests active\n");
xid = GlobalCurrentXid++;
spin_unlock(&GlobalMid_Lock);
return xid;
}
void
_free_xid(unsigned int xid)
{
spin_lock(&GlobalMid_Lock);
/* if (GlobalTotalActiveXid == 0)
BUG(); */
GlobalTotalActiveXid--;
spin_unlock(&GlobalMid_Lock);
}
struct cifs_ses *
sesInfoAlloc(void)
{
struct cifs_ses *ret_buf;
ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
if (ret_buf) {
atomic_inc(&sesInfoAllocCount);
ret_buf->status = CifsNew;
++ret_buf->ses_count;
INIT_LIST_HEAD(&ret_buf->smb_ses_list);
INIT_LIST_HEAD(&ret_buf->tcon_list);
mutex_init(&ret_buf->session_mutex);
}
return ret_buf;
}
void
sesInfoFree(struct cifs_ses *buf_to_free)
{
if (buf_to_free == NULL) {
cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
return;
}
atomic_dec(&sesInfoAllocCount);
kfree(buf_to_free->serverOS);
kfree(buf_to_free->serverDomain);
kfree(buf_to_free->serverNOS);
if (buf_to_free->password) {
memset(buf_to_free->password, 0, strlen(buf_to_free->password));
kfree(buf_to_free->password);
}
kfree(buf_to_free->user_name);
kfree(buf_to_free->domainName);
kfree(buf_to_free);
}
struct cifs_tcon *
tconInfoAlloc(void)
{
struct cifs_tcon *ret_buf;
ret_buf = kzalloc(sizeof(struct cifs_tcon), GFP_KERNEL);
if (ret_buf) {
atomic_inc(&tconInfoAllocCount);
ret_buf->tidStatus = CifsNew;
++ret_buf->tc_count;
INIT_LIST_HEAD(&ret_buf->openFileList);
INIT_LIST_HEAD(&ret_buf->tcon_list);
#ifdef CONFIG_CIFS_STATS
spin_lock_init(&ret_buf->stat_lock);
#endif
}
return ret_buf;
}
void
tconInfoFree(struct cifs_tcon *buf_to_free)
{
if (buf_to_free == NULL) {
cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
return;
}
atomic_dec(&tconInfoAllocCount);
kfree(buf_to_free->nativeFileSystem);
if (buf_to_free->password) {
memset(buf_to_free->password, 0, strlen(buf_to_free->password));
kfree(buf_to_free->password);
}
kfree(buf_to_free);
}
struct smb_hdr *
cifs_buf_get(void)
{
struct smb_hdr *ret_buf = NULL;
size_t buf_size = sizeof(struct smb_hdr);
#ifdef CONFIG_CIFS_SMB2
/*
* SMB2 header is bigger than CIFS one - no problems to clean some
* more bytes for CIFS.
*/
buf_size = sizeof(struct smb2_hdr);
#endif
/*
* We could use negotiated size instead of max_msgsize -
* but it may be more efficient to always alloc same size
* albeit slightly larger than necessary and maxbuffersize
* defaults to this and can not be bigger.
*/
ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
/* clear the first few header bytes */
/* for most paths, more is cleared in header_assemble */
if (ret_buf) {
memset(ret_buf, 0, buf_size + 3);
atomic_inc(&bufAllocCount);
#ifdef CONFIG_CIFS_STATS2
atomic_inc(&totBufAllocCount);
#endif /* CONFIG_CIFS_STATS2 */
}
return ret_buf;
}
void
cifs_buf_release(void *buf_to_free)
{
if (buf_to_free == NULL) {
/* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
return;
}
mempool_free(buf_to_free, cifs_req_poolp);
atomic_dec(&bufAllocCount);
return;
}
struct smb_hdr *
cifs_small_buf_get(void)
{
struct smb_hdr *ret_buf = NULL;
/* We could use negotiated size instead of max_msgsize -
but it may be more efficient to always alloc same size
albeit slightly larger than necessary and maxbuffersize
defaults to this and can not be bigger */
ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
if (ret_buf) {
/* No need to clear memory here, cleared in header assemble */
/* memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
atomic_inc(&smBufAllocCount);
#ifdef CONFIG_CIFS_STATS2
atomic_inc(&totSmBufAllocCount);
#endif /* CONFIG_CIFS_STATS2 */
}
return ret_buf;
}
void
cifs_small_buf_release(void *buf_to_free)
{
if (buf_to_free == NULL) {
cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
return;
}
mempool_free(buf_to_free, cifs_sm_req_poolp);
atomic_dec(&smBufAllocCount);
return;
}
/* NB: MID can not be set if treeCon not passed in, in that
case it is responsbility of caller to set the mid */
void
header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
const struct cifs_tcon *treeCon, int word_count
/* length of fixed section (word count) in two byte units */)
{
char *temp = (char *) buffer;
memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
buffer->smb_buf_length = cpu_to_be32(
(2 * word_count) + sizeof(struct smb_hdr) -
4 /* RFC 1001 length field does not count */ +
2 /* for bcc field itself */) ;
buffer->Protocol[0] = 0xFF;
buffer->Protocol[1] = 'S';
buffer->Protocol[2] = 'M';
buffer->Protocol[3] = 'B';
buffer->Command = smb_command;
buffer->Flags = 0x00; /* case sensitive */
buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
buffer->Pid = cpu_to_le16((__u16)current->tgid);
buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
if (treeCon) {
buffer->Tid = treeCon->tid;
if (treeCon->ses) {
if (treeCon->ses->capabilities & CAP_UNICODE)
buffer->Flags2 |= SMBFLG2_UNICODE;
if (treeCon->ses->capabilities & CAP_STATUS32)
buffer->Flags2 |= SMBFLG2_ERR_STATUS;
/* Uid is not converted */
buffer->Uid = treeCon->ses->Suid;
buffer->Mid = get_next_mid(treeCon->ses->server);
}
if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
buffer->Flags2 |= SMBFLG2_DFS;
if (treeCon->nocase)
buffer->Flags |= SMBFLG_CASELESS;
if ((treeCon->ses) && (treeCon->ses->server))
if (treeCon->ses->server->sec_mode &
(SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
}
/* endian conversion of flags is now done just before sending */
buffer->WordCount = (char) word_count;
return;
}
static int
check_smb_hdr(struct smb_hdr *smb, __u16 mid)
{
/* does it have the right SMB "signature" ? */
if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
*(unsigned int *)smb->Protocol);
return 1;
}
/* Make sure that message ids match */
if (mid != smb->Mid) {
cifs_dbg(VFS, "Mids do not match. received=%u expected=%u\n",
smb->Mid, mid);
return 1;
}
/* if it's a response then accept */
if (smb->Flags & SMBFLG_RESPONSE)
return 0;
/* only one valid case where server sends us request */
if (smb->Command == SMB_COM_LOCKING_ANDX)
return 0;
cifs_dbg(VFS, "Server sent request, not response. mid=%u\n", smb->Mid);
return 1;
}
int
checkSMB(char *buf, unsigned int total_read)
{
struct smb_hdr *smb = (struct smb_hdr *)buf;
__u16 mid = smb->Mid;
__u32 rfclen = be32_to_cpu(smb->smb_buf_length);
__u32 clc_len; /* calculated length */
cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
total_read, rfclen);
/* is this frame too small to even get to a BCC? */
if (total_read < 2 + sizeof(struct smb_hdr)) {
if ((total_read >= sizeof(struct smb_hdr) - 1)
&& (smb->Status.CifsError != 0)) {
/* it's an error return */
smb->WordCount = 0;
/* some error cases do not return wct and bcc */
return 0;
} else if ((total_read == sizeof(struct smb_hdr) + 1) &&
(smb->WordCount == 0)) {
char *tmp = (char *)smb;
/* Need to work around a bug in two servers here */
/* First, check if the part of bcc they sent was zero */
if (tmp[sizeof(struct smb_hdr)] == 0) {
/* some servers return only half of bcc
* on simple responses (wct, bcc both zero)
* in particular have seen this on
* ulogoffX and FindClose. This leaves
* one byte of bcc potentially unitialized
*/
/* zero rest of bcc */
tmp[sizeof(struct smb_hdr)+1] = 0;
return 0;
}
cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
} else {
cifs_dbg(VFS, "Length less than smb header size\n");
}
return -EIO;
}
/* otherwise, there is enough to get to the BCC */
if (check_smb_hdr(smb, mid))
return -EIO;
clc_len = smbCalcSize(smb);
if (4 + rfclen != total_read) {
cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
rfclen);
return -EIO;
}
if (4 + rfclen != clc_len) {
/* check if bcc wrapped around for large read responses */
if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
/* check if lengths match mod 64K */
if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
return 0; /* bcc wrapped */
}
cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
clc_len, 4 + rfclen, smb->Mid);
if (4 + rfclen < clc_len) {
cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
rfclen, smb->Mid);
return -EIO;
} else if (rfclen > clc_len + 512) {
/*
* Some servers (Windows XP in particular) send more
* data than the lengths in the SMB packet would
* indicate on certain calls (byte range locks and
* trans2 find first calls in particular). While the
* client can handle such a frame by ignoring the
* trailing data, we choose limit the amount of extra
* data to 512 bytes.
*/
cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
rfclen, smb->Mid);
return -EIO;
}
}
return 0;
}
bool
is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
{
struct smb_hdr *buf = (struct smb_hdr *)buffer;
struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
struct list_head *tmp, *tmp1, *tmp2;
struct cifs_ses *ses;
struct cifs_tcon *tcon;
struct cifsInodeInfo *pCifsInode;
struct cifsFileInfo *netfile;
cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
(pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
struct smb_com_transaction_change_notify_rsp *pSMBr =
(struct smb_com_transaction_change_notify_rsp *)buf;
struct file_notify_information *pnotify;
__u32 data_offset = 0;
if (get_bcc(buf) > sizeof(struct file_notify_information)) {
data_offset = le32_to_cpu(pSMBr->DataOffset);
pnotify = (struct file_notify_information *)
((char *)&pSMBr->hdr.Protocol + data_offset);
cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
pnotify->FileName, pnotify->Action);
/* cifs_dump_mem("Rcvd notify Data: ",buf,
sizeof(struct smb_hdr)+60); */
return true;
}
if (pSMBr->hdr.Status.CifsError) {
cifs_dbg(FYI, "notify err 0x%d\n",
pSMBr->hdr.Status.CifsError);
return true;
}
return false;
}
if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
return false;
if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
/* no sense logging error on invalid handle on oplock
break - harmless race between close request and oplock
break response is expected from time to time writing out
large dirty files cached on the client */
if ((NT_STATUS_INVALID_HANDLE) ==
le32_to_cpu(pSMB->hdr.Status.CifsError)) {
cifs_dbg(FYI, "invalid handle on oplock break\n");
return true;
} else if (ERRbadfid ==
le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
return true;
} else {
return false; /* on valid oplock brk we get "request" */
}
}
if (pSMB->hdr.WordCount != 8)
return false;
cifs_dbg(FYI, "oplock type 0x%d level 0x%d\n",
pSMB->LockType, pSMB->OplockLevel);
if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
return false;
/* look up tcon based on tid & uid */
spin_lock(&cifs_tcp_ses_lock);
list_for_each(tmp, &srv->smb_ses_list) {
ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
list_for_each(tmp1, &ses->tcon_list) {
tcon = list_entry(tmp1, struct cifs_tcon, tcon_list);
if (tcon->tid != buf->Tid)
continue;
cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
spin_lock(&cifs_file_list_lock);
list_for_each(tmp2, &tcon->openFileList) {
netfile = list_entry(tmp2, struct cifsFileInfo,
tlist);
if (pSMB->Fid != netfile->fid.netfid)
continue;
cifs_dbg(FYI, "file id match, oplock break\n");
pCifsInode = CIFS_I(netfile->dentry->d_inode);
cifs_set_oplock_level(pCifsInode,
pSMB->OplockLevel ? OPLOCK_READ : 0);
queue_work(cifsiod_wq,
&netfile->oplock_break);
netfile->oplock_break_cancelled = false;
spin_unlock(&cifs_file_list_lock);
spin_unlock(&cifs_tcp_ses_lock);
return true;
}
spin_unlock(&cifs_file_list_lock);
spin_unlock(&cifs_tcp_ses_lock);
cifs_dbg(FYI, "No matching file for oplock break\n");
return true;
}
}
spin_unlock(&cifs_tcp_ses_lock);
cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
return true;
}
void
dump_smb(void *buf, int smb_buf_length)
{
int i, j;
char debug_line[17];
unsigned char *buffer = buf;
if (traceSMB == 0)
return;
for (i = 0, j = 0; i < smb_buf_length; i++, j++) {
if (i % 8 == 0) {
/* have reached the beginning of line */
printk(KERN_DEBUG "| ");
j = 0;
}
printk("%0#4x ", buffer[i]);
debug_line[2 * j] = ' ';
if (isprint(buffer[i]))
debug_line[1 + (2 * j)] = buffer[i];
else
debug_line[1 + (2 * j)] = '_';
if (i % 8 == 7) {
/* reached end of line, time to print ascii */
debug_line[16] = 0;
printk(" | %s\n", debug_line);
}
}
for (; j < 8; j++) {
printk(" ");
debug_line[2 * j] = ' ';
debug_line[1 + (2 * j)] = ' ';
}
printk(" | %s\n", debug_line);
return;
}
void
cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
{
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s. This server doesn't seem to support them properly. Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n",
cifs_sb_master_tcon(cifs_sb)->treeName);
}
}
void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
{
oplock &= 0xF;
if (oplock == OPLOCK_EXCLUSIVE) {
cinode->clientCanCacheAll = true;
cinode->clientCanCacheRead = true;
cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
&cinode->vfs_inode);
} else if (oplock == OPLOCK_READ) {
cinode->clientCanCacheAll = false;
cinode->clientCanCacheRead = true;
cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
&cinode->vfs_inode);
} else {
cinode->clientCanCacheAll = false;
cinode->clientCanCacheRead = false;
}
}
bool
backup_cred(struct cifs_sb_info *cifs_sb)
{
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
if (uid_eq(cifs_sb->mnt_backupuid, current_fsuid()))
return true;
}
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
if (in_group_p(cifs_sb->mnt_backupgid))
return true;
}
return false;
}
void
cifs_del_pending_open(struct cifs_pending_open *open)
{
spin_lock(&cifs_file_list_lock);
list_del(&open->olist);
spin_unlock(&cifs_file_list_lock);
}
void
cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
struct cifs_pending_open *open)
{
#ifdef CONFIG_CIFS_SMB2
memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
#endif
open->oplock = CIFS_OPLOCK_NO_CHANGE;
open->tlink = tlink;
fid->pending_open = open;
list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
}
void
cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
struct cifs_pending_open *open)
{
spin_lock(&cifs_file_list_lock);
cifs_add_pending_open_locked(fid, tlink, open);
spin_unlock(&cifs_file_list_lock);
}
| gpl-2.0 |
phuthinh100/Kernel-JB--sky-A830L | drivers/gpu/drm/i915/i915_suspend.c | 3102 | 29502 | /*
*
* Copyright 2008 (c) Intel Corporation
* Jesse Barnes <jbarnes@virtuousgeek.org>
*
* 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, sub license, 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL TUNGSTEN GRAPHICS 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 "drmP.h"
#include "drm.h"
#include "i915_drm.h"
#include "intel_drv.h"
#include "i915_reg.h"
static bool i915_pipe_enabled(struct drm_device *dev, enum pipe pipe)
{
struct drm_i915_private *dev_priv = dev->dev_private;
u32 dpll_reg;
/* On IVB, 3rd pipe shares PLL with another one */
if (pipe > 1)
return false;
if (HAS_PCH_SPLIT(dev))
dpll_reg = PCH_DPLL(pipe);
else
dpll_reg = (pipe == PIPE_A) ? _DPLL_A : _DPLL_B;
return (I915_READ(dpll_reg) & DPLL_VCO_ENABLE);
}
static void i915_save_palette(struct drm_device *dev, enum pipe pipe)
{
struct drm_i915_private *dev_priv = dev->dev_private;
unsigned long reg = (pipe == PIPE_A ? _PALETTE_A : _PALETTE_B);
u32 *array;
int i;
if (!i915_pipe_enabled(dev, pipe))
return;
if (HAS_PCH_SPLIT(dev))
reg = (pipe == PIPE_A) ? _LGC_PALETTE_A : _LGC_PALETTE_B;
if (pipe == PIPE_A)
array = dev_priv->save_palette_a;
else
array = dev_priv->save_palette_b;
for (i = 0; i < 256; i++)
array[i] = I915_READ(reg + (i << 2));
}
static void i915_restore_palette(struct drm_device *dev, enum pipe pipe)
{
struct drm_i915_private *dev_priv = dev->dev_private;
unsigned long reg = (pipe == PIPE_A ? _PALETTE_A : _PALETTE_B);
u32 *array;
int i;
if (!i915_pipe_enabled(dev, pipe))
return;
if (HAS_PCH_SPLIT(dev))
reg = (pipe == PIPE_A) ? _LGC_PALETTE_A : _LGC_PALETTE_B;
if (pipe == PIPE_A)
array = dev_priv->save_palette_a;
else
array = dev_priv->save_palette_b;
for (i = 0; i < 256; i++)
I915_WRITE(reg + (i << 2), array[i]);
}
static u8 i915_read_indexed(struct drm_device *dev, u16 index_port, u16 data_port, u8 reg)
{
struct drm_i915_private *dev_priv = dev->dev_private;
I915_WRITE8(index_port, reg);
return I915_READ8(data_port);
}
static u8 i915_read_ar(struct drm_device *dev, u16 st01, u8 reg, u16 palette_enable)
{
struct drm_i915_private *dev_priv = dev->dev_private;
I915_READ8(st01);
I915_WRITE8(VGA_AR_INDEX, palette_enable | reg);
return I915_READ8(VGA_AR_DATA_READ);
}
static void i915_write_ar(struct drm_device *dev, u16 st01, u8 reg, u8 val, u16 palette_enable)
{
struct drm_i915_private *dev_priv = dev->dev_private;
I915_READ8(st01);
I915_WRITE8(VGA_AR_INDEX, palette_enable | reg);
I915_WRITE8(VGA_AR_DATA_WRITE, val);
}
static void i915_write_indexed(struct drm_device *dev, u16 index_port, u16 data_port, u8 reg, u8 val)
{
struct drm_i915_private *dev_priv = dev->dev_private;
I915_WRITE8(index_port, reg);
I915_WRITE8(data_port, val);
}
static void i915_save_vga(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
int i;
u16 cr_index, cr_data, st01;
/* VGA color palette registers */
dev_priv->saveDACMASK = I915_READ8(VGA_DACMASK);
/* MSR bits */
dev_priv->saveMSR = I915_READ8(VGA_MSR_READ);
if (dev_priv->saveMSR & VGA_MSR_CGA_MODE) {
cr_index = VGA_CR_INDEX_CGA;
cr_data = VGA_CR_DATA_CGA;
st01 = VGA_ST01_CGA;
} else {
cr_index = VGA_CR_INDEX_MDA;
cr_data = VGA_CR_DATA_MDA;
st01 = VGA_ST01_MDA;
}
/* CRT controller regs */
i915_write_indexed(dev, cr_index, cr_data, 0x11,
i915_read_indexed(dev, cr_index, cr_data, 0x11) &
(~0x80));
for (i = 0; i <= 0x24; i++)
dev_priv->saveCR[i] =
i915_read_indexed(dev, cr_index, cr_data, i);
/* Make sure we don't turn off CR group 0 writes */
dev_priv->saveCR[0x11] &= ~0x80;
/* Attribute controller registers */
I915_READ8(st01);
dev_priv->saveAR_INDEX = I915_READ8(VGA_AR_INDEX);
for (i = 0; i <= 0x14; i++)
dev_priv->saveAR[i] = i915_read_ar(dev, st01, i, 0);
I915_READ8(st01);
I915_WRITE8(VGA_AR_INDEX, dev_priv->saveAR_INDEX);
I915_READ8(st01);
/* Graphics controller registers */
for (i = 0; i < 9; i++)
dev_priv->saveGR[i] =
i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, i);
dev_priv->saveGR[0x10] =
i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x10);
dev_priv->saveGR[0x11] =
i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x11);
dev_priv->saveGR[0x18] =
i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x18);
/* Sequencer registers */
for (i = 0; i < 8; i++)
dev_priv->saveSR[i] =
i915_read_indexed(dev, VGA_SR_INDEX, VGA_SR_DATA, i);
}
static void i915_restore_vga(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
int i;
u16 cr_index, cr_data, st01;
/* MSR bits */
I915_WRITE8(VGA_MSR_WRITE, dev_priv->saveMSR);
if (dev_priv->saveMSR & VGA_MSR_CGA_MODE) {
cr_index = VGA_CR_INDEX_CGA;
cr_data = VGA_CR_DATA_CGA;
st01 = VGA_ST01_CGA;
} else {
cr_index = VGA_CR_INDEX_MDA;
cr_data = VGA_CR_DATA_MDA;
st01 = VGA_ST01_MDA;
}
/* Sequencer registers, don't write SR07 */
for (i = 0; i < 7; i++)
i915_write_indexed(dev, VGA_SR_INDEX, VGA_SR_DATA, i,
dev_priv->saveSR[i]);
/* CRT controller regs */
/* Enable CR group 0 writes */
i915_write_indexed(dev, cr_index, cr_data, 0x11, dev_priv->saveCR[0x11]);
for (i = 0; i <= 0x24; i++)
i915_write_indexed(dev, cr_index, cr_data, i, dev_priv->saveCR[i]);
/* Graphics controller regs */
for (i = 0; i < 9; i++)
i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, i,
dev_priv->saveGR[i]);
i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x10,
dev_priv->saveGR[0x10]);
i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x11,
dev_priv->saveGR[0x11]);
i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x18,
dev_priv->saveGR[0x18]);
/* Attribute controller registers */
I915_READ8(st01); /* switch back to index mode */
for (i = 0; i <= 0x14; i++)
i915_write_ar(dev, st01, i, dev_priv->saveAR[i], 0);
I915_READ8(st01); /* switch back to index mode */
I915_WRITE8(VGA_AR_INDEX, dev_priv->saveAR_INDEX | 0x20);
I915_READ8(st01);
/* VGA color palette registers */
I915_WRITE8(VGA_DACMASK, dev_priv->saveDACMASK);
}
static void i915_save_modeset_reg(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
int i;
if (drm_core_check_feature(dev, DRIVER_MODESET))
return;
/* Cursor state */
dev_priv->saveCURACNTR = I915_READ(_CURACNTR);
dev_priv->saveCURAPOS = I915_READ(_CURAPOS);
dev_priv->saveCURABASE = I915_READ(_CURABASE);
dev_priv->saveCURBCNTR = I915_READ(_CURBCNTR);
dev_priv->saveCURBPOS = I915_READ(_CURBPOS);
dev_priv->saveCURBBASE = I915_READ(_CURBBASE);
if (IS_GEN2(dev))
dev_priv->saveCURSIZE = I915_READ(CURSIZE);
if (HAS_PCH_SPLIT(dev)) {
dev_priv->savePCH_DREF_CONTROL = I915_READ(PCH_DREF_CONTROL);
dev_priv->saveDISP_ARB_CTL = I915_READ(DISP_ARB_CTL);
}
/* Pipe & plane A info */
dev_priv->savePIPEACONF = I915_READ(_PIPEACONF);
dev_priv->savePIPEASRC = I915_READ(_PIPEASRC);
if (HAS_PCH_SPLIT(dev)) {
dev_priv->saveFPA0 = I915_READ(_PCH_FPA0);
dev_priv->saveFPA1 = I915_READ(_PCH_FPA1);
dev_priv->saveDPLL_A = I915_READ(_PCH_DPLL_A);
} else {
dev_priv->saveFPA0 = I915_READ(_FPA0);
dev_priv->saveFPA1 = I915_READ(_FPA1);
dev_priv->saveDPLL_A = I915_READ(_DPLL_A);
}
if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev))
dev_priv->saveDPLL_A_MD = I915_READ(_DPLL_A_MD);
dev_priv->saveHTOTAL_A = I915_READ(_HTOTAL_A);
dev_priv->saveHBLANK_A = I915_READ(_HBLANK_A);
dev_priv->saveHSYNC_A = I915_READ(_HSYNC_A);
dev_priv->saveVTOTAL_A = I915_READ(_VTOTAL_A);
dev_priv->saveVBLANK_A = I915_READ(_VBLANK_A);
dev_priv->saveVSYNC_A = I915_READ(_VSYNC_A);
if (!HAS_PCH_SPLIT(dev))
dev_priv->saveBCLRPAT_A = I915_READ(_BCLRPAT_A);
if (HAS_PCH_SPLIT(dev)) {
dev_priv->savePIPEA_DATA_M1 = I915_READ(_PIPEA_DATA_M1);
dev_priv->savePIPEA_DATA_N1 = I915_READ(_PIPEA_DATA_N1);
dev_priv->savePIPEA_LINK_M1 = I915_READ(_PIPEA_LINK_M1);
dev_priv->savePIPEA_LINK_N1 = I915_READ(_PIPEA_LINK_N1);
dev_priv->saveFDI_TXA_CTL = I915_READ(_FDI_TXA_CTL);
dev_priv->saveFDI_RXA_CTL = I915_READ(_FDI_RXA_CTL);
dev_priv->savePFA_CTL_1 = I915_READ(_PFA_CTL_1);
dev_priv->savePFA_WIN_SZ = I915_READ(_PFA_WIN_SZ);
dev_priv->savePFA_WIN_POS = I915_READ(_PFA_WIN_POS);
dev_priv->saveTRANSACONF = I915_READ(_TRANSACONF);
dev_priv->saveTRANS_HTOTAL_A = I915_READ(_TRANS_HTOTAL_A);
dev_priv->saveTRANS_HBLANK_A = I915_READ(_TRANS_HBLANK_A);
dev_priv->saveTRANS_HSYNC_A = I915_READ(_TRANS_HSYNC_A);
dev_priv->saveTRANS_VTOTAL_A = I915_READ(_TRANS_VTOTAL_A);
dev_priv->saveTRANS_VBLANK_A = I915_READ(_TRANS_VBLANK_A);
dev_priv->saveTRANS_VSYNC_A = I915_READ(_TRANS_VSYNC_A);
}
dev_priv->saveDSPACNTR = I915_READ(_DSPACNTR);
dev_priv->saveDSPASTRIDE = I915_READ(_DSPASTRIDE);
dev_priv->saveDSPASIZE = I915_READ(_DSPASIZE);
dev_priv->saveDSPAPOS = I915_READ(_DSPAPOS);
dev_priv->saveDSPAADDR = I915_READ(_DSPAADDR);
if (INTEL_INFO(dev)->gen >= 4) {
dev_priv->saveDSPASURF = I915_READ(_DSPASURF);
dev_priv->saveDSPATILEOFF = I915_READ(_DSPATILEOFF);
}
i915_save_palette(dev, PIPE_A);
dev_priv->savePIPEASTAT = I915_READ(_PIPEASTAT);
/* Pipe & plane B info */
dev_priv->savePIPEBCONF = I915_READ(_PIPEBCONF);
dev_priv->savePIPEBSRC = I915_READ(_PIPEBSRC);
if (HAS_PCH_SPLIT(dev)) {
dev_priv->saveFPB0 = I915_READ(_PCH_FPB0);
dev_priv->saveFPB1 = I915_READ(_PCH_FPB1);
dev_priv->saveDPLL_B = I915_READ(_PCH_DPLL_B);
} else {
dev_priv->saveFPB0 = I915_READ(_FPB0);
dev_priv->saveFPB1 = I915_READ(_FPB1);
dev_priv->saveDPLL_B = I915_READ(_DPLL_B);
}
if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev))
dev_priv->saveDPLL_B_MD = I915_READ(_DPLL_B_MD);
dev_priv->saveHTOTAL_B = I915_READ(_HTOTAL_B);
dev_priv->saveHBLANK_B = I915_READ(_HBLANK_B);
dev_priv->saveHSYNC_B = I915_READ(_HSYNC_B);
dev_priv->saveVTOTAL_B = I915_READ(_VTOTAL_B);
dev_priv->saveVBLANK_B = I915_READ(_VBLANK_B);
dev_priv->saveVSYNC_B = I915_READ(_VSYNC_B);
if (!HAS_PCH_SPLIT(dev))
dev_priv->saveBCLRPAT_B = I915_READ(_BCLRPAT_B);
if (HAS_PCH_SPLIT(dev)) {
dev_priv->savePIPEB_DATA_M1 = I915_READ(_PIPEB_DATA_M1);
dev_priv->savePIPEB_DATA_N1 = I915_READ(_PIPEB_DATA_N1);
dev_priv->savePIPEB_LINK_M1 = I915_READ(_PIPEB_LINK_M1);
dev_priv->savePIPEB_LINK_N1 = I915_READ(_PIPEB_LINK_N1);
dev_priv->saveFDI_TXB_CTL = I915_READ(_FDI_TXB_CTL);
dev_priv->saveFDI_RXB_CTL = I915_READ(_FDI_RXB_CTL);
dev_priv->savePFB_CTL_1 = I915_READ(_PFB_CTL_1);
dev_priv->savePFB_WIN_SZ = I915_READ(_PFB_WIN_SZ);
dev_priv->savePFB_WIN_POS = I915_READ(_PFB_WIN_POS);
dev_priv->saveTRANSBCONF = I915_READ(_TRANSBCONF);
dev_priv->saveTRANS_HTOTAL_B = I915_READ(_TRANS_HTOTAL_B);
dev_priv->saveTRANS_HBLANK_B = I915_READ(_TRANS_HBLANK_B);
dev_priv->saveTRANS_HSYNC_B = I915_READ(_TRANS_HSYNC_B);
dev_priv->saveTRANS_VTOTAL_B = I915_READ(_TRANS_VTOTAL_B);
dev_priv->saveTRANS_VBLANK_B = I915_READ(_TRANS_VBLANK_B);
dev_priv->saveTRANS_VSYNC_B = I915_READ(_TRANS_VSYNC_B);
}
dev_priv->saveDSPBCNTR = I915_READ(_DSPBCNTR);
dev_priv->saveDSPBSTRIDE = I915_READ(_DSPBSTRIDE);
dev_priv->saveDSPBSIZE = I915_READ(_DSPBSIZE);
dev_priv->saveDSPBPOS = I915_READ(_DSPBPOS);
dev_priv->saveDSPBADDR = I915_READ(_DSPBADDR);
if (INTEL_INFO(dev)->gen >= 4) {
dev_priv->saveDSPBSURF = I915_READ(_DSPBSURF);
dev_priv->saveDSPBTILEOFF = I915_READ(_DSPBTILEOFF);
}
i915_save_palette(dev, PIPE_B);
dev_priv->savePIPEBSTAT = I915_READ(_PIPEBSTAT);
/* Fences */
switch (INTEL_INFO(dev)->gen) {
case 7:
case 6:
for (i = 0; i < 16; i++)
dev_priv->saveFENCE[i] = I915_READ64(FENCE_REG_SANDYBRIDGE_0 + (i * 8));
break;
case 5:
case 4:
for (i = 0; i < 16; i++)
dev_priv->saveFENCE[i] = I915_READ64(FENCE_REG_965_0 + (i * 8));
break;
case 3:
if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
for (i = 0; i < 8; i++)
dev_priv->saveFENCE[i+8] = I915_READ(FENCE_REG_945_8 + (i * 4));
case 2:
for (i = 0; i < 8; i++)
dev_priv->saveFENCE[i] = I915_READ(FENCE_REG_830_0 + (i * 4));
break;
}
return;
}
static void i915_restore_modeset_reg(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
int dpll_a_reg, fpa0_reg, fpa1_reg;
int dpll_b_reg, fpb0_reg, fpb1_reg;
int i;
if (drm_core_check_feature(dev, DRIVER_MODESET))
return;
/* Fences */
switch (INTEL_INFO(dev)->gen) {
case 7:
case 6:
for (i = 0; i < 16; i++)
I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (i * 8), dev_priv->saveFENCE[i]);
break;
case 5:
case 4:
for (i = 0; i < 16; i++)
I915_WRITE64(FENCE_REG_965_0 + (i * 8), dev_priv->saveFENCE[i]);
break;
case 3:
case 2:
if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
for (i = 0; i < 8; i++)
I915_WRITE(FENCE_REG_945_8 + (i * 4), dev_priv->saveFENCE[i+8]);
for (i = 0; i < 8; i++)
I915_WRITE(FENCE_REG_830_0 + (i * 4), dev_priv->saveFENCE[i]);
break;
}
if (HAS_PCH_SPLIT(dev)) {
dpll_a_reg = _PCH_DPLL_A;
dpll_b_reg = _PCH_DPLL_B;
fpa0_reg = _PCH_FPA0;
fpb0_reg = _PCH_FPB0;
fpa1_reg = _PCH_FPA1;
fpb1_reg = _PCH_FPB1;
} else {
dpll_a_reg = _DPLL_A;
dpll_b_reg = _DPLL_B;
fpa0_reg = _FPA0;
fpb0_reg = _FPB0;
fpa1_reg = _FPA1;
fpb1_reg = _FPB1;
}
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(PCH_DREF_CONTROL, dev_priv->savePCH_DREF_CONTROL);
I915_WRITE(DISP_ARB_CTL, dev_priv->saveDISP_ARB_CTL);
}
/* Pipe & plane A info */
/* Prime the clock */
if (dev_priv->saveDPLL_A & DPLL_VCO_ENABLE) {
I915_WRITE(dpll_a_reg, dev_priv->saveDPLL_A &
~DPLL_VCO_ENABLE);
POSTING_READ(dpll_a_reg);
udelay(150);
}
I915_WRITE(fpa0_reg, dev_priv->saveFPA0);
I915_WRITE(fpa1_reg, dev_priv->saveFPA1);
/* Actually enable it */
I915_WRITE(dpll_a_reg, dev_priv->saveDPLL_A);
POSTING_READ(dpll_a_reg);
udelay(150);
if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) {
I915_WRITE(_DPLL_A_MD, dev_priv->saveDPLL_A_MD);
POSTING_READ(_DPLL_A_MD);
}
udelay(150);
/* Restore mode */
I915_WRITE(_HTOTAL_A, dev_priv->saveHTOTAL_A);
I915_WRITE(_HBLANK_A, dev_priv->saveHBLANK_A);
I915_WRITE(_HSYNC_A, dev_priv->saveHSYNC_A);
I915_WRITE(_VTOTAL_A, dev_priv->saveVTOTAL_A);
I915_WRITE(_VBLANK_A, dev_priv->saveVBLANK_A);
I915_WRITE(_VSYNC_A, dev_priv->saveVSYNC_A);
if (!HAS_PCH_SPLIT(dev))
I915_WRITE(_BCLRPAT_A, dev_priv->saveBCLRPAT_A);
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(_PIPEA_DATA_M1, dev_priv->savePIPEA_DATA_M1);
I915_WRITE(_PIPEA_DATA_N1, dev_priv->savePIPEA_DATA_N1);
I915_WRITE(_PIPEA_LINK_M1, dev_priv->savePIPEA_LINK_M1);
I915_WRITE(_PIPEA_LINK_N1, dev_priv->savePIPEA_LINK_N1);
I915_WRITE(_FDI_RXA_CTL, dev_priv->saveFDI_RXA_CTL);
I915_WRITE(_FDI_TXA_CTL, dev_priv->saveFDI_TXA_CTL);
I915_WRITE(_PFA_CTL_1, dev_priv->savePFA_CTL_1);
I915_WRITE(_PFA_WIN_SZ, dev_priv->savePFA_WIN_SZ);
I915_WRITE(_PFA_WIN_POS, dev_priv->savePFA_WIN_POS);
I915_WRITE(_TRANSACONF, dev_priv->saveTRANSACONF);
I915_WRITE(_TRANS_HTOTAL_A, dev_priv->saveTRANS_HTOTAL_A);
I915_WRITE(_TRANS_HBLANK_A, dev_priv->saveTRANS_HBLANK_A);
I915_WRITE(_TRANS_HSYNC_A, dev_priv->saveTRANS_HSYNC_A);
I915_WRITE(_TRANS_VTOTAL_A, dev_priv->saveTRANS_VTOTAL_A);
I915_WRITE(_TRANS_VBLANK_A, dev_priv->saveTRANS_VBLANK_A);
I915_WRITE(_TRANS_VSYNC_A, dev_priv->saveTRANS_VSYNC_A);
}
/* Restore plane info */
I915_WRITE(_DSPASIZE, dev_priv->saveDSPASIZE);
I915_WRITE(_DSPAPOS, dev_priv->saveDSPAPOS);
I915_WRITE(_PIPEASRC, dev_priv->savePIPEASRC);
I915_WRITE(_DSPAADDR, dev_priv->saveDSPAADDR);
I915_WRITE(_DSPASTRIDE, dev_priv->saveDSPASTRIDE);
if (INTEL_INFO(dev)->gen >= 4) {
I915_WRITE(_DSPASURF, dev_priv->saveDSPASURF);
I915_WRITE(_DSPATILEOFF, dev_priv->saveDSPATILEOFF);
}
I915_WRITE(_PIPEACONF, dev_priv->savePIPEACONF);
i915_restore_palette(dev, PIPE_A);
/* Enable the plane */
I915_WRITE(_DSPACNTR, dev_priv->saveDSPACNTR);
I915_WRITE(_DSPAADDR, I915_READ(_DSPAADDR));
/* Pipe & plane B info */
if (dev_priv->saveDPLL_B & DPLL_VCO_ENABLE) {
I915_WRITE(dpll_b_reg, dev_priv->saveDPLL_B &
~DPLL_VCO_ENABLE);
POSTING_READ(dpll_b_reg);
udelay(150);
}
I915_WRITE(fpb0_reg, dev_priv->saveFPB0);
I915_WRITE(fpb1_reg, dev_priv->saveFPB1);
/* Actually enable it */
I915_WRITE(dpll_b_reg, dev_priv->saveDPLL_B);
POSTING_READ(dpll_b_reg);
udelay(150);
if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) {
I915_WRITE(_DPLL_B_MD, dev_priv->saveDPLL_B_MD);
POSTING_READ(_DPLL_B_MD);
}
udelay(150);
/* Restore mode */
I915_WRITE(_HTOTAL_B, dev_priv->saveHTOTAL_B);
I915_WRITE(_HBLANK_B, dev_priv->saveHBLANK_B);
I915_WRITE(_HSYNC_B, dev_priv->saveHSYNC_B);
I915_WRITE(_VTOTAL_B, dev_priv->saveVTOTAL_B);
I915_WRITE(_VBLANK_B, dev_priv->saveVBLANK_B);
I915_WRITE(_VSYNC_B, dev_priv->saveVSYNC_B);
if (!HAS_PCH_SPLIT(dev))
I915_WRITE(_BCLRPAT_B, dev_priv->saveBCLRPAT_B);
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(_PIPEB_DATA_M1, dev_priv->savePIPEB_DATA_M1);
I915_WRITE(_PIPEB_DATA_N1, dev_priv->savePIPEB_DATA_N1);
I915_WRITE(_PIPEB_LINK_M1, dev_priv->savePIPEB_LINK_M1);
I915_WRITE(_PIPEB_LINK_N1, dev_priv->savePIPEB_LINK_N1);
I915_WRITE(_FDI_RXB_CTL, dev_priv->saveFDI_RXB_CTL);
I915_WRITE(_FDI_TXB_CTL, dev_priv->saveFDI_TXB_CTL);
I915_WRITE(_PFB_CTL_1, dev_priv->savePFB_CTL_1);
I915_WRITE(_PFB_WIN_SZ, dev_priv->savePFB_WIN_SZ);
I915_WRITE(_PFB_WIN_POS, dev_priv->savePFB_WIN_POS);
I915_WRITE(_TRANSBCONF, dev_priv->saveTRANSBCONF);
I915_WRITE(_TRANS_HTOTAL_B, dev_priv->saveTRANS_HTOTAL_B);
I915_WRITE(_TRANS_HBLANK_B, dev_priv->saveTRANS_HBLANK_B);
I915_WRITE(_TRANS_HSYNC_B, dev_priv->saveTRANS_HSYNC_B);
I915_WRITE(_TRANS_VTOTAL_B, dev_priv->saveTRANS_VTOTAL_B);
I915_WRITE(_TRANS_VBLANK_B, dev_priv->saveTRANS_VBLANK_B);
I915_WRITE(_TRANS_VSYNC_B, dev_priv->saveTRANS_VSYNC_B);
}
/* Restore plane info */
I915_WRITE(_DSPBSIZE, dev_priv->saveDSPBSIZE);
I915_WRITE(_DSPBPOS, dev_priv->saveDSPBPOS);
I915_WRITE(_PIPEBSRC, dev_priv->savePIPEBSRC);
I915_WRITE(_DSPBADDR, dev_priv->saveDSPBADDR);
I915_WRITE(_DSPBSTRIDE, dev_priv->saveDSPBSTRIDE);
if (INTEL_INFO(dev)->gen >= 4) {
I915_WRITE(_DSPBSURF, dev_priv->saveDSPBSURF);
I915_WRITE(_DSPBTILEOFF, dev_priv->saveDSPBTILEOFF);
}
I915_WRITE(_PIPEBCONF, dev_priv->savePIPEBCONF);
i915_restore_palette(dev, PIPE_B);
/* Enable the plane */
I915_WRITE(_DSPBCNTR, dev_priv->saveDSPBCNTR);
I915_WRITE(_DSPBADDR, I915_READ(_DSPBADDR));
/* Cursor state */
I915_WRITE(_CURAPOS, dev_priv->saveCURAPOS);
I915_WRITE(_CURACNTR, dev_priv->saveCURACNTR);
I915_WRITE(_CURABASE, dev_priv->saveCURABASE);
I915_WRITE(_CURBPOS, dev_priv->saveCURBPOS);
I915_WRITE(_CURBCNTR, dev_priv->saveCURBCNTR);
I915_WRITE(_CURBBASE, dev_priv->saveCURBBASE);
if (IS_GEN2(dev))
I915_WRITE(CURSIZE, dev_priv->saveCURSIZE);
return;
}
static void i915_save_display(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
/* Display arbitration control */
dev_priv->saveDSPARB = I915_READ(DSPARB);
/* This is only meaningful in non-KMS mode */
/* Don't save them in KMS mode */
i915_save_modeset_reg(dev);
/* CRT state */
if (HAS_PCH_SPLIT(dev)) {
dev_priv->saveADPA = I915_READ(PCH_ADPA);
} else {
dev_priv->saveADPA = I915_READ(ADPA);
}
/* LVDS state */
if (HAS_PCH_SPLIT(dev)) {
dev_priv->savePP_CONTROL = I915_READ(PCH_PP_CONTROL);
dev_priv->saveBLC_PWM_CTL = I915_READ(BLC_PWM_PCH_CTL1);
dev_priv->saveBLC_PWM_CTL2 = I915_READ(BLC_PWM_PCH_CTL2);
dev_priv->saveBLC_CPU_PWM_CTL = I915_READ(BLC_PWM_CPU_CTL);
dev_priv->saveBLC_CPU_PWM_CTL2 = I915_READ(BLC_PWM_CPU_CTL2);
dev_priv->saveLVDS = I915_READ(PCH_LVDS);
} else {
dev_priv->savePP_CONTROL = I915_READ(PP_CONTROL);
dev_priv->savePFIT_PGM_RATIOS = I915_READ(PFIT_PGM_RATIOS);
dev_priv->saveBLC_PWM_CTL = I915_READ(BLC_PWM_CTL);
dev_priv->saveBLC_HIST_CTL = I915_READ(BLC_HIST_CTL);
if (INTEL_INFO(dev)->gen >= 4)
dev_priv->saveBLC_PWM_CTL2 = I915_READ(BLC_PWM_CTL2);
if (IS_MOBILE(dev) && !IS_I830(dev))
dev_priv->saveLVDS = I915_READ(LVDS);
}
if (!IS_I830(dev) && !IS_845G(dev) && !HAS_PCH_SPLIT(dev))
dev_priv->savePFIT_CONTROL = I915_READ(PFIT_CONTROL);
if (HAS_PCH_SPLIT(dev)) {
dev_priv->savePP_ON_DELAYS = I915_READ(PCH_PP_ON_DELAYS);
dev_priv->savePP_OFF_DELAYS = I915_READ(PCH_PP_OFF_DELAYS);
dev_priv->savePP_DIVISOR = I915_READ(PCH_PP_DIVISOR);
} else {
dev_priv->savePP_ON_DELAYS = I915_READ(PP_ON_DELAYS);
dev_priv->savePP_OFF_DELAYS = I915_READ(PP_OFF_DELAYS);
dev_priv->savePP_DIVISOR = I915_READ(PP_DIVISOR);
}
/* Display Port state */
if (SUPPORTS_INTEGRATED_DP(dev)) {
dev_priv->saveDP_B = I915_READ(DP_B);
dev_priv->saveDP_C = I915_READ(DP_C);
dev_priv->saveDP_D = I915_READ(DP_D);
dev_priv->savePIPEA_GMCH_DATA_M = I915_READ(_PIPEA_GMCH_DATA_M);
dev_priv->savePIPEB_GMCH_DATA_M = I915_READ(_PIPEB_GMCH_DATA_M);
dev_priv->savePIPEA_GMCH_DATA_N = I915_READ(_PIPEA_GMCH_DATA_N);
dev_priv->savePIPEB_GMCH_DATA_N = I915_READ(_PIPEB_GMCH_DATA_N);
dev_priv->savePIPEA_DP_LINK_M = I915_READ(_PIPEA_DP_LINK_M);
dev_priv->savePIPEB_DP_LINK_M = I915_READ(_PIPEB_DP_LINK_M);
dev_priv->savePIPEA_DP_LINK_N = I915_READ(_PIPEA_DP_LINK_N);
dev_priv->savePIPEB_DP_LINK_N = I915_READ(_PIPEB_DP_LINK_N);
}
/* FIXME: save TV & SDVO state */
/* Only save FBC state on the platform that supports FBC */
if (I915_HAS_FBC(dev)) {
if (HAS_PCH_SPLIT(dev)) {
dev_priv->saveDPFC_CB_BASE = I915_READ(ILK_DPFC_CB_BASE);
} else if (IS_GM45(dev)) {
dev_priv->saveDPFC_CB_BASE = I915_READ(DPFC_CB_BASE);
} else {
dev_priv->saveFBC_CFB_BASE = I915_READ(FBC_CFB_BASE);
dev_priv->saveFBC_LL_BASE = I915_READ(FBC_LL_BASE);
dev_priv->saveFBC_CONTROL2 = I915_READ(FBC_CONTROL2);
dev_priv->saveFBC_CONTROL = I915_READ(FBC_CONTROL);
}
}
/* VGA state */
dev_priv->saveVGA0 = I915_READ(VGA0);
dev_priv->saveVGA1 = I915_READ(VGA1);
dev_priv->saveVGA_PD = I915_READ(VGA_PD);
if (HAS_PCH_SPLIT(dev))
dev_priv->saveVGACNTRL = I915_READ(CPU_VGACNTRL);
else
dev_priv->saveVGACNTRL = I915_READ(VGACNTRL);
i915_save_vga(dev);
}
static void i915_restore_display(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
/* Display arbitration */
I915_WRITE(DSPARB, dev_priv->saveDSPARB);
/* Display port ratios (must be done before clock is set) */
if (SUPPORTS_INTEGRATED_DP(dev)) {
I915_WRITE(_PIPEA_GMCH_DATA_M, dev_priv->savePIPEA_GMCH_DATA_M);
I915_WRITE(_PIPEB_GMCH_DATA_M, dev_priv->savePIPEB_GMCH_DATA_M);
I915_WRITE(_PIPEA_GMCH_DATA_N, dev_priv->savePIPEA_GMCH_DATA_N);
I915_WRITE(_PIPEB_GMCH_DATA_N, dev_priv->savePIPEB_GMCH_DATA_N);
I915_WRITE(_PIPEA_DP_LINK_M, dev_priv->savePIPEA_DP_LINK_M);
I915_WRITE(_PIPEB_DP_LINK_M, dev_priv->savePIPEB_DP_LINK_M);
I915_WRITE(_PIPEA_DP_LINK_N, dev_priv->savePIPEA_DP_LINK_N);
I915_WRITE(_PIPEB_DP_LINK_N, dev_priv->savePIPEB_DP_LINK_N);
}
/* This is only meaningful in non-KMS mode */
/* Don't restore them in KMS mode */
i915_restore_modeset_reg(dev);
/* CRT state */
if (HAS_PCH_SPLIT(dev))
I915_WRITE(PCH_ADPA, dev_priv->saveADPA);
else
I915_WRITE(ADPA, dev_priv->saveADPA);
/* LVDS state */
if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev))
I915_WRITE(BLC_PWM_CTL2, dev_priv->saveBLC_PWM_CTL2);
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(PCH_LVDS, dev_priv->saveLVDS);
} else if (IS_MOBILE(dev) && !IS_I830(dev))
I915_WRITE(LVDS, dev_priv->saveLVDS);
if (!IS_I830(dev) && !IS_845G(dev) && !HAS_PCH_SPLIT(dev))
I915_WRITE(PFIT_CONTROL, dev_priv->savePFIT_CONTROL);
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(BLC_PWM_PCH_CTL1, dev_priv->saveBLC_PWM_CTL);
I915_WRITE(BLC_PWM_PCH_CTL2, dev_priv->saveBLC_PWM_CTL2);
I915_WRITE(BLC_PWM_CPU_CTL, dev_priv->saveBLC_CPU_PWM_CTL);
I915_WRITE(BLC_PWM_CPU_CTL2, dev_priv->saveBLC_CPU_PWM_CTL2);
I915_WRITE(PCH_PP_ON_DELAYS, dev_priv->savePP_ON_DELAYS);
I915_WRITE(PCH_PP_OFF_DELAYS, dev_priv->savePP_OFF_DELAYS);
I915_WRITE(PCH_PP_DIVISOR, dev_priv->savePP_DIVISOR);
I915_WRITE(PCH_PP_CONTROL, dev_priv->savePP_CONTROL);
I915_WRITE(RSTDBYCTL,
dev_priv->saveMCHBAR_RENDER_STANDBY);
} else {
I915_WRITE(PFIT_PGM_RATIOS, dev_priv->savePFIT_PGM_RATIOS);
I915_WRITE(BLC_PWM_CTL, dev_priv->saveBLC_PWM_CTL);
I915_WRITE(BLC_HIST_CTL, dev_priv->saveBLC_HIST_CTL);
I915_WRITE(PP_ON_DELAYS, dev_priv->savePP_ON_DELAYS);
I915_WRITE(PP_OFF_DELAYS, dev_priv->savePP_OFF_DELAYS);
I915_WRITE(PP_DIVISOR, dev_priv->savePP_DIVISOR);
I915_WRITE(PP_CONTROL, dev_priv->savePP_CONTROL);
}
/* Display Port state */
if (SUPPORTS_INTEGRATED_DP(dev)) {
I915_WRITE(DP_B, dev_priv->saveDP_B);
I915_WRITE(DP_C, dev_priv->saveDP_C);
I915_WRITE(DP_D, dev_priv->saveDP_D);
}
/* FIXME: restore TV & SDVO state */
/* only restore FBC info on the platform that supports FBC*/
intel_disable_fbc(dev);
if (I915_HAS_FBC(dev)) {
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(ILK_DPFC_CB_BASE, dev_priv->saveDPFC_CB_BASE);
} else if (IS_GM45(dev)) {
I915_WRITE(DPFC_CB_BASE, dev_priv->saveDPFC_CB_BASE);
} else {
I915_WRITE(FBC_CFB_BASE, dev_priv->saveFBC_CFB_BASE);
I915_WRITE(FBC_LL_BASE, dev_priv->saveFBC_LL_BASE);
I915_WRITE(FBC_CONTROL2, dev_priv->saveFBC_CONTROL2);
I915_WRITE(FBC_CONTROL, dev_priv->saveFBC_CONTROL);
}
}
/* VGA state */
if (HAS_PCH_SPLIT(dev))
I915_WRITE(CPU_VGACNTRL, dev_priv->saveVGACNTRL);
else
I915_WRITE(VGACNTRL, dev_priv->saveVGACNTRL);
I915_WRITE(VGA0, dev_priv->saveVGA0);
I915_WRITE(VGA1, dev_priv->saveVGA1);
I915_WRITE(VGA_PD, dev_priv->saveVGA_PD);
POSTING_READ(VGA_PD);
udelay(150);
i915_restore_vga(dev);
}
int i915_save_state(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
int i;
pci_read_config_byte(dev->pdev, LBB, &dev_priv->saveLBB);
mutex_lock(&dev->struct_mutex);
/* Hardware status page */
dev_priv->saveHWS = I915_READ(HWS_PGA);
i915_save_display(dev);
/* Interrupt state */
if (HAS_PCH_SPLIT(dev)) {
dev_priv->saveDEIER = I915_READ(DEIER);
dev_priv->saveDEIMR = I915_READ(DEIMR);
dev_priv->saveGTIER = I915_READ(GTIER);
dev_priv->saveGTIMR = I915_READ(GTIMR);
dev_priv->saveFDI_RXA_IMR = I915_READ(_FDI_RXA_IMR);
dev_priv->saveFDI_RXB_IMR = I915_READ(_FDI_RXB_IMR);
dev_priv->saveMCHBAR_RENDER_STANDBY =
I915_READ(RSTDBYCTL);
dev_priv->savePCH_PORT_HOTPLUG = I915_READ(PCH_PORT_HOTPLUG);
} else {
dev_priv->saveIER = I915_READ(IER);
dev_priv->saveIMR = I915_READ(IMR);
}
if (IS_IRONLAKE_M(dev))
ironlake_disable_drps(dev);
if (INTEL_INFO(dev)->gen >= 6)
gen6_disable_rps(dev);
/* Cache mode state */
dev_priv->saveCACHE_MODE_0 = I915_READ(CACHE_MODE_0);
/* Memory Arbitration state */
dev_priv->saveMI_ARB_STATE = I915_READ(MI_ARB_STATE);
/* Scratch space */
for (i = 0; i < 16; i++) {
dev_priv->saveSWF0[i] = I915_READ(SWF00 + (i << 2));
dev_priv->saveSWF1[i] = I915_READ(SWF10 + (i << 2));
}
for (i = 0; i < 3; i++)
dev_priv->saveSWF2[i] = I915_READ(SWF30 + (i << 2));
mutex_unlock(&dev->struct_mutex);
return 0;
}
int i915_restore_state(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
int i;
pci_write_config_byte(dev->pdev, LBB, dev_priv->saveLBB);
mutex_lock(&dev->struct_mutex);
/* Hardware status page */
I915_WRITE(HWS_PGA, dev_priv->saveHWS);
i915_restore_display(dev);
/* Interrupt state */
if (HAS_PCH_SPLIT(dev)) {
I915_WRITE(DEIER, dev_priv->saveDEIER);
I915_WRITE(DEIMR, dev_priv->saveDEIMR);
I915_WRITE(GTIER, dev_priv->saveGTIER);
I915_WRITE(GTIMR, dev_priv->saveGTIMR);
I915_WRITE(_FDI_RXA_IMR, dev_priv->saveFDI_RXA_IMR);
I915_WRITE(_FDI_RXB_IMR, dev_priv->saveFDI_RXB_IMR);
I915_WRITE(PCH_PORT_HOTPLUG, dev_priv->savePCH_PORT_HOTPLUG);
} else {
I915_WRITE(IER, dev_priv->saveIER);
I915_WRITE(IMR, dev_priv->saveIMR);
}
mutex_unlock(&dev->struct_mutex);
if (drm_core_check_feature(dev, DRIVER_MODESET))
intel_init_clock_gating(dev);
if (IS_IRONLAKE_M(dev)) {
ironlake_enable_drps(dev);
intel_init_emon(dev);
}
if (INTEL_INFO(dev)->gen >= 6) {
gen6_enable_rps(dev_priv);
gen6_update_ring_freq(dev_priv);
}
mutex_lock(&dev->struct_mutex);
/* Cache mode state */
I915_WRITE(CACHE_MODE_0, dev_priv->saveCACHE_MODE_0 | 0xffff0000);
/* Memory arbitration state */
I915_WRITE(MI_ARB_STATE, dev_priv->saveMI_ARB_STATE | 0xffff0000);
for (i = 0; i < 16; i++) {
I915_WRITE(SWF00 + (i << 2), dev_priv->saveSWF0[i]);
I915_WRITE(SWF10 + (i << 2), dev_priv->saveSWF1[i]);
}
for (i = 0; i < 3; i++)
I915_WRITE(SWF30 + (i << 2), dev_priv->saveSWF2[i]);
mutex_unlock(&dev->struct_mutex);
intel_i2c_reset(dev);
return 0;
}
| gpl-2.0 |
krosk/android-omap-tuna-sideload | lib/atomic64.c | 3614 | 4218 | /*
* Generic implementation of 64-bit atomics using spinlocks,
* useful on processors that don't have 64-bit atomic instructions.
*
* Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/cache.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/module.h>
#include <asm/atomic.h>
/*
* We use a hashed array of spinlocks to provide exclusive access
* to each atomic64_t variable. Since this is expected to used on
* systems with small numbers of CPUs (<= 4 or so), we use a
* relatively small array of 16 spinlocks to avoid wasting too much
* memory on the spinlock array.
*/
#define NR_LOCKS 16
/*
* Ensure each lock is in a separate cacheline.
*/
static union {
spinlock_t lock;
char pad[L1_CACHE_BYTES];
} atomic64_lock[NR_LOCKS] __cacheline_aligned_in_smp;
static inline spinlock_t *lock_addr(const atomic64_t *v)
{
unsigned long addr = (unsigned long) v;
addr >>= L1_CACHE_SHIFT;
addr ^= (addr >> 8) ^ (addr >> 16);
return &atomic64_lock[addr & (NR_LOCKS - 1)].lock;
}
long long atomic64_read(const atomic64_t *v)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
long long val;
spin_lock_irqsave(lock, flags);
val = v->counter;
spin_unlock_irqrestore(lock, flags);
return val;
}
EXPORT_SYMBOL(atomic64_read);
void atomic64_set(atomic64_t *v, long long i)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
spin_lock_irqsave(lock, flags);
v->counter = i;
spin_unlock_irqrestore(lock, flags);
}
EXPORT_SYMBOL(atomic64_set);
void atomic64_add(long long a, atomic64_t *v)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
spin_lock_irqsave(lock, flags);
v->counter += a;
spin_unlock_irqrestore(lock, flags);
}
EXPORT_SYMBOL(atomic64_add);
long long atomic64_add_return(long long a, atomic64_t *v)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
long long val;
spin_lock_irqsave(lock, flags);
val = v->counter += a;
spin_unlock_irqrestore(lock, flags);
return val;
}
EXPORT_SYMBOL(atomic64_add_return);
void atomic64_sub(long long a, atomic64_t *v)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
spin_lock_irqsave(lock, flags);
v->counter -= a;
spin_unlock_irqrestore(lock, flags);
}
EXPORT_SYMBOL(atomic64_sub);
long long atomic64_sub_return(long long a, atomic64_t *v)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
long long val;
spin_lock_irqsave(lock, flags);
val = v->counter -= a;
spin_unlock_irqrestore(lock, flags);
return val;
}
EXPORT_SYMBOL(atomic64_sub_return);
long long atomic64_dec_if_positive(atomic64_t *v)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
long long val;
spin_lock_irqsave(lock, flags);
val = v->counter - 1;
if (val >= 0)
v->counter = val;
spin_unlock_irqrestore(lock, flags);
return val;
}
EXPORT_SYMBOL(atomic64_dec_if_positive);
long long atomic64_cmpxchg(atomic64_t *v, long long o, long long n)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
long long val;
spin_lock_irqsave(lock, flags);
val = v->counter;
if (val == o)
v->counter = n;
spin_unlock_irqrestore(lock, flags);
return val;
}
EXPORT_SYMBOL(atomic64_cmpxchg);
long long atomic64_xchg(atomic64_t *v, long long new)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
long long val;
spin_lock_irqsave(lock, flags);
val = v->counter;
v->counter = new;
spin_unlock_irqrestore(lock, flags);
return val;
}
EXPORT_SYMBOL(atomic64_xchg);
int atomic64_add_unless(atomic64_t *v, long long a, long long u)
{
unsigned long flags;
spinlock_t *lock = lock_addr(v);
int ret = 0;
spin_lock_irqsave(lock, flags);
if (v->counter != u) {
v->counter += a;
ret = 1;
}
spin_unlock_irqrestore(lock, flags);
return ret;
}
EXPORT_SYMBOL(atomic64_add_unless);
static int init_atomic64_lock(void)
{
int i;
for (i = 0; i < NR_LOCKS; ++i)
spin_lock_init(&atomic64_lock[i].lock);
return 0;
}
pure_initcall(init_atomic64_lock);
| gpl-2.0 |
flar2/m7wl-ElementalX | drivers/power/charger-manager.c | 3614 | 26806 | /*
* Copyright (C) 2011 Samsung Electronics Co., Ltd.
* MyungJoo Ham <myungjoo.ham@samsung.com>
*
* This driver enables to monitor battery health and control charger
* during suspend-to-mem.
* Charger manager depends on other devices. register this later than
* the depending devices.
*
* 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/io.h>
#include <linux/module.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/platform_device.h>
#include <linux/power/charger-manager.h>
#include <linux/regulator/consumer.h>
/*
* Regard CM_JIFFIES_SMALL jiffies is small enough to ignore for
* delayed works so that we can run delayed works with CM_JIFFIES_SMALL
* without any delays.
*/
#define CM_JIFFIES_SMALL (2)
/* If y is valid (> 0) and smaller than x, do x = y */
#define CM_MIN_VALID(x, y) x = (((y > 0) && ((x) > (y))) ? (y) : (x))
/*
* Regard CM_RTC_SMALL (sec) is small enough to ignore error in invoking
* rtc alarm. It should be 2 or larger
*/
#define CM_RTC_SMALL (2)
#define UEVENT_BUF_SIZE 32
static LIST_HEAD(cm_list);
static DEFINE_MUTEX(cm_list_mtx);
/* About in-suspend (suspend-again) monitoring */
static struct rtc_device *rtc_dev;
/*
* Backup RTC alarm
* Save the wakeup alarm before entering suspend-to-RAM
*/
static struct rtc_wkalrm rtc_wkalarm_save;
/* Backup RTC alarm time in terms of seconds since 01-01-1970 00:00:00 */
static unsigned long rtc_wkalarm_save_time;
static bool cm_suspended;
static bool cm_rtc_set;
static unsigned long cm_suspend_duration_ms;
/* Global charger-manager description */
static struct charger_global_desc *g_desc; /* init with setup_charger_manager */
/**
* is_batt_present - See if the battery presents in place.
* @cm: the Charger Manager representing the battery.
*/
static bool is_batt_present(struct charger_manager *cm)
{
union power_supply_propval val;
bool present = false;
int i, ret;
switch (cm->desc->battery_present) {
case CM_FUEL_GAUGE:
ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_PRESENT, &val);
if (ret == 0 && val.intval)
present = true;
break;
case CM_CHARGER_STAT:
for (i = 0; cm->charger_stat[i]; i++) {
ret = cm->charger_stat[i]->get_property(
cm->charger_stat[i],
POWER_SUPPLY_PROP_PRESENT, &val);
if (ret == 0 && val.intval) {
present = true;
break;
}
}
break;
}
return present;
}
/**
* is_ext_pwr_online - See if an external power source is attached to charge
* @cm: the Charger Manager representing the battery.
*
* Returns true if at least one of the chargers of the battery has an external
* power source attached to charge the battery regardless of whether it is
* actually charging or not.
*/
static bool is_ext_pwr_online(struct charger_manager *cm)
{
union power_supply_propval val;
bool online = false;
int i, ret;
/* If at least one of them has one, it's yes. */
for (i = 0; cm->charger_stat[i]; i++) {
ret = cm->charger_stat[i]->get_property(
cm->charger_stat[i],
POWER_SUPPLY_PROP_ONLINE, &val);
if (ret == 0 && val.intval) {
online = true;
break;
}
}
return online;
}
/**
* get_batt_uV - Get the voltage level of the battery
* @cm: the Charger Manager representing the battery.
* @uV: the voltage level returned.
*
* Returns 0 if there is no error.
* Returns a negative value on error.
*/
static int get_batt_uV(struct charger_manager *cm, int *uV)
{
union power_supply_propval val;
int ret;
if (!cm->fuel_gauge)
return -ENODEV;
ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_VOLTAGE_NOW, &val);
if (ret)
return ret;
*uV = val.intval;
return 0;
}
/**
* is_charging - Returns true if the battery is being charged.
* @cm: the Charger Manager representing the battery.
*/
static bool is_charging(struct charger_manager *cm)
{
int i, ret;
bool charging = false;
union power_supply_propval val;
/* If there is no battery, it cannot be charged */
if (!is_batt_present(cm))
return false;
/* If at least one of the charger is charging, return yes */
for (i = 0; cm->charger_stat[i]; i++) {
/* 1. The charger sholuld not be DISABLED */
if (cm->emergency_stop)
continue;
if (!cm->charger_enabled)
continue;
/* 2. The charger should be online (ext-power) */
ret = cm->charger_stat[i]->get_property(
cm->charger_stat[i],
POWER_SUPPLY_PROP_ONLINE, &val);
if (ret) {
dev_warn(cm->dev, "Cannot read ONLINE value from %s.\n",
cm->desc->psy_charger_stat[i]);
continue;
}
if (val.intval == 0)
continue;
/*
* 3. The charger should not be FULL, DISCHARGING,
* or NOT_CHARGING.
*/
ret = cm->charger_stat[i]->get_property(
cm->charger_stat[i],
POWER_SUPPLY_PROP_STATUS, &val);
if (ret) {
dev_warn(cm->dev, "Cannot read STATUS value from %s.\n",
cm->desc->psy_charger_stat[i]);
continue;
}
if (val.intval == POWER_SUPPLY_STATUS_FULL ||
val.intval == POWER_SUPPLY_STATUS_DISCHARGING ||
val.intval == POWER_SUPPLY_STATUS_NOT_CHARGING)
continue;
/* Then, this is charging. */
charging = true;
break;
}
return charging;
}
/**
* is_polling_required - Return true if need to continue polling for this CM.
* @cm: the Charger Manager representing the battery.
*/
static bool is_polling_required(struct charger_manager *cm)
{
switch (cm->desc->polling_mode) {
case CM_POLL_DISABLE:
return false;
case CM_POLL_ALWAYS:
return true;
case CM_POLL_EXTERNAL_POWER_ONLY:
return is_ext_pwr_online(cm);
case CM_POLL_CHARGING_ONLY:
return is_charging(cm);
default:
dev_warn(cm->dev, "Incorrect polling_mode (%d)\n",
cm->desc->polling_mode);
}
return false;
}
/**
* try_charger_enable - Enable/Disable chargers altogether
* @cm: the Charger Manager representing the battery.
* @enable: true: enable / false: disable
*
* Note that Charger Manager keeps the charger enabled regardless whether
* the charger is charging or not (because battery is full or no external
* power source exists) except when CM needs to disable chargers forcibly
* bacause of emergency causes; when the battery is overheated or too cold.
*/
static int try_charger_enable(struct charger_manager *cm, bool enable)
{
int err = 0, i;
struct charger_desc *desc = cm->desc;
/* Ignore if it's redundent command */
if (enable == cm->charger_enabled)
return 0;
if (enable) {
if (cm->emergency_stop)
return -EAGAIN;
err = regulator_bulk_enable(desc->num_charger_regulators,
desc->charger_regulators);
} else {
/*
* Abnormal battery state - Stop charging forcibly,
* even if charger was enabled at the other places
*/
err = regulator_bulk_disable(desc->num_charger_regulators,
desc->charger_regulators);
for (i = 0; i < desc->num_charger_regulators; i++) {
if (regulator_is_enabled(
desc->charger_regulators[i].consumer)) {
regulator_force_disable(
desc->charger_regulators[i].consumer);
dev_warn(cm->dev,
"Disable regulator(%s) forcibly.\n",
desc->charger_regulators[i].supply);
}
}
}
if (!err)
cm->charger_enabled = enable;
return err;
}
/**
* uevent_notify - Let users know something has changed.
* @cm: the Charger Manager representing the battery.
* @event: the event string.
*
* If @event is null, it implies that uevent_notify is called
* by resume function. When called in the resume function, cm_suspended
* should be already reset to false in order to let uevent_notify
* notify the recent event during the suspend to users. While
* suspended, uevent_notify does not notify users, but tracks
* events so that uevent_notify can notify users later after resumed.
*/
static void uevent_notify(struct charger_manager *cm, const char *event)
{
static char env_str[UEVENT_BUF_SIZE + 1] = "";
static char env_str_save[UEVENT_BUF_SIZE + 1] = "";
if (cm_suspended) {
/* Nothing in suspended-event buffer */
if (env_str_save[0] == 0) {
if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
return; /* status not changed */
strncpy(env_str_save, event, UEVENT_BUF_SIZE);
return;
}
if (!strncmp(env_str_save, event, UEVENT_BUF_SIZE))
return; /* Duplicated. */
strncpy(env_str_save, event, UEVENT_BUF_SIZE);
return;
}
if (event == NULL) {
/* No messages pending */
if (!env_str_save[0])
return;
strncpy(env_str, env_str_save, UEVENT_BUF_SIZE);
kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
env_str_save[0] = 0;
return;
}
/* status not changed */
if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
return;
/* save the status and notify the update */
strncpy(env_str, event, UEVENT_BUF_SIZE);
kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
dev_info(cm->dev, event);
}
/**
* _cm_monitor - Monitor the temperature and return true for exceptions.
* @cm: the Charger Manager representing the battery.
*
* Returns true if there is an event to notify for the battery.
* (True if the status of "emergency_stop" changes)
*/
static bool _cm_monitor(struct charger_manager *cm)
{
struct charger_desc *desc = cm->desc;
int temp = desc->temperature_out_of_range(&cm->last_temp_mC);
dev_dbg(cm->dev, "monitoring (%2.2d.%3.3dC)\n",
cm->last_temp_mC / 1000, cm->last_temp_mC % 1000);
/* It has been stopped or charging already */
if (!!temp == !!cm->emergency_stop)
return false;
if (temp) {
cm->emergency_stop = temp;
if (!try_charger_enable(cm, false)) {
if (temp > 0)
uevent_notify(cm, "OVERHEAT");
else
uevent_notify(cm, "COLD");
}
} else {
cm->emergency_stop = 0;
if (!try_charger_enable(cm, true))
uevent_notify(cm, "CHARGING");
}
return true;
}
/**
* cm_monitor - Monitor every battery.
*
* Returns true if there is an event to notify from any of the batteries.
* (True if the status of "emergency_stop" changes)
*/
static bool cm_monitor(void)
{
bool stop = false;
struct charger_manager *cm;
mutex_lock(&cm_list_mtx);
list_for_each_entry(cm, &cm_list, entry) {
if (_cm_monitor(cm))
stop = true;
}
mutex_unlock(&cm_list_mtx);
return stop;
}
static int charger_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct charger_manager *cm = container_of(psy,
struct charger_manager, charger_psy);
struct charger_desc *desc = cm->desc;
int ret = 0;
int uV;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
if (is_charging(cm))
val->intval = POWER_SUPPLY_STATUS_CHARGING;
else if (is_ext_pwr_online(cm))
val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
else
val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
break;
case POWER_SUPPLY_PROP_HEALTH:
if (cm->emergency_stop > 0)
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
else if (cm->emergency_stop < 0)
val->intval = POWER_SUPPLY_HEALTH_COLD;
else
val->intval = POWER_SUPPLY_HEALTH_GOOD;
break;
case POWER_SUPPLY_PROP_PRESENT:
if (is_batt_present(cm))
val->intval = 1;
else
val->intval = 0;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
ret = get_batt_uV(cm, &val->intval);
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CURRENT_NOW, val);
break;
case POWER_SUPPLY_PROP_TEMP:
/* in thenth of centigrade */
if (cm->last_temp_mC == INT_MIN)
desc->temperature_out_of_range(&cm->last_temp_mC);
val->intval = cm->last_temp_mC / 100;
if (!desc->measure_battery_temp)
ret = -ENODEV;
break;
case POWER_SUPPLY_PROP_TEMP_AMBIENT:
/* in thenth of centigrade */
if (cm->last_temp_mC == INT_MIN)
desc->temperature_out_of_range(&cm->last_temp_mC);
val->intval = cm->last_temp_mC / 100;
if (desc->measure_battery_temp)
ret = -ENODEV;
break;
case POWER_SUPPLY_PROP_CAPACITY:
if (!cm->fuel_gauge) {
ret = -ENODEV;
break;
}
if (!is_batt_present(cm)) {
/* There is no battery. Assume 100% */
val->intval = 100;
break;
}
ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CAPACITY, val);
if (ret)
break;
if (val->intval > 100) {
val->intval = 100;
break;
}
if (val->intval < 0)
val->intval = 0;
/* Do not adjust SOC when charging: voltage is overrated */
if (is_charging(cm))
break;
/*
* If the capacity value is inconsistent, calibrate it base on
* the battery voltage values and the thresholds given as desc
*/
ret = get_batt_uV(cm, &uV);
if (ret) {
/* Voltage information not available. No calibration */
ret = 0;
break;
}
if (desc->fullbatt_uV > 0 && uV >= desc->fullbatt_uV &&
!is_charging(cm)) {
val->intval = 100;
break;
}
break;
case POWER_SUPPLY_PROP_ONLINE:
if (is_ext_pwr_online(cm))
val->intval = 1;
else
val->intval = 0;
break;
case POWER_SUPPLY_PROP_CHARGE_FULL:
if (cm->fuel_gauge) {
if (cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CHARGE_FULL, val) == 0)
break;
}
if (is_ext_pwr_online(cm)) {
/* Not full if it's charging. */
if (is_charging(cm)) {
val->intval = 0;
break;
}
/*
* Full if it's powered but not charging andi
* not forced stop by emergency
*/
if (!cm->emergency_stop) {
val->intval = 1;
break;
}
}
/* Full if it's over the fullbatt voltage */
ret = get_batt_uV(cm, &uV);
if (!ret && desc->fullbatt_uV > 0 && uV >= desc->fullbatt_uV &&
!is_charging(cm)) {
val->intval = 1;
break;
}
/* Full if the cap is 100 */
if (cm->fuel_gauge) {
ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CAPACITY, val);
if (!ret && val->intval >= 100 && !is_charging(cm)) {
val->intval = 1;
break;
}
}
val->intval = 0;
ret = 0;
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
if (is_charging(cm)) {
ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CHARGE_NOW,
val);
if (ret) {
val->intval = 1;
ret = 0;
} else {
/* If CHARGE_NOW is supplied, use it */
val->intval = (val->intval > 0) ?
val->intval : 1;
}
} else {
val->intval = 0;
}
break;
default:
return -EINVAL;
}
return ret;
}
#define NUM_CHARGER_PSY_OPTIONAL (4)
static enum power_supply_property default_charger_props[] = {
/* Guaranteed to provide */
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_CHARGE_FULL,
/*
* Optional properties are:
* POWER_SUPPLY_PROP_CHARGE_NOW,
* POWER_SUPPLY_PROP_CURRENT_NOW,
* POWER_SUPPLY_PROP_TEMP, and
* POWER_SUPPLY_PROP_TEMP_AMBIENT,
*/
};
static struct power_supply psy_default = {
.name = "battery",
.type = POWER_SUPPLY_TYPE_BATTERY,
.properties = default_charger_props,
.num_properties = ARRAY_SIZE(default_charger_props),
.get_property = charger_get_property,
};
/**
* cm_setup_timer - For in-suspend monitoring setup wakeup alarm
* for suspend_again.
*
* Returns true if the alarm is set for Charger Manager to use.
* Returns false if
* cm_setup_timer fails to set an alarm,
* cm_setup_timer does not need to set an alarm for Charger Manager,
* or an alarm previously configured is to be used.
*/
static bool cm_setup_timer(void)
{
struct charger_manager *cm;
unsigned int wakeup_ms = UINT_MAX;
bool ret = false;
mutex_lock(&cm_list_mtx);
list_for_each_entry(cm, &cm_list, entry) {
/* Skip if polling is not required for this CM */
if (!is_polling_required(cm) && !cm->emergency_stop)
continue;
if (cm->desc->polling_interval_ms == 0)
continue;
CM_MIN_VALID(wakeup_ms, cm->desc->polling_interval_ms);
}
mutex_unlock(&cm_list_mtx);
if (wakeup_ms < UINT_MAX && wakeup_ms > 0) {
pr_info("Charger Manager wakeup timer: %u ms.\n", wakeup_ms);
if (rtc_dev) {
struct rtc_wkalrm tmp;
unsigned long time, now;
unsigned long add = DIV_ROUND_UP(wakeup_ms, 1000);
/*
* Set alarm with the polling interval (wakeup_ms)
* except when rtc_wkalarm_save comes first.
* However, the alarm time should be NOW +
* CM_RTC_SMALL or later.
*/
tmp.enabled = 1;
rtc_read_time(rtc_dev, &tmp.time);
rtc_tm_to_time(&tmp.time, &now);
if (add < CM_RTC_SMALL)
add = CM_RTC_SMALL;
time = now + add;
ret = true;
if (rtc_wkalarm_save.enabled &&
rtc_wkalarm_save_time &&
rtc_wkalarm_save_time < time) {
if (rtc_wkalarm_save_time < now + CM_RTC_SMALL)
time = now + CM_RTC_SMALL;
else
time = rtc_wkalarm_save_time;
/* The timer is not appointed by CM */
ret = false;
}
pr_info("Waking up after %lu secs.\n",
time - now);
rtc_time_to_tm(time, &tmp.time);
rtc_set_alarm(rtc_dev, &tmp);
cm_suspend_duration_ms += wakeup_ms;
return ret;
}
}
if (rtc_dev)
rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
return false;
}
/**
* cm_suspend_again - Determine whether suspend again or not
*
* Returns true if the system should be suspended again
* Returns false if the system should be woken up
*/
bool cm_suspend_again(void)
{
struct charger_manager *cm;
bool ret = false;
if (!g_desc || !g_desc->rtc_only_wakeup || !g_desc->rtc_only_wakeup() ||
!cm_rtc_set)
return false;
if (cm_monitor())
goto out;
ret = true;
mutex_lock(&cm_list_mtx);
list_for_each_entry(cm, &cm_list, entry) {
if (cm->status_save_ext_pwr_inserted != is_ext_pwr_online(cm) ||
cm->status_save_batt != is_batt_present(cm)) {
ret = false;
break;
}
}
mutex_unlock(&cm_list_mtx);
cm_rtc_set = cm_setup_timer();
out:
/* It's about the time when the non-CM appointed timer goes off */
if (rtc_wkalarm_save.enabled) {
unsigned long now;
struct rtc_time tmp;
rtc_read_time(rtc_dev, &tmp);
rtc_tm_to_time(&tmp, &now);
if (rtc_wkalarm_save_time &&
now + CM_RTC_SMALL >= rtc_wkalarm_save_time)
return false;
}
return ret;
}
EXPORT_SYMBOL_GPL(cm_suspend_again);
/**
* setup_charger_manager - initialize charger_global_desc data
* @gd: pointer to instance of charger_global_desc
*/
int setup_charger_manager(struct charger_global_desc *gd)
{
if (!gd)
return -EINVAL;
if (rtc_dev)
rtc_class_close(rtc_dev);
rtc_dev = NULL;
g_desc = NULL;
if (!gd->rtc_only_wakeup) {
pr_err("The callback rtc_only_wakeup is not given.\n");
return -EINVAL;
}
if (gd->rtc_name) {
rtc_dev = rtc_class_open(gd->rtc_name);
if (IS_ERR_OR_NULL(rtc_dev)) {
rtc_dev = NULL;
/* Retry at probe. RTC may be not registered yet */
}
} else {
pr_warn("No wakeup timer is given for charger manager."
"In-suspend monitoring won't work.\n");
}
g_desc = gd;
return 0;
}
EXPORT_SYMBOL_GPL(setup_charger_manager);
static int charger_manager_probe(struct platform_device *pdev)
{
struct charger_desc *desc = dev_get_platdata(&pdev->dev);
struct charger_manager *cm;
int ret = 0, i = 0;
union power_supply_propval val;
if (g_desc && !rtc_dev && g_desc->rtc_name) {
rtc_dev = rtc_class_open(g_desc->rtc_name);
if (IS_ERR_OR_NULL(rtc_dev)) {
rtc_dev = NULL;
dev_err(&pdev->dev, "Cannot get RTC %s.\n",
g_desc->rtc_name);
ret = -ENODEV;
goto err_alloc;
}
}
if (!desc) {
dev_err(&pdev->dev, "No platform data (desc) found.\n");
ret = -ENODEV;
goto err_alloc;
}
cm = kzalloc(sizeof(struct charger_manager), GFP_KERNEL);
if (!cm) {
dev_err(&pdev->dev, "Cannot allocate memory.\n");
ret = -ENOMEM;
goto err_alloc;
}
/* Basic Values. Unspecified are Null or 0 */
cm->dev = &pdev->dev;
cm->desc = kzalloc(sizeof(struct charger_desc), GFP_KERNEL);
if (!cm->desc) {
dev_err(&pdev->dev, "Cannot allocate memory.\n");
ret = -ENOMEM;
goto err_alloc_desc;
}
memcpy(cm->desc, desc, sizeof(struct charger_desc));
cm->last_temp_mC = INT_MIN; /* denotes "unmeasured, yet" */
if (!desc->charger_regulators || desc->num_charger_regulators < 1) {
ret = -EINVAL;
dev_err(&pdev->dev, "charger_regulators undefined.\n");
goto err_no_charger;
}
if (!desc->psy_charger_stat || !desc->psy_charger_stat[0]) {
dev_err(&pdev->dev, "No power supply defined.\n");
ret = -EINVAL;
goto err_no_charger_stat;
}
/* Counting index only */
while (desc->psy_charger_stat[i])
i++;
cm->charger_stat = kzalloc(sizeof(struct power_supply *) * (i + 1),
GFP_KERNEL);
if (!cm->charger_stat) {
ret = -ENOMEM;
goto err_no_charger_stat;
}
for (i = 0; desc->psy_charger_stat[i]; i++) {
cm->charger_stat[i] = power_supply_get_by_name(
desc->psy_charger_stat[i]);
if (!cm->charger_stat[i]) {
dev_err(&pdev->dev, "Cannot find power supply "
"\"%s\"\n",
desc->psy_charger_stat[i]);
ret = -ENODEV;
goto err_chg_stat;
}
}
cm->fuel_gauge = power_supply_get_by_name(desc->psy_fuel_gauge);
if (!cm->fuel_gauge) {
dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
desc->psy_fuel_gauge);
ret = -ENODEV;
goto err_chg_stat;
}
if (desc->polling_interval_ms == 0 ||
msecs_to_jiffies(desc->polling_interval_ms) <= CM_JIFFIES_SMALL) {
dev_err(&pdev->dev, "polling_interval_ms is too small\n");
ret = -EINVAL;
goto err_chg_stat;
}
if (!desc->temperature_out_of_range) {
dev_err(&pdev->dev, "there is no temperature_out_of_range\n");
ret = -EINVAL;
goto err_chg_stat;
}
platform_set_drvdata(pdev, cm);
memcpy(&cm->charger_psy, &psy_default, sizeof(psy_default));
if (!desc->psy_name) {
strncpy(cm->psy_name_buf, psy_default.name, PSY_NAME_MAX);
} else {
strncpy(cm->psy_name_buf, desc->psy_name, PSY_NAME_MAX);
}
cm->charger_psy.name = cm->psy_name_buf;
/* Allocate for psy properties because they may vary */
cm->charger_psy.properties = kzalloc(sizeof(enum power_supply_property)
* (ARRAY_SIZE(default_charger_props) +
NUM_CHARGER_PSY_OPTIONAL),
GFP_KERNEL);
if (!cm->charger_psy.properties) {
dev_err(&pdev->dev, "Cannot allocate for psy properties.\n");
ret = -ENOMEM;
goto err_chg_stat;
}
memcpy(cm->charger_psy.properties, default_charger_props,
sizeof(enum power_supply_property) *
ARRAY_SIZE(default_charger_props));
cm->charger_psy.num_properties = psy_default.num_properties;
/* Find which optional psy-properties are available */
if (!cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CHARGE_NOW, &val)) {
cm->charger_psy.properties[cm->charger_psy.num_properties] =
POWER_SUPPLY_PROP_CHARGE_NOW;
cm->charger_psy.num_properties++;
}
if (!cm->fuel_gauge->get_property(cm->fuel_gauge,
POWER_SUPPLY_PROP_CURRENT_NOW,
&val)) {
cm->charger_psy.properties[cm->charger_psy.num_properties] =
POWER_SUPPLY_PROP_CURRENT_NOW;
cm->charger_psy.num_properties++;
}
if (desc->measure_battery_temp) {
cm->charger_psy.properties[cm->charger_psy.num_properties] =
POWER_SUPPLY_PROP_TEMP;
cm->charger_psy.num_properties++;
} else {
cm->charger_psy.properties[cm->charger_psy.num_properties] =
POWER_SUPPLY_PROP_TEMP_AMBIENT;
cm->charger_psy.num_properties++;
}
ret = power_supply_register(NULL, &cm->charger_psy);
if (ret) {
dev_err(&pdev->dev, "Cannot register charger-manager with"
" name \"%s\".\n", cm->charger_psy.name);
goto err_register;
}
ret = regulator_bulk_get(&pdev->dev, desc->num_charger_regulators,
desc->charger_regulators);
if (ret) {
dev_err(&pdev->dev, "Cannot get charger regulators.\n");
goto err_bulk_get;
}
ret = try_charger_enable(cm, true);
if (ret) {
dev_err(&pdev->dev, "Cannot enable charger regulators\n");
goto err_chg_enable;
}
/* Add to the list */
mutex_lock(&cm_list_mtx);
list_add(&cm->entry, &cm_list);
mutex_unlock(&cm_list_mtx);
return 0;
err_chg_enable:
regulator_bulk_free(desc->num_charger_regulators,
desc->charger_regulators);
err_bulk_get:
power_supply_unregister(&cm->charger_psy);
err_register:
kfree(cm->charger_psy.properties);
err_chg_stat:
kfree(cm->charger_stat);
err_no_charger_stat:
err_no_charger:
kfree(cm->desc);
err_alloc_desc:
kfree(cm);
err_alloc:
return ret;
}
static int __devexit charger_manager_remove(struct platform_device *pdev)
{
struct charger_manager *cm = platform_get_drvdata(pdev);
struct charger_desc *desc = cm->desc;
/* Remove from the list */
mutex_lock(&cm_list_mtx);
list_del(&cm->entry);
mutex_unlock(&cm_list_mtx);
regulator_bulk_free(desc->num_charger_regulators,
desc->charger_regulators);
power_supply_unregister(&cm->charger_psy);
kfree(cm->charger_psy.properties);
kfree(cm->charger_stat);
kfree(cm->desc);
kfree(cm);
return 0;
}
static const struct platform_device_id charger_manager_id[] = {
{ "charger-manager", 0 },
{ },
};
MODULE_DEVICE_TABLE(platform, charger_manager_id);
static int cm_suspend_prepare(struct device *dev)
{
struct charger_manager *cm = dev_get_drvdata(dev);
if (!cm_suspended) {
if (rtc_dev) {
struct rtc_time tmp;
unsigned long now;
rtc_read_alarm(rtc_dev, &rtc_wkalarm_save);
rtc_read_time(rtc_dev, &tmp);
if (rtc_wkalarm_save.enabled) {
rtc_tm_to_time(&rtc_wkalarm_save.time,
&rtc_wkalarm_save_time);
rtc_tm_to_time(&tmp, &now);
if (now > rtc_wkalarm_save_time)
rtc_wkalarm_save_time = 0;
} else {
rtc_wkalarm_save_time = 0;
}
}
cm_suspended = true;
}
cm->status_save_ext_pwr_inserted = is_ext_pwr_online(cm);
cm->status_save_batt = is_batt_present(cm);
if (!cm_rtc_set) {
cm_suspend_duration_ms = 0;
cm_rtc_set = cm_setup_timer();
}
return 0;
}
static void cm_suspend_complete(struct device *dev)
{
struct charger_manager *cm = dev_get_drvdata(dev);
if (cm_suspended) {
if (rtc_dev) {
struct rtc_wkalrm tmp;
rtc_read_alarm(rtc_dev, &tmp);
rtc_wkalarm_save.pending = tmp.pending;
rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
}
cm_suspended = false;
cm_rtc_set = false;
}
uevent_notify(cm, NULL);
}
static const struct dev_pm_ops charger_manager_pm = {
.prepare = cm_suspend_prepare,
.complete = cm_suspend_complete,
};
static struct platform_driver charger_manager_driver = {
.driver = {
.name = "charger-manager",
.owner = THIS_MODULE,
.pm = &charger_manager_pm,
},
.probe = charger_manager_probe,
.remove = __devexit_p(charger_manager_remove),
.id_table = charger_manager_id,
};
static int __init charger_manager_init(void)
{
return platform_driver_register(&charger_manager_driver);
}
late_initcall(charger_manager_init);
static void __exit charger_manager_cleanup(void)
{
platform_driver_unregister(&charger_manager_driver);
}
module_exit(charger_manager_cleanup);
MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
MODULE_DESCRIPTION("Charger Manager");
MODULE_LICENSE("GPL");
| gpl-2.0 |
psachin/old.apc-rock-II-kernel | drivers/media/video/au0828/au0828-video.c | 3870 | 50041 | /*
* Auvitek AU0828 USB Bridge (Analog video support)
*
* Copyright (C) 2009 Devin Heitmueller <dheitmueller@linuxtv.org>
* Copyright (C) 2005-2008 Auvitek International, Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* As published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/* Developer Notes:
*
* VBI support is not yet working
* The hardware scaler supported is unimplemented
* AC97 audio support is unimplemented (only i2s audio mode)
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/suspend.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-chip-ident.h>
#include <media/tuner.h>
#include "au0828.h"
#include "au0828-reg.h"
static DEFINE_MUTEX(au0828_sysfs_lock);
/* ------------------------------------------------------------------
Videobuf operations
------------------------------------------------------------------*/
static unsigned int isoc_debug;
module_param(isoc_debug, int, 0644);
MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
#define au0828_isocdbg(fmt, arg...) \
do {\
if (isoc_debug) { \
printk(KERN_INFO "au0828 %s :"fmt, \
__func__ , ##arg); \
} \
} while (0)
static inline void print_err_status(struct au0828_dev *dev,
int packet, int status)
{
char *errmsg = "Unknown";
switch (status) {
case -ENOENT:
errmsg = "unlinked synchronuously";
break;
case -ECONNRESET:
errmsg = "unlinked asynchronuously";
break;
case -ENOSR:
errmsg = "Buffer error (overrun)";
break;
case -EPIPE:
errmsg = "Stalled (device not responding)";
break;
case -EOVERFLOW:
errmsg = "Babble (bad cable?)";
break;
case -EPROTO:
errmsg = "Bit-stuff error (bad cable?)";
break;
case -EILSEQ:
errmsg = "CRC/Timeout (could be anything)";
break;
case -ETIME:
errmsg = "Device does not respond";
break;
}
if (packet < 0) {
au0828_isocdbg("URB status %d [%s].\n", status, errmsg);
} else {
au0828_isocdbg("URB packet %d, status %d [%s].\n",
packet, status, errmsg);
}
}
static int check_dev(struct au0828_dev *dev)
{
if (dev->dev_state & DEV_DISCONNECTED) {
printk(KERN_INFO "v4l2 ioctl: device not present\n");
return -ENODEV;
}
if (dev->dev_state & DEV_MISCONFIGURED) {
printk(KERN_INFO "v4l2 ioctl: device is misconfigured; "
"close and open it again\n");
return -EIO;
}
return 0;
}
/*
* IRQ callback, called by URB callback
*/
static void au0828_irq_callback(struct urb *urb)
{
struct au0828_dmaqueue *dma_q = urb->context;
struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
unsigned long flags = 0;
int rc, i;
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
au0828_isocdbg("au0828_irq_callback called: status kill\n");
return;
default: /* unknown error */
au0828_isocdbg("urb completition error %d.\n", urb->status);
break;
}
/* Copy data from URB */
spin_lock_irqsave(&dev->slock, flags);
rc = dev->isoc_ctl.isoc_copy(dev, urb);
spin_unlock_irqrestore(&dev->slock, flags);
/* Reset urb buffers */
for (i = 0; i < urb->number_of_packets; i++) {
urb->iso_frame_desc[i].status = 0;
urb->iso_frame_desc[i].actual_length = 0;
}
urb->status = 0;
urb->status = usb_submit_urb(urb, GFP_ATOMIC);
if (urb->status) {
au0828_isocdbg("urb resubmit failed (error=%i)\n",
urb->status);
}
}
/*
* Stop and Deallocate URBs
*/
void au0828_uninit_isoc(struct au0828_dev *dev)
{
struct urb *urb;
int i;
au0828_isocdbg("au0828: called au0828_uninit_isoc\n");
dev->isoc_ctl.nfields = -1;
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
urb = dev->isoc_ctl.urb[i];
if (urb) {
if (!irqs_disabled())
usb_kill_urb(urb);
else
usb_unlink_urb(urb);
if (dev->isoc_ctl.transfer_buffer[i]) {
usb_free_coherent(dev->usbdev,
urb->transfer_buffer_length,
dev->isoc_ctl.transfer_buffer[i],
urb->transfer_dma);
}
usb_free_urb(urb);
dev->isoc_ctl.urb[i] = NULL;
}
dev->isoc_ctl.transfer_buffer[i] = NULL;
}
kfree(dev->isoc_ctl.urb);
kfree(dev->isoc_ctl.transfer_buffer);
dev->isoc_ctl.urb = NULL;
dev->isoc_ctl.transfer_buffer = NULL;
dev->isoc_ctl.num_bufs = 0;
}
/*
* Allocate URBs and start IRQ
*/
int au0828_init_isoc(struct au0828_dev *dev, int max_packets,
int num_bufs, int max_pkt_size,
int (*isoc_copy) (struct au0828_dev *dev, struct urb *urb))
{
struct au0828_dmaqueue *dma_q = &dev->vidq;
int i;
int sb_size, pipe;
struct urb *urb;
int j, k;
int rc;
au0828_isocdbg("au0828: called au0828_prepare_isoc\n");
/* De-allocates all pending stuff */
au0828_uninit_isoc(dev);
dev->isoc_ctl.isoc_copy = isoc_copy;
dev->isoc_ctl.num_bufs = num_bufs;
dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs, GFP_KERNEL);
if (!dev->isoc_ctl.urb) {
au0828_isocdbg("cannot alloc memory for usb buffers\n");
return -ENOMEM;
}
dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
GFP_KERNEL);
if (!dev->isoc_ctl.transfer_buffer) {
au0828_isocdbg("cannot allocate memory for usb transfer\n");
kfree(dev->isoc_ctl.urb);
return -ENOMEM;
}
dev->isoc_ctl.max_pkt_size = max_pkt_size;
dev->isoc_ctl.buf = NULL;
sb_size = max_packets * dev->isoc_ctl.max_pkt_size;
/* allocate urbs and transfer buffers */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
urb = usb_alloc_urb(max_packets, GFP_KERNEL);
if (!urb) {
au0828_isocdbg("cannot alloc isoc_ctl.urb %i\n", i);
au0828_uninit_isoc(dev);
return -ENOMEM;
}
dev->isoc_ctl.urb[i] = urb;
dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->usbdev,
sb_size, GFP_KERNEL, &urb->transfer_dma);
if (!dev->isoc_ctl.transfer_buffer[i]) {
printk("unable to allocate %i bytes for transfer"
" buffer %i%s\n",
sb_size, i,
in_interrupt() ? " while in int" : "");
au0828_uninit_isoc(dev);
return -ENOMEM;
}
memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
pipe = usb_rcvisocpipe(dev->usbdev,
dev->isoc_in_endpointaddr),
usb_fill_int_urb(urb, dev->usbdev, pipe,
dev->isoc_ctl.transfer_buffer[i], sb_size,
au0828_irq_callback, dma_q, 1);
urb->number_of_packets = max_packets;
urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
k = 0;
for (j = 0; j < max_packets; j++) {
urb->iso_frame_desc[j].offset = k;
urb->iso_frame_desc[j].length =
dev->isoc_ctl.max_pkt_size;
k += dev->isoc_ctl.max_pkt_size;
}
}
init_waitqueue_head(&dma_q->wq);
/* submit urbs and enables IRQ */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
if (rc) {
au0828_isocdbg("submit of urb %i failed (error=%i)\n",
i, rc);
au0828_uninit_isoc(dev);
return rc;
}
}
return 0;
}
/*
* Announces that a buffer were filled and request the next
*/
static inline void buffer_filled(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf)
{
/* Advice that buffer was filled */
au0828_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
dev->isoc_ctl.buf = NULL;
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
}
static inline void vbi_buffer_filled(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf)
{
/* Advice that buffer was filled */
au0828_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
dev->isoc_ctl.vbi_buf = NULL;
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
}
/*
* Identify the buffer header type and properly handles
*/
static void au0828_copy_video(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf,
unsigned char *p,
unsigned char *outp, unsigned long len)
{
void *fieldstart, *startwrite, *startread;
int linesdone, currlinedone, offset, lencopy, remain;
int bytesperline = dev->width << 1; /* Assumes 16-bit depth @@@@ */
if (len == 0)
return;
if (dma_q->pos + len > buf->vb.size)
len = buf->vb.size - dma_q->pos;
startread = p;
remain = len;
/* Interlaces frame */
if (buf->top_field)
fieldstart = outp;
else
fieldstart = outp + bytesperline;
linesdone = dma_q->pos / bytesperline;
currlinedone = dma_q->pos % bytesperline;
offset = linesdone * bytesperline * 2 + currlinedone;
startwrite = fieldstart + offset;
lencopy = bytesperline - currlinedone;
lencopy = lencopy > remain ? remain : lencopy;
if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
au0828_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
((char *)startwrite + lencopy) -
((char *)outp + buf->vb.size));
remain = (char *)outp + buf->vb.size - (char *)startwrite;
lencopy = remain;
}
if (lencopy <= 0)
return;
memcpy(startwrite, startread, lencopy);
remain -= lencopy;
while (remain > 0) {
startwrite += lencopy + bytesperline;
startread += lencopy;
if (bytesperline > remain)
lencopy = remain;
else
lencopy = bytesperline;
if ((char *)startwrite + lencopy > (char *)outp +
buf->vb.size) {
au0828_isocdbg("Overflow %zi bytes past buf end (2)\n",
((char *)startwrite + lencopy) -
((char *)outp + buf->vb.size));
lencopy = remain = (char *)outp + buf->vb.size -
(char *)startwrite;
}
if (lencopy <= 0)
break;
memcpy(startwrite, startread, lencopy);
remain -= lencopy;
}
if (offset > 1440) {
/* We have enough data to check for greenscreen */
if (outp[0] < 0x60 && outp[1440] < 0x60)
dev->greenscreen_detected = 1;
}
dma_q->pos += len;
}
/*
* video-buf generic routine to get the next available buffer
*/
static inline void get_next_buf(struct au0828_dmaqueue *dma_q,
struct au0828_buffer **buf)
{
struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
if (list_empty(&dma_q->active)) {
au0828_isocdbg("No active queue to serve\n");
dev->isoc_ctl.buf = NULL;
*buf = NULL;
return;
}
/* Get the next buffer */
*buf = list_entry(dma_q->active.next, struct au0828_buffer, vb.queue);
dev->isoc_ctl.buf = *buf;
return;
}
static void au0828_copy_vbi(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf,
unsigned char *p,
unsigned char *outp, unsigned long len)
{
unsigned char *startwrite, *startread;
int bytesperline;
int i, j = 0;
if (dev == NULL) {
au0828_isocdbg("dev is null\n");
return;
}
if (dma_q == NULL) {
au0828_isocdbg("dma_q is null\n");
return;
}
if (buf == NULL)
return;
if (p == NULL) {
au0828_isocdbg("p is null\n");
return;
}
if (outp == NULL) {
au0828_isocdbg("outp is null\n");
return;
}
bytesperline = dev->vbi_width;
if (dma_q->pos + len > buf->vb.size)
len = buf->vb.size - dma_q->pos;
startread = p;
startwrite = outp + (dma_q->pos / 2);
/* Make sure the bottom field populates the second half of the frame */
if (buf->top_field == 0)
startwrite += bytesperline * dev->vbi_height;
for (i = 0; i < len; i += 2)
startwrite[j++] = startread[i+1];
dma_q->pos += len;
}
/*
* video-buf generic routine to get the next available VBI buffer
*/
static inline void vbi_get_next_buf(struct au0828_dmaqueue *dma_q,
struct au0828_buffer **buf)
{
struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vbiq);
char *outp;
if (list_empty(&dma_q->active)) {
au0828_isocdbg("No active queue to serve\n");
dev->isoc_ctl.vbi_buf = NULL;
*buf = NULL;
return;
}
/* Get the next buffer */
*buf = list_entry(dma_q->active.next, struct au0828_buffer, vb.queue);
/* Cleans up buffer - Useful for testing for frame/URB loss */
outp = videobuf_to_vmalloc(&(*buf)->vb);
memset(outp, 0x00, (*buf)->vb.size);
dev->isoc_ctl.vbi_buf = *buf;
return;
}
/*
* Controls the isoc copy of each urb packet
*/
static inline int au0828_isoc_copy(struct au0828_dev *dev, struct urb *urb)
{
struct au0828_buffer *buf;
struct au0828_buffer *vbi_buf;
struct au0828_dmaqueue *dma_q = urb->context;
struct au0828_dmaqueue *vbi_dma_q = &dev->vbiq;
unsigned char *outp = NULL;
unsigned char *vbioutp = NULL;
int i, len = 0, rc = 1;
unsigned char *p;
unsigned char fbyte;
unsigned int vbi_field_size;
unsigned int remain, lencopy;
if (!dev)
return 0;
if ((dev->dev_state & DEV_DISCONNECTED) ||
(dev->dev_state & DEV_MISCONFIGURED))
return 0;
if (urb->status < 0) {
print_err_status(dev, -1, urb->status);
if (urb->status == -ENOENT)
return 0;
}
buf = dev->isoc_ctl.buf;
if (buf != NULL)
outp = videobuf_to_vmalloc(&buf->vb);
vbi_buf = dev->isoc_ctl.vbi_buf;
if (vbi_buf != NULL)
vbioutp = videobuf_to_vmalloc(&vbi_buf->vb);
for (i = 0; i < urb->number_of_packets; i++) {
int status = urb->iso_frame_desc[i].status;
if (status < 0) {
print_err_status(dev, i, status);
if (urb->iso_frame_desc[i].status != -EPROTO)
continue;
}
if (urb->iso_frame_desc[i].actual_length <= 0)
continue;
if (urb->iso_frame_desc[i].actual_length >
dev->max_pkt_size) {
au0828_isocdbg("packet bigger than packet size");
continue;
}
p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
fbyte = p[0];
len = urb->iso_frame_desc[i].actual_length - 4;
p += 4;
if (fbyte & 0x80) {
len -= 4;
p += 4;
au0828_isocdbg("Video frame %s\n",
(fbyte & 0x40) ? "odd" : "even");
if (fbyte & 0x40) {
/* VBI */
if (vbi_buf != NULL)
vbi_buffer_filled(dev,
vbi_dma_q,
vbi_buf);
vbi_get_next_buf(vbi_dma_q, &vbi_buf);
if (vbi_buf == NULL)
vbioutp = NULL;
else
vbioutp = videobuf_to_vmalloc(
&vbi_buf->vb);
/* Video */
if (buf != NULL)
buffer_filled(dev, dma_q, buf);
get_next_buf(dma_q, &buf);
if (buf == NULL)
outp = NULL;
else
outp = videobuf_to_vmalloc(&buf->vb);
/* As long as isoc traffic is arriving, keep
resetting the timer */
if (dev->vid_timeout_running)
mod_timer(&dev->vid_timeout,
jiffies + (HZ / 10));
if (dev->vbi_timeout_running)
mod_timer(&dev->vbi_timeout,
jiffies + (HZ / 10));
}
if (buf != NULL) {
if (fbyte & 0x40)
buf->top_field = 1;
else
buf->top_field = 0;
}
if (vbi_buf != NULL) {
if (fbyte & 0x40)
vbi_buf->top_field = 1;
else
vbi_buf->top_field = 0;
}
dev->vbi_read = 0;
vbi_dma_q->pos = 0;
dma_q->pos = 0;
}
vbi_field_size = dev->vbi_width * dev->vbi_height * 2;
if (dev->vbi_read < vbi_field_size) {
remain = vbi_field_size - dev->vbi_read;
if (len < remain)
lencopy = len;
else
lencopy = remain;
if (vbi_buf != NULL)
au0828_copy_vbi(dev, vbi_dma_q, vbi_buf, p,
vbioutp, len);
len -= lencopy;
p += lencopy;
dev->vbi_read += lencopy;
}
if (dev->vbi_read >= vbi_field_size && buf != NULL)
au0828_copy_video(dev, dma_q, buf, p, outp, len);
}
return rc;
}
static int
buffer_setup(struct videobuf_queue *vq, unsigned int *count,
unsigned int *size)
{
struct au0828_fh *fh = vq->priv_data;
*size = (fh->dev->width * fh->dev->height * 16 + 7) >> 3;
if (0 == *count)
*count = AU0828_DEF_BUF;
if (*count < AU0828_MIN_BUF)
*count = AU0828_MIN_BUF;
return 0;
}
/* This is called *without* dev->slock held; please keep it that way */
static void free_buffer(struct videobuf_queue *vq, struct au0828_buffer *buf)
{
struct au0828_fh *fh = vq->priv_data;
struct au0828_dev *dev = fh->dev;
unsigned long flags = 0;
if (in_interrupt())
BUG();
/* We used to wait for the buffer to finish here, but this didn't work
because, as we were keeping the state as VIDEOBUF_QUEUED,
videobuf_queue_cancel marked it as finished for us.
(Also, it could wedge forever if the hardware was misconfigured.)
This should be safe; by the time we get here, the buffer isn't
queued anymore. If we ever start marking the buffers as
VIDEOBUF_ACTIVE, it won't be, though.
*/
spin_lock_irqsave(&dev->slock, flags);
if (dev->isoc_ctl.buf == buf)
dev->isoc_ctl.buf = NULL;
spin_unlock_irqrestore(&dev->slock, flags);
videobuf_vmalloc_free(&buf->vb);
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
static int
buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct au0828_fh *fh = vq->priv_data;
struct au0828_buffer *buf = container_of(vb, struct au0828_buffer, vb);
struct au0828_dev *dev = fh->dev;
int rc = 0, urb_init = 0;
buf->vb.size = (fh->dev->width * fh->dev->height * 16 + 7) >> 3;
if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
return -EINVAL;
buf->vb.width = dev->width;
buf->vb.height = dev->height;
buf->vb.field = field;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
rc = videobuf_iolock(vq, &buf->vb, NULL);
if (rc < 0) {
printk(KERN_INFO "videobuf_iolock failed\n");
goto fail;
}
}
if (!dev->isoc_ctl.num_bufs)
urb_init = 1;
if (urb_init) {
rc = au0828_init_isoc(dev, AU0828_ISO_PACKETS_PER_URB,
AU0828_MAX_ISO_BUFS, dev->max_pkt_size,
au0828_isoc_copy);
if (rc < 0) {
printk(KERN_INFO "au0828_init_isoc failed\n");
goto fail;
}
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
free_buffer(vq, buf);
return rc;
}
static void
buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct au0828_buffer *buf = container_of(vb,
struct au0828_buffer,
vb);
struct au0828_fh *fh = vq->priv_data;
struct au0828_dev *dev = fh->dev;
struct au0828_dmaqueue *vidq = &dev->vidq;
buf->vb.state = VIDEOBUF_QUEUED;
list_add_tail(&buf->vb.queue, &vidq->active);
}
static void buffer_release(struct videobuf_queue *vq,
struct videobuf_buffer *vb)
{
struct au0828_buffer *buf = container_of(vb,
struct au0828_buffer,
vb);
free_buffer(vq, buf);
}
static struct videobuf_queue_ops au0828_video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
/* ------------------------------------------------------------------
V4L2 interface
------------------------------------------------------------------*/
static int au0828_i2s_init(struct au0828_dev *dev)
{
/* Enable i2s mode */
au0828_writereg(dev, AU0828_AUDIOCTRL_50C, 0x01);
return 0;
}
/*
* Auvitek au0828 analog stream enable
* Please set interface0 to AS5 before enable the stream
*/
int au0828_analog_stream_enable(struct au0828_dev *d)
{
dprintk(1, "au0828_analog_stream_enable called\n");
au0828_writereg(d, AU0828_SENSORCTRL_VBI_103, 0x00);
au0828_writereg(d, 0x106, 0x00);
/* set x position */
au0828_writereg(d, 0x110, 0x00);
au0828_writereg(d, 0x111, 0x00);
au0828_writereg(d, 0x114, 0xa0);
au0828_writereg(d, 0x115, 0x05);
/* set y position */
au0828_writereg(d, 0x112, 0x00);
au0828_writereg(d, 0x113, 0x00);
au0828_writereg(d, 0x116, 0xf2);
au0828_writereg(d, 0x117, 0x00);
au0828_writereg(d, AU0828_SENSORCTRL_100, 0xb3);
return 0;
}
int au0828_analog_stream_disable(struct au0828_dev *d)
{
dprintk(1, "au0828_analog_stream_disable called\n");
au0828_writereg(d, AU0828_SENSORCTRL_100, 0x0);
return 0;
}
void au0828_analog_stream_reset(struct au0828_dev *dev)
{
dprintk(1, "au0828_analog_stream_reset called\n");
au0828_writereg(dev, AU0828_SENSORCTRL_100, 0x0);
mdelay(30);
au0828_writereg(dev, AU0828_SENSORCTRL_100, 0xb3);
}
/*
* Some operations needs to stop current streaming
*/
static int au0828_stream_interrupt(struct au0828_dev *dev)
{
int ret = 0;
dev->stream_state = STREAM_INTERRUPT;
if (dev->dev_state == DEV_DISCONNECTED)
return -ENODEV;
else if (ret) {
dev->dev_state = DEV_MISCONFIGURED;
dprintk(1, "%s device is misconfigured!\n", __func__);
return ret;
}
return 0;
}
/*
* au0828_release_resources
* unregister v4l2 devices
*/
void au0828_analog_unregister(struct au0828_dev *dev)
{
dprintk(1, "au0828_release_resources called\n");
mutex_lock(&au0828_sysfs_lock);
if (dev->vdev)
video_unregister_device(dev->vdev);
if (dev->vbi_dev)
video_unregister_device(dev->vbi_dev);
mutex_unlock(&au0828_sysfs_lock);
}
/* Usage lock check functions */
static int res_get(struct au0828_fh *fh, unsigned int bit)
{
struct au0828_dev *dev = fh->dev;
if (fh->resources & bit)
/* have it already allocated */
return 1;
/* is it free? */
mutex_lock(&dev->lock);
if (dev->resources & bit) {
/* no, someone else uses it */
mutex_unlock(&dev->lock);
return 0;
}
/* it's free, grab it */
fh->resources |= bit;
dev->resources |= bit;
dprintk(1, "res: get %d\n", bit);
mutex_unlock(&dev->lock);
return 1;
}
static int res_check(struct au0828_fh *fh, unsigned int bit)
{
return fh->resources & bit;
}
static int res_locked(struct au0828_dev *dev, unsigned int bit)
{
return dev->resources & bit;
}
static void res_free(struct au0828_fh *fh, unsigned int bits)
{
struct au0828_dev *dev = fh->dev;
BUG_ON((fh->resources & bits) != bits);
mutex_lock(&dev->lock);
fh->resources &= ~bits;
dev->resources &= ~bits;
dprintk(1, "res: put %d\n", bits);
mutex_unlock(&dev->lock);
}
static int get_ressource(struct au0828_fh *fh)
{
switch (fh->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
return AU0828_RESOURCE_VIDEO;
case V4L2_BUF_TYPE_VBI_CAPTURE:
return AU0828_RESOURCE_VBI;
default:
BUG();
return 0;
}
}
/* This function ensures that video frames continue to be delivered even if
the ITU-656 input isn't receiving any data (thereby preventing applications
such as tvtime from hanging) */
void au0828_vid_buffer_timeout(unsigned long data)
{
struct au0828_dev *dev = (struct au0828_dev *) data;
struct au0828_dmaqueue *dma_q = &dev->vidq;
struct au0828_buffer *buf;
unsigned char *vid_data;
unsigned long flags = 0;
spin_lock_irqsave(&dev->slock, flags);
buf = dev->isoc_ctl.buf;
if (buf != NULL) {
vid_data = videobuf_to_vmalloc(&buf->vb);
memset(vid_data, 0x00, buf->vb.size); /* Blank green frame */
buffer_filled(dev, dma_q, buf);
}
get_next_buf(dma_q, &buf);
if (dev->vid_timeout_running == 1)
mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
spin_unlock_irqrestore(&dev->slock, flags);
}
void au0828_vbi_buffer_timeout(unsigned long data)
{
struct au0828_dev *dev = (struct au0828_dev *) data;
struct au0828_dmaqueue *dma_q = &dev->vbiq;
struct au0828_buffer *buf;
unsigned char *vbi_data;
unsigned long flags = 0;
spin_lock_irqsave(&dev->slock, flags);
buf = dev->isoc_ctl.vbi_buf;
if (buf != NULL) {
vbi_data = videobuf_to_vmalloc(&buf->vb);
memset(vbi_data, 0x00, buf->vb.size);
vbi_buffer_filled(dev, dma_q, buf);
}
vbi_get_next_buf(dma_q, &buf);
if (dev->vbi_timeout_running == 1)
mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
spin_unlock_irqrestore(&dev->slock, flags);
}
static int au0828_v4l2_open(struct file *filp)
{
int ret = 0;
struct video_device *vdev = video_devdata(filp);
struct au0828_dev *dev = video_drvdata(filp);
struct au0828_fh *fh;
int type;
switch (vdev->vfl_type) {
case VFL_TYPE_GRABBER:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
break;
case VFL_TYPE_VBI:
type = V4L2_BUF_TYPE_VBI_CAPTURE;
break;
default:
return -EINVAL;
}
fh = kzalloc(sizeof(struct au0828_fh), GFP_KERNEL);
if (NULL == fh) {
dprintk(1, "Failed allocate au0828_fh struct!\n");
return -ENOMEM;
}
fh->type = type;
fh->dev = dev;
filp->private_data = fh;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
/* set au0828 interface0 to AS5 here again */
ret = usb_set_interface(dev->usbdev, 0, 5);
if (ret < 0) {
printk(KERN_INFO "Au0828 can't set alternate to 5!\n");
return -EBUSY;
}
dev->width = NTSC_STD_W;
dev->height = NTSC_STD_H;
dev->frame_size = dev->width * dev->height * 2;
dev->field_size = dev->width * dev->height;
dev->bytesperline = dev->width * 2;
au0828_analog_stream_enable(dev);
au0828_analog_stream_reset(dev);
/* If we were doing ac97 instead of i2s, it would go here...*/
au0828_i2s_init(dev);
dev->stream_state = STREAM_OFF;
dev->dev_state |= DEV_INITIALIZED;
}
dev->users++;
videobuf_queue_vmalloc_init(&fh->vb_vidq, &au0828_video_qops,
NULL, &dev->slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_INTERLACED,
sizeof(struct au0828_buffer), fh, NULL);
/* VBI Setup */
dev->vbi_width = 720;
dev->vbi_height = 1;
videobuf_queue_vmalloc_init(&fh->vb_vbiq, &au0828_vbi_qops,
NULL, &dev->slock,
V4L2_BUF_TYPE_VBI_CAPTURE,
V4L2_FIELD_SEQ_TB,
sizeof(struct au0828_buffer), fh, NULL);
return ret;
}
static int au0828_v4l2_close(struct file *filp)
{
int ret;
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
if (res_check(fh, AU0828_RESOURCE_VIDEO)) {
/* Cancel timeout thread in case they didn't call streamoff */
dev->vid_timeout_running = 0;
del_timer_sync(&dev->vid_timeout);
videobuf_stop(&fh->vb_vidq);
res_free(fh, AU0828_RESOURCE_VIDEO);
}
if (res_check(fh, AU0828_RESOURCE_VBI)) {
/* Cancel timeout thread in case they didn't call streamoff */
dev->vbi_timeout_running = 0;
del_timer_sync(&dev->vbi_timeout);
videobuf_stop(&fh->vb_vbiq);
res_free(fh, AU0828_RESOURCE_VBI);
}
if (dev->users == 1) {
if (dev->dev_state & DEV_DISCONNECTED) {
au0828_analog_unregister(dev);
kfree(dev);
return 0;
}
au0828_analog_stream_disable(dev);
au0828_uninit_isoc(dev);
/* Save some power by putting tuner to sleep */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_power, 0);
/* When close the device, set the usb intf0 into alt0 to free
USB bandwidth */
ret = usb_set_interface(dev->usbdev, 0, 0);
if (ret < 0)
printk(KERN_INFO "Au0828 can't set alternate to 0!\n");
}
videobuf_mmap_free(&fh->vb_vidq);
videobuf_mmap_free(&fh->vb_vbiq);
kfree(fh);
dev->users--;
wake_up_interruptible_nr(&dev->open, 1);
return 0;
}
static ssize_t au0828_v4l2_read(struct file *filp, char __user *buf,
size_t count, loff_t *pos)
{
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
if (res_locked(dev, AU0828_RESOURCE_VIDEO))
return -EBUSY;
return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
filp->f_flags & O_NONBLOCK);
}
if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
if (!res_get(fh, AU0828_RESOURCE_VBI))
return -EBUSY;
if (dev->vbi_timeout_running == 0) {
/* Handle case where caller tries to read without
calling streamon first */
dev->vbi_timeout_running = 1;
mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
}
return videobuf_read_stream(&fh->vb_vbiq, buf, count, pos, 0,
filp->f_flags & O_NONBLOCK);
}
return 0;
}
static unsigned int au0828_v4l2_poll(struct file *filp, poll_table *wait)
{
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
if (!res_get(fh, AU0828_RESOURCE_VIDEO))
return POLLERR;
return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
if (!res_get(fh, AU0828_RESOURCE_VBI))
return POLLERR;
return videobuf_poll_stream(filp, &fh->vb_vbiq, wait);
} else {
return POLLERR;
}
}
static int au0828_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
{
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_mmap_mapper(&fh->vb_vbiq, vma);
return rc;
}
static int au0828_set_format(struct au0828_dev *dev, unsigned int cmd,
struct v4l2_format *format)
{
int ret;
int width = format->fmt.pix.width;
int height = format->fmt.pix.height;
if (format->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
/* If they are demanding a format other than the one we support,
bail out (tvtime asks for UYVY and then retries with YUYV) */
if (format->fmt.pix.pixelformat != V4L2_PIX_FMT_UYVY)
return -EINVAL;
/* format->fmt.pix.width only support 720 and height 480 */
if (width != 720)
width = 720;
if (height != 480)
height = 480;
format->fmt.pix.width = width;
format->fmt.pix.height = height;
format->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
format->fmt.pix.bytesperline = width * 2;
format->fmt.pix.sizeimage = width * height * 2;
format->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
format->fmt.pix.field = V4L2_FIELD_INTERLACED;
if (cmd == VIDIOC_TRY_FMT)
return 0;
/* maybe set new image format, driver current only support 720*480 */
dev->width = width;
dev->height = height;
dev->frame_size = width * height * 2;
dev->field_size = width * height;
dev->bytesperline = width * 2;
if (dev->stream_state == STREAM_ON) {
dprintk(1, "VIDIOC_SET_FMT: interrupting stream!\n");
ret = au0828_stream_interrupt(dev);
if (ret != 0) {
dprintk(1, "error interrupting video stream!\n");
return ret;
}
}
/* set au0828 interface0 to AS5 here again */
ret = usb_set_interface(dev->usbdev, 0, 5);
if (ret < 0) {
printk(KERN_INFO "Au0828 can't set alt setting to 5!\n");
return -EBUSY;
}
au0828_analog_stream_enable(dev);
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, queryctrl, qc);
if (qc->type)
return 0;
else
return -EINVAL;
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
strlcpy(cap->driver, "au0828", sizeof(cap->driver));
strlcpy(cap->card, dev->board.name, sizeof(cap->card));
strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));
/*set the device capabilities */
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_VBI_CAPTURE |
V4L2_CAP_AUDIO |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING |
V4L2_CAP_TUNER;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index)
return -EINVAL;
f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
strcpy(f->description, "Packed YUV2");
f->flags = 0;
f->pixelformat = V4L2_PIX_FMT_UYVY;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
f->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
f->fmt.pix.bytesperline = dev->bytesperline;
f->fmt.pix.sizeimage = dev->frame_size;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M; /* NTSC/PAL */
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
return au0828_set_format(dev, VIDIOC_TRY_FMT, f);
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
mutex_lock(&dev->lock);
if (videobuf_queue_is_busy(&fh->vb_vidq)) {
printk(KERN_INFO "%s queue busy\n", __func__);
rc = -EBUSY;
goto out;
}
rc = au0828_set_format(dev, VIDIOC_S_FMT, f);
out:
mutex_unlock(&dev->lock);
return rc;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id * norm)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
/* FIXME: when we support something other than NTSC, we are going to
have to make the au0828 bridge adjust the size of its capture
buffer, which is currently hardcoded at 720x480 */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std, *norm);
return 0;
}
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *input)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
unsigned int tmp;
static const char *inames[] = {
[AU0828_VMUX_UNDEFINED] = "Undefined",
[AU0828_VMUX_COMPOSITE] = "Composite",
[AU0828_VMUX_SVIDEO] = "S-Video",
[AU0828_VMUX_CABLE] = "Cable TV",
[AU0828_VMUX_TELEVISION] = "Television",
[AU0828_VMUX_DVB] = "DVB",
[AU0828_VMUX_DEBUG] = "tv debug"
};
tmp = input->index;
if (tmp >= AU0828_MAX_INPUT)
return -EINVAL;
if (AUVI_INPUT(tmp).type == 0)
return -EINVAL;
input->index = tmp;
strcpy(input->name, inames[AUVI_INPUT(tmp).type]);
if ((AUVI_INPUT(tmp).type == AU0828_VMUX_TELEVISION) ||
(AUVI_INPUT(tmp).type == AU0828_VMUX_CABLE))
input->type |= V4L2_INPUT_TYPE_TUNER;
else
input->type |= V4L2_INPUT_TYPE_CAMERA;
input->std = dev->vdev->tvnorms;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
*i = dev->ctrl_input;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int index)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int i;
dprintk(1, "VIDIOC_S_INPUT in function %s, input=%d\n", __func__,
index);
if (index >= AU0828_MAX_INPUT)
return -EINVAL;
if (AUVI_INPUT(index).type == 0)
return -EINVAL;
dev->ctrl_input = index;
switch (AUVI_INPUT(index).type) {
case AU0828_VMUX_SVIDEO:
dev->input_type = AU0828_VMUX_SVIDEO;
break;
case AU0828_VMUX_COMPOSITE:
dev->input_type = AU0828_VMUX_COMPOSITE;
break;
case AU0828_VMUX_TELEVISION:
dev->input_type = AU0828_VMUX_TELEVISION;
break;
default:
dprintk(1, "VIDIOC_S_INPUT unknown input type set [%d]\n",
AUVI_INPUT(index).type);
break;
}
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_routing,
AUVI_INPUT(index).vmux, 0, 0);
for (i = 0; i < AU0828_MAX_INPUT; i++) {
int enable = 0;
if (AUVI_INPUT(i).audio_setup == NULL)
continue;
if (i == index)
enable = 1;
else
enable = 0;
if (enable) {
(AUVI_INPUT(i).audio_setup)(dev, enable);
} else {
/* Make sure we leave it turned on if some
other input is routed to this callback */
if ((AUVI_INPUT(i).audio_setup) !=
((AUVI_INPUT(index).audio_setup))) {
(AUVI_INPUT(i).audio_setup)(dev, enable);
}
}
}
v4l2_device_call_all(&dev->v4l2_dev, 0, audio, s_routing,
AUVI_INPUT(index).amux, 0, 0);
return 0;
}
static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
unsigned int index = a->index;
if (a->index > 1)
return -EINVAL;
index = dev->ctrl_ainput;
if (index == 0)
strcpy(a->name, "Television");
else
strcpy(a->name, "Line in");
a->capability = V4L2_AUDCAP_STEREO;
a->index = index;
return 0;
}
static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (a->index != dev->ctrl_ainput)
return -EINVAL;
return 0;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_ctrl, ctrl);
return 0;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_ctrl, ctrl);
return 0;
}
static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (t->index != 0)
return -EINVAL;
strcpy(t->name, "Auvitek tuner");
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (t->index != 0)
return -EINVAL;
t->type = V4L2_TUNER_ANALOG_TV;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
dprintk(1, "VIDIOC_S_TUNER: signal = %x, afc = %x\n", t->signal,
t->afc);
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *freq)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
freq->type = V4L2_TUNER_ANALOG_TV;
freq->frequency = dev->ctrl_freq;
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *freq)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (freq->tuner != 0)
return -EINVAL;
if (freq->type != V4L2_TUNER_ANALOG_TV)
return -EINVAL;
dev->ctrl_freq = freq->frequency;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, freq);
au0828_analog_stream_reset(dev);
return 0;
}
/* RAW VBI ioctls */
static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
struct v4l2_format *format)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
format->fmt.vbi.samples_per_line = dev->vbi_width;
format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
format->fmt.vbi.offset = 0;
format->fmt.vbi.flags = 0;
format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
format->fmt.vbi.count[0] = dev->vbi_height;
format->fmt.vbi.count[1] = dev->vbi_height;
format->fmt.vbi.start[0] = 21;
format->fmt.vbi.start[1] = 284;
return 0;
}
static int vidioc_g_chip_ident(struct file *file, void *priv,
struct v4l2_dbg_chip_ident *chip)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
chip->ident = V4L2_IDENT_NONE;
chip->revision = 0;
if (v4l2_chip_match_host(&chip->match)) {
chip->ident = V4L2_IDENT_AU0828;
return 0;
}
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_chip_ident, chip);
if (chip->ident == V4L2_IDENT_NONE)
return -EINVAL;
return 0;
}
static int vidioc_cropcap(struct file *file, void *priv,
struct v4l2_cropcap *cc)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
cc->bounds.left = 0;
cc->bounds.top = 0;
cc->bounds.width = dev->width;
cc->bounds.height = dev->height;
cc->defrect = cc->bounds;
cc->pixelaspect.numerator = 54;
cc->pixelaspect.denominator = 59;
return 0;
}
static int vidioc_streamon(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc = -EINVAL;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (unlikely(type != fh->type))
return -EINVAL;
dprintk(1, "vidioc_streamon fh=%p t=%d fh->res=%d dev->res=%d\n",
fh, type, fh->resources, dev->resources);
if (unlikely(!res_get(fh, get_ressource(fh))))
return -EBUSY;
if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
au0828_analog_stream_enable(dev);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 1);
}
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
rc = videobuf_streamon(&fh->vb_vidq);
dev->vid_timeout_running = 1;
mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
rc = videobuf_streamon(&fh->vb_vbiq);
dev->vbi_timeout_running = 1;
mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
}
return rc;
}
static int vidioc_streamoff(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
int i;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
fh->type != V4L2_BUF_TYPE_VBI_CAPTURE)
return -EINVAL;
if (type != fh->type)
return -EINVAL;
dprintk(1, "vidioc_streamoff fh=%p t=%d fh->res=%d dev->res=%d\n",
fh, type, fh->resources, dev->resources);
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
dev->vid_timeout_running = 0;
del_timer_sync(&dev->vid_timeout);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
rc = au0828_stream_interrupt(dev);
if (rc != 0)
return rc;
for (i = 0; i < AU0828_MAX_INPUT; i++) {
if (AUVI_INPUT(i).audio_setup == NULL)
continue;
(AUVI_INPUT(i).audio_setup)(dev, 0);
}
videobuf_streamoff(&fh->vb_vidq);
res_free(fh, AU0828_RESOURCE_VIDEO);
} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
dev->vbi_timeout_running = 0;
del_timer_sync(&dev->vbi_timeout);
videobuf_streamoff(&fh->vb_vbiq);
res_free(fh, AU0828_RESOURCE_VBI);
}
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int vidioc_g_register(struct file *file, void *priv,
struct v4l2_dbg_register *reg)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_register, reg);
return 0;
default:
return -EINVAL;
}
}
static int vidioc_s_register(struct file *file, void *priv,
struct v4l2_dbg_register *reg)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_register, reg);
return 0;
default:
return -EINVAL;
}
return 0;
}
#endif
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *rb)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_reqbufs(&fh->vb_vidq, rb);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_reqbufs(&fh->vb_vbiq, rb);
return rc;
}
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *b)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_querybuf(&fh->vb_vidq, b);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_querybuf(&fh->vb_vbiq, b);
return rc;
}
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_qbuf(&fh->vb_vidq, b);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_qbuf(&fh->vb_vbiq, b);
return rc;
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
/* Workaround for a bug in the au0828 hardware design that sometimes
results in the colorspace being inverted */
if (dev->greenscreen_detected == 1) {
dprintk(1, "Detected green frame. Resetting stream...\n");
au0828_analog_stream_reset(dev);
dev->greenscreen_detected = 0;
}
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags & O_NONBLOCK);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_dqbuf(&fh->vb_vbiq, b, file->f_flags & O_NONBLOCK);
return rc;
}
static struct v4l2_file_operations au0828_v4l_fops = {
.owner = THIS_MODULE,
.open = au0828_v4l2_open,
.release = au0828_v4l2_close,
.read = au0828_v4l2_read,
.poll = au0828_v4l2_poll,
.mmap = au0828_v4l2_mmap,
.ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops video_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_g_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_s_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_cropcap = vidioc_cropcap,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.vidioc_g_register = vidioc_g_register,
.vidioc_s_register = vidioc_s_register,
#endif
.vidioc_g_chip_ident = vidioc_g_chip_ident,
};
static const struct video_device au0828_video_template = {
.fops = &au0828_v4l_fops,
.release = video_device_release,
.ioctl_ops = &video_ioctl_ops,
.tvnorms = V4L2_STD_NTSC_M,
.current_norm = V4L2_STD_NTSC_M,
};
/**************************************************************************/
int au0828_analog_register(struct au0828_dev *dev,
struct usb_interface *interface)
{
int retval = -ENOMEM;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int i;
dprintk(1, "au0828_analog_register called!\n");
/* set au0828 usb interface0 to as5 */
retval = usb_set_interface(dev->usbdev,
interface->cur_altsetting->desc.bInterfaceNumber, 5);
if (retval != 0) {
printk(KERN_INFO "Failure setting usb interface0 to as5\n");
return retval;
}
/* Figure out which endpoint has the isoc interface */
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
endpoint = &iface_desc->endpoint[i].desc;
if (((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
== USB_DIR_IN) &&
((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)) {
/* we find our isoc in endpoint */
u16 tmp = le16_to_cpu(endpoint->wMaxPacketSize);
dev->max_pkt_size = (tmp & 0x07ff) *
(((tmp & 0x1800) >> 11) + 1);
dev->isoc_in_endpointaddr = endpoint->bEndpointAddress;
}
}
if (!(dev->isoc_in_endpointaddr)) {
printk(KERN_INFO "Could not locate isoc endpoint\n");
kfree(dev);
return -ENODEV;
}
init_waitqueue_head(&dev->open);
spin_lock_init(&dev->slock);
mutex_init(&dev->lock);
/* init video dma queues */
INIT_LIST_HEAD(&dev->vidq.active);
INIT_LIST_HEAD(&dev->vidq.queued);
INIT_LIST_HEAD(&dev->vbiq.active);
INIT_LIST_HEAD(&dev->vbiq.queued);
dev->vid_timeout.function = au0828_vid_buffer_timeout;
dev->vid_timeout.data = (unsigned long) dev;
init_timer(&dev->vid_timeout);
dev->vbi_timeout.function = au0828_vbi_buffer_timeout;
dev->vbi_timeout.data = (unsigned long) dev;
init_timer(&dev->vbi_timeout);
dev->width = NTSC_STD_W;
dev->height = NTSC_STD_H;
dev->field_size = dev->width * dev->height;
dev->frame_size = dev->field_size << 1;
dev->bytesperline = dev->width << 1;
dev->ctrl_ainput = 0;
/* allocate and fill v4l2 video struct */
dev->vdev = video_device_alloc();
if (NULL == dev->vdev) {
dprintk(1, "Can't allocate video_device.\n");
return -ENOMEM;
}
/* allocate the VBI struct */
dev->vbi_dev = video_device_alloc();
if (NULL == dev->vbi_dev) {
dprintk(1, "Can't allocate vbi_device.\n");
kfree(dev->vdev);
return -ENOMEM;
}
/* Fill the video capture device struct */
*dev->vdev = au0828_video_template;
dev->vdev->parent = &dev->usbdev->dev;
strcpy(dev->vdev->name, "au0828a video");
/* Setup the VBI device */
*dev->vbi_dev = au0828_video_template;
dev->vbi_dev->parent = &dev->usbdev->dev;
strcpy(dev->vbi_dev->name, "au0828a vbi");
/* Register the v4l2 device */
video_set_drvdata(dev->vdev, dev);
retval = video_register_device(dev->vdev, VFL_TYPE_GRABBER, -1);
if (retval != 0) {
dprintk(1, "unable to register video device (error = %d).\n",
retval);
video_device_release(dev->vdev);
return -ENODEV;
}
/* Register the vbi device */
video_set_drvdata(dev->vbi_dev, dev);
retval = video_register_device(dev->vbi_dev, VFL_TYPE_VBI, -1);
if (retval != 0) {
dprintk(1, "unable to register vbi device (error = %d).\n",
retval);
video_device_release(dev->vbi_dev);
video_device_release(dev->vdev);
return -ENODEV;
}
dprintk(1, "%s completed!\n", __func__);
return 0;
}
| gpl-2.0 |
Oct-mm/kraken_kernel_samsung_d2 | arch/powerpc/platforms/powermac/low_i2c.c | 4382 | 37281 | /*
* arch/powerpc/platforms/powermac/low_i2c.c
*
* Copyright (C) 2003-2005 Ben. Herrenschmidt (benh@kernel.crashing.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.
*
* The linux i2c layer isn't completely suitable for our needs for various
* reasons ranging from too late initialisation to semantics not perfectly
* matching some requirements of the apple platform functions etc...
*
* This file thus provides a simple low level unified i2c interface for
* powermac that covers the various types of i2c busses used in Apple machines.
* For now, keywest, PMU and SMU, though we could add Cuda, or other bit
* banging busses found on older chipstes in earlier machines if we ever need
* one of them.
*
* The drivers in this file are synchronous/blocking. In addition, the
* keywest one is fairly slow due to the use of msleep instead of interrupts
* as the interrupt is currently used by i2c-keywest. In the long run, we
* might want to get rid of those high-level interfaces to linux i2c layer
* either completely (converting all drivers) or replacing them all with a
* single stub driver on top of this one. Once done, the interrupt will be
* available for our use.
*/
#undef DEBUG
#undef DEBUG_LOW
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/export.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/timer.h>
#include <linux/mutex.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <asm/keylargo.h>
#include <asm/uninorth.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/smu.h>
#include <asm/pmac_pfunc.h>
#include <asm/pmac_low_i2c.h>
#ifdef DEBUG
#define DBG(x...) do {\
printk(KERN_DEBUG "low_i2c:" x); \
} while(0)
#else
#define DBG(x...)
#endif
#ifdef DEBUG_LOW
#define DBG_LOW(x...) do {\
printk(KERN_DEBUG "low_i2c:" x); \
} while(0)
#else
#define DBG_LOW(x...)
#endif
static int pmac_i2c_force_poll = 1;
/*
* A bus structure. Each bus in the system has such a structure associated.
*/
struct pmac_i2c_bus
{
struct list_head link;
struct device_node *controller;
struct device_node *busnode;
int type;
int flags;
struct i2c_adapter adapter;
void *hostdata;
int channel; /* some hosts have multiple */
int mode; /* current mode */
struct mutex mutex;
int opened;
int polled; /* open mode */
struct platform_device *platform_dev;
/* ops */
int (*open)(struct pmac_i2c_bus *bus);
void (*close)(struct pmac_i2c_bus *bus);
int (*xfer)(struct pmac_i2c_bus *bus, u8 addrdir, int subsize,
u32 subaddr, u8 *data, int len);
};
static LIST_HEAD(pmac_i2c_busses);
/*
* Keywest implementation
*/
struct pmac_i2c_host_kw
{
struct mutex mutex; /* Access mutex for use by
* i2c-keywest */
void __iomem *base; /* register base address */
int bsteps; /* register stepping */
int speed; /* speed */
int irq;
u8 *data;
unsigned len;
int state;
int rw;
int polled;
int result;
struct completion complete;
spinlock_t lock;
struct timer_list timeout_timer;
};
/* Register indices */
typedef enum {
reg_mode = 0,
reg_control,
reg_status,
reg_isr,
reg_ier,
reg_addr,
reg_subaddr,
reg_data
} reg_t;
/* The Tumbler audio equalizer can be really slow sometimes */
#define KW_POLL_TIMEOUT (2*HZ)
/* Mode register */
#define KW_I2C_MODE_100KHZ 0x00
#define KW_I2C_MODE_50KHZ 0x01
#define KW_I2C_MODE_25KHZ 0x02
#define KW_I2C_MODE_DUMB 0x00
#define KW_I2C_MODE_STANDARD 0x04
#define KW_I2C_MODE_STANDARDSUB 0x08
#define KW_I2C_MODE_COMBINED 0x0C
#define KW_I2C_MODE_MODE_MASK 0x0C
#define KW_I2C_MODE_CHAN_MASK 0xF0
/* Control register */
#define KW_I2C_CTL_AAK 0x01
#define KW_I2C_CTL_XADDR 0x02
#define KW_I2C_CTL_STOP 0x04
#define KW_I2C_CTL_START 0x08
/* Status register */
#define KW_I2C_STAT_BUSY 0x01
#define KW_I2C_STAT_LAST_AAK 0x02
#define KW_I2C_STAT_LAST_RW 0x04
#define KW_I2C_STAT_SDA 0x08
#define KW_I2C_STAT_SCL 0x10
/* IER & ISR registers */
#define KW_I2C_IRQ_DATA 0x01
#define KW_I2C_IRQ_ADDR 0x02
#define KW_I2C_IRQ_STOP 0x04
#define KW_I2C_IRQ_START 0x08
#define KW_I2C_IRQ_MASK 0x0F
/* State machine states */
enum {
state_idle,
state_addr,
state_read,
state_write,
state_stop,
state_dead
};
#define WRONG_STATE(name) do {\
printk(KERN_DEBUG "KW: wrong state. Got %s, state: %s " \
"(isr: %02x)\n", \
name, __kw_state_names[host->state], isr); \
} while(0)
static const char *__kw_state_names[] = {
"state_idle",
"state_addr",
"state_read",
"state_write",
"state_stop",
"state_dead"
};
static inline u8 __kw_read_reg(struct pmac_i2c_host_kw *host, reg_t reg)
{
return readb(host->base + (((unsigned int)reg) << host->bsteps));
}
static inline void __kw_write_reg(struct pmac_i2c_host_kw *host,
reg_t reg, u8 val)
{
writeb(val, host->base + (((unsigned)reg) << host->bsteps));
(void)__kw_read_reg(host, reg_subaddr);
}
#define kw_write_reg(reg, val) __kw_write_reg(host, reg, val)
#define kw_read_reg(reg) __kw_read_reg(host, reg)
static u8 kw_i2c_wait_interrupt(struct pmac_i2c_host_kw *host)
{
int i, j;
u8 isr;
for (i = 0; i < 1000; i++) {
isr = kw_read_reg(reg_isr) & KW_I2C_IRQ_MASK;
if (isr != 0)
return isr;
/* This code is used with the timebase frozen, we cannot rely
* on udelay nor schedule when in polled mode !
* For now, just use a bogus loop....
*/
if (host->polled) {
for (j = 1; j < 100000; j++)
mb();
} else
msleep(1);
}
return isr;
}
static void kw_i2c_do_stop(struct pmac_i2c_host_kw *host, int result)
{
kw_write_reg(reg_control, KW_I2C_CTL_STOP);
host->state = state_stop;
host->result = result;
}
static void kw_i2c_handle_interrupt(struct pmac_i2c_host_kw *host, u8 isr)
{
u8 ack;
DBG_LOW("kw_handle_interrupt(%s, isr: %x)\n",
__kw_state_names[host->state], isr);
if (host->state == state_idle) {
printk(KERN_WARNING "low_i2c: Keywest got an out of state"
" interrupt, ignoring\n");
kw_write_reg(reg_isr, isr);
return;
}
if (isr == 0) {
printk(KERN_WARNING "low_i2c: Timeout in i2c transfer"
" on keywest !\n");
if (host->state != state_stop) {
kw_i2c_do_stop(host, -EIO);
return;
}
ack = kw_read_reg(reg_status);
if (ack & KW_I2C_STAT_BUSY)
kw_write_reg(reg_status, 0);
host->state = state_idle;
kw_write_reg(reg_ier, 0x00);
if (!host->polled)
complete(&host->complete);
return;
}
if (isr & KW_I2C_IRQ_ADDR) {
ack = kw_read_reg(reg_status);
if (host->state != state_addr) {
WRONG_STATE("KW_I2C_IRQ_ADDR");
kw_i2c_do_stop(host, -EIO);
}
if ((ack & KW_I2C_STAT_LAST_AAK) == 0) {
host->result = -ENXIO;
host->state = state_stop;
DBG_LOW("KW: NAK on address\n");
} else {
if (host->len == 0)
kw_i2c_do_stop(host, 0);
else if (host->rw) {
host->state = state_read;
if (host->len > 1)
kw_write_reg(reg_control,
KW_I2C_CTL_AAK);
} else {
host->state = state_write;
kw_write_reg(reg_data, *(host->data++));
host->len--;
}
}
kw_write_reg(reg_isr, KW_I2C_IRQ_ADDR);
}
if (isr & KW_I2C_IRQ_DATA) {
if (host->state == state_read) {
*(host->data++) = kw_read_reg(reg_data);
host->len--;
kw_write_reg(reg_isr, KW_I2C_IRQ_DATA);
if (host->len == 0)
host->state = state_stop;
else if (host->len == 1)
kw_write_reg(reg_control, 0);
} else if (host->state == state_write) {
ack = kw_read_reg(reg_status);
if ((ack & KW_I2C_STAT_LAST_AAK) == 0) {
DBG_LOW("KW: nack on data write\n");
host->result = -EFBIG;
host->state = state_stop;
} else if (host->len) {
kw_write_reg(reg_data, *(host->data++));
host->len--;
} else
kw_i2c_do_stop(host, 0);
} else {
WRONG_STATE("KW_I2C_IRQ_DATA");
if (host->state != state_stop)
kw_i2c_do_stop(host, -EIO);
}
kw_write_reg(reg_isr, KW_I2C_IRQ_DATA);
}
if (isr & KW_I2C_IRQ_STOP) {
kw_write_reg(reg_isr, KW_I2C_IRQ_STOP);
if (host->state != state_stop) {
WRONG_STATE("KW_I2C_IRQ_STOP");
host->result = -EIO;
}
host->state = state_idle;
if (!host->polled)
complete(&host->complete);
}
/* Below should only happen in manual mode which we don't use ... */
if (isr & KW_I2C_IRQ_START)
kw_write_reg(reg_isr, KW_I2C_IRQ_START);
}
/* Interrupt handler */
static irqreturn_t kw_i2c_irq(int irq, void *dev_id)
{
struct pmac_i2c_host_kw *host = dev_id;
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
del_timer(&host->timeout_timer);
kw_i2c_handle_interrupt(host, kw_read_reg(reg_isr));
if (host->state != state_idle) {
host->timeout_timer.expires = jiffies + KW_POLL_TIMEOUT;
add_timer(&host->timeout_timer);
}
spin_unlock_irqrestore(&host->lock, flags);
return IRQ_HANDLED;
}
static void kw_i2c_timeout(unsigned long data)
{
struct pmac_i2c_host_kw *host = (struct pmac_i2c_host_kw *)data;
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
/*
* If the timer is pending, that means we raced with the
* irq, in which case we just return
*/
if (timer_pending(&host->timeout_timer))
goto skip;
kw_i2c_handle_interrupt(host, kw_read_reg(reg_isr));
if (host->state != state_idle) {
host->timeout_timer.expires = jiffies + KW_POLL_TIMEOUT;
add_timer(&host->timeout_timer);
}
skip:
spin_unlock_irqrestore(&host->lock, flags);
}
static int kw_i2c_open(struct pmac_i2c_bus *bus)
{
struct pmac_i2c_host_kw *host = bus->hostdata;
mutex_lock(&host->mutex);
return 0;
}
static void kw_i2c_close(struct pmac_i2c_bus *bus)
{
struct pmac_i2c_host_kw *host = bus->hostdata;
mutex_unlock(&host->mutex);
}
static int kw_i2c_xfer(struct pmac_i2c_bus *bus, u8 addrdir, int subsize,
u32 subaddr, u8 *data, int len)
{
struct pmac_i2c_host_kw *host = bus->hostdata;
u8 mode_reg = host->speed;
int use_irq = host->irq != NO_IRQ && !bus->polled;
/* Setup mode & subaddress if any */
switch(bus->mode) {
case pmac_i2c_mode_dumb:
return -EINVAL;
case pmac_i2c_mode_std:
mode_reg |= KW_I2C_MODE_STANDARD;
if (subsize != 0)
return -EINVAL;
break;
case pmac_i2c_mode_stdsub:
mode_reg |= KW_I2C_MODE_STANDARDSUB;
if (subsize != 1)
return -EINVAL;
break;
case pmac_i2c_mode_combined:
mode_reg |= KW_I2C_MODE_COMBINED;
if (subsize != 1)
return -EINVAL;
break;
}
/* Setup channel & clear pending irqs */
kw_write_reg(reg_isr, kw_read_reg(reg_isr));
kw_write_reg(reg_mode, mode_reg | (bus->channel << 4));
kw_write_reg(reg_status, 0);
/* Set up address and r/w bit, strip possible stale bus number from
* address top bits
*/
kw_write_reg(reg_addr, addrdir & 0xff);
/* Set up the sub address */
if ((mode_reg & KW_I2C_MODE_MODE_MASK) == KW_I2C_MODE_STANDARDSUB
|| (mode_reg & KW_I2C_MODE_MODE_MASK) == KW_I2C_MODE_COMBINED)
kw_write_reg(reg_subaddr, subaddr);
/* Prepare for async operations */
host->data = data;
host->len = len;
host->state = state_addr;
host->result = 0;
host->rw = (addrdir & 1);
host->polled = bus->polled;
/* Enable interrupt if not using polled mode and interrupt is
* available
*/
if (use_irq) {
/* Clear completion */
INIT_COMPLETION(host->complete);
/* Ack stale interrupts */
kw_write_reg(reg_isr, kw_read_reg(reg_isr));
/* Arm timeout */
host->timeout_timer.expires = jiffies + KW_POLL_TIMEOUT;
add_timer(&host->timeout_timer);
/* Enable emission */
kw_write_reg(reg_ier, KW_I2C_IRQ_MASK);
}
/* Start sending address */
kw_write_reg(reg_control, KW_I2C_CTL_XADDR);
/* Wait for completion */
if (use_irq)
wait_for_completion(&host->complete);
else {
while(host->state != state_idle) {
unsigned long flags;
u8 isr = kw_i2c_wait_interrupt(host);
spin_lock_irqsave(&host->lock, flags);
kw_i2c_handle_interrupt(host, isr);
spin_unlock_irqrestore(&host->lock, flags);
}
}
/* Disable emission */
kw_write_reg(reg_ier, 0);
return host->result;
}
static struct pmac_i2c_host_kw *__init kw_i2c_host_init(struct device_node *np)
{
struct pmac_i2c_host_kw *host;
const u32 *psteps, *prate, *addrp;
u32 steps;
host = kzalloc(sizeof(struct pmac_i2c_host_kw), GFP_KERNEL);
if (host == NULL) {
printk(KERN_ERR "low_i2c: Can't allocate host for %s\n",
np->full_name);
return NULL;
}
/* Apple is kind enough to provide a valid AAPL,address property
* on all i2c keywest nodes so far ... we would have to fallback
* to macio parsing if that wasn't the case
*/
addrp = of_get_property(np, "AAPL,address", NULL);
if (addrp == NULL) {
printk(KERN_ERR "low_i2c: Can't find address for %s\n",
np->full_name);
kfree(host);
return NULL;
}
mutex_init(&host->mutex);
init_completion(&host->complete);
spin_lock_init(&host->lock);
init_timer(&host->timeout_timer);
host->timeout_timer.function = kw_i2c_timeout;
host->timeout_timer.data = (unsigned long)host;
psteps = of_get_property(np, "AAPL,address-step", NULL);
steps = psteps ? (*psteps) : 0x10;
for (host->bsteps = 0; (steps & 0x01) == 0; host->bsteps++)
steps >>= 1;
/* Select interface rate */
host->speed = KW_I2C_MODE_25KHZ;
prate = of_get_property(np, "AAPL,i2c-rate", NULL);
if (prate) switch(*prate) {
case 100:
host->speed = KW_I2C_MODE_100KHZ;
break;
case 50:
host->speed = KW_I2C_MODE_50KHZ;
break;
case 25:
host->speed = KW_I2C_MODE_25KHZ;
break;
}
host->irq = irq_of_parse_and_map(np, 0);
if (host->irq == NO_IRQ)
printk(KERN_WARNING
"low_i2c: Failed to map interrupt for %s\n",
np->full_name);
host->base = ioremap((*addrp), 0x1000);
if (host->base == NULL) {
printk(KERN_ERR "low_i2c: Can't map registers for %s\n",
np->full_name);
kfree(host);
return NULL;
}
/* Make sure IRQ is disabled */
kw_write_reg(reg_ier, 0);
/* Request chip interrupt. We set IRQF_NO_SUSPEND because we don't
* want that interrupt disabled between the 2 passes of driver
* suspend or we'll have issues running the pfuncs
*/
if (request_irq(host->irq, kw_i2c_irq, IRQF_NO_SUSPEND,
"keywest i2c", host))
host->irq = NO_IRQ;
printk(KERN_INFO "KeyWest i2c @0x%08x irq %d %s\n",
*addrp, host->irq, np->full_name);
return host;
}
static void __init kw_i2c_add(struct pmac_i2c_host_kw *host,
struct device_node *controller,
struct device_node *busnode,
int channel)
{
struct pmac_i2c_bus *bus;
bus = kzalloc(sizeof(struct pmac_i2c_bus), GFP_KERNEL);
if (bus == NULL)
return;
bus->controller = of_node_get(controller);
bus->busnode = of_node_get(busnode);
bus->type = pmac_i2c_bus_keywest;
bus->hostdata = host;
bus->channel = channel;
bus->mode = pmac_i2c_mode_std;
bus->open = kw_i2c_open;
bus->close = kw_i2c_close;
bus->xfer = kw_i2c_xfer;
mutex_init(&bus->mutex);
if (controller == busnode)
bus->flags = pmac_i2c_multibus;
list_add(&bus->link, &pmac_i2c_busses);
printk(KERN_INFO " channel %d bus %s\n", channel,
(controller == busnode) ? "<multibus>" : busnode->full_name);
}
static void __init kw_i2c_probe(void)
{
struct device_node *np, *child, *parent;
/* Probe keywest-i2c busses */
for_each_compatible_node(np, "i2c","keywest-i2c") {
struct pmac_i2c_host_kw *host;
int multibus;
/* Found one, init a host structure */
host = kw_i2c_host_init(np);
if (host == NULL)
continue;
/* Now check if we have a multibus setup (old style) or if we
* have proper bus nodes. Note that the "new" way (proper bus
* nodes) might cause us to not create some busses that are
* kept hidden in the device-tree. In the future, we might
* want to work around that by creating busses without a node
* but not for now
*/
child = of_get_next_child(np, NULL);
multibus = !child || strcmp(child->name, "i2c-bus");
of_node_put(child);
/* For a multibus setup, we get the bus count based on the
* parent type
*/
if (multibus) {
int chans, i;
parent = of_get_parent(np);
if (parent == NULL)
continue;
chans = parent->name[0] == 'u' ? 2 : 1;
for (i = 0; i < chans; i++)
kw_i2c_add(host, np, np, i);
} else {
for (child = NULL;
(child = of_get_next_child(np, child)) != NULL;) {
const u32 *reg = of_get_property(child,
"reg", NULL);
if (reg == NULL)
continue;
kw_i2c_add(host, np, child, *reg);
}
}
}
}
/*
*
* PMU implementation
*
*/
#ifdef CONFIG_ADB_PMU
/*
* i2c command block to the PMU
*/
struct pmu_i2c_hdr {
u8 bus;
u8 mode;
u8 bus2;
u8 address;
u8 sub_addr;
u8 comb_addr;
u8 count;
u8 data[];
};
static void pmu_i2c_complete(struct adb_request *req)
{
complete(req->arg);
}
static int pmu_i2c_xfer(struct pmac_i2c_bus *bus, u8 addrdir, int subsize,
u32 subaddr, u8 *data, int len)
{
struct adb_request *req = bus->hostdata;
struct pmu_i2c_hdr *hdr = (struct pmu_i2c_hdr *)&req->data[1];
struct completion comp;
int read = addrdir & 1;
int retry;
int rc = 0;
/* For now, limit ourselves to 16 bytes transfers */
if (len > 16)
return -EINVAL;
init_completion(&comp);
for (retry = 0; retry < 16; retry++) {
memset(req, 0, sizeof(struct adb_request));
hdr->bus = bus->channel;
hdr->count = len;
switch(bus->mode) {
case pmac_i2c_mode_std:
if (subsize != 0)
return -EINVAL;
hdr->address = addrdir;
hdr->mode = PMU_I2C_MODE_SIMPLE;
break;
case pmac_i2c_mode_stdsub:
case pmac_i2c_mode_combined:
if (subsize != 1)
return -EINVAL;
hdr->address = addrdir & 0xfe;
hdr->comb_addr = addrdir;
hdr->sub_addr = subaddr;
if (bus->mode == pmac_i2c_mode_stdsub)
hdr->mode = PMU_I2C_MODE_STDSUB;
else
hdr->mode = PMU_I2C_MODE_COMBINED;
break;
default:
return -EINVAL;
}
INIT_COMPLETION(comp);
req->data[0] = PMU_I2C_CMD;
req->reply[0] = 0xff;
req->nbytes = sizeof(struct pmu_i2c_hdr) + 1;
req->done = pmu_i2c_complete;
req->arg = ∁
if (!read && len) {
memcpy(hdr->data, data, len);
req->nbytes += len;
}
rc = pmu_queue_request(req);
if (rc)
return rc;
wait_for_completion(&comp);
if (req->reply[0] == PMU_I2C_STATUS_OK)
break;
msleep(15);
}
if (req->reply[0] != PMU_I2C_STATUS_OK)
return -EIO;
for (retry = 0; retry < 16; retry++) {
memset(req, 0, sizeof(struct adb_request));
/* I know that looks like a lot, slow as hell, but darwin
* does it so let's be on the safe side for now
*/
msleep(15);
hdr->bus = PMU_I2C_BUS_STATUS;
INIT_COMPLETION(comp);
req->data[0] = PMU_I2C_CMD;
req->reply[0] = 0xff;
req->nbytes = 2;
req->done = pmu_i2c_complete;
req->arg = ∁
rc = pmu_queue_request(req);
if (rc)
return rc;
wait_for_completion(&comp);
if (req->reply[0] == PMU_I2C_STATUS_OK && !read)
return 0;
if (req->reply[0] == PMU_I2C_STATUS_DATAREAD && read) {
int rlen = req->reply_len - 1;
if (rlen != len) {
printk(KERN_WARNING "low_i2c: PMU returned %d"
" bytes, expected %d !\n", rlen, len);
return -EIO;
}
if (len)
memcpy(data, &req->reply[1], len);
return 0;
}
}
return -EIO;
}
static void __init pmu_i2c_probe(void)
{
struct pmac_i2c_bus *bus;
struct device_node *busnode;
int channel, sz;
if (!pmu_present())
return;
/* There might or might not be a "pmu-i2c" node, we use that
* or via-pmu itself, whatever we find. I haven't seen a machine
* with separate bus nodes, so we assume a multibus setup
*/
busnode = of_find_node_by_name(NULL, "pmu-i2c");
if (busnode == NULL)
busnode = of_find_node_by_name(NULL, "via-pmu");
if (busnode == NULL)
return;
printk(KERN_INFO "PMU i2c %s\n", busnode->full_name);
/*
* We add bus 1 and 2 only for now, bus 0 is "special"
*/
for (channel = 1; channel <= 2; channel++) {
sz = sizeof(struct pmac_i2c_bus) + sizeof(struct adb_request);
bus = kzalloc(sz, GFP_KERNEL);
if (bus == NULL)
return;
bus->controller = busnode;
bus->busnode = busnode;
bus->type = pmac_i2c_bus_pmu;
bus->channel = channel;
bus->mode = pmac_i2c_mode_std;
bus->hostdata = bus + 1;
bus->xfer = pmu_i2c_xfer;
mutex_init(&bus->mutex);
bus->flags = pmac_i2c_multibus;
list_add(&bus->link, &pmac_i2c_busses);
printk(KERN_INFO " channel %d bus <multibus>\n", channel);
}
}
#endif /* CONFIG_ADB_PMU */
/*
*
* SMU implementation
*
*/
#ifdef CONFIG_PMAC_SMU
static void smu_i2c_complete(struct smu_i2c_cmd *cmd, void *misc)
{
complete(misc);
}
static int smu_i2c_xfer(struct pmac_i2c_bus *bus, u8 addrdir, int subsize,
u32 subaddr, u8 *data, int len)
{
struct smu_i2c_cmd *cmd = bus->hostdata;
struct completion comp;
int read = addrdir & 1;
int rc = 0;
if ((read && len > SMU_I2C_READ_MAX) ||
((!read) && len > SMU_I2C_WRITE_MAX))
return -EINVAL;
memset(cmd, 0, sizeof(struct smu_i2c_cmd));
cmd->info.bus = bus->channel;
cmd->info.devaddr = addrdir;
cmd->info.datalen = len;
switch(bus->mode) {
case pmac_i2c_mode_std:
if (subsize != 0)
return -EINVAL;
cmd->info.type = SMU_I2C_TRANSFER_SIMPLE;
break;
case pmac_i2c_mode_stdsub:
case pmac_i2c_mode_combined:
if (subsize > 3 || subsize < 1)
return -EINVAL;
cmd->info.sublen = subsize;
/* that's big-endian only but heh ! */
memcpy(&cmd->info.subaddr, ((char *)&subaddr) + (4 - subsize),
subsize);
if (bus->mode == pmac_i2c_mode_stdsub)
cmd->info.type = SMU_I2C_TRANSFER_STDSUB;
else
cmd->info.type = SMU_I2C_TRANSFER_COMBINED;
break;
default:
return -EINVAL;
}
if (!read && len)
memcpy(cmd->info.data, data, len);
init_completion(&comp);
cmd->done = smu_i2c_complete;
cmd->misc = ∁
rc = smu_queue_i2c(cmd);
if (rc < 0)
return rc;
wait_for_completion(&comp);
rc = cmd->status;
if (read && len)
memcpy(data, cmd->info.data, len);
return rc < 0 ? rc : 0;
}
static void __init smu_i2c_probe(void)
{
struct device_node *controller, *busnode;
struct pmac_i2c_bus *bus;
const u32 *reg;
int sz;
if (!smu_present())
return;
controller = of_find_node_by_name(NULL, "smu-i2c-control");
if (controller == NULL)
controller = of_find_node_by_name(NULL, "smu");
if (controller == NULL)
return;
printk(KERN_INFO "SMU i2c %s\n", controller->full_name);
/* Look for childs, note that they might not be of the right
* type as older device trees mix i2c busses and other things
* at the same level
*/
for (busnode = NULL;
(busnode = of_get_next_child(controller, busnode)) != NULL;) {
if (strcmp(busnode->type, "i2c") &&
strcmp(busnode->type, "i2c-bus"))
continue;
reg = of_get_property(busnode, "reg", NULL);
if (reg == NULL)
continue;
sz = sizeof(struct pmac_i2c_bus) + sizeof(struct smu_i2c_cmd);
bus = kzalloc(sz, GFP_KERNEL);
if (bus == NULL)
return;
bus->controller = controller;
bus->busnode = of_node_get(busnode);
bus->type = pmac_i2c_bus_smu;
bus->channel = *reg;
bus->mode = pmac_i2c_mode_std;
bus->hostdata = bus + 1;
bus->xfer = smu_i2c_xfer;
mutex_init(&bus->mutex);
bus->flags = 0;
list_add(&bus->link, &pmac_i2c_busses);
printk(KERN_INFO " channel %x bus %s\n",
bus->channel, busnode->full_name);
}
}
#endif /* CONFIG_PMAC_SMU */
/*
*
* Core code
*
*/
struct pmac_i2c_bus *pmac_i2c_find_bus(struct device_node *node)
{
struct device_node *p = of_node_get(node);
struct device_node *prev = NULL;
struct pmac_i2c_bus *bus;
while(p) {
list_for_each_entry(bus, &pmac_i2c_busses, link) {
if (p == bus->busnode) {
if (prev && bus->flags & pmac_i2c_multibus) {
const u32 *reg;
reg = of_get_property(prev, "reg",
NULL);
if (!reg)
continue;
if (((*reg) >> 8) != bus->channel)
continue;
}
of_node_put(p);
of_node_put(prev);
return bus;
}
}
of_node_put(prev);
prev = p;
p = of_get_parent(p);
}
return NULL;
}
EXPORT_SYMBOL_GPL(pmac_i2c_find_bus);
u8 pmac_i2c_get_dev_addr(struct device_node *device)
{
const u32 *reg = of_get_property(device, "reg", NULL);
if (reg == NULL)
return 0;
return (*reg) & 0xff;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_dev_addr);
struct device_node *pmac_i2c_get_controller(struct pmac_i2c_bus *bus)
{
return bus->controller;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_controller);
struct device_node *pmac_i2c_get_bus_node(struct pmac_i2c_bus *bus)
{
return bus->busnode;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_bus_node);
int pmac_i2c_get_type(struct pmac_i2c_bus *bus)
{
return bus->type;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_type);
int pmac_i2c_get_flags(struct pmac_i2c_bus *bus)
{
return bus->flags;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_flags);
int pmac_i2c_get_channel(struct pmac_i2c_bus *bus)
{
return bus->channel;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_channel);
struct i2c_adapter *pmac_i2c_get_adapter(struct pmac_i2c_bus *bus)
{
return &bus->adapter;
}
EXPORT_SYMBOL_GPL(pmac_i2c_get_adapter);
struct pmac_i2c_bus *pmac_i2c_adapter_to_bus(struct i2c_adapter *adapter)
{
struct pmac_i2c_bus *bus;
list_for_each_entry(bus, &pmac_i2c_busses, link)
if (&bus->adapter == adapter)
return bus;
return NULL;
}
EXPORT_SYMBOL_GPL(pmac_i2c_adapter_to_bus);
int pmac_i2c_match_adapter(struct device_node *dev, struct i2c_adapter *adapter)
{
struct pmac_i2c_bus *bus = pmac_i2c_find_bus(dev);
if (bus == NULL)
return 0;
return (&bus->adapter == adapter);
}
EXPORT_SYMBOL_GPL(pmac_i2c_match_adapter);
int pmac_low_i2c_lock(struct device_node *np)
{
struct pmac_i2c_bus *bus, *found = NULL;
list_for_each_entry(bus, &pmac_i2c_busses, link) {
if (np == bus->controller) {
found = bus;
break;
}
}
if (!found)
return -ENODEV;
return pmac_i2c_open(bus, 0);
}
EXPORT_SYMBOL_GPL(pmac_low_i2c_lock);
int pmac_low_i2c_unlock(struct device_node *np)
{
struct pmac_i2c_bus *bus, *found = NULL;
list_for_each_entry(bus, &pmac_i2c_busses, link) {
if (np == bus->controller) {
found = bus;
break;
}
}
if (!found)
return -ENODEV;
pmac_i2c_close(bus);
return 0;
}
EXPORT_SYMBOL_GPL(pmac_low_i2c_unlock);
int pmac_i2c_open(struct pmac_i2c_bus *bus, int polled)
{
int rc;
mutex_lock(&bus->mutex);
bus->polled = polled || pmac_i2c_force_poll;
bus->opened = 1;
bus->mode = pmac_i2c_mode_std;
if (bus->open && (rc = bus->open(bus)) != 0) {
bus->opened = 0;
mutex_unlock(&bus->mutex);
return rc;
}
return 0;
}
EXPORT_SYMBOL_GPL(pmac_i2c_open);
void pmac_i2c_close(struct pmac_i2c_bus *bus)
{
WARN_ON(!bus->opened);
if (bus->close)
bus->close(bus);
bus->opened = 0;
mutex_unlock(&bus->mutex);
}
EXPORT_SYMBOL_GPL(pmac_i2c_close);
int pmac_i2c_setmode(struct pmac_i2c_bus *bus, int mode)
{
WARN_ON(!bus->opened);
/* Report me if you see the error below as there might be a new
* "combined4" mode that I need to implement for the SMU bus
*/
if (mode < pmac_i2c_mode_dumb || mode > pmac_i2c_mode_combined) {
printk(KERN_ERR "low_i2c: Invalid mode %d requested on"
" bus %s !\n", mode, bus->busnode->full_name);
return -EINVAL;
}
bus->mode = mode;
return 0;
}
EXPORT_SYMBOL_GPL(pmac_i2c_setmode);
int pmac_i2c_xfer(struct pmac_i2c_bus *bus, u8 addrdir, int subsize,
u32 subaddr, u8 *data, int len)
{
int rc;
WARN_ON(!bus->opened);
DBG("xfer() chan=%d, addrdir=0x%x, mode=%d, subsize=%d, subaddr=0x%x,"
" %d bytes, bus %s\n", bus->channel, addrdir, bus->mode, subsize,
subaddr, len, bus->busnode->full_name);
rc = bus->xfer(bus, addrdir, subsize, subaddr, data, len);
#ifdef DEBUG
if (rc)
DBG("xfer error %d\n", rc);
#endif
return rc;
}
EXPORT_SYMBOL_GPL(pmac_i2c_xfer);
/* some quirks for platform function decoding */
enum {
pmac_i2c_quirk_invmask = 0x00000001u,
pmac_i2c_quirk_skip = 0x00000002u,
};
static void pmac_i2c_devscan(void (*callback)(struct device_node *dev,
int quirks))
{
struct pmac_i2c_bus *bus;
struct device_node *np;
static struct whitelist_ent {
char *name;
char *compatible;
int quirks;
} whitelist[] = {
/* XXX Study device-tree's & apple drivers are get the quirks
* right !
*/
/* Workaround: It seems that running the clockspreading
* properties on the eMac will cause lockups during boot.
* The machine seems to work fine without that. So for now,
* let's make sure i2c-hwclock doesn't match about "imic"
* clocks and we'll figure out if we really need to do
* something special about those later.
*/
{ "i2c-hwclock", "imic5002", pmac_i2c_quirk_skip },
{ "i2c-hwclock", "imic5003", pmac_i2c_quirk_skip },
{ "i2c-hwclock", NULL, pmac_i2c_quirk_invmask },
{ "i2c-cpu-voltage", NULL, 0},
{ "temp-monitor", NULL, 0 },
{ "supply-monitor", NULL, 0 },
{ NULL, NULL, 0 },
};
/* Only some devices need to have platform functions instanciated
* here. For now, we have a table. Others, like 9554 i2c GPIOs used
* on Xserve, if we ever do a driver for them, will use their own
* platform function instance
*/
list_for_each_entry(bus, &pmac_i2c_busses, link) {
for (np = NULL;
(np = of_get_next_child(bus->busnode, np)) != NULL;) {
struct whitelist_ent *p;
/* If multibus, check if device is on that bus */
if (bus->flags & pmac_i2c_multibus)
if (bus != pmac_i2c_find_bus(np))
continue;
for (p = whitelist; p->name != NULL; p++) {
if (strcmp(np->name, p->name))
continue;
if (p->compatible &&
!of_device_is_compatible(np, p->compatible))
continue;
if (p->quirks & pmac_i2c_quirk_skip)
break;
callback(np, p->quirks);
break;
}
}
}
}
#define MAX_I2C_DATA 64
struct pmac_i2c_pf_inst
{
struct pmac_i2c_bus *bus;
u8 addr;
u8 buffer[MAX_I2C_DATA];
u8 scratch[MAX_I2C_DATA];
int bytes;
int quirks;
};
static void* pmac_i2c_do_begin(struct pmf_function *func, struct pmf_args *args)
{
struct pmac_i2c_pf_inst *inst;
struct pmac_i2c_bus *bus;
bus = pmac_i2c_find_bus(func->node);
if (bus == NULL) {
printk(KERN_ERR "low_i2c: Can't find bus for %s (pfunc)\n",
func->node->full_name);
return NULL;
}
if (pmac_i2c_open(bus, 0)) {
printk(KERN_ERR "low_i2c: Can't open i2c bus for %s (pfunc)\n",
func->node->full_name);
return NULL;
}
/* XXX might need GFP_ATOMIC when called during the suspend process,
* but then, there are already lots of issues with suspending when
* near OOM that need to be resolved, the allocator itself should
* probably make GFP_NOIO implicit during suspend
*/
inst = kzalloc(sizeof(struct pmac_i2c_pf_inst), GFP_KERNEL);
if (inst == NULL) {
pmac_i2c_close(bus);
return NULL;
}
inst->bus = bus;
inst->addr = pmac_i2c_get_dev_addr(func->node);
inst->quirks = (int)(long)func->driver_data;
return inst;
}
static void pmac_i2c_do_end(struct pmf_function *func, void *instdata)
{
struct pmac_i2c_pf_inst *inst = instdata;
if (inst == NULL)
return;
pmac_i2c_close(inst->bus);
kfree(inst);
}
static int pmac_i2c_do_read(PMF_STD_ARGS, u32 len)
{
struct pmac_i2c_pf_inst *inst = instdata;
inst->bytes = len;
return pmac_i2c_xfer(inst->bus, inst->addr | pmac_i2c_read, 0, 0,
inst->buffer, len);
}
static int pmac_i2c_do_write(PMF_STD_ARGS, u32 len, const u8 *data)
{
struct pmac_i2c_pf_inst *inst = instdata;
return pmac_i2c_xfer(inst->bus, inst->addr | pmac_i2c_write, 0, 0,
(u8 *)data, len);
}
/* This function is used to do the masking & OR'ing for the "rmw" type
* callbacks. Ze should apply the mask and OR in the values in the
* buffer before writing back. The problem is that it seems that
* various darwin drivers implement the mask/or differently, thus
* we need to check the quirks first
*/
static void pmac_i2c_do_apply_rmw(struct pmac_i2c_pf_inst *inst,
u32 len, const u8 *mask, const u8 *val)
{
int i;
if (inst->quirks & pmac_i2c_quirk_invmask) {
for (i = 0; i < len; i ++)
inst->scratch[i] = (inst->buffer[i] & mask[i]) | val[i];
} else {
for (i = 0; i < len; i ++)
inst->scratch[i] = (inst->buffer[i] & ~mask[i])
| (val[i] & mask[i]);
}
}
static int pmac_i2c_do_rmw(PMF_STD_ARGS, u32 masklen, u32 valuelen,
u32 totallen, const u8 *maskdata,
const u8 *valuedata)
{
struct pmac_i2c_pf_inst *inst = instdata;
if (masklen > inst->bytes || valuelen > inst->bytes ||
totallen > inst->bytes || valuelen > masklen)
return -EINVAL;
pmac_i2c_do_apply_rmw(inst, masklen, maskdata, valuedata);
return pmac_i2c_xfer(inst->bus, inst->addr | pmac_i2c_write, 0, 0,
inst->scratch, totallen);
}
static int pmac_i2c_do_read_sub(PMF_STD_ARGS, u8 subaddr, u32 len)
{
struct pmac_i2c_pf_inst *inst = instdata;
inst->bytes = len;
return pmac_i2c_xfer(inst->bus, inst->addr | pmac_i2c_read, 1, subaddr,
inst->buffer, len);
}
static int pmac_i2c_do_write_sub(PMF_STD_ARGS, u8 subaddr, u32 len,
const u8 *data)
{
struct pmac_i2c_pf_inst *inst = instdata;
return pmac_i2c_xfer(inst->bus, inst->addr | pmac_i2c_write, 1,
subaddr, (u8 *)data, len);
}
static int pmac_i2c_do_set_mode(PMF_STD_ARGS, int mode)
{
struct pmac_i2c_pf_inst *inst = instdata;
return pmac_i2c_setmode(inst->bus, mode);
}
static int pmac_i2c_do_rmw_sub(PMF_STD_ARGS, u8 subaddr, u32 masklen,
u32 valuelen, u32 totallen, const u8 *maskdata,
const u8 *valuedata)
{
struct pmac_i2c_pf_inst *inst = instdata;
if (masklen > inst->bytes || valuelen > inst->bytes ||
totallen > inst->bytes || valuelen > masklen)
return -EINVAL;
pmac_i2c_do_apply_rmw(inst, masklen, maskdata, valuedata);
return pmac_i2c_xfer(inst->bus, inst->addr | pmac_i2c_write, 1,
subaddr, inst->scratch, totallen);
}
static int pmac_i2c_do_mask_and_comp(PMF_STD_ARGS, u32 len,
const u8 *maskdata,
const u8 *valuedata)
{
struct pmac_i2c_pf_inst *inst = instdata;
int i, match;
/* Get return value pointer, it's assumed to be a u32 */
if (!args || !args->count || !args->u[0].p)
return -EINVAL;
/* Check buffer */
if (len > inst->bytes)
return -EINVAL;
for (i = 0, match = 1; match && i < len; i ++)
if ((inst->buffer[i] & maskdata[i]) != valuedata[i])
match = 0;
*args->u[0].p = match;
return 0;
}
static int pmac_i2c_do_delay(PMF_STD_ARGS, u32 duration)
{
msleep((duration + 999) / 1000);
return 0;
}
static struct pmf_handlers pmac_i2c_pfunc_handlers = {
.begin = pmac_i2c_do_begin,
.end = pmac_i2c_do_end,
.read_i2c = pmac_i2c_do_read,
.write_i2c = pmac_i2c_do_write,
.rmw_i2c = pmac_i2c_do_rmw,
.read_i2c_sub = pmac_i2c_do_read_sub,
.write_i2c_sub = pmac_i2c_do_write_sub,
.rmw_i2c_sub = pmac_i2c_do_rmw_sub,
.set_i2c_mode = pmac_i2c_do_set_mode,
.mask_and_compare = pmac_i2c_do_mask_and_comp,
.delay = pmac_i2c_do_delay,
};
static void __init pmac_i2c_dev_create(struct device_node *np, int quirks)
{
DBG("dev_create(%s)\n", np->full_name);
pmf_register_driver(np, &pmac_i2c_pfunc_handlers,
(void *)(long)quirks);
}
static void __init pmac_i2c_dev_init(struct device_node *np, int quirks)
{
DBG("dev_create(%s)\n", np->full_name);
pmf_do_functions(np, NULL, 0, PMF_FLAGS_ON_INIT, NULL);
}
static void pmac_i2c_dev_suspend(struct device_node *np, int quirks)
{
DBG("dev_suspend(%s)\n", np->full_name);
pmf_do_functions(np, NULL, 0, PMF_FLAGS_ON_SLEEP, NULL);
}
static void pmac_i2c_dev_resume(struct device_node *np, int quirks)
{
DBG("dev_resume(%s)\n", np->full_name);
pmf_do_functions(np, NULL, 0, PMF_FLAGS_ON_WAKE, NULL);
}
void pmac_pfunc_i2c_suspend(void)
{
pmac_i2c_devscan(pmac_i2c_dev_suspend);
}
void pmac_pfunc_i2c_resume(void)
{
pmac_i2c_devscan(pmac_i2c_dev_resume);
}
/*
* Initialize us: probe all i2c busses on the machine, instantiate
* busses and platform functions as needed.
*/
/* This is non-static as it might be called early by smp code */
int __init pmac_i2c_init(void)
{
static int i2c_inited;
if (i2c_inited)
return 0;
i2c_inited = 1;
/* Probe keywest-i2c busses */
kw_i2c_probe();
#ifdef CONFIG_ADB_PMU
/* Probe PMU i2c busses */
pmu_i2c_probe();
#endif
#ifdef CONFIG_PMAC_SMU
/* Probe SMU i2c busses */
smu_i2c_probe();
#endif
/* Now add plaform functions for some known devices */
pmac_i2c_devscan(pmac_i2c_dev_create);
return 0;
}
machine_arch_initcall(powermac, pmac_i2c_init);
/* Since pmac_i2c_init can be called too early for the platform device
* registration, we need to do it at a later time. In our case, subsys
* happens to fit well, though I agree it's a bit of a hack...
*/
static int __init pmac_i2c_create_platform_devices(void)
{
struct pmac_i2c_bus *bus;
int i = 0;
/* In the case where we are initialized from smp_init(), we must
* not use the timer (and thus the irq). It's safe from now on
* though
*/
pmac_i2c_force_poll = 0;
/* Create platform devices */
list_for_each_entry(bus, &pmac_i2c_busses, link) {
bus->platform_dev =
platform_device_alloc("i2c-powermac", i++);
if (bus->platform_dev == NULL)
return -ENOMEM;
bus->platform_dev->dev.platform_data = bus;
platform_device_add(bus->platform_dev);
}
/* Now call platform "init" functions */
pmac_i2c_devscan(pmac_i2c_dev_init);
return 0;
}
machine_subsys_initcall(powermac, pmac_i2c_create_platform_devices);
| gpl-2.0 |
JoshWu/linux-at91 | fs/hfs/extent.c | 4382 | 14179 | /*
* linux/fs/hfs/extent.c
*
* Copyright (C) 1995-1997 Paul H. Hargrove
* (C) 2003 Ardis Technologies <roman@ardistech.com>
* This file may be distributed under the terms of the GNU General Public License.
*
* This file contains the functions related to the extents B-tree.
*/
#include <linux/pagemap.h>
#include "hfs_fs.h"
#include "btree.h"
/*================ File-local functions ================*/
/*
* build_key
*/
static void hfs_ext_build_key(hfs_btree_key *key, u32 cnid, u16 block, u8 type)
{
key->key_len = 7;
key->ext.FkType = type;
key->ext.FNum = cpu_to_be32(cnid);
key->ext.FABN = cpu_to_be16(block);
}
/*
* hfs_ext_compare()
*
* Description:
* This is the comparison function used for the extents B-tree. In
* comparing extent B-tree entries, the file id is the most
* significant field (compared as unsigned ints); the fork type is
* the second most significant field (compared as unsigned chars);
* and the allocation block number field is the least significant
* (compared as unsigned ints).
* Input Variable(s):
* struct hfs_ext_key *key1: pointer to the first key to compare
* struct hfs_ext_key *key2: pointer to the second key to compare
* Output Variable(s):
* NONE
* Returns:
* int: negative if key1<key2, positive if key1>key2, and 0 if key1==key2
* Preconditions:
* key1 and key2 point to "valid" (struct hfs_ext_key)s.
* Postconditions:
* This function has no side-effects */
int hfs_ext_keycmp(const btree_key *key1, const btree_key *key2)
{
__be32 fnum1, fnum2;
__be16 block1, block2;
fnum1 = key1->ext.FNum;
fnum2 = key2->ext.FNum;
if (fnum1 != fnum2)
return be32_to_cpu(fnum1) < be32_to_cpu(fnum2) ? -1 : 1;
if (key1->ext.FkType != key2->ext.FkType)
return key1->ext.FkType < key2->ext.FkType ? -1 : 1;
block1 = key1->ext.FABN;
block2 = key2->ext.FABN;
if (block1 == block2)
return 0;
return be16_to_cpu(block1) < be16_to_cpu(block2) ? -1 : 1;
}
/*
* hfs_ext_find_block
*
* Find a block within an extent record
*/
static u16 hfs_ext_find_block(struct hfs_extent *ext, u16 off)
{
int i;
u16 count;
for (i = 0; i < 3; ext++, i++) {
count = be16_to_cpu(ext->count);
if (off < count)
return be16_to_cpu(ext->block) + off;
off -= count;
}
/* panic? */
return 0;
}
static int hfs_ext_block_count(struct hfs_extent *ext)
{
int i;
u16 count = 0;
for (i = 0; i < 3; ext++, i++)
count += be16_to_cpu(ext->count);
return count;
}
static u16 hfs_ext_lastblock(struct hfs_extent *ext)
{
int i;
ext += 2;
for (i = 0; i < 2; ext--, i++)
if (ext->count)
break;
return be16_to_cpu(ext->block) + be16_to_cpu(ext->count);
}
static int __hfs_ext_write_extent(struct inode *inode, struct hfs_find_data *fd)
{
int res;
hfs_ext_build_key(fd->search_key, inode->i_ino, HFS_I(inode)->cached_start,
HFS_IS_RSRC(inode) ? HFS_FK_RSRC : HFS_FK_DATA);
res = hfs_brec_find(fd);
if (HFS_I(inode)->flags & HFS_FLG_EXT_NEW) {
if (res != -ENOENT)
return res;
hfs_brec_insert(fd, HFS_I(inode)->cached_extents, sizeof(hfs_extent_rec));
HFS_I(inode)->flags &= ~(HFS_FLG_EXT_DIRTY|HFS_FLG_EXT_NEW);
} else {
if (res)
return res;
hfs_bnode_write(fd->bnode, HFS_I(inode)->cached_extents, fd->entryoffset, fd->entrylength);
HFS_I(inode)->flags &= ~HFS_FLG_EXT_DIRTY;
}
return 0;
}
int hfs_ext_write_extent(struct inode *inode)
{
struct hfs_find_data fd;
int res = 0;
if (HFS_I(inode)->flags & HFS_FLG_EXT_DIRTY) {
res = hfs_find_init(HFS_SB(inode->i_sb)->ext_tree, &fd);
if (res)
return res;
res = __hfs_ext_write_extent(inode, &fd);
hfs_find_exit(&fd);
}
return res;
}
static inline int __hfs_ext_read_extent(struct hfs_find_data *fd, struct hfs_extent *extent,
u32 cnid, u32 block, u8 type)
{
int res;
hfs_ext_build_key(fd->search_key, cnid, block, type);
fd->key->ext.FNum = 0;
res = hfs_brec_find(fd);
if (res && res != -ENOENT)
return res;
if (fd->key->ext.FNum != fd->search_key->ext.FNum ||
fd->key->ext.FkType != fd->search_key->ext.FkType)
return -ENOENT;
if (fd->entrylength != sizeof(hfs_extent_rec))
return -EIO;
hfs_bnode_read(fd->bnode, extent, fd->entryoffset, sizeof(hfs_extent_rec));
return 0;
}
static inline int __hfs_ext_cache_extent(struct hfs_find_data *fd, struct inode *inode, u32 block)
{
int res;
if (HFS_I(inode)->flags & HFS_FLG_EXT_DIRTY) {
res = __hfs_ext_write_extent(inode, fd);
if (res)
return res;
}
res = __hfs_ext_read_extent(fd, HFS_I(inode)->cached_extents, inode->i_ino,
block, HFS_IS_RSRC(inode) ? HFS_FK_RSRC : HFS_FK_DATA);
if (!res) {
HFS_I(inode)->cached_start = be16_to_cpu(fd->key->ext.FABN);
HFS_I(inode)->cached_blocks = hfs_ext_block_count(HFS_I(inode)->cached_extents);
} else {
HFS_I(inode)->cached_start = HFS_I(inode)->cached_blocks = 0;
HFS_I(inode)->flags &= ~(HFS_FLG_EXT_DIRTY|HFS_FLG_EXT_NEW);
}
return res;
}
static int hfs_ext_read_extent(struct inode *inode, u16 block)
{
struct hfs_find_data fd;
int res;
if (block >= HFS_I(inode)->cached_start &&
block < HFS_I(inode)->cached_start + HFS_I(inode)->cached_blocks)
return 0;
res = hfs_find_init(HFS_SB(inode->i_sb)->ext_tree, &fd);
if (!res) {
res = __hfs_ext_cache_extent(&fd, inode, block);
hfs_find_exit(&fd);
}
return res;
}
static void hfs_dump_extent(struct hfs_extent *extent)
{
int i;
hfs_dbg(EXTENT, " ");
for (i = 0; i < 3; i++)
hfs_dbg_cont(EXTENT, " %u:%u",
be16_to_cpu(extent[i].block),
be16_to_cpu(extent[i].count));
hfs_dbg_cont(EXTENT, "\n");
}
static int hfs_add_extent(struct hfs_extent *extent, u16 offset,
u16 alloc_block, u16 block_count)
{
u16 count, start;
int i;
hfs_dump_extent(extent);
for (i = 0; i < 3; extent++, i++) {
count = be16_to_cpu(extent->count);
if (offset == count) {
start = be16_to_cpu(extent->block);
if (alloc_block != start + count) {
if (++i >= 3)
return -ENOSPC;
extent++;
extent->block = cpu_to_be16(alloc_block);
} else
block_count += count;
extent->count = cpu_to_be16(block_count);
return 0;
} else if (offset < count)
break;
offset -= count;
}
/* panic? */
return -EIO;
}
static int hfs_free_extents(struct super_block *sb, struct hfs_extent *extent,
u16 offset, u16 block_nr)
{
u16 count, start;
int i;
hfs_dump_extent(extent);
for (i = 0; i < 3; extent++, i++) {
count = be16_to_cpu(extent->count);
if (offset == count)
goto found;
else if (offset < count)
break;
offset -= count;
}
/* panic? */
return -EIO;
found:
for (;;) {
start = be16_to_cpu(extent->block);
if (count <= block_nr) {
hfs_clear_vbm_bits(sb, start, count);
extent->block = 0;
extent->count = 0;
block_nr -= count;
} else {
count -= block_nr;
hfs_clear_vbm_bits(sb, start + count, block_nr);
extent->count = cpu_to_be16(count);
block_nr = 0;
}
if (!block_nr || !i)
return 0;
i--;
extent--;
count = be16_to_cpu(extent->count);
}
}
int hfs_free_fork(struct super_block *sb, struct hfs_cat_file *file, int type)
{
struct hfs_find_data fd;
u32 total_blocks, blocks, start;
u32 cnid = be32_to_cpu(file->FlNum);
struct hfs_extent *extent;
int res, i;
if (type == HFS_FK_DATA) {
total_blocks = be32_to_cpu(file->PyLen);
extent = file->ExtRec;
} else {
total_blocks = be32_to_cpu(file->RPyLen);
extent = file->RExtRec;
}
total_blocks /= HFS_SB(sb)->alloc_blksz;
if (!total_blocks)
return 0;
blocks = 0;
for (i = 0; i < 3; extent++, i++)
blocks += be16_to_cpu(extent[i].count);
res = hfs_free_extents(sb, extent, blocks, blocks);
if (res)
return res;
if (total_blocks == blocks)
return 0;
res = hfs_find_init(HFS_SB(sb)->ext_tree, &fd);
if (res)
return res;
do {
res = __hfs_ext_read_extent(&fd, extent, cnid, total_blocks, type);
if (res)
break;
start = be16_to_cpu(fd.key->ext.FABN);
hfs_free_extents(sb, extent, total_blocks - start, total_blocks);
hfs_brec_remove(&fd);
total_blocks = start;
} while (total_blocks > blocks);
hfs_find_exit(&fd);
return res;
}
/*
* hfs_get_block
*/
int hfs_get_block(struct inode *inode, sector_t block,
struct buffer_head *bh_result, int create)
{
struct super_block *sb;
u16 dblock, ablock;
int res;
sb = inode->i_sb;
/* Convert inode block to disk allocation block */
ablock = (u32)block / HFS_SB(sb)->fs_div;
if (block >= HFS_I(inode)->fs_blocks) {
if (block > HFS_I(inode)->fs_blocks || !create)
return -EIO;
if (ablock >= HFS_I(inode)->alloc_blocks) {
res = hfs_extend_file(inode);
if (res)
return res;
}
} else
create = 0;
if (ablock < HFS_I(inode)->first_blocks) {
dblock = hfs_ext_find_block(HFS_I(inode)->first_extents, ablock);
goto done;
}
mutex_lock(&HFS_I(inode)->extents_lock);
res = hfs_ext_read_extent(inode, ablock);
if (!res)
dblock = hfs_ext_find_block(HFS_I(inode)->cached_extents,
ablock - HFS_I(inode)->cached_start);
else {
mutex_unlock(&HFS_I(inode)->extents_lock);
return -EIO;
}
mutex_unlock(&HFS_I(inode)->extents_lock);
done:
map_bh(bh_result, sb, HFS_SB(sb)->fs_start +
dblock * HFS_SB(sb)->fs_div +
(u32)block % HFS_SB(sb)->fs_div);
if (create) {
set_buffer_new(bh_result);
HFS_I(inode)->phys_size += sb->s_blocksize;
HFS_I(inode)->fs_blocks++;
inode_add_bytes(inode, sb->s_blocksize);
mark_inode_dirty(inode);
}
return 0;
}
int hfs_extend_file(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
u32 start, len, goal;
int res;
mutex_lock(&HFS_I(inode)->extents_lock);
if (HFS_I(inode)->alloc_blocks == HFS_I(inode)->first_blocks)
goal = hfs_ext_lastblock(HFS_I(inode)->first_extents);
else {
res = hfs_ext_read_extent(inode, HFS_I(inode)->alloc_blocks);
if (res)
goto out;
goal = hfs_ext_lastblock(HFS_I(inode)->cached_extents);
}
len = HFS_I(inode)->clump_blocks;
start = hfs_vbm_search_free(sb, goal, &len);
if (!len) {
res = -ENOSPC;
goto out;
}
hfs_dbg(EXTENT, "extend %lu: %u,%u\n", inode->i_ino, start, len);
if (HFS_I(inode)->alloc_blocks == HFS_I(inode)->first_blocks) {
if (!HFS_I(inode)->first_blocks) {
hfs_dbg(EXTENT, "first extents\n");
/* no extents yet */
HFS_I(inode)->first_extents[0].block = cpu_to_be16(start);
HFS_I(inode)->first_extents[0].count = cpu_to_be16(len);
res = 0;
} else {
/* try to append to extents in inode */
res = hfs_add_extent(HFS_I(inode)->first_extents,
HFS_I(inode)->alloc_blocks,
start, len);
if (res == -ENOSPC)
goto insert_extent;
}
if (!res) {
hfs_dump_extent(HFS_I(inode)->first_extents);
HFS_I(inode)->first_blocks += len;
}
} else {
res = hfs_add_extent(HFS_I(inode)->cached_extents,
HFS_I(inode)->alloc_blocks -
HFS_I(inode)->cached_start,
start, len);
if (!res) {
hfs_dump_extent(HFS_I(inode)->cached_extents);
HFS_I(inode)->flags |= HFS_FLG_EXT_DIRTY;
HFS_I(inode)->cached_blocks += len;
} else if (res == -ENOSPC)
goto insert_extent;
}
out:
mutex_unlock(&HFS_I(inode)->extents_lock);
if (!res) {
HFS_I(inode)->alloc_blocks += len;
mark_inode_dirty(inode);
if (inode->i_ino < HFS_FIRSTUSER_CNID)
set_bit(HFS_FLG_ALT_MDB_DIRTY, &HFS_SB(sb)->flags);
set_bit(HFS_FLG_MDB_DIRTY, &HFS_SB(sb)->flags);
hfs_mark_mdb_dirty(sb);
}
return res;
insert_extent:
hfs_dbg(EXTENT, "insert new extent\n");
res = hfs_ext_write_extent(inode);
if (res)
goto out;
memset(HFS_I(inode)->cached_extents, 0, sizeof(hfs_extent_rec));
HFS_I(inode)->cached_extents[0].block = cpu_to_be16(start);
HFS_I(inode)->cached_extents[0].count = cpu_to_be16(len);
hfs_dump_extent(HFS_I(inode)->cached_extents);
HFS_I(inode)->flags |= HFS_FLG_EXT_DIRTY|HFS_FLG_EXT_NEW;
HFS_I(inode)->cached_start = HFS_I(inode)->alloc_blocks;
HFS_I(inode)->cached_blocks = len;
res = 0;
goto out;
}
void hfs_file_truncate(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
u16 blk_cnt, alloc_cnt, start;
u32 size;
int res;
hfs_dbg(INODE, "truncate: %lu, %Lu -> %Lu\n",
inode->i_ino, (long long)HFS_I(inode)->phys_size,
inode->i_size);
if (inode->i_size > HFS_I(inode)->phys_size) {
struct address_space *mapping = inode->i_mapping;
void *fsdata;
struct page *page;
/* XXX: Can use generic_cont_expand? */
size = inode->i_size - 1;
res = pagecache_write_begin(NULL, mapping, size+1, 0,
AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
if (!res) {
res = pagecache_write_end(NULL, mapping, size+1, 0, 0,
page, fsdata);
}
if (res)
inode->i_size = HFS_I(inode)->phys_size;
return;
} else if (inode->i_size == HFS_I(inode)->phys_size)
return;
size = inode->i_size + HFS_SB(sb)->alloc_blksz - 1;
blk_cnt = size / HFS_SB(sb)->alloc_blksz;
alloc_cnt = HFS_I(inode)->alloc_blocks;
if (blk_cnt == alloc_cnt)
goto out;
mutex_lock(&HFS_I(inode)->extents_lock);
res = hfs_find_init(HFS_SB(sb)->ext_tree, &fd);
if (res) {
mutex_unlock(&HFS_I(inode)->extents_lock);
/* XXX: We lack error handling of hfs_file_truncate() */
return;
}
while (1) {
if (alloc_cnt == HFS_I(inode)->first_blocks) {
hfs_free_extents(sb, HFS_I(inode)->first_extents,
alloc_cnt, alloc_cnt - blk_cnt);
hfs_dump_extent(HFS_I(inode)->first_extents);
HFS_I(inode)->first_blocks = blk_cnt;
break;
}
res = __hfs_ext_cache_extent(&fd, inode, alloc_cnt);
if (res)
break;
start = HFS_I(inode)->cached_start;
hfs_free_extents(sb, HFS_I(inode)->cached_extents,
alloc_cnt - start, alloc_cnt - blk_cnt);
hfs_dump_extent(HFS_I(inode)->cached_extents);
if (blk_cnt > start) {
HFS_I(inode)->flags |= HFS_FLG_EXT_DIRTY;
break;
}
alloc_cnt = start;
HFS_I(inode)->cached_start = HFS_I(inode)->cached_blocks = 0;
HFS_I(inode)->flags &= ~(HFS_FLG_EXT_DIRTY|HFS_FLG_EXT_NEW);
hfs_brec_remove(&fd);
}
hfs_find_exit(&fd);
mutex_unlock(&HFS_I(inode)->extents_lock);
HFS_I(inode)->alloc_blocks = blk_cnt;
out:
HFS_I(inode)->phys_size = inode->i_size;
HFS_I(inode)->fs_blocks = (inode->i_size + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
inode_set_bytes(inode, HFS_I(inode)->fs_blocks << sb->s_blocksize_bits);
mark_inode_dirty(inode);
}
| gpl-2.0 |
yagay/android_kernel_nubia_nx507j | net/netfilter/nf_conntrack_extend.c | 4638 | 4923 | /* Structure dynamic extension infrastructure
* Copyright (C) 2004 Rusty Russell IBM Corporation
* Copyright (C) 2007 Netfilter Core Team <coreteam@netfilter.org>
* Copyright (C) 2007 USAGI/WIDE Project <http://www.linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/rcupdate.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <net/netfilter/nf_conntrack_extend.h>
static struct nf_ct_ext_type __rcu *nf_ct_ext_types[NF_CT_EXT_NUM];
static DEFINE_MUTEX(nf_ct_ext_type_mutex);
void __nf_ct_ext_destroy(struct nf_conn *ct)
{
unsigned int i;
struct nf_ct_ext_type *t;
struct nf_ct_ext *ext = ct->ext;
for (i = 0; i < NF_CT_EXT_NUM; i++) {
if (!__nf_ct_ext_exist(ext, i))
continue;
rcu_read_lock();
t = rcu_dereference(nf_ct_ext_types[i]);
/* Here the nf_ct_ext_type might have been unregisterd.
* I.e., it has responsible to cleanup private
* area in all conntracks when it is unregisterd.
*/
if (t && t->destroy)
t->destroy(ct);
rcu_read_unlock();
}
}
EXPORT_SYMBOL(__nf_ct_ext_destroy);
static void *
nf_ct_ext_create(struct nf_ct_ext **ext, enum nf_ct_ext_id id, gfp_t gfp)
{
unsigned int off, len;
struct nf_ct_ext_type *t;
size_t alloc_size;
rcu_read_lock();
t = rcu_dereference(nf_ct_ext_types[id]);
BUG_ON(t == NULL);
off = ALIGN(sizeof(struct nf_ct_ext), t->align);
len = off + t->len;
alloc_size = t->alloc_size;
rcu_read_unlock();
*ext = kzalloc(alloc_size, gfp);
if (!*ext)
return NULL;
(*ext)->offset[id] = off;
(*ext)->len = len;
return (void *)(*ext) + off;
}
void *__nf_ct_ext_add(struct nf_conn *ct, enum nf_ct_ext_id id, gfp_t gfp)
{
struct nf_ct_ext *old, *new;
int i, newlen, newoff;
struct nf_ct_ext_type *t;
/* Conntrack must not be confirmed to avoid races on reallocation. */
NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
old = ct->ext;
if (!old)
return nf_ct_ext_create(&ct->ext, id, gfp);
if (__nf_ct_ext_exist(old, id))
return NULL;
rcu_read_lock();
t = rcu_dereference(nf_ct_ext_types[id]);
BUG_ON(t == NULL);
newoff = ALIGN(old->len, t->align);
newlen = newoff + t->len;
rcu_read_unlock();
new = __krealloc(old, newlen, gfp);
if (!new)
return NULL;
if (new != old) {
for (i = 0; i < NF_CT_EXT_NUM; i++) {
if (!__nf_ct_ext_exist(old, i))
continue;
rcu_read_lock();
t = rcu_dereference(nf_ct_ext_types[i]);
if (t && t->move)
t->move((void *)new + new->offset[i],
(void *)old + old->offset[i]);
rcu_read_unlock();
}
kfree_rcu(old, rcu);
ct->ext = new;
}
new->offset[id] = newoff;
new->len = newlen;
memset((void *)new + newoff, 0, newlen - newoff);
return (void *)new + newoff;
}
EXPORT_SYMBOL(__nf_ct_ext_add);
static void update_alloc_size(struct nf_ct_ext_type *type)
{
int i, j;
struct nf_ct_ext_type *t1, *t2;
enum nf_ct_ext_id min = 0, max = NF_CT_EXT_NUM - 1;
/* unnecessary to update all types */
if ((type->flags & NF_CT_EXT_F_PREALLOC) == 0) {
min = type->id;
max = type->id;
}
/* This assumes that extended areas in conntrack for the types
whose NF_CT_EXT_F_PREALLOC bit set are allocated in order */
for (i = min; i <= max; i++) {
t1 = rcu_dereference_protected(nf_ct_ext_types[i],
lockdep_is_held(&nf_ct_ext_type_mutex));
if (!t1)
continue;
t1->alloc_size = ALIGN(sizeof(struct nf_ct_ext), t1->align) +
t1->len;
for (j = 0; j < NF_CT_EXT_NUM; j++) {
t2 = rcu_dereference_protected(nf_ct_ext_types[j],
lockdep_is_held(&nf_ct_ext_type_mutex));
if (t2 == NULL || t2 == t1 ||
(t2->flags & NF_CT_EXT_F_PREALLOC) == 0)
continue;
t1->alloc_size = ALIGN(t1->alloc_size, t2->align)
+ t2->len;
}
}
}
/* This MUST be called in process context. */
int nf_ct_extend_register(struct nf_ct_ext_type *type)
{
int ret = 0;
mutex_lock(&nf_ct_ext_type_mutex);
if (nf_ct_ext_types[type->id]) {
ret = -EBUSY;
goto out;
}
/* This ensures that nf_ct_ext_create() can allocate enough area
before updating alloc_size */
type->alloc_size = ALIGN(sizeof(struct nf_ct_ext), type->align)
+ type->len;
rcu_assign_pointer(nf_ct_ext_types[type->id], type);
update_alloc_size(type);
out:
mutex_unlock(&nf_ct_ext_type_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(nf_ct_extend_register);
/* This MUST be called in process context. */
void nf_ct_extend_unregister(struct nf_ct_ext_type *type)
{
mutex_lock(&nf_ct_ext_type_mutex);
RCU_INIT_POINTER(nf_ct_ext_types[type->id], NULL);
update_alloc_size(type);
mutex_unlock(&nf_ct_ext_type_mutex);
rcu_barrier(); /* Wait for completion of call_rcu()'s */
}
EXPORT_SYMBOL_GPL(nf_ct_extend_unregister);
| gpl-2.0 |
MattCrystal/tripping-hipster | sound/pci/cmipci.c | 4894 | 104405 | /*
* Driver for C-Media CMI8338 and 8738 PCI soundcards.
* Copyright (c) 2000 by Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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
*/
/* Does not work. Warning may block system in capture mode */
/* #define USE_VAR48KRATE */
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/sb.h>
#include <sound/asoundef.h>
#include <sound/initval.h>
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("C-Media CMI8x38 PCI");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{C-Media,CMI8738},"
"{C-Media,CMI8738B},"
"{C-Media,CMI8338A},"
"{C-Media,CMI8338B}}");
#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
#define SUPPORT_JOYSTICK 1
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable switches */
static long mpu_port[SNDRV_CARDS];
static long fm_port[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)]=1};
static bool soft_ac3[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)]=1};
#ifdef SUPPORT_JOYSTICK
static int joystick_port[SNDRV_CARDS];
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for C-Media PCI soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for C-Media PCI soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable C-Media PCI soundcard.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port.");
module_param_array(soft_ac3, bool, NULL, 0444);
MODULE_PARM_DESC(soft_ac3, "Software-conversion of raw SPDIF packets (model 033 only).");
#ifdef SUPPORT_JOYSTICK
module_param_array(joystick_port, int, NULL, 0444);
MODULE_PARM_DESC(joystick_port, "Joystick port address.");
#endif
/*
* CM8x38 registers definition
*/
#define CM_REG_FUNCTRL0 0x00
#define CM_RST_CH1 0x00080000
#define CM_RST_CH0 0x00040000
#define CM_CHEN1 0x00020000 /* ch1: enable */
#define CM_CHEN0 0x00010000 /* ch0: enable */
#define CM_PAUSE1 0x00000008 /* ch1: pause */
#define CM_PAUSE0 0x00000004 /* ch0: pause */
#define CM_CHADC1 0x00000002 /* ch1, 0:playback, 1:record */
#define CM_CHADC0 0x00000001 /* ch0, 0:playback, 1:record */
#define CM_REG_FUNCTRL1 0x04
#define CM_DSFC_MASK 0x0000E000 /* channel 1 (DAC?) sampling frequency */
#define CM_DSFC_SHIFT 13
#define CM_ASFC_MASK 0x00001C00 /* channel 0 (ADC?) sampling frequency */
#define CM_ASFC_SHIFT 10
#define CM_SPDF_1 0x00000200 /* SPDIF IN/OUT at channel B */
#define CM_SPDF_0 0x00000100 /* SPDIF OUT only channel A */
#define CM_SPDFLOOP 0x00000080 /* ext. SPDIIF/IN -> OUT loopback */
#define CM_SPDO2DAC 0x00000040 /* SPDIF/OUT can be heard from internal DAC */
#define CM_INTRM 0x00000020 /* master control block (MCB) interrupt enabled */
#define CM_BREQ 0x00000010 /* bus master enabled */
#define CM_VOICE_EN 0x00000008 /* legacy voice (SB16,FM) */
#define CM_UART_EN 0x00000004 /* legacy UART */
#define CM_JYSTK_EN 0x00000002 /* legacy joystick */
#define CM_ZVPORT 0x00000001 /* ZVPORT */
#define CM_REG_CHFORMAT 0x08
#define CM_CHB3D5C 0x80000000 /* 5,6 channels */
#define CM_FMOFFSET2 0x40000000 /* initial FM PCM offset 2 when Fmute=1 */
#define CM_CHB3D 0x20000000 /* 4 channels */
#define CM_CHIP_MASK1 0x1f000000
#define CM_CHIP_037 0x01000000
#define CM_SETLAT48 0x00800000 /* set latency timer 48h */
#define CM_EDGEIRQ 0x00400000 /* emulated edge trigger legacy IRQ */
#define CM_SPD24SEL39 0x00200000 /* 24-bit spdif: model 039 */
#define CM_AC3EN1 0x00100000 /* enable AC3: model 037 */
#define CM_SPDIF_SELECT1 0x00080000 /* for model <= 037 ? */
#define CM_SPD24SEL 0x00020000 /* 24bit spdif: model 037 */
/* #define CM_SPDIF_INVERSE 0x00010000 */ /* ??? */
#define CM_ADCBITLEN_MASK 0x0000C000
#define CM_ADCBITLEN_16 0x00000000
#define CM_ADCBITLEN_15 0x00004000
#define CM_ADCBITLEN_14 0x00008000
#define CM_ADCBITLEN_13 0x0000C000
#define CM_ADCDACLEN_MASK 0x00003000 /* model 037 */
#define CM_ADCDACLEN_060 0x00000000
#define CM_ADCDACLEN_066 0x00001000
#define CM_ADCDACLEN_130 0x00002000
#define CM_ADCDACLEN_280 0x00003000
#define CM_ADCDLEN_MASK 0x00003000 /* model 039 */
#define CM_ADCDLEN_ORIGINAL 0x00000000
#define CM_ADCDLEN_EXTRA 0x00001000
#define CM_ADCDLEN_24K 0x00002000
#define CM_ADCDLEN_WEIGHT 0x00003000
#define CM_CH1_SRATE_176K 0x00000800
#define CM_CH1_SRATE_96K 0x00000800 /* model 055? */
#define CM_CH1_SRATE_88K 0x00000400
#define CM_CH0_SRATE_176K 0x00000200
#define CM_CH0_SRATE_96K 0x00000200 /* model 055? */
#define CM_CH0_SRATE_88K 0x00000100
#define CM_CH0_SRATE_128K 0x00000300
#define CM_CH0_SRATE_MASK 0x00000300
#define CM_SPDIF_INVERSE2 0x00000080 /* model 055? */
#define CM_DBLSPDS 0x00000040 /* double SPDIF sample rate 88.2/96 */
#define CM_POLVALID 0x00000020 /* inverse SPDIF/IN valid bit */
#define CM_SPDLOCKED 0x00000010
#define CM_CH1FMT_MASK 0x0000000C /* bit 3: 16 bits, bit 2: stereo */
#define CM_CH1FMT_SHIFT 2
#define CM_CH0FMT_MASK 0x00000003 /* bit 1: 16 bits, bit 0: stereo */
#define CM_CH0FMT_SHIFT 0
#define CM_REG_INT_HLDCLR 0x0C
#define CM_CHIP_MASK2 0xff000000
#define CM_CHIP_8768 0x20000000
#define CM_CHIP_055 0x08000000
#define CM_CHIP_039 0x04000000
#define CM_CHIP_039_6CH 0x01000000
#define CM_UNKNOWN_INT_EN 0x00080000 /* ? */
#define CM_TDMA_INT_EN 0x00040000
#define CM_CH1_INT_EN 0x00020000
#define CM_CH0_INT_EN 0x00010000
#define CM_REG_INT_STATUS 0x10
#define CM_INTR 0x80000000
#define CM_VCO 0x08000000 /* Voice Control? CMI8738 */
#define CM_MCBINT 0x04000000 /* Master Control Block abort cond.? */
#define CM_UARTINT 0x00010000
#define CM_LTDMAINT 0x00008000
#define CM_HTDMAINT 0x00004000
#define CM_XDO46 0x00000080 /* Modell 033? Direct programming EEPROM (read data register) */
#define CM_LHBTOG 0x00000040 /* High/Low status from DMA ctrl register */
#define CM_LEG_HDMA 0x00000020 /* Legacy is in High DMA channel */
#define CM_LEG_STEREO 0x00000010 /* Legacy is in Stereo mode */
#define CM_CH1BUSY 0x00000008
#define CM_CH0BUSY 0x00000004
#define CM_CHINT1 0x00000002
#define CM_CHINT0 0x00000001
#define CM_REG_LEGACY_CTRL 0x14
#define CM_NXCHG 0x80000000 /* don't map base reg dword->sample */
#define CM_VMPU_MASK 0x60000000 /* MPU401 i/o port address */
#define CM_VMPU_330 0x00000000
#define CM_VMPU_320 0x20000000
#define CM_VMPU_310 0x40000000
#define CM_VMPU_300 0x60000000
#define CM_ENWR8237 0x10000000 /* enable bus master to write 8237 base reg */
#define CM_VSBSEL_MASK 0x0C000000 /* SB16 base address */
#define CM_VSBSEL_220 0x00000000
#define CM_VSBSEL_240 0x04000000
#define CM_VSBSEL_260 0x08000000
#define CM_VSBSEL_280 0x0C000000
#define CM_FMSEL_MASK 0x03000000 /* FM OPL3 base address */
#define CM_FMSEL_388 0x00000000
#define CM_FMSEL_3C8 0x01000000
#define CM_FMSEL_3E0 0x02000000
#define CM_FMSEL_3E8 0x03000000
#define CM_ENSPDOUT 0x00800000 /* enable XSPDIF/OUT to I/O interface */
#define CM_SPDCOPYRHT 0x00400000 /* spdif in/out copyright bit */
#define CM_DAC2SPDO 0x00200000 /* enable wave+fm_midi -> SPDIF/OUT */
#define CM_INVIDWEN 0x00100000 /* internal vendor ID write enable, model 039? */
#define CM_SETRETRY 0x00100000 /* 0: legacy i/o wait (default), 1: legacy i/o bus retry */
#define CM_C_EEACCESS 0x00080000 /* direct programming eeprom regs */
#define CM_C_EECS 0x00040000
#define CM_C_EEDI46 0x00020000
#define CM_C_EECK46 0x00010000
#define CM_CHB3D6C 0x00008000 /* 5.1 channels support */
#define CM_CENTR2LIN 0x00004000 /* line-in as center out */
#define CM_BASE2LIN 0x00002000 /* line-in as bass out */
#define CM_EXBASEN 0x00001000 /* external bass input enable */
#define CM_REG_MISC_CTRL 0x18
#define CM_PWD 0x80000000 /* power down */
#define CM_RESET 0x40000000
#define CM_SFIL_MASK 0x30000000 /* filter control at front end DAC, model 037? */
#define CM_VMGAIN 0x10000000 /* analog master amp +6dB, model 039? */
#define CM_TXVX 0x08000000 /* model 037? */
#define CM_N4SPK3D 0x04000000 /* copy front to rear */
#define CM_SPDO5V 0x02000000 /* 5V spdif output (1 = 0.5v (coax)) */
#define CM_SPDIF48K 0x01000000 /* write */
#define CM_SPATUS48K 0x01000000 /* read */
#define CM_ENDBDAC 0x00800000 /* enable double dac */
#define CM_XCHGDAC 0x00400000 /* 0: front=ch0, 1: front=ch1 */
#define CM_SPD32SEL 0x00200000 /* 0: 16bit SPDIF, 1: 32bit */
#define CM_SPDFLOOPI 0x00100000 /* int. SPDIF-OUT -> int. IN */
#define CM_FM_EN 0x00080000 /* enable legacy FM */
#define CM_AC3EN2 0x00040000 /* enable AC3: model 039 */
#define CM_ENWRASID 0x00010000 /* choose writable internal SUBID (audio) */
#define CM_VIDWPDSB 0x00010000 /* model 037? */
#define CM_SPDF_AC97 0x00008000 /* 0: SPDIF/OUT 44.1K, 1: 48K */
#define CM_MASK_EN 0x00004000 /* activate channel mask on legacy DMA */
#define CM_ENWRMSID 0x00002000 /* choose writable internal SUBID (modem) */
#define CM_VIDWPPRT 0x00002000 /* model 037? */
#define CM_SFILENB 0x00001000 /* filter stepping at front end DAC, model 037? */
#define CM_MMODE_MASK 0x00000E00 /* model DAA interface mode */
#define CM_SPDIF_SELECT2 0x00000100 /* for model > 039 ? */
#define CM_ENCENTER 0x00000080
#define CM_FLINKON 0x00000040 /* force modem link detection on, model 037 */
#define CM_MUTECH1 0x00000040 /* mute PCI ch1 to DAC */
#define CM_FLINKOFF 0x00000020 /* force modem link detection off, model 037 */
#define CM_MIDSMP 0x00000010 /* 1/2 interpolation at front end DAC */
#define CM_UPDDMA_MASK 0x0000000C /* TDMA position update notification */
#define CM_UPDDMA_2048 0x00000000
#define CM_UPDDMA_1024 0x00000004
#define CM_UPDDMA_512 0x00000008
#define CM_UPDDMA_256 0x0000000C
#define CM_TWAIT_MASK 0x00000003 /* model 037 */
#define CM_TWAIT1 0x00000002 /* FM i/o cycle, 0: 48, 1: 64 PCICLKs */
#define CM_TWAIT0 0x00000001 /* i/o cycle, 0: 4, 1: 6 PCICLKs */
#define CM_REG_TDMA_POSITION 0x1C
#define CM_TDMA_CNT_MASK 0xFFFF0000 /* current byte/word count */
#define CM_TDMA_ADR_MASK 0x0000FFFF /* current address */
/* byte */
#define CM_REG_MIXER0 0x20
#define CM_REG_SBVR 0x20 /* write: sb16 version */
#define CM_REG_DEV 0x20 /* read: hardware device version */
#define CM_REG_MIXER21 0x21
#define CM_UNKNOWN_21_MASK 0x78 /* ? */
#define CM_X_ADPCM 0x04 /* SB16 ADPCM enable */
#define CM_PROINV 0x02 /* SBPro left/right channel switching */
#define CM_X_SB16 0x01 /* SB16 compatible */
#define CM_REG_SB16_DATA 0x22
#define CM_REG_SB16_ADDR 0x23
#define CM_REFFREQ_XIN (315*1000*1000)/22 /* 14.31818 Mhz reference clock frequency pin XIN */
#define CM_ADCMULT_XIN 512 /* Guessed (487 best for 44.1kHz, not for 88/176kHz) */
#define CM_TOLERANCE_RATE 0.001 /* Tolerance sample rate pitch (1000ppm) */
#define CM_MAXIMUM_RATE 80000000 /* Note more than 80MHz */
#define CM_REG_MIXER1 0x24
#define CM_FMMUTE 0x80 /* mute FM */
#define CM_FMMUTE_SHIFT 7
#define CM_WSMUTE 0x40 /* mute PCM */
#define CM_WSMUTE_SHIFT 6
#define CM_REAR2LIN 0x20 /* lin-in -> rear line out */
#define CM_REAR2LIN_SHIFT 5
#define CM_REAR2FRONT 0x10 /* exchange rear/front */
#define CM_REAR2FRONT_SHIFT 4
#define CM_WAVEINL 0x08 /* digital wave rec. left chan */
#define CM_WAVEINL_SHIFT 3
#define CM_WAVEINR 0x04 /* digical wave rec. right */
#define CM_WAVEINR_SHIFT 2
#define CM_X3DEN 0x02 /* 3D surround enable */
#define CM_X3DEN_SHIFT 1
#define CM_CDPLAY 0x01 /* enable SPDIF/IN PCM -> DAC */
#define CM_CDPLAY_SHIFT 0
#define CM_REG_MIXER2 0x25
#define CM_RAUXREN 0x80 /* AUX right capture */
#define CM_RAUXREN_SHIFT 7
#define CM_RAUXLEN 0x40 /* AUX left capture */
#define CM_RAUXLEN_SHIFT 6
#define CM_VAUXRM 0x20 /* AUX right mute */
#define CM_VAUXRM_SHIFT 5
#define CM_VAUXLM 0x10 /* AUX left mute */
#define CM_VAUXLM_SHIFT 4
#define CM_VADMIC_MASK 0x0e /* mic gain level (0-3) << 1 */
#define CM_VADMIC_SHIFT 1
#define CM_MICGAINZ 0x01 /* mic boost */
#define CM_MICGAINZ_SHIFT 0
#define CM_REG_MIXER3 0x24
#define CM_REG_AUX_VOL 0x26
#define CM_VAUXL_MASK 0xf0
#define CM_VAUXR_MASK 0x0f
#define CM_REG_MISC 0x27
#define CM_UNKNOWN_27_MASK 0xd8 /* ? */
#define CM_XGPO1 0x20
// #define CM_XGPBIO 0x04
#define CM_MIC_CENTER_LFE 0x04 /* mic as center/lfe out? (model 039 or later?) */
#define CM_SPDIF_INVERSE 0x04 /* spdif input phase inverse (model 037) */
#define CM_SPDVALID 0x02 /* spdif input valid check */
#define CM_DMAUTO 0x01 /* SB16 DMA auto detect */
#define CM_REG_AC97 0x28 /* hmmm.. do we have ac97 link? */
/*
* For CMI-8338 (0x28 - 0x2b) .. is this valid for CMI-8738
* or identical with AC97 codec?
*/
#define CM_REG_EXTERN_CODEC CM_REG_AC97
/*
* MPU401 pci port index address 0x40 - 0x4f (CMI-8738 spec ver. 0.6)
*/
#define CM_REG_MPU_PCI 0x40
/*
* FM pci port index address 0x50 - 0x5f (CMI-8738 spec ver. 0.6)
*/
#define CM_REG_FM_PCI 0x50
/*
* access from SB-mixer port
*/
#define CM_REG_EXTENT_IND 0xf0
#define CM_VPHONE_MASK 0xe0 /* Phone volume control (0-3) << 5 */
#define CM_VPHONE_SHIFT 5
#define CM_VPHOM 0x10 /* Phone mute control */
#define CM_VSPKM 0x08 /* Speaker mute control, default high */
#define CM_RLOOPREN 0x04 /* Rec. R-channel enable */
#define CM_RLOOPLEN 0x02 /* Rec. L-channel enable */
#define CM_VADMIC3 0x01 /* Mic record boost */
/*
* CMI-8338 spec ver 0.5 (this is not valid for CMI-8738):
* the 8 registers 0xf8 - 0xff are used for programming m/n counter by the PLL
* unit (readonly?).
*/
#define CM_REG_PLL 0xf8
/*
* extended registers
*/
#define CM_REG_CH0_FRAME1 0x80 /* write: base address */
#define CM_REG_CH0_FRAME2 0x84 /* read: current address */
#define CM_REG_CH1_FRAME1 0x88 /* 0-15: count of samples at bus master; buffer size */
#define CM_REG_CH1_FRAME2 0x8C /* 16-31: count of samples at codec; fragment size */
#define CM_REG_EXT_MISC 0x90
#define CM_ADC48K44K 0x10000000 /* ADC parameters group, 0: 44k, 1: 48k */
#define CM_CHB3D8C 0x00200000 /* 7.1 channels support */
#define CM_SPD32FMT 0x00100000 /* SPDIF/IN 32k sample rate */
#define CM_ADC2SPDIF 0x00080000 /* ADC output to SPDIF/OUT */
#define CM_SHAREADC 0x00040000 /* DAC in ADC as Center/LFE */
#define CM_REALTCMP 0x00020000 /* monitor the CMPL/CMPR of ADC */
#define CM_INVLRCK 0x00010000 /* invert ZVPORT's LRCK */
#define CM_UNKNOWN_90_MASK 0x0000FFFF /* ? */
/*
* size of i/o region
*/
#define CM_EXTENT_CODEC 0x100
#define CM_EXTENT_MIDI 0x2
#define CM_EXTENT_SYNTH 0x4
/*
* channels for playback / capture
*/
#define CM_CH_PLAY 0
#define CM_CH_CAPT 1
/*
* flags to check device open/close
*/
#define CM_OPEN_NONE 0
#define CM_OPEN_CH_MASK 0x01
#define CM_OPEN_DAC 0x10
#define CM_OPEN_ADC 0x20
#define CM_OPEN_SPDIF 0x40
#define CM_OPEN_MCHAN 0x80
#define CM_OPEN_PLAYBACK (CM_CH_PLAY | CM_OPEN_DAC)
#define CM_OPEN_PLAYBACK2 (CM_CH_CAPT | CM_OPEN_DAC)
#define CM_OPEN_PLAYBACK_MULTI (CM_CH_PLAY | CM_OPEN_DAC | CM_OPEN_MCHAN)
#define CM_OPEN_CAPTURE (CM_CH_CAPT | CM_OPEN_ADC)
#define CM_OPEN_SPDIF_PLAYBACK (CM_CH_PLAY | CM_OPEN_DAC | CM_OPEN_SPDIF)
#define CM_OPEN_SPDIF_CAPTURE (CM_CH_CAPT | CM_OPEN_ADC | CM_OPEN_SPDIF)
#if CM_CH_PLAY == 1
#define CM_PLAYBACK_SRATE_176K CM_CH1_SRATE_176K
#define CM_PLAYBACK_SPDF CM_SPDF_1
#define CM_CAPTURE_SPDF CM_SPDF_0
#else
#define CM_PLAYBACK_SRATE_176K CM_CH0_SRATE_176K
#define CM_PLAYBACK_SPDF CM_SPDF_0
#define CM_CAPTURE_SPDF CM_SPDF_1
#endif
/*
* driver data
*/
struct cmipci_pcm {
struct snd_pcm_substream *substream;
u8 running; /* dac/adc running? */
u8 fmt; /* format bits */
u8 is_dac;
u8 needs_silencing;
unsigned int dma_size; /* in frames */
unsigned int shift;
unsigned int ch; /* channel (0/1) */
unsigned int offset; /* physical address of the buffer */
};
/* mixer elements toggled/resumed during ac3 playback */
struct cmipci_mixer_auto_switches {
const char *name; /* switch to toggle */
int toggle_on; /* value to change when ac3 mode */
};
static const struct cmipci_mixer_auto_switches cm_saved_mixer[] = {
{"PCM Playback Switch", 0},
{"IEC958 Output Switch", 1},
{"IEC958 Mix Analog", 0},
// {"IEC958 Out To DAC", 1}, // no longer used
{"IEC958 Loop", 0},
};
#define CM_SAVED_MIXERS ARRAY_SIZE(cm_saved_mixer)
struct cmipci {
struct snd_card *card;
struct pci_dev *pci;
unsigned int device; /* device ID */
int irq;
unsigned long iobase;
unsigned int ctrl; /* FUNCTRL0 current value */
struct snd_pcm *pcm; /* DAC/ADC PCM */
struct snd_pcm *pcm2; /* 2nd DAC */
struct snd_pcm *pcm_spdif; /* SPDIF */
int chip_version;
int max_channels;
unsigned int can_ac3_sw: 1;
unsigned int can_ac3_hw: 1;
unsigned int can_multi_ch: 1;
unsigned int can_96k: 1; /* samplerate above 48k */
unsigned int do_soft_ac3: 1;
unsigned int spdif_playback_avail: 1; /* spdif ready? */
unsigned int spdif_playback_enabled: 1; /* spdif switch enabled? */
int spdif_counter; /* for software AC3 */
unsigned int dig_status;
unsigned int dig_pcm_status;
struct snd_pcm_hardware *hw_info[3]; /* for playbacks */
int opened[2]; /* open mode */
struct mutex open_mutex;
unsigned int mixer_insensitive: 1;
struct snd_kcontrol *mixer_res_ctl[CM_SAVED_MIXERS];
int mixer_res_status[CM_SAVED_MIXERS];
struct cmipci_pcm channel[2]; /* ch0 - DAC, ch1 - ADC or 2nd DAC */
/* external MIDI */
struct snd_rawmidi *rmidi;
#ifdef SUPPORT_JOYSTICK
struct gameport *gameport;
#endif
spinlock_t reg_lock;
#ifdef CONFIG_PM
unsigned int saved_regs[0x20];
unsigned char saved_mixers[0x20];
#endif
};
/* read/write operations for dword register */
static inline void snd_cmipci_write(struct cmipci *cm, unsigned int cmd, unsigned int data)
{
outl(data, cm->iobase + cmd);
}
static inline unsigned int snd_cmipci_read(struct cmipci *cm, unsigned int cmd)
{
return inl(cm->iobase + cmd);
}
/* read/write operations for word register */
static inline void snd_cmipci_write_w(struct cmipci *cm, unsigned int cmd, unsigned short data)
{
outw(data, cm->iobase + cmd);
}
static inline unsigned short snd_cmipci_read_w(struct cmipci *cm, unsigned int cmd)
{
return inw(cm->iobase + cmd);
}
/* read/write operations for byte register */
static inline void snd_cmipci_write_b(struct cmipci *cm, unsigned int cmd, unsigned char data)
{
outb(data, cm->iobase + cmd);
}
static inline unsigned char snd_cmipci_read_b(struct cmipci *cm, unsigned int cmd)
{
return inb(cm->iobase + cmd);
}
/* bit operations for dword register */
static int snd_cmipci_set_bit(struct cmipci *cm, unsigned int cmd, unsigned int flag)
{
unsigned int val, oval;
val = oval = inl(cm->iobase + cmd);
val |= flag;
if (val == oval)
return 0;
outl(val, cm->iobase + cmd);
return 1;
}
static int snd_cmipci_clear_bit(struct cmipci *cm, unsigned int cmd, unsigned int flag)
{
unsigned int val, oval;
val = oval = inl(cm->iobase + cmd);
val &= ~flag;
if (val == oval)
return 0;
outl(val, cm->iobase + cmd);
return 1;
}
/* bit operations for byte register */
static int snd_cmipci_set_bit_b(struct cmipci *cm, unsigned int cmd, unsigned char flag)
{
unsigned char val, oval;
val = oval = inb(cm->iobase + cmd);
val |= flag;
if (val == oval)
return 0;
outb(val, cm->iobase + cmd);
return 1;
}
static int snd_cmipci_clear_bit_b(struct cmipci *cm, unsigned int cmd, unsigned char flag)
{
unsigned char val, oval;
val = oval = inb(cm->iobase + cmd);
val &= ~flag;
if (val == oval)
return 0;
outb(val, cm->iobase + cmd);
return 1;
}
/*
* PCM interface
*/
/*
* calculate frequency
*/
static unsigned int rates[] = { 5512, 11025, 22050, 44100, 8000, 16000, 32000, 48000 };
static unsigned int snd_cmipci_rate_freq(unsigned int rate)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(rates); i++) {
if (rates[i] == rate)
return i;
}
snd_BUG();
return 0;
}
#ifdef USE_VAR48KRATE
/*
* Determine PLL values for frequency setup, maybe the CMI8338 (CMI8738???)
* does it this way .. maybe not. Never get any information from C-Media about
* that <werner@suse.de>.
*/
static int snd_cmipci_pll_rmn(unsigned int rate, unsigned int adcmult, int *r, int *m, int *n)
{
unsigned int delta, tolerance;
int xm, xn, xr;
for (*r = 0; rate < CM_MAXIMUM_RATE/adcmult; *r += (1<<5))
rate <<= 1;
*n = -1;
if (*r > 0xff)
goto out;
tolerance = rate*CM_TOLERANCE_RATE;
for (xn = (1+2); xn < (0x1f+2); xn++) {
for (xm = (1+2); xm < (0xff+2); xm++) {
xr = ((CM_REFFREQ_XIN/adcmult) * xm) / xn;
if (xr < rate)
delta = rate - xr;
else
delta = xr - rate;
/*
* If we found one, remember this,
* and try to find a closer one
*/
if (delta < tolerance) {
tolerance = delta;
*m = xm - 2;
*n = xn - 2;
}
}
}
out:
return (*n > -1);
}
/*
* Program pll register bits, I assume that the 8 registers 0xf8 up to 0xff
* are mapped onto the 8 ADC/DAC sampling frequency which can be chosen
* at the register CM_REG_FUNCTRL1 (0x04).
* Problem: other ways are also possible (any information about that?)
*/
static void snd_cmipci_set_pll(struct cmipci *cm, unsigned int rate, unsigned int slot)
{
unsigned int reg = CM_REG_PLL + slot;
/*
* Guess that this programs at reg. 0x04 the pos 15:13/12:10
* for DSFC/ASFC (000 up to 111).
*/
/* FIXME: Init (Do we've to set an other register first before programming?) */
/* FIXME: Is this correct? Or shouldn't the m/n/r values be used for that? */
snd_cmipci_write_b(cm, reg, rate>>8);
snd_cmipci_write_b(cm, reg, rate&0xff);
/* FIXME: Setup (Do we've to set an other register first to enable this?) */
}
#endif /* USE_VAR48KRATE */
static int snd_cmipci_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_cmipci_playback2_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
if (params_channels(hw_params) > 2) {
mutex_lock(&cm->open_mutex);
if (cm->opened[CM_CH_PLAY]) {
mutex_unlock(&cm->open_mutex);
return -EBUSY;
}
/* reserve the channel A */
cm->opened[CM_CH_PLAY] = CM_OPEN_PLAYBACK_MULTI;
mutex_unlock(&cm->open_mutex);
}
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static void snd_cmipci_ch_reset(struct cmipci *cm, int ch)
{
int reset = CM_RST_CH0 << (cm->channel[ch].ch);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | reset);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~reset);
udelay(10);
}
static int snd_cmipci_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
/*
*/
static unsigned int hw_channels[] = {1, 2, 4, 6, 8};
static struct snd_pcm_hw_constraint_list hw_constraints_channels_4 = {
.count = 3,
.list = hw_channels,
.mask = 0,
};
static struct snd_pcm_hw_constraint_list hw_constraints_channels_6 = {
.count = 4,
.list = hw_channels,
.mask = 0,
};
static struct snd_pcm_hw_constraint_list hw_constraints_channels_8 = {
.count = 5,
.list = hw_channels,
.mask = 0,
};
static int set_dac_channels(struct cmipci *cm, struct cmipci_pcm *rec, int channels)
{
if (channels > 2) {
if (!cm->can_multi_ch || !rec->ch)
return -EINVAL;
if (rec->fmt != 0x03) /* stereo 16bit only */
return -EINVAL;
}
if (cm->can_multi_ch) {
spin_lock_irq(&cm->reg_lock);
if (channels > 2) {
snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_NXCHG);
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
} else {
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_NXCHG);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
}
if (channels == 8)
snd_cmipci_set_bit(cm, CM_REG_EXT_MISC, CM_CHB3D8C);
else
snd_cmipci_clear_bit(cm, CM_REG_EXT_MISC, CM_CHB3D8C);
if (channels == 6) {
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
} else {
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
}
if (channels == 4)
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
else
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
spin_unlock_irq(&cm->reg_lock);
}
return 0;
}
/*
* prepare playback/capture channel
* channel to be used must have been set in rec->ch.
*/
static int snd_cmipci_pcm_prepare(struct cmipci *cm, struct cmipci_pcm *rec,
struct snd_pcm_substream *substream)
{
unsigned int reg, freq, freq_ext, val;
unsigned int period_size;
struct snd_pcm_runtime *runtime = substream->runtime;
rec->fmt = 0;
rec->shift = 0;
if (snd_pcm_format_width(runtime->format) >= 16) {
rec->fmt |= 0x02;
if (snd_pcm_format_width(runtime->format) > 16)
rec->shift++; /* 24/32bit */
}
if (runtime->channels > 1)
rec->fmt |= 0x01;
if (rec->is_dac && set_dac_channels(cm, rec, runtime->channels) < 0) {
snd_printd("cannot set dac channels\n");
return -EINVAL;
}
rec->offset = runtime->dma_addr;
/* buffer and period sizes in frame */
rec->dma_size = runtime->buffer_size << rec->shift;
period_size = runtime->period_size << rec->shift;
if (runtime->channels > 2) {
/* multi-channels */
rec->dma_size = (rec->dma_size * runtime->channels) / 2;
period_size = (period_size * runtime->channels) / 2;
}
spin_lock_irq(&cm->reg_lock);
/* set buffer address */
reg = rec->ch ? CM_REG_CH1_FRAME1 : CM_REG_CH0_FRAME1;
snd_cmipci_write(cm, reg, rec->offset);
/* program sample counts */
reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
snd_cmipci_write_w(cm, reg, rec->dma_size - 1);
snd_cmipci_write_w(cm, reg + 2, period_size - 1);
/* set adc/dac flag */
val = rec->ch ? CM_CHADC1 : CM_CHADC0;
if (rec->is_dac)
cm->ctrl &= ~val;
else
cm->ctrl |= val;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
//snd_printd("cmipci: functrl0 = %08x\n", cm->ctrl);
/* set sample rate */
freq = 0;
freq_ext = 0;
if (runtime->rate > 48000)
switch (runtime->rate) {
case 88200: freq_ext = CM_CH0_SRATE_88K; break;
case 96000: freq_ext = CM_CH0_SRATE_96K; break;
case 128000: freq_ext = CM_CH0_SRATE_128K; break;
default: snd_BUG(); break;
}
else
freq = snd_cmipci_rate_freq(runtime->rate);
val = snd_cmipci_read(cm, CM_REG_FUNCTRL1);
if (rec->ch) {
val &= ~CM_DSFC_MASK;
val |= (freq << CM_DSFC_SHIFT) & CM_DSFC_MASK;
} else {
val &= ~CM_ASFC_MASK;
val |= (freq << CM_ASFC_SHIFT) & CM_ASFC_MASK;
}
snd_cmipci_write(cm, CM_REG_FUNCTRL1, val);
//snd_printd("cmipci: functrl1 = %08x\n", val);
/* set format */
val = snd_cmipci_read(cm, CM_REG_CHFORMAT);
if (rec->ch) {
val &= ~CM_CH1FMT_MASK;
val |= rec->fmt << CM_CH1FMT_SHIFT;
} else {
val &= ~CM_CH0FMT_MASK;
val |= rec->fmt << CM_CH0FMT_SHIFT;
}
if (cm->can_96k) {
val &= ~(CM_CH0_SRATE_MASK << (rec->ch * 2));
val |= freq_ext << (rec->ch * 2);
}
snd_cmipci_write(cm, CM_REG_CHFORMAT, val);
//snd_printd("cmipci: chformat = %08x\n", val);
if (!rec->is_dac && cm->chip_version) {
if (runtime->rate > 44100)
snd_cmipci_set_bit(cm, CM_REG_EXT_MISC, CM_ADC48K44K);
else
snd_cmipci_clear_bit(cm, CM_REG_EXT_MISC, CM_ADC48K44K);
}
rec->running = 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
/*
* PCM trigger/stop
*/
static int snd_cmipci_pcm_trigger(struct cmipci *cm, struct cmipci_pcm *rec,
int cmd)
{
unsigned int inthld, chen, reset, pause;
int result = 0;
inthld = CM_CH0_INT_EN << rec->ch;
chen = CM_CHEN0 << rec->ch;
reset = CM_RST_CH0 << rec->ch;
pause = CM_PAUSE0 << rec->ch;
spin_lock(&cm->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
rec->running = 1;
/* set interrupt */
snd_cmipci_set_bit(cm, CM_REG_INT_HLDCLR, inthld);
cm->ctrl |= chen;
/* enable channel */
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
//snd_printd("cmipci: functrl0 = %08x\n", cm->ctrl);
break;
case SNDRV_PCM_TRIGGER_STOP:
rec->running = 0;
/* disable interrupt */
snd_cmipci_clear_bit(cm, CM_REG_INT_HLDCLR, inthld);
/* reset */
cm->ctrl &= ~chen;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | reset);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~reset);
rec->needs_silencing = rec->is_dac;
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
cm->ctrl |= pause;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
cm->ctrl &= ~pause;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&cm->reg_lock);
return result;
}
/*
* return the current pointer
*/
static snd_pcm_uframes_t snd_cmipci_pcm_pointer(struct cmipci *cm, struct cmipci_pcm *rec,
struct snd_pcm_substream *substream)
{
size_t ptr;
unsigned int reg, rem, tries;
if (!rec->running)
return 0;
#if 1 // this seems better..
reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
for (tries = 0; tries < 3; tries++) {
rem = snd_cmipci_read_w(cm, reg);
if (rem < rec->dma_size)
goto ok;
}
printk(KERN_ERR "cmipci: invalid PCM pointer: %#x\n", rem);
return SNDRV_PCM_POS_XRUN;
ok:
ptr = (rec->dma_size - (rem + 1)) >> rec->shift;
#else
reg = rec->ch ? CM_REG_CH1_FRAME1 : CM_REG_CH0_FRAME1;
ptr = snd_cmipci_read(cm, reg) - rec->offset;
ptr = bytes_to_frames(substream->runtime, ptr);
#endif
if (substream->runtime->channels > 2)
ptr = (ptr * 2) / substream->runtime->channels;
return ptr;
}
/*
* playback
*/
static int snd_cmipci_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_trigger(cm, &cm->channel[CM_CH_PLAY], cmd);
}
static snd_pcm_uframes_t snd_cmipci_playback_pointer(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_pointer(cm, &cm->channel[CM_CH_PLAY], substream);
}
/*
* capture
*/
static int snd_cmipci_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_trigger(cm, &cm->channel[CM_CH_CAPT], cmd);
}
static snd_pcm_uframes_t snd_cmipci_capture_pointer(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_pointer(cm, &cm->channel[CM_CH_CAPT], substream);
}
/*
* hw preparation for spdif
*/
static int snd_cmipci_spdif_default_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_cmipci_spdif_default_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
ucontrol->value.iec958.status[i] = (chip->dig_status >> (i * 8)) & 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cmipci_spdif_default_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i, change;
unsigned int val;
val = 0;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
val |= (unsigned int)ucontrol->value.iec958.status[i] << (i * 8);
change = val != chip->dig_status;
chip->dig_status = val;
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_cmipci_spdif_default __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = snd_cmipci_spdif_default_info,
.get = snd_cmipci_spdif_default_get,
.put = snd_cmipci_spdif_default_put
};
static int snd_cmipci_spdif_mask_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_cmipci_spdif_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.iec958.status[0] = 0xff;
ucontrol->value.iec958.status[1] = 0xff;
ucontrol->value.iec958.status[2] = 0xff;
ucontrol->value.iec958.status[3] = 0xff;
return 0;
}
static struct snd_kcontrol_new snd_cmipci_spdif_mask __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
.info = snd_cmipci_spdif_mask_info,
.get = snd_cmipci_spdif_mask_get,
};
static int snd_cmipci_spdif_stream_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_cmipci_spdif_stream_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
ucontrol->value.iec958.status[i] = (chip->dig_pcm_status >> (i * 8)) & 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cmipci_spdif_stream_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i, change;
unsigned int val;
val = 0;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
val |= (unsigned int)ucontrol->value.iec958.status[i] << (i * 8);
change = val != chip->dig_pcm_status;
chip->dig_pcm_status = val;
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_cmipci_spdif_stream __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
.info = snd_cmipci_spdif_stream_info,
.get = snd_cmipci_spdif_stream_get,
.put = snd_cmipci_spdif_stream_put
};
/*
*/
/* save mixer setting and mute for AC3 playback */
static int save_mixer_state(struct cmipci *cm)
{
if (! cm->mixer_insensitive) {
struct snd_ctl_elem_value *val;
unsigned int i;
val = kmalloc(sizeof(*val), GFP_ATOMIC);
if (!val)
return -ENOMEM;
for (i = 0; i < CM_SAVED_MIXERS; i++) {
struct snd_kcontrol *ctl = cm->mixer_res_ctl[i];
if (ctl) {
int event;
memset(val, 0, sizeof(*val));
ctl->get(ctl, val);
cm->mixer_res_status[i] = val->value.integer.value[0];
val->value.integer.value[0] = cm_saved_mixer[i].toggle_on;
event = SNDRV_CTL_EVENT_MASK_INFO;
if (cm->mixer_res_status[i] != val->value.integer.value[0]) {
ctl->put(ctl, val); /* toggle */
event |= SNDRV_CTL_EVENT_MASK_VALUE;
}
ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(cm->card, event, &ctl->id);
}
}
kfree(val);
cm->mixer_insensitive = 1;
}
return 0;
}
/* restore the previously saved mixer status */
static void restore_mixer_state(struct cmipci *cm)
{
if (cm->mixer_insensitive) {
struct snd_ctl_elem_value *val;
unsigned int i;
val = kmalloc(sizeof(*val), GFP_KERNEL);
if (!val)
return;
cm->mixer_insensitive = 0; /* at first clear this;
otherwise the changes will be ignored */
for (i = 0; i < CM_SAVED_MIXERS; i++) {
struct snd_kcontrol *ctl = cm->mixer_res_ctl[i];
if (ctl) {
int event;
memset(val, 0, sizeof(*val));
ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
ctl->get(ctl, val);
event = SNDRV_CTL_EVENT_MASK_INFO;
if (val->value.integer.value[0] != cm->mixer_res_status[i]) {
val->value.integer.value[0] = cm->mixer_res_status[i];
ctl->put(ctl, val);
event |= SNDRV_CTL_EVENT_MASK_VALUE;
}
snd_ctl_notify(cm->card, event, &ctl->id);
}
}
kfree(val);
}
}
/* spinlock held! */
static void setup_ac3(struct cmipci *cm, struct snd_pcm_substream *subs, int do_ac3, int rate)
{
if (do_ac3) {
/* AC3EN for 037 */
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_AC3EN1);
/* AC3EN for 039 */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_AC3EN2);
if (cm->can_ac3_hw) {
/* SPD24SEL for 037, 0x02 */
/* SPD24SEL for 039, 0x20, but cannot be set */
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
} else { /* can_ac3_sw */
/* SPD32SEL for 037 & 039, 0x20 */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
/* set 176K sample rate to fix 033 HW bug */
if (cm->chip_version == 33) {
if (rate >= 48000) {
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
} else {
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
}
}
}
} else {
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_AC3EN1);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_AC3EN2);
if (cm->can_ac3_hw) {
/* chip model >= 37 */
if (snd_pcm_format_width(subs->runtime->format) > 16) {
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
} else {
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
}
} else {
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
}
}
}
static int setup_spdif_playback(struct cmipci *cm, struct snd_pcm_substream *subs, int up, int do_ac3)
{
int rate, err;
rate = subs->runtime->rate;
if (up && do_ac3)
if ((err = save_mixer_state(cm)) < 0)
return err;
spin_lock_irq(&cm->reg_lock);
cm->spdif_playback_avail = up;
if (up) {
/* they are controlled via "IEC958 Output Switch" */
/* snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT); */
/* snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_SPDO2DAC); */
if (cm->spdif_playback_enabled)
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
setup_ac3(cm, subs, do_ac3, rate);
if (rate == 48000 || rate == 96000)
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K | CM_SPDF_AC97);
else
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K | CM_SPDF_AC97);
if (rate > 48000)
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
else
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
} else {
/* they are controlled via "IEC958 Output Switch" */
/* snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT); */
/* snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_SPDO2DAC); */
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
setup_ac3(cm, subs, 0, 0);
}
spin_unlock_irq(&cm->reg_lock);
return 0;
}
/*
* preparation
*/
/* playback - enable spdif only on the certain condition */
static int snd_cmipci_playback_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
int rate = substream->runtime->rate;
int err, do_spdif, do_ac3 = 0;
do_spdif = (rate >= 44100 && rate <= 96000 &&
substream->runtime->format == SNDRV_PCM_FORMAT_S16_LE &&
substream->runtime->channels == 2);
if (do_spdif && cm->can_ac3_hw)
do_ac3 = cm->dig_pcm_status & IEC958_AES0_NONAUDIO;
if ((err = setup_spdif_playback(cm, substream, do_spdif, do_ac3)) < 0)
return err;
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_PLAY], substream);
}
/* playback (via device #2) - enable spdif always */
static int snd_cmipci_playback_spdif_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
int err, do_ac3;
if (cm->can_ac3_hw)
do_ac3 = cm->dig_pcm_status & IEC958_AES0_NONAUDIO;
else
do_ac3 = 1; /* doesn't matter */
if ((err = setup_spdif_playback(cm, substream, 1, do_ac3)) < 0)
return err;
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_PLAY], substream);
}
/*
* Apparently, the samples last played on channel A stay in some buffer, even
* after the channel is reset, and get added to the data for the rear DACs when
* playing a multichannel stream on channel B. This is likely to generate
* wraparounds and thus distortions.
* To avoid this, we play at least one zero sample after the actual stream has
* stopped.
*/
static void snd_cmipci_silence_hack(struct cmipci *cm, struct cmipci_pcm *rec)
{
struct snd_pcm_runtime *runtime = rec->substream->runtime;
unsigned int reg, val;
if (rec->needs_silencing && runtime && runtime->dma_area) {
/* set up a small silence buffer */
memset(runtime->dma_area, 0, PAGE_SIZE);
reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
val = ((PAGE_SIZE / 4) - 1) | (((PAGE_SIZE / 4) / 2 - 1) << 16);
snd_cmipci_write(cm, reg, val);
/* configure for 16 bits, 2 channels, 8 kHz */
if (runtime->channels > 2)
set_dac_channels(cm, rec, 2);
spin_lock_irq(&cm->reg_lock);
val = snd_cmipci_read(cm, CM_REG_FUNCTRL1);
val &= ~(CM_ASFC_MASK << (rec->ch * 3));
val |= (4 << CM_ASFC_SHIFT) << (rec->ch * 3);
snd_cmipci_write(cm, CM_REG_FUNCTRL1, val);
val = snd_cmipci_read(cm, CM_REG_CHFORMAT);
val &= ~(CM_CH0FMT_MASK << (rec->ch * 2));
val |= (3 << CM_CH0FMT_SHIFT) << (rec->ch * 2);
if (cm->can_96k)
val &= ~(CM_CH0_SRATE_MASK << (rec->ch * 2));
snd_cmipci_write(cm, CM_REG_CHFORMAT, val);
/* start stream (we don't need interrupts) */
cm->ctrl |= CM_CHEN0 << rec->ch;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
spin_unlock_irq(&cm->reg_lock);
msleep(1);
/* stop and reset stream */
spin_lock_irq(&cm->reg_lock);
cm->ctrl &= ~(CM_CHEN0 << rec->ch);
val = CM_RST_CH0 << rec->ch;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | val);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~val);
spin_unlock_irq(&cm->reg_lock);
rec->needs_silencing = 0;
}
}
static int snd_cmipci_playback_hw_free(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
setup_spdif_playback(cm, substream, 0, 0);
restore_mixer_state(cm);
snd_cmipci_silence_hack(cm, &cm->channel[0]);
return snd_cmipci_hw_free(substream);
}
static int snd_cmipci_playback2_hw_free(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
snd_cmipci_silence_hack(cm, &cm->channel[1]);
return snd_cmipci_hw_free(substream);
}
/* capture */
static int snd_cmipci_capture_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_CAPT], substream);
}
/* capture with spdif (via device #2) */
static int snd_cmipci_capture_spdif_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
spin_lock_irq(&cm->reg_lock);
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_CAPTURE_SPDF);
if (cm->can_96k) {
if (substream->runtime->rate > 48000)
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
else
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
}
if (snd_pcm_format_width(substream->runtime->format) > 16)
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
else
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
spin_unlock_irq(&cm->reg_lock);
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_CAPT], substream);
}
static int snd_cmipci_capture_spdif_hw_free(struct snd_pcm_substream *subs)
{
struct cmipci *cm = snd_pcm_substream_chip(subs);
spin_lock_irq(&cm->reg_lock);
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_CAPTURE_SPDF);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
spin_unlock_irq(&cm->reg_lock);
return snd_cmipci_hw_free(subs);
}
/*
* interrupt handler
*/
static irqreturn_t snd_cmipci_interrupt(int irq, void *dev_id)
{
struct cmipci *cm = dev_id;
unsigned int status, mask = 0;
/* fastpath out, to ease interrupt sharing */
status = snd_cmipci_read(cm, CM_REG_INT_STATUS);
if (!(status & CM_INTR))
return IRQ_NONE;
/* acknowledge interrupt */
spin_lock(&cm->reg_lock);
if (status & CM_CHINT0)
mask |= CM_CH0_INT_EN;
if (status & CM_CHINT1)
mask |= CM_CH1_INT_EN;
snd_cmipci_clear_bit(cm, CM_REG_INT_HLDCLR, mask);
snd_cmipci_set_bit(cm, CM_REG_INT_HLDCLR, mask);
spin_unlock(&cm->reg_lock);
if (cm->rmidi && (status & CM_UARTINT))
snd_mpu401_uart_interrupt(irq, cm->rmidi->private_data);
if (cm->pcm) {
if ((status & CM_CHINT0) && cm->channel[0].running)
snd_pcm_period_elapsed(cm->channel[0].substream);
if ((status & CM_CHINT1) && cm->channel[1].running)
snd_pcm_period_elapsed(cm->channel[1].substream);
}
return IRQ_HANDLED;
}
/*
* h/w infos
*/
/* playback on channel A */
static struct snd_pcm_hardware snd_cmipci_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* capture on channel B */
static struct snd_pcm_hardware snd_cmipci_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* playback on channel B - stereo 16bit only? */
static struct snd_pcm_hardware snd_cmipci_playback2 =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* spdif playback on channel A */
static struct snd_pcm_hardware snd_cmipci_playback_spdif =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* spdif playback on channel A (32bit, IEC958 subframes) */
static struct snd_pcm_hardware snd_cmipci_playback_iec958_subframe =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* spdif capture on channel B */
static struct snd_pcm_hardware snd_cmipci_capture_spdif =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
static unsigned int rate_constraints[] = { 5512, 8000, 11025, 16000, 22050,
32000, 44100, 48000, 88200, 96000, 128000 };
static struct snd_pcm_hw_constraint_list hw_constraints_rates = {
.count = ARRAY_SIZE(rate_constraints),
.list = rate_constraints,
.mask = 0,
};
/*
* check device open/close
*/
static int open_device_check(struct cmipci *cm, int mode, struct snd_pcm_substream *subs)
{
int ch = mode & CM_OPEN_CH_MASK;
/* FIXME: a file should wait until the device becomes free
* when it's opened on blocking mode. however, since the current
* pcm framework doesn't pass file pointer before actually opened,
* we can't know whether blocking mode or not in open callback..
*/
mutex_lock(&cm->open_mutex);
if (cm->opened[ch]) {
mutex_unlock(&cm->open_mutex);
return -EBUSY;
}
cm->opened[ch] = mode;
cm->channel[ch].substream = subs;
if (! (mode & CM_OPEN_DAC)) {
/* disable dual DAC mode */
cm->channel[ch].is_dac = 0;
spin_lock_irq(&cm->reg_lock);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC);
spin_unlock_irq(&cm->reg_lock);
}
mutex_unlock(&cm->open_mutex);
return 0;
}
static void close_device_check(struct cmipci *cm, int mode)
{
int ch = mode & CM_OPEN_CH_MASK;
mutex_lock(&cm->open_mutex);
if (cm->opened[ch] == mode) {
if (cm->channel[ch].substream) {
snd_cmipci_ch_reset(cm, ch);
cm->channel[ch].running = 0;
cm->channel[ch].substream = NULL;
}
cm->opened[ch] = 0;
if (! cm->channel[ch].is_dac) {
/* enable dual DAC mode again */
cm->channel[ch].is_dac = 1;
spin_lock_irq(&cm->reg_lock);
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC);
spin_unlock_irq(&cm->reg_lock);
}
}
mutex_unlock(&cm->open_mutex);
}
/*
*/
static int snd_cmipci_playback_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_PLAYBACK, substream)) < 0)
return err;
runtime->hw = snd_cmipci_playback;
if (cm->chip_version == 68) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
} else if (cm->chip_version == 55) {
err = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates);
if (err < 0)
return err;
runtime->hw.rates |= SNDRV_PCM_RATE_KNOT;
runtime->hw.rate_max = 128000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
cm->dig_pcm_status = cm->dig_status;
return 0;
}
static int snd_cmipci_capture_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_CAPTURE, substream)) < 0)
return err;
runtime->hw = snd_cmipci_capture;
if (cm->chip_version == 68) { // 8768 only supports 44k/48k recording
runtime->hw.rate_min = 41000;
runtime->hw.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000;
} else if (cm->chip_version == 55) {
err = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates);
if (err < 0)
return err;
runtime->hw.rates |= SNDRV_PCM_RATE_KNOT;
runtime->hw.rate_max = 128000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
return 0;
}
static int snd_cmipci_playback2_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_PLAYBACK2, substream)) < 0) /* use channel B */
return err;
runtime->hw = snd_cmipci_playback2;
mutex_lock(&cm->open_mutex);
if (! cm->opened[CM_CH_PLAY]) {
if (cm->can_multi_ch) {
runtime->hw.channels_max = cm->max_channels;
if (cm->max_channels == 4)
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_4);
else if (cm->max_channels == 6)
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_6);
else if (cm->max_channels == 8)
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_8);
}
}
mutex_unlock(&cm->open_mutex);
if (cm->chip_version == 68) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
} else if (cm->chip_version == 55) {
err = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates);
if (err < 0)
return err;
runtime->hw.rates |= SNDRV_PCM_RATE_KNOT;
runtime->hw.rate_max = 128000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
return 0;
}
static int snd_cmipci_playback_spdif_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_SPDIF_PLAYBACK, substream)) < 0) /* use channel A */
return err;
if (cm->can_ac3_hw) {
runtime->hw = snd_cmipci_playback_spdif;
if (cm->chip_version >= 37) {
runtime->hw.formats |= SNDRV_PCM_FMTBIT_S32_LE;
snd_pcm_hw_constraint_msbits(runtime, 0, 32, 24);
}
if (cm->can_96k) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
}
} else {
runtime->hw = snd_cmipci_playback_iec958_subframe;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x40000);
cm->dig_pcm_status = cm->dig_status;
return 0;
}
static int snd_cmipci_capture_spdif_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_SPDIF_CAPTURE, substream)) < 0) /* use channel B */
return err;
runtime->hw = snd_cmipci_capture_spdif;
if (cm->can_96k && !(cm->chip_version == 68)) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x40000);
return 0;
}
/*
*/
static int snd_cmipci_playback_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_PLAYBACK);
return 0;
}
static int snd_cmipci_capture_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_CAPTURE);
return 0;
}
static int snd_cmipci_playback2_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_PLAYBACK2);
close_device_check(cm, CM_OPEN_PLAYBACK_MULTI);
return 0;
}
static int snd_cmipci_playback_spdif_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_SPDIF_PLAYBACK);
return 0;
}
static int snd_cmipci_capture_spdif_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_SPDIF_CAPTURE);
return 0;
}
/*
*/
static struct snd_pcm_ops snd_cmipci_playback_ops = {
.open = snd_cmipci_playback_open,
.close = snd_cmipci_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_playback_hw_free,
.prepare = snd_cmipci_playback_prepare,
.trigger = snd_cmipci_playback_trigger,
.pointer = snd_cmipci_playback_pointer,
};
static struct snd_pcm_ops snd_cmipci_capture_ops = {
.open = snd_cmipci_capture_open,
.close = snd_cmipci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_hw_free,
.prepare = snd_cmipci_capture_prepare,
.trigger = snd_cmipci_capture_trigger,
.pointer = snd_cmipci_capture_pointer,
};
static struct snd_pcm_ops snd_cmipci_playback2_ops = {
.open = snd_cmipci_playback2_open,
.close = snd_cmipci_playback2_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_playback2_hw_params,
.hw_free = snd_cmipci_playback2_hw_free,
.prepare = snd_cmipci_capture_prepare, /* channel B */
.trigger = snd_cmipci_capture_trigger, /* channel B */
.pointer = snd_cmipci_capture_pointer, /* channel B */
};
static struct snd_pcm_ops snd_cmipci_playback_spdif_ops = {
.open = snd_cmipci_playback_spdif_open,
.close = snd_cmipci_playback_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_playback_hw_free,
.prepare = snd_cmipci_playback_spdif_prepare, /* set up rate */
.trigger = snd_cmipci_playback_trigger,
.pointer = snd_cmipci_playback_pointer,
};
static struct snd_pcm_ops snd_cmipci_capture_spdif_ops = {
.open = snd_cmipci_capture_spdif_open,
.close = snd_cmipci_capture_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_capture_spdif_hw_free,
.prepare = snd_cmipci_capture_spdif_prepare,
.trigger = snd_cmipci_capture_trigger,
.pointer = snd_cmipci_capture_pointer,
};
/*
*/
static int __devinit snd_cmipci_pcm_new(struct cmipci *cm, int device)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cmipci_capture_ops);
pcm->private_data = cm;
pcm->info_flags = 0;
strcpy(pcm->name, "C-Media PCI DAC/ADC");
cm->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
return 0;
}
static int __devinit snd_cmipci_pcm2_new(struct cmipci *cm, int device)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 0, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback2_ops);
pcm->private_data = cm;
pcm->info_flags = 0;
strcpy(pcm->name, "C-Media PCI 2nd DAC");
cm->pcm2 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
return 0;
}
static int __devinit snd_cmipci_pcm_spdif_new(struct cmipci *cm, int device)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_spdif_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cmipci_capture_spdif_ops);
pcm->private_data = cm;
pcm->info_flags = 0;
strcpy(pcm->name, "C-Media PCI IEC958");
cm->pcm_spdif = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
return 0;
}
/*
* mixer interface:
* - CM8338/8738 has a compatible mixer interface with SB16, but
* lack of some elements like tone control, i/o gain and AGC.
* - Access to native registers:
* - A 3D switch
* - Output mute switches
*/
static void snd_cmipci_mixer_write(struct cmipci *s, unsigned char idx, unsigned char data)
{
outb(idx, s->iobase + CM_REG_SB16_ADDR);
outb(data, s->iobase + CM_REG_SB16_DATA);
}
static unsigned char snd_cmipci_mixer_read(struct cmipci *s, unsigned char idx)
{
unsigned char v;
outb(idx, s->iobase + CM_REG_SB16_ADDR);
v = inb(s->iobase + CM_REG_SB16_DATA);
return v;
}
/*
* general mixer element
*/
struct cmipci_sb_reg {
unsigned int left_reg, right_reg;
unsigned int left_shift, right_shift;
unsigned int mask;
unsigned int invert: 1;
unsigned int stereo: 1;
};
#define COMPOSE_SB_REG(lreg,rreg,lshift,rshift,mask,invert,stereo) \
((lreg) | ((rreg) << 8) | (lshift << 16) | (rshift << 19) | (mask << 24) | (invert << 22) | (stereo << 23))
#define CMIPCI_DOUBLE(xname, left_reg, right_reg, left_shift, right_shift, mask, invert, stereo) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_volume, \
.get = snd_cmipci_get_volume, .put = snd_cmipci_put_volume, \
.private_value = COMPOSE_SB_REG(left_reg, right_reg, left_shift, right_shift, mask, invert, stereo), \
}
#define CMIPCI_SB_VOL_STEREO(xname,reg,shift,mask) CMIPCI_DOUBLE(xname, reg, reg+1, shift, shift, mask, 0, 1)
#define CMIPCI_SB_VOL_MONO(xname,reg,shift,mask) CMIPCI_DOUBLE(xname, reg, reg, shift, shift, mask, 0, 0)
#define CMIPCI_SB_SW_STEREO(xname,lshift,rshift) CMIPCI_DOUBLE(xname, SB_DSP4_OUTPUT_SW, SB_DSP4_OUTPUT_SW, lshift, rshift, 1, 0, 1)
#define CMIPCI_SB_SW_MONO(xname,shift) CMIPCI_DOUBLE(xname, SB_DSP4_OUTPUT_SW, SB_DSP4_OUTPUT_SW, shift, shift, 1, 0, 0)
static void cmipci_sb_reg_decode(struct cmipci_sb_reg *r, unsigned long val)
{
r->left_reg = val & 0xff;
r->right_reg = (val >> 8) & 0xff;
r->left_shift = (val >> 16) & 0x07;
r->right_shift = (val >> 19) & 0x07;
r->invert = (val >> 22) & 1;
r->stereo = (val >> 23) & 1;
r->mask = (val >> 24) & 0xff;
}
static int snd_cmipci_info_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct cmipci_sb_reg reg;
cmipci_sb_reg_decode(®, kcontrol->private_value);
uinfo->type = reg.mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = reg.stereo + 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = reg.mask;
return 0;
}
static int snd_cmipci_get_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int val;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
val = (snd_cmipci_mixer_read(cm, reg.left_reg) >> reg.left_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[0] = val;
if (reg.stereo) {
val = (snd_cmipci_mixer_read(cm, reg.right_reg) >> reg.right_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[1] = val;
}
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_put_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int change;
int left, right, oleft, oright;
cmipci_sb_reg_decode(®, kcontrol->private_value);
left = ucontrol->value.integer.value[0] & reg.mask;
if (reg.invert)
left = reg.mask - left;
left <<= reg.left_shift;
if (reg.stereo) {
right = ucontrol->value.integer.value[1] & reg.mask;
if (reg.invert)
right = reg.mask - right;
right <<= reg.right_shift;
} else
right = 0;
spin_lock_irq(&cm->reg_lock);
oleft = snd_cmipci_mixer_read(cm, reg.left_reg);
left |= oleft & ~(reg.mask << reg.left_shift);
change = left != oleft;
if (reg.stereo) {
if (reg.left_reg != reg.right_reg) {
snd_cmipci_mixer_write(cm, reg.left_reg, left);
oright = snd_cmipci_mixer_read(cm, reg.right_reg);
} else
oright = left;
right |= oright & ~(reg.mask << reg.right_shift);
change |= right != oright;
snd_cmipci_mixer_write(cm, reg.right_reg, right);
} else
snd_cmipci_mixer_write(cm, reg.left_reg, left);
spin_unlock_irq(&cm->reg_lock);
return change;
}
/*
* input route (left,right) -> (left,right)
*/
#define CMIPCI_SB_INPUT_SW(xname, left_shift, right_shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_input_sw, \
.get = snd_cmipci_get_input_sw, .put = snd_cmipci_put_input_sw, \
.private_value = COMPOSE_SB_REG(SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT, left_shift, right_shift, 1, 0, 1), \
}
static int snd_cmipci_info_input_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 4;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
static int snd_cmipci_get_input_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int val1, val2;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
val1 = snd_cmipci_mixer_read(cm, reg.left_reg);
val2 = snd_cmipci_mixer_read(cm, reg.right_reg);
spin_unlock_irq(&cm->reg_lock);
ucontrol->value.integer.value[0] = (val1 >> reg.left_shift) & 1;
ucontrol->value.integer.value[1] = (val2 >> reg.left_shift) & 1;
ucontrol->value.integer.value[2] = (val1 >> reg.right_shift) & 1;
ucontrol->value.integer.value[3] = (val2 >> reg.right_shift) & 1;
return 0;
}
static int snd_cmipci_put_input_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int change;
int val1, val2, oval1, oval2;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
oval1 = snd_cmipci_mixer_read(cm, reg.left_reg);
oval2 = snd_cmipci_mixer_read(cm, reg.right_reg);
val1 = oval1 & ~((1 << reg.left_shift) | (1 << reg.right_shift));
val2 = oval2 & ~((1 << reg.left_shift) | (1 << reg.right_shift));
val1 |= (ucontrol->value.integer.value[0] & 1) << reg.left_shift;
val2 |= (ucontrol->value.integer.value[1] & 1) << reg.left_shift;
val1 |= (ucontrol->value.integer.value[2] & 1) << reg.right_shift;
val2 |= (ucontrol->value.integer.value[3] & 1) << reg.right_shift;
change = val1 != oval1 || val2 != oval2;
snd_cmipci_mixer_write(cm, reg.left_reg, val1);
snd_cmipci_mixer_write(cm, reg.right_reg, val2);
spin_unlock_irq(&cm->reg_lock);
return change;
}
/*
* native mixer switches/volumes
*/
#define CMIPCI_MIXER_SW_STEREO(xname, reg, lshift, rshift, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, lshift, rshift, 1, invert, 1), \
}
#define CMIPCI_MIXER_SW_MONO(xname, reg, shift, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, shift, shift, 1, invert, 0), \
}
#define CMIPCI_MIXER_VOL_STEREO(xname, reg, lshift, rshift, mask) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, lshift, rshift, mask, 0, 1), \
}
#define CMIPCI_MIXER_VOL_MONO(xname, reg, shift, mask) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, shift, shift, mask, 0, 0), \
}
static int snd_cmipci_info_native_mixer(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct cmipci_sb_reg reg;
cmipci_sb_reg_decode(®, kcontrol->private_value);
uinfo->type = reg.mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = reg.stereo + 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = reg.mask;
return 0;
}
static int snd_cmipci_get_native_mixer(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
unsigned char oreg, val;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
oreg = inb(cm->iobase + reg.left_reg);
val = (oreg >> reg.left_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[0] = val;
if (reg.stereo) {
val = (oreg >> reg.right_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[1] = val;
}
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_put_native_mixer(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
unsigned char oreg, nreg, val;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
oreg = inb(cm->iobase + reg.left_reg);
val = ucontrol->value.integer.value[0] & reg.mask;
if (reg.invert)
val = reg.mask - val;
nreg = oreg & ~(reg.mask << reg.left_shift);
nreg |= (val << reg.left_shift);
if (reg.stereo) {
val = ucontrol->value.integer.value[1] & reg.mask;
if (reg.invert)
val = reg.mask - val;
nreg &= ~(reg.mask << reg.right_shift);
nreg |= (val << reg.right_shift);
}
outb(nreg, cm->iobase + reg.left_reg);
spin_unlock_irq(&cm->reg_lock);
return (nreg != oreg);
}
/*
* special case - check mixer sensitivity
*/
static int snd_cmipci_get_native_mixer_sensitive(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
//struct cmipci *cm = snd_kcontrol_chip(kcontrol);
return snd_cmipci_get_native_mixer(kcontrol, ucontrol);
}
static int snd_cmipci_put_native_mixer_sensitive(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
if (cm->mixer_insensitive) {
/* ignored */
return 0;
}
return snd_cmipci_put_native_mixer(kcontrol, ucontrol);
}
static struct snd_kcontrol_new snd_cmipci_mixers[] __devinitdata = {
CMIPCI_SB_VOL_STEREO("Master Playback Volume", SB_DSP4_MASTER_DEV, 3, 31),
CMIPCI_MIXER_SW_MONO("3D Control - Switch", CM_REG_MIXER1, CM_X3DEN_SHIFT, 0),
CMIPCI_SB_VOL_STEREO("PCM Playback Volume", SB_DSP4_PCM_DEV, 3, 31),
//CMIPCI_MIXER_SW_MONO("PCM Playback Switch", CM_REG_MIXER1, CM_WSMUTE_SHIFT, 1),
{ /* switch with sensitivity */
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Switch",
.info = snd_cmipci_info_native_mixer,
.get = snd_cmipci_get_native_mixer_sensitive,
.put = snd_cmipci_put_native_mixer_sensitive,
.private_value = COMPOSE_SB_REG(CM_REG_MIXER1, CM_REG_MIXER1, CM_WSMUTE_SHIFT, CM_WSMUTE_SHIFT, 1, 1, 0),
},
CMIPCI_MIXER_SW_STEREO("PCM Capture Switch", CM_REG_MIXER1, CM_WAVEINL_SHIFT, CM_WAVEINR_SHIFT, 0),
CMIPCI_SB_VOL_STEREO("Synth Playback Volume", SB_DSP4_SYNTH_DEV, 3, 31),
CMIPCI_MIXER_SW_MONO("Synth Playback Switch", CM_REG_MIXER1, CM_FMMUTE_SHIFT, 1),
CMIPCI_SB_INPUT_SW("Synth Capture Route", 6, 5),
CMIPCI_SB_VOL_STEREO("CD Playback Volume", SB_DSP4_CD_DEV, 3, 31),
CMIPCI_SB_SW_STEREO("CD Playback Switch", 2, 1),
CMIPCI_SB_INPUT_SW("CD Capture Route", 2, 1),
CMIPCI_SB_VOL_STEREO("Line Playback Volume", SB_DSP4_LINE_DEV, 3, 31),
CMIPCI_SB_SW_STEREO("Line Playback Switch", 4, 3),
CMIPCI_SB_INPUT_SW("Line Capture Route", 4, 3),
CMIPCI_SB_VOL_MONO("Mic Playback Volume", SB_DSP4_MIC_DEV, 3, 31),
CMIPCI_SB_SW_MONO("Mic Playback Switch", 0),
CMIPCI_DOUBLE("Mic Capture Switch", SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT, 0, 0, 1, 0, 0),
CMIPCI_SB_VOL_MONO("Beep Playback Volume", SB_DSP4_SPEAKER_DEV, 6, 3),
CMIPCI_MIXER_VOL_STEREO("Aux Playback Volume", CM_REG_AUX_VOL, 4, 0, 15),
CMIPCI_MIXER_SW_STEREO("Aux Playback Switch", CM_REG_MIXER2, CM_VAUXLM_SHIFT, CM_VAUXRM_SHIFT, 0),
CMIPCI_MIXER_SW_STEREO("Aux Capture Switch", CM_REG_MIXER2, CM_RAUXLEN_SHIFT, CM_RAUXREN_SHIFT, 0),
CMIPCI_MIXER_SW_MONO("Mic Boost Playback Switch", CM_REG_MIXER2, CM_MICGAINZ_SHIFT, 1),
CMIPCI_MIXER_VOL_MONO("Mic Capture Volume", CM_REG_MIXER2, CM_VADMIC_SHIFT, 7),
CMIPCI_SB_VOL_MONO("Phone Playback Volume", CM_REG_EXTENT_IND, 5, 7),
CMIPCI_DOUBLE("Phone Playback Switch", CM_REG_EXTENT_IND, CM_REG_EXTENT_IND, 4, 4, 1, 0, 0),
CMIPCI_DOUBLE("Beep Playback Switch", CM_REG_EXTENT_IND, CM_REG_EXTENT_IND, 3, 3, 1, 0, 0),
CMIPCI_DOUBLE("Mic Boost Capture Switch", CM_REG_EXTENT_IND, CM_REG_EXTENT_IND, 0, 0, 1, 0, 0),
};
/*
* other switches
*/
struct cmipci_switch_args {
int reg; /* register index */
unsigned int mask; /* mask bits */
unsigned int mask_on; /* mask bits to turn on */
unsigned int is_byte: 1; /* byte access? */
unsigned int ac3_sensitive: 1; /* access forbidden during
* non-audio operation?
*/
};
#define snd_cmipci_uswitch_info snd_ctl_boolean_mono_info
static int _snd_cmipci_uswitch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol,
struct cmipci_switch_args *args)
{
unsigned int val;
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&cm->reg_lock);
if (args->ac3_sensitive && cm->mixer_insensitive) {
ucontrol->value.integer.value[0] = 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
if (args->is_byte)
val = inb(cm->iobase + args->reg);
else
val = snd_cmipci_read(cm, args->reg);
ucontrol->value.integer.value[0] = ((val & args->mask) == args->mask_on) ? 1 : 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_uswitch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci_switch_args *args;
args = (struct cmipci_switch_args *)kcontrol->private_value;
if (snd_BUG_ON(!args))
return -EINVAL;
return _snd_cmipci_uswitch_get(kcontrol, ucontrol, args);
}
static int _snd_cmipci_uswitch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol,
struct cmipci_switch_args *args)
{
unsigned int val;
int change;
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&cm->reg_lock);
if (args->ac3_sensitive && cm->mixer_insensitive) {
/* ignored */
spin_unlock_irq(&cm->reg_lock);
return 0;
}
if (args->is_byte)
val = inb(cm->iobase + args->reg);
else
val = snd_cmipci_read(cm, args->reg);
change = (val & args->mask) != (ucontrol->value.integer.value[0] ?
args->mask_on : (args->mask & ~args->mask_on));
if (change) {
val &= ~args->mask;
if (ucontrol->value.integer.value[0])
val |= args->mask_on;
else
val |= (args->mask & ~args->mask_on);
if (args->is_byte)
outb((unsigned char)val, cm->iobase + args->reg);
else
snd_cmipci_write(cm, args->reg, val);
}
spin_unlock_irq(&cm->reg_lock);
return change;
}
static int snd_cmipci_uswitch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci_switch_args *args;
args = (struct cmipci_switch_args *)kcontrol->private_value;
if (snd_BUG_ON(!args))
return -EINVAL;
return _snd_cmipci_uswitch_put(kcontrol, ucontrol, args);
}
#define DEFINE_SWITCH_ARG(sname, xreg, xmask, xmask_on, xis_byte, xac3) \
static struct cmipci_switch_args cmipci_switch_arg_##sname = { \
.reg = xreg, \
.mask = xmask, \
.mask_on = xmask_on, \
.is_byte = xis_byte, \
.ac3_sensitive = xac3, \
}
#define DEFINE_BIT_SWITCH_ARG(sname, xreg, xmask, xis_byte, xac3) \
DEFINE_SWITCH_ARG(sname, xreg, xmask, xmask, xis_byte, xac3)
#if 0 /* these will be controlled in pcm device */
DEFINE_BIT_SWITCH_ARG(spdif_in, CM_REG_FUNCTRL1, CM_SPDF_1, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_out, CM_REG_FUNCTRL1, CM_SPDF_0, 0, 0);
#endif
DEFINE_BIT_SWITCH_ARG(spdif_in_sel1, CM_REG_CHFORMAT, CM_SPDIF_SELECT1, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_in_sel2, CM_REG_MISC_CTRL, CM_SPDIF_SELECT2, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_enable, CM_REG_LEGACY_CTRL, CM_ENSPDOUT, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdo2dac, CM_REG_FUNCTRL1, CM_SPDO2DAC, 0, 1);
DEFINE_BIT_SWITCH_ARG(spdi_valid, CM_REG_MISC, CM_SPDVALID, 1, 0);
DEFINE_BIT_SWITCH_ARG(spdif_copyright, CM_REG_LEGACY_CTRL, CM_SPDCOPYRHT, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_dac_out, CM_REG_LEGACY_CTRL, CM_DAC2SPDO, 0, 1);
DEFINE_SWITCH_ARG(spdo_5v, CM_REG_MISC_CTRL, CM_SPDO5V, 0, 0, 0); /* inverse: 0 = 5V */
// DEFINE_BIT_SWITCH_ARG(spdo_48k, CM_REG_MISC_CTRL, CM_SPDF_AC97|CM_SPDIF48K, 0, 1);
DEFINE_BIT_SWITCH_ARG(spdif_loop, CM_REG_FUNCTRL1, CM_SPDFLOOP, 0, 1);
DEFINE_BIT_SWITCH_ARG(spdi_monitor, CM_REG_MIXER1, CM_CDPLAY, 1, 0);
/* DEFINE_BIT_SWITCH_ARG(spdi_phase, CM_REG_CHFORMAT, CM_SPDIF_INVERSE, 0, 0); */
DEFINE_BIT_SWITCH_ARG(spdi_phase, CM_REG_MISC, CM_SPDIF_INVERSE, 1, 0);
DEFINE_BIT_SWITCH_ARG(spdi_phase2, CM_REG_CHFORMAT, CM_SPDIF_INVERSE2, 0, 0);
#if CM_CH_PLAY == 1
DEFINE_SWITCH_ARG(exchange_dac, CM_REG_MISC_CTRL, CM_XCHGDAC, 0, 0, 0); /* reversed */
#else
DEFINE_SWITCH_ARG(exchange_dac, CM_REG_MISC_CTRL, CM_XCHGDAC, CM_XCHGDAC, 0, 0);
#endif
DEFINE_BIT_SWITCH_ARG(fourch, CM_REG_MISC_CTRL, CM_N4SPK3D, 0, 0);
// DEFINE_BIT_SWITCH_ARG(line_rear, CM_REG_MIXER1, CM_REAR2LIN, 1, 0);
// DEFINE_BIT_SWITCH_ARG(line_bass, CM_REG_LEGACY_CTRL, CM_CENTR2LIN|CM_BASE2LIN, 0, 0);
// DEFINE_BIT_SWITCH_ARG(joystick, CM_REG_FUNCTRL1, CM_JYSTK_EN, 0, 0); /* now module option */
DEFINE_SWITCH_ARG(modem, CM_REG_MISC_CTRL, CM_FLINKON|CM_FLINKOFF, CM_FLINKON, 0, 0);
#define DEFINE_SWITCH(sname, stype, sarg) \
{ .name = sname, \
.iface = stype, \
.info = snd_cmipci_uswitch_info, \
.get = snd_cmipci_uswitch_get, \
.put = snd_cmipci_uswitch_put, \
.private_value = (unsigned long)&cmipci_switch_arg_##sarg,\
}
#define DEFINE_CARD_SWITCH(sname, sarg) DEFINE_SWITCH(sname, SNDRV_CTL_ELEM_IFACE_CARD, sarg)
#define DEFINE_MIXER_SWITCH(sname, sarg) DEFINE_SWITCH(sname, SNDRV_CTL_ELEM_IFACE_MIXER, sarg)
/*
* callbacks for spdif output switch
* needs toggle two registers..
*/
static int snd_cmipci_spdout_enable_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int changed;
changed = _snd_cmipci_uswitch_get(kcontrol, ucontrol, &cmipci_switch_arg_spdif_enable);
changed |= _snd_cmipci_uswitch_get(kcontrol, ucontrol, &cmipci_switch_arg_spdo2dac);
return changed;
}
static int snd_cmipci_spdout_enable_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int changed;
changed = _snd_cmipci_uswitch_put(kcontrol, ucontrol, &cmipci_switch_arg_spdif_enable);
changed |= _snd_cmipci_uswitch_put(kcontrol, ucontrol, &cmipci_switch_arg_spdo2dac);
if (changed) {
if (ucontrol->value.integer.value[0]) {
if (chip->spdif_playback_avail)
snd_cmipci_set_bit(chip, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
} else {
if (chip->spdif_playback_avail)
snd_cmipci_clear_bit(chip, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
}
}
chip->spdif_playback_enabled = ucontrol->value.integer.value[0];
return changed;
}
static int snd_cmipci_line_in_mode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
static const char *const texts[3] = {
"Line-In", "Rear Output", "Bass Output"
};
return snd_ctl_enum_info(uinfo, 1,
cm->chip_version >= 39 ? 3 : 2, texts);
}
static inline unsigned int get_line_in_mode(struct cmipci *cm)
{
unsigned int val;
if (cm->chip_version >= 39) {
val = snd_cmipci_read(cm, CM_REG_LEGACY_CTRL);
if (val & (CM_CENTR2LIN | CM_BASE2LIN))
return 2;
}
val = snd_cmipci_read_b(cm, CM_REG_MIXER1);
if (val & CM_REAR2LIN)
return 1;
return 0;
}
static int snd_cmipci_line_in_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&cm->reg_lock);
ucontrol->value.enumerated.item[0] = get_line_in_mode(cm);
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_line_in_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
int change;
spin_lock_irq(&cm->reg_lock);
if (ucontrol->value.enumerated.item[0] == 2)
change = snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_CENTR2LIN | CM_BASE2LIN);
else
change = snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_CENTR2LIN | CM_BASE2LIN);
if (ucontrol->value.enumerated.item[0] == 1)
change |= snd_cmipci_set_bit_b(cm, CM_REG_MIXER1, CM_REAR2LIN);
else
change |= snd_cmipci_clear_bit_b(cm, CM_REG_MIXER1, CM_REAR2LIN);
spin_unlock_irq(&cm->reg_lock);
return change;
}
static int snd_cmipci_mic_in_mode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *const texts[2] = { "Mic-In", "Center/LFE Output" };
return snd_ctl_enum_info(uinfo, 1, 2, texts);
}
static int snd_cmipci_mic_in_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
/* same bit as spdi_phase */
spin_lock_irq(&cm->reg_lock);
ucontrol->value.enumerated.item[0] =
(snd_cmipci_read_b(cm, CM_REG_MISC) & CM_SPDIF_INVERSE) ? 1 : 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_mic_in_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
int change;
spin_lock_irq(&cm->reg_lock);
if (ucontrol->value.enumerated.item[0])
change = snd_cmipci_set_bit_b(cm, CM_REG_MISC, CM_SPDIF_INVERSE);
else
change = snd_cmipci_clear_bit_b(cm, CM_REG_MISC, CM_SPDIF_INVERSE);
spin_unlock_irq(&cm->reg_lock);
return change;
}
/* both for CM8338/8738 */
static struct snd_kcontrol_new snd_cmipci_mixer_switches[] __devinitdata = {
DEFINE_MIXER_SWITCH("Four Channel Mode", fourch),
{
.name = "Line-In Mode",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_cmipci_line_in_mode_info,
.get = snd_cmipci_line_in_mode_get,
.put = snd_cmipci_line_in_mode_put,
},
};
/* for non-multichannel chips */
static struct snd_kcontrol_new snd_cmipci_nomulti_switch __devinitdata =
DEFINE_MIXER_SWITCH("Exchange DAC", exchange_dac);
/* only for CM8738 */
static struct snd_kcontrol_new snd_cmipci_8738_mixer_switches[] __devinitdata = {
#if 0 /* controlled in pcm device */
DEFINE_MIXER_SWITCH("IEC958 In Record", spdif_in),
DEFINE_MIXER_SWITCH("IEC958 Out", spdif_out),
DEFINE_MIXER_SWITCH("IEC958 Out To DAC", spdo2dac),
#endif
// DEFINE_MIXER_SWITCH("IEC958 Output Switch", spdif_enable),
{ .name = "IEC958 Output Switch",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_cmipci_uswitch_info,
.get = snd_cmipci_spdout_enable_get,
.put = snd_cmipci_spdout_enable_put,
},
DEFINE_MIXER_SWITCH("IEC958 In Valid", spdi_valid),
DEFINE_MIXER_SWITCH("IEC958 Copyright", spdif_copyright),
DEFINE_MIXER_SWITCH("IEC958 5V", spdo_5v),
// DEFINE_MIXER_SWITCH("IEC958 In/Out 48KHz", spdo_48k),
DEFINE_MIXER_SWITCH("IEC958 Loop", spdif_loop),
DEFINE_MIXER_SWITCH("IEC958 In Monitor", spdi_monitor),
};
/* only for model 033/037 */
static struct snd_kcontrol_new snd_cmipci_old_mixer_switches[] __devinitdata = {
DEFINE_MIXER_SWITCH("IEC958 Mix Analog", spdif_dac_out),
DEFINE_MIXER_SWITCH("IEC958 In Phase Inverse", spdi_phase),
DEFINE_MIXER_SWITCH("IEC958 In Select", spdif_in_sel1),
};
/* only for model 039 or later */
static struct snd_kcontrol_new snd_cmipci_extra_mixer_switches[] __devinitdata = {
DEFINE_MIXER_SWITCH("IEC958 In Select", spdif_in_sel2),
DEFINE_MIXER_SWITCH("IEC958 In Phase Inverse", spdi_phase2),
{
.name = "Mic-In Mode",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_cmipci_mic_in_mode_info,
.get = snd_cmipci_mic_in_mode_get,
.put = snd_cmipci_mic_in_mode_put,
}
};
/* card control switches */
static struct snd_kcontrol_new snd_cmipci_modem_switch __devinitdata =
DEFINE_CARD_SWITCH("Modem", modem);
static int __devinit snd_cmipci_mixer_new(struct cmipci *cm, int pcm_spdif_device)
{
struct snd_card *card;
struct snd_kcontrol_new *sw;
struct snd_kcontrol *kctl;
unsigned int idx;
int err;
if (snd_BUG_ON(!cm || !cm->card))
return -EINVAL;
card = cm->card;
strcpy(card->mixername, "CMedia PCI");
spin_lock_irq(&cm->reg_lock);
snd_cmipci_mixer_write(cm, 0x00, 0x00); /* mixer reset */
spin_unlock_irq(&cm->reg_lock);
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_mixers); idx++) {
if (cm->chip_version == 68) { // 8768 has no PCM volume
if (!strcmp(snd_cmipci_mixers[idx].name,
"PCM Playback Volume"))
continue;
}
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_cmipci_mixers[idx], cm))) < 0)
return err;
}
/* mixer switches */
sw = snd_cmipci_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
if (! cm->can_multi_ch) {
err = snd_ctl_add(cm->card, snd_ctl_new1(&snd_cmipci_nomulti_switch, cm));
if (err < 0)
return err;
}
if (cm->device == PCI_DEVICE_ID_CMEDIA_CM8738 ||
cm->device == PCI_DEVICE_ID_CMEDIA_CM8738B) {
sw = snd_cmipci_8738_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_8738_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
if (cm->can_ac3_hw) {
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_default, cm))) < 0)
return err;
kctl->id.device = pcm_spdif_device;
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_mask, cm))) < 0)
return err;
kctl->id.device = pcm_spdif_device;
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_stream, cm))) < 0)
return err;
kctl->id.device = pcm_spdif_device;
}
if (cm->chip_version <= 37) {
sw = snd_cmipci_old_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_old_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
}
}
if (cm->chip_version >= 39) {
sw = snd_cmipci_extra_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_extra_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
}
/* card switches */
/*
* newer chips don't have the register bits to force modem link
* detection; the bit that was FLINKON now mutes CH1
*/
if (cm->chip_version < 39) {
err = snd_ctl_add(cm->card,
snd_ctl_new1(&snd_cmipci_modem_switch, cm));
if (err < 0)
return err;
}
for (idx = 0; idx < CM_SAVED_MIXERS; idx++) {
struct snd_ctl_elem_id elem_id;
struct snd_kcontrol *ctl;
memset(&elem_id, 0, sizeof(elem_id));
elem_id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
strcpy(elem_id.name, cm_saved_mixer[idx].name);
ctl = snd_ctl_find_id(cm->card, &elem_id);
if (ctl)
cm->mixer_res_ctl[idx] = ctl;
}
return 0;
}
/*
* proc interface
*/
#ifdef CONFIG_PROC_FS
static void snd_cmipci_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct cmipci *cm = entry->private_data;
int i, v;
snd_iprintf(buffer, "%s\n", cm->card->longname);
for (i = 0; i < 0x94; i++) {
if (i == 0x28)
i = 0x90;
v = inb(cm->iobase + i);
if (i % 4 == 0)
snd_iprintf(buffer, "\n%02x:", i);
snd_iprintf(buffer, " %02x", v);
}
snd_iprintf(buffer, "\n");
}
static void __devinit snd_cmipci_proc_init(struct cmipci *cm)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(cm->card, "cmipci", &entry))
snd_info_set_text_ops(entry, cm, snd_cmipci_proc_read);
}
#else /* !CONFIG_PROC_FS */
static inline void snd_cmipci_proc_init(struct cmipci *cm) {}
#endif
static DEFINE_PCI_DEVICE_TABLE(snd_cmipci_ids) = {
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338A), 0},
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338B), 0},
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738), 0},
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738B), 0},
{PCI_VDEVICE(AL, PCI_DEVICE_ID_CMEDIA_CM8738), 0},
{0,},
};
/*
* check chip version and capabilities
* driver name is modified according to the chip model
*/
static void __devinit query_chip(struct cmipci *cm)
{
unsigned int detect;
/* check reg 0Ch, bit 24-31 */
detect = snd_cmipci_read(cm, CM_REG_INT_HLDCLR) & CM_CHIP_MASK2;
if (! detect) {
/* check reg 08h, bit 24-28 */
detect = snd_cmipci_read(cm, CM_REG_CHFORMAT) & CM_CHIP_MASK1;
switch (detect) {
case 0:
cm->chip_version = 33;
if (cm->do_soft_ac3)
cm->can_ac3_sw = 1;
else
cm->can_ac3_hw = 1;
break;
case CM_CHIP_037:
cm->chip_version = 37;
cm->can_ac3_hw = 1;
break;
default:
cm->chip_version = 39;
cm->can_ac3_hw = 1;
break;
}
cm->max_channels = 2;
} else {
if (detect & CM_CHIP_039) {
cm->chip_version = 39;
if (detect & CM_CHIP_039_6CH) /* 4 or 6 channels */
cm->max_channels = 6;
else
cm->max_channels = 4;
} else if (detect & CM_CHIP_8768) {
cm->chip_version = 68;
cm->max_channels = 8;
cm->can_96k = 1;
} else {
cm->chip_version = 55;
cm->max_channels = 6;
cm->can_96k = 1;
}
cm->can_ac3_hw = 1;
cm->can_multi_ch = 1;
}
}
#ifdef SUPPORT_JOYSTICK
static int __devinit snd_cmipci_create_gameport(struct cmipci *cm, int dev)
{
static int ports[] = { 0x201, 0x200, 0 }; /* FIXME: majority is 0x201? */
struct gameport *gp;
struct resource *r = NULL;
int i, io_port = 0;
if (joystick_port[dev] == 0)
return -ENODEV;
if (joystick_port[dev] == 1) { /* auto-detect */
for (i = 0; ports[i]; i++) {
io_port = ports[i];
r = request_region(io_port, 1, "CMIPCI gameport");
if (r)
break;
}
} else {
io_port = joystick_port[dev];
r = request_region(io_port, 1, "CMIPCI gameport");
}
if (!r) {
printk(KERN_WARNING "cmipci: cannot reserve joystick ports\n");
return -EBUSY;
}
cm->gameport = gp = gameport_allocate_port();
if (!gp) {
printk(KERN_ERR "cmipci: cannot allocate memory for gameport\n");
release_and_free_resource(r);
return -ENOMEM;
}
gameport_set_name(gp, "C-Media Gameport");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(cm->pci));
gameport_set_dev_parent(gp, &cm->pci->dev);
gp->io = io_port;
gameport_set_port_data(gp, r);
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
gameport_register_port(cm->gameport);
return 0;
}
static void snd_cmipci_free_gameport(struct cmipci *cm)
{
if (cm->gameport) {
struct resource *r = gameport_get_port_data(cm->gameport);
gameport_unregister_port(cm->gameport);
cm->gameport = NULL;
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
release_and_free_resource(r);
}
}
#else
static inline int snd_cmipci_create_gameport(struct cmipci *cm, int dev) { return -ENOSYS; }
static inline void snd_cmipci_free_gameport(struct cmipci *cm) { }
#endif
static int snd_cmipci_free(struct cmipci *cm)
{
if (cm->irq >= 0) {
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT);
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0); /* disable ints */
snd_cmipci_ch_reset(cm, CM_CH_PLAY);
snd_cmipci_ch_reset(cm, CM_CH_CAPT);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, 0); /* disable channels */
snd_cmipci_write(cm, CM_REG_FUNCTRL1, 0);
/* reset mixer */
snd_cmipci_mixer_write(cm, 0, 0);
free_irq(cm->irq, cm);
}
snd_cmipci_free_gameport(cm);
pci_release_regions(cm->pci);
pci_disable_device(cm->pci);
kfree(cm);
return 0;
}
static int snd_cmipci_dev_free(struct snd_device *device)
{
struct cmipci *cm = device->device_data;
return snd_cmipci_free(cm);
}
static int __devinit snd_cmipci_create_fm(struct cmipci *cm, long fm_port)
{
long iosynth;
unsigned int val;
struct snd_opl3 *opl3;
int err;
if (!fm_port)
goto disable_fm;
if (cm->chip_version >= 39) {
/* first try FM regs in PCI port range */
iosynth = cm->iobase + CM_REG_FM_PCI;
err = snd_opl3_create(cm->card, iosynth, iosynth + 2,
OPL3_HW_OPL3, 1, &opl3);
} else {
err = -EIO;
}
if (err < 0) {
/* then try legacy ports */
val = snd_cmipci_read(cm, CM_REG_LEGACY_CTRL) & ~CM_FMSEL_MASK;
iosynth = fm_port;
switch (iosynth) {
case 0x3E8: val |= CM_FMSEL_3E8; break;
case 0x3E0: val |= CM_FMSEL_3E0; break;
case 0x3C8: val |= CM_FMSEL_3C8; break;
case 0x388: val |= CM_FMSEL_388; break;
default:
goto disable_fm;
}
snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val);
/* enable FM */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
if (snd_opl3_create(cm->card, iosynth, iosynth + 2,
OPL3_HW_OPL3, 0, &opl3) < 0) {
printk(KERN_ERR "cmipci: no OPL device at %#lx, "
"skipping...\n", iosynth);
goto disable_fm;
}
}
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
printk(KERN_ERR "cmipci: cannot create OPL3 hwdep\n");
return err;
}
return 0;
disable_fm:
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_FMSEL_MASK);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
return 0;
}
static int __devinit snd_cmipci_create(struct snd_card *card, struct pci_dev *pci,
int dev, struct cmipci **rcmipci)
{
struct cmipci *cm;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_cmipci_dev_free,
};
unsigned int val;
long iomidi = 0;
int integrated_midi = 0;
char modelstr[16];
int pcm_index, pcm_spdif_index;
static DEFINE_PCI_DEVICE_TABLE(intel_82437vx) = {
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437VX) },
{ },
};
*rcmipci = NULL;
if ((err = pci_enable_device(pci)) < 0)
return err;
cm = kzalloc(sizeof(*cm), GFP_KERNEL);
if (cm == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&cm->reg_lock);
mutex_init(&cm->open_mutex);
cm->device = pci->device;
cm->card = card;
cm->pci = pci;
cm->irq = -1;
cm->channel[0].ch = 0;
cm->channel[1].ch = 1;
cm->channel[0].is_dac = cm->channel[1].is_dac = 1; /* dual DAC mode */
if ((err = pci_request_regions(pci, card->driver)) < 0) {
kfree(cm);
pci_disable_device(pci);
return err;
}
cm->iobase = pci_resource_start(pci, 0);
if (request_irq(pci->irq, snd_cmipci_interrupt,
IRQF_SHARED, KBUILD_MODNAME, cm)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_cmipci_free(cm);
return -EBUSY;
}
cm->irq = pci->irq;
pci_set_master(cm->pci);
/*
* check chip version, max channels and capabilities
*/
cm->chip_version = 0;
cm->max_channels = 2;
cm->do_soft_ac3 = soft_ac3[dev];
if (pci->device != PCI_DEVICE_ID_CMEDIA_CM8338A &&
pci->device != PCI_DEVICE_ID_CMEDIA_CM8338B)
query_chip(cm);
/* added -MCx suffix for chip supporting multi-channels */
if (cm->can_multi_ch)
sprintf(cm->card->driver + strlen(cm->card->driver),
"-MC%d", cm->max_channels);
else if (cm->can_ac3_sw)
strcpy(cm->card->driver + strlen(cm->card->driver), "-SWIEC");
cm->dig_status = SNDRV_PCM_DEFAULT_CON_SPDIF;
cm->dig_pcm_status = SNDRV_PCM_DEFAULT_CON_SPDIF;
#if CM_CH_PLAY == 1
cm->ctrl = CM_CHADC0; /* default FUNCNTRL0 */
#else
cm->ctrl = CM_CHADC1; /* default FUNCNTRL0 */
#endif
/* initialize codec registers */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_RESET);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_RESET);
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0); /* disable ints */
snd_cmipci_ch_reset(cm, CM_CH_PLAY);
snd_cmipci_ch_reset(cm, CM_CH_CAPT);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, 0); /* disable channels */
snd_cmipci_write(cm, CM_REG_FUNCTRL1, 0);
snd_cmipci_write(cm, CM_REG_CHFORMAT, 0);
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC|CM_N4SPK3D);
#if CM_CH_PLAY == 1
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
#else
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
#endif
if (cm->chip_version) {
snd_cmipci_write_b(cm, CM_REG_EXT_MISC, 0x20); /* magic */
snd_cmipci_write_b(cm, CM_REG_EXT_MISC + 1, 0x09); /* more magic */
}
/* Set Bus Master Request */
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_BREQ);
/* Assume TX and compatible chip set (Autodetection required for VX chip sets) */
switch (pci->device) {
case PCI_DEVICE_ID_CMEDIA_CM8738:
case PCI_DEVICE_ID_CMEDIA_CM8738B:
if (!pci_dev_present(intel_82437vx))
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_TXVX);
break;
default:
break;
}
if (cm->chip_version < 68) {
val = pci->device < 0x110 ? 8338 : 8738;
} else {
switch (snd_cmipci_read_b(cm, CM_REG_INT_HLDCLR + 3) & 0x03) {
case 0:
val = 8769;
break;
case 2:
val = 8762;
break;
default:
switch ((pci->subsystem_vendor << 16) |
pci->subsystem_device) {
case 0x13f69761:
case 0x584d3741:
case 0x584d3751:
case 0x584d3761:
case 0x584d3771:
case 0x72848384:
val = 8770;
break;
default:
val = 8768;
break;
}
}
}
sprintf(card->shortname, "C-Media CMI%d", val);
if (cm->chip_version < 68)
sprintf(modelstr, " (model %d)", cm->chip_version);
else
modelstr[0] = '\0';
sprintf(card->longname, "%s%s at %#lx, irq %i",
card->shortname, modelstr, cm->iobase, cm->irq);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, cm, &ops)) < 0) {
snd_cmipci_free(cm);
return err;
}
if (cm->chip_version >= 39) {
val = snd_cmipci_read_b(cm, CM_REG_MPU_PCI + 1);
if (val != 0x00 && val != 0xff) {
iomidi = cm->iobase + CM_REG_MPU_PCI;
integrated_midi = 1;
}
}
if (!integrated_midi) {
val = 0;
iomidi = mpu_port[dev];
switch (iomidi) {
case 0x320: val = CM_VMPU_320; break;
case 0x310: val = CM_VMPU_310; break;
case 0x300: val = CM_VMPU_300; break;
case 0x330: val = CM_VMPU_330; break;
default:
iomidi = 0; break;
}
if (iomidi > 0) {
snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val);
/* enable UART */
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_UART_EN);
if (inb(iomidi + 1) == 0xff) {
snd_printk(KERN_ERR "cannot enable MPU-401 port"
" at %#lx\n", iomidi);
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1,
CM_UART_EN);
iomidi = 0;
}
}
}
if (cm->chip_version < 68) {
err = snd_cmipci_create_fm(cm, fm_port[dev]);
if (err < 0)
return err;
}
/* reset mixer */
snd_cmipci_mixer_write(cm, 0, 0);
snd_cmipci_proc_init(cm);
/* create pcm devices */
pcm_index = pcm_spdif_index = 0;
if ((err = snd_cmipci_pcm_new(cm, pcm_index)) < 0)
return err;
pcm_index++;
if ((err = snd_cmipci_pcm2_new(cm, pcm_index)) < 0)
return err;
pcm_index++;
if (cm->can_ac3_hw || cm->can_ac3_sw) {
pcm_spdif_index = pcm_index;
if ((err = snd_cmipci_pcm_spdif_new(cm, pcm_index)) < 0)
return err;
}
/* create mixer interface & switches */
if ((err = snd_cmipci_mixer_new(cm, pcm_spdif_index)) < 0)
return err;
if (iomidi > 0) {
if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_CMIPCI,
iomidi,
(integrated_midi ?
MPU401_INFO_INTEGRATED : 0) |
MPU401_INFO_IRQ_HOOK,
-1, &cm->rmidi)) < 0) {
printk(KERN_ERR "cmipci: no UART401 device at 0x%lx\n", iomidi);
}
}
#ifdef USE_VAR48KRATE
for (val = 0; val < ARRAY_SIZE(rates); val++)
snd_cmipci_set_pll(cm, rates[val], val);
/*
* (Re-)Enable external switch spdo_48k
*/
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K|CM_SPDF_AC97);
#endif /* USE_VAR48KRATE */
if (snd_cmipci_create_gameport(cm, dev) < 0)
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
snd_card_set_dev(card, &pci->dev);
*rcmipci = cm;
return 0;
}
/*
*/
MODULE_DEVICE_TABLE(pci, snd_cmipci_ids);
static int __devinit snd_cmipci_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct cmipci *cm;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (! enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
switch (pci->device) {
case PCI_DEVICE_ID_CMEDIA_CM8738:
case PCI_DEVICE_ID_CMEDIA_CM8738B:
strcpy(card->driver, "CMI8738");
break;
case PCI_DEVICE_ID_CMEDIA_CM8338A:
case PCI_DEVICE_ID_CMEDIA_CM8338B:
strcpy(card->driver, "CMI8338");
break;
default:
strcpy(card->driver, "CMIPCI");
break;
}
if ((err = snd_cmipci_create(card, pci, dev, &cm)) < 0) {
snd_card_free(card);
return err;
}
card->private_data = cm;
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void __devexit snd_cmipci_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
#ifdef CONFIG_PM
/*
* power management
*/
static unsigned char saved_regs[] = {
CM_REG_FUNCTRL1, CM_REG_CHFORMAT, CM_REG_LEGACY_CTRL, CM_REG_MISC_CTRL,
CM_REG_MIXER0, CM_REG_MIXER1, CM_REG_MIXER2, CM_REG_MIXER3, CM_REG_PLL,
CM_REG_CH0_FRAME1, CM_REG_CH0_FRAME2,
CM_REG_CH1_FRAME1, CM_REG_CH1_FRAME2, CM_REG_EXT_MISC,
CM_REG_INT_STATUS, CM_REG_INT_HLDCLR, CM_REG_FUNCTRL0,
};
static unsigned char saved_mixers[] = {
SB_DSP4_MASTER_DEV, SB_DSP4_MASTER_DEV + 1,
SB_DSP4_PCM_DEV, SB_DSP4_PCM_DEV + 1,
SB_DSP4_SYNTH_DEV, SB_DSP4_SYNTH_DEV + 1,
SB_DSP4_CD_DEV, SB_DSP4_CD_DEV + 1,
SB_DSP4_LINE_DEV, SB_DSP4_LINE_DEV + 1,
SB_DSP4_MIC_DEV, SB_DSP4_SPEAKER_DEV,
CM_REG_EXTENT_IND, SB_DSP4_OUTPUT_SW,
SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT,
};
static int snd_cmipci_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct cmipci *cm = card->private_data;
int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(cm->pcm);
snd_pcm_suspend_all(cm->pcm2);
snd_pcm_suspend_all(cm->pcm_spdif);
/* save registers */
for (i = 0; i < ARRAY_SIZE(saved_regs); i++)
cm->saved_regs[i] = snd_cmipci_read(cm, saved_regs[i]);
for (i = 0; i < ARRAY_SIZE(saved_mixers); i++)
cm->saved_mixers[i] = snd_cmipci_mixer_read(cm, saved_mixers[i]);
/* disable ints */
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int snd_cmipci_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct cmipci *cm = card->private_data;
int i;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "cmipci: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
/* reset / initialize to a sane state */
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0);
snd_cmipci_ch_reset(cm, CM_CH_PLAY);
snd_cmipci_ch_reset(cm, CM_CH_CAPT);
snd_cmipci_mixer_write(cm, 0, 0);
/* restore registers */
for (i = 0; i < ARRAY_SIZE(saved_regs); i++)
snd_cmipci_write(cm, saved_regs[i], cm->saved_regs[i]);
for (i = 0; i < ARRAY_SIZE(saved_mixers); i++)
snd_cmipci_mixer_write(cm, saved_mixers[i], cm->saved_mixers[i]);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver driver = {
.name = KBUILD_MODNAME,
.id_table = snd_cmipci_ids,
.probe = snd_cmipci_probe,
.remove = __devexit_p(snd_cmipci_remove),
#ifdef CONFIG_PM
.suspend = snd_cmipci_suspend,
.resume = snd_cmipci_resume,
#endif
};
static int __init alsa_card_cmipci_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_cmipci_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_cmipci_init)
module_exit(alsa_card_cmipci_exit)
| gpl-2.0 |
turtlekiosk/coms4118 | sound/pci/cmipci.c | 4894 | 104405 | /*
* Driver for C-Media CMI8338 and 8738 PCI soundcards.
* Copyright (c) 2000 by Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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
*/
/* Does not work. Warning may block system in capture mode */
/* #define USE_VAR48KRATE */
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/sb.h>
#include <sound/asoundef.h>
#include <sound/initval.h>
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("C-Media CMI8x38 PCI");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{C-Media,CMI8738},"
"{C-Media,CMI8738B},"
"{C-Media,CMI8338A},"
"{C-Media,CMI8338B}}");
#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
#define SUPPORT_JOYSTICK 1
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable switches */
static long mpu_port[SNDRV_CARDS];
static long fm_port[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)]=1};
static bool soft_ac3[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)]=1};
#ifdef SUPPORT_JOYSTICK
static int joystick_port[SNDRV_CARDS];
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for C-Media PCI soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for C-Media PCI soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable C-Media PCI soundcard.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port.");
module_param_array(soft_ac3, bool, NULL, 0444);
MODULE_PARM_DESC(soft_ac3, "Software-conversion of raw SPDIF packets (model 033 only).");
#ifdef SUPPORT_JOYSTICK
module_param_array(joystick_port, int, NULL, 0444);
MODULE_PARM_DESC(joystick_port, "Joystick port address.");
#endif
/*
* CM8x38 registers definition
*/
#define CM_REG_FUNCTRL0 0x00
#define CM_RST_CH1 0x00080000
#define CM_RST_CH0 0x00040000
#define CM_CHEN1 0x00020000 /* ch1: enable */
#define CM_CHEN0 0x00010000 /* ch0: enable */
#define CM_PAUSE1 0x00000008 /* ch1: pause */
#define CM_PAUSE0 0x00000004 /* ch0: pause */
#define CM_CHADC1 0x00000002 /* ch1, 0:playback, 1:record */
#define CM_CHADC0 0x00000001 /* ch0, 0:playback, 1:record */
#define CM_REG_FUNCTRL1 0x04
#define CM_DSFC_MASK 0x0000E000 /* channel 1 (DAC?) sampling frequency */
#define CM_DSFC_SHIFT 13
#define CM_ASFC_MASK 0x00001C00 /* channel 0 (ADC?) sampling frequency */
#define CM_ASFC_SHIFT 10
#define CM_SPDF_1 0x00000200 /* SPDIF IN/OUT at channel B */
#define CM_SPDF_0 0x00000100 /* SPDIF OUT only channel A */
#define CM_SPDFLOOP 0x00000080 /* ext. SPDIIF/IN -> OUT loopback */
#define CM_SPDO2DAC 0x00000040 /* SPDIF/OUT can be heard from internal DAC */
#define CM_INTRM 0x00000020 /* master control block (MCB) interrupt enabled */
#define CM_BREQ 0x00000010 /* bus master enabled */
#define CM_VOICE_EN 0x00000008 /* legacy voice (SB16,FM) */
#define CM_UART_EN 0x00000004 /* legacy UART */
#define CM_JYSTK_EN 0x00000002 /* legacy joystick */
#define CM_ZVPORT 0x00000001 /* ZVPORT */
#define CM_REG_CHFORMAT 0x08
#define CM_CHB3D5C 0x80000000 /* 5,6 channels */
#define CM_FMOFFSET2 0x40000000 /* initial FM PCM offset 2 when Fmute=1 */
#define CM_CHB3D 0x20000000 /* 4 channels */
#define CM_CHIP_MASK1 0x1f000000
#define CM_CHIP_037 0x01000000
#define CM_SETLAT48 0x00800000 /* set latency timer 48h */
#define CM_EDGEIRQ 0x00400000 /* emulated edge trigger legacy IRQ */
#define CM_SPD24SEL39 0x00200000 /* 24-bit spdif: model 039 */
#define CM_AC3EN1 0x00100000 /* enable AC3: model 037 */
#define CM_SPDIF_SELECT1 0x00080000 /* for model <= 037 ? */
#define CM_SPD24SEL 0x00020000 /* 24bit spdif: model 037 */
/* #define CM_SPDIF_INVERSE 0x00010000 */ /* ??? */
#define CM_ADCBITLEN_MASK 0x0000C000
#define CM_ADCBITLEN_16 0x00000000
#define CM_ADCBITLEN_15 0x00004000
#define CM_ADCBITLEN_14 0x00008000
#define CM_ADCBITLEN_13 0x0000C000
#define CM_ADCDACLEN_MASK 0x00003000 /* model 037 */
#define CM_ADCDACLEN_060 0x00000000
#define CM_ADCDACLEN_066 0x00001000
#define CM_ADCDACLEN_130 0x00002000
#define CM_ADCDACLEN_280 0x00003000
#define CM_ADCDLEN_MASK 0x00003000 /* model 039 */
#define CM_ADCDLEN_ORIGINAL 0x00000000
#define CM_ADCDLEN_EXTRA 0x00001000
#define CM_ADCDLEN_24K 0x00002000
#define CM_ADCDLEN_WEIGHT 0x00003000
#define CM_CH1_SRATE_176K 0x00000800
#define CM_CH1_SRATE_96K 0x00000800 /* model 055? */
#define CM_CH1_SRATE_88K 0x00000400
#define CM_CH0_SRATE_176K 0x00000200
#define CM_CH0_SRATE_96K 0x00000200 /* model 055? */
#define CM_CH0_SRATE_88K 0x00000100
#define CM_CH0_SRATE_128K 0x00000300
#define CM_CH0_SRATE_MASK 0x00000300
#define CM_SPDIF_INVERSE2 0x00000080 /* model 055? */
#define CM_DBLSPDS 0x00000040 /* double SPDIF sample rate 88.2/96 */
#define CM_POLVALID 0x00000020 /* inverse SPDIF/IN valid bit */
#define CM_SPDLOCKED 0x00000010
#define CM_CH1FMT_MASK 0x0000000C /* bit 3: 16 bits, bit 2: stereo */
#define CM_CH1FMT_SHIFT 2
#define CM_CH0FMT_MASK 0x00000003 /* bit 1: 16 bits, bit 0: stereo */
#define CM_CH0FMT_SHIFT 0
#define CM_REG_INT_HLDCLR 0x0C
#define CM_CHIP_MASK2 0xff000000
#define CM_CHIP_8768 0x20000000
#define CM_CHIP_055 0x08000000
#define CM_CHIP_039 0x04000000
#define CM_CHIP_039_6CH 0x01000000
#define CM_UNKNOWN_INT_EN 0x00080000 /* ? */
#define CM_TDMA_INT_EN 0x00040000
#define CM_CH1_INT_EN 0x00020000
#define CM_CH0_INT_EN 0x00010000
#define CM_REG_INT_STATUS 0x10
#define CM_INTR 0x80000000
#define CM_VCO 0x08000000 /* Voice Control? CMI8738 */
#define CM_MCBINT 0x04000000 /* Master Control Block abort cond.? */
#define CM_UARTINT 0x00010000
#define CM_LTDMAINT 0x00008000
#define CM_HTDMAINT 0x00004000
#define CM_XDO46 0x00000080 /* Modell 033? Direct programming EEPROM (read data register) */
#define CM_LHBTOG 0x00000040 /* High/Low status from DMA ctrl register */
#define CM_LEG_HDMA 0x00000020 /* Legacy is in High DMA channel */
#define CM_LEG_STEREO 0x00000010 /* Legacy is in Stereo mode */
#define CM_CH1BUSY 0x00000008
#define CM_CH0BUSY 0x00000004
#define CM_CHINT1 0x00000002
#define CM_CHINT0 0x00000001
#define CM_REG_LEGACY_CTRL 0x14
#define CM_NXCHG 0x80000000 /* don't map base reg dword->sample */
#define CM_VMPU_MASK 0x60000000 /* MPU401 i/o port address */
#define CM_VMPU_330 0x00000000
#define CM_VMPU_320 0x20000000
#define CM_VMPU_310 0x40000000
#define CM_VMPU_300 0x60000000
#define CM_ENWR8237 0x10000000 /* enable bus master to write 8237 base reg */
#define CM_VSBSEL_MASK 0x0C000000 /* SB16 base address */
#define CM_VSBSEL_220 0x00000000
#define CM_VSBSEL_240 0x04000000
#define CM_VSBSEL_260 0x08000000
#define CM_VSBSEL_280 0x0C000000
#define CM_FMSEL_MASK 0x03000000 /* FM OPL3 base address */
#define CM_FMSEL_388 0x00000000
#define CM_FMSEL_3C8 0x01000000
#define CM_FMSEL_3E0 0x02000000
#define CM_FMSEL_3E8 0x03000000
#define CM_ENSPDOUT 0x00800000 /* enable XSPDIF/OUT to I/O interface */
#define CM_SPDCOPYRHT 0x00400000 /* spdif in/out copyright bit */
#define CM_DAC2SPDO 0x00200000 /* enable wave+fm_midi -> SPDIF/OUT */
#define CM_INVIDWEN 0x00100000 /* internal vendor ID write enable, model 039? */
#define CM_SETRETRY 0x00100000 /* 0: legacy i/o wait (default), 1: legacy i/o bus retry */
#define CM_C_EEACCESS 0x00080000 /* direct programming eeprom regs */
#define CM_C_EECS 0x00040000
#define CM_C_EEDI46 0x00020000
#define CM_C_EECK46 0x00010000
#define CM_CHB3D6C 0x00008000 /* 5.1 channels support */
#define CM_CENTR2LIN 0x00004000 /* line-in as center out */
#define CM_BASE2LIN 0x00002000 /* line-in as bass out */
#define CM_EXBASEN 0x00001000 /* external bass input enable */
#define CM_REG_MISC_CTRL 0x18
#define CM_PWD 0x80000000 /* power down */
#define CM_RESET 0x40000000
#define CM_SFIL_MASK 0x30000000 /* filter control at front end DAC, model 037? */
#define CM_VMGAIN 0x10000000 /* analog master amp +6dB, model 039? */
#define CM_TXVX 0x08000000 /* model 037? */
#define CM_N4SPK3D 0x04000000 /* copy front to rear */
#define CM_SPDO5V 0x02000000 /* 5V spdif output (1 = 0.5v (coax)) */
#define CM_SPDIF48K 0x01000000 /* write */
#define CM_SPATUS48K 0x01000000 /* read */
#define CM_ENDBDAC 0x00800000 /* enable double dac */
#define CM_XCHGDAC 0x00400000 /* 0: front=ch0, 1: front=ch1 */
#define CM_SPD32SEL 0x00200000 /* 0: 16bit SPDIF, 1: 32bit */
#define CM_SPDFLOOPI 0x00100000 /* int. SPDIF-OUT -> int. IN */
#define CM_FM_EN 0x00080000 /* enable legacy FM */
#define CM_AC3EN2 0x00040000 /* enable AC3: model 039 */
#define CM_ENWRASID 0x00010000 /* choose writable internal SUBID (audio) */
#define CM_VIDWPDSB 0x00010000 /* model 037? */
#define CM_SPDF_AC97 0x00008000 /* 0: SPDIF/OUT 44.1K, 1: 48K */
#define CM_MASK_EN 0x00004000 /* activate channel mask on legacy DMA */
#define CM_ENWRMSID 0x00002000 /* choose writable internal SUBID (modem) */
#define CM_VIDWPPRT 0x00002000 /* model 037? */
#define CM_SFILENB 0x00001000 /* filter stepping at front end DAC, model 037? */
#define CM_MMODE_MASK 0x00000E00 /* model DAA interface mode */
#define CM_SPDIF_SELECT2 0x00000100 /* for model > 039 ? */
#define CM_ENCENTER 0x00000080
#define CM_FLINKON 0x00000040 /* force modem link detection on, model 037 */
#define CM_MUTECH1 0x00000040 /* mute PCI ch1 to DAC */
#define CM_FLINKOFF 0x00000020 /* force modem link detection off, model 037 */
#define CM_MIDSMP 0x00000010 /* 1/2 interpolation at front end DAC */
#define CM_UPDDMA_MASK 0x0000000C /* TDMA position update notification */
#define CM_UPDDMA_2048 0x00000000
#define CM_UPDDMA_1024 0x00000004
#define CM_UPDDMA_512 0x00000008
#define CM_UPDDMA_256 0x0000000C
#define CM_TWAIT_MASK 0x00000003 /* model 037 */
#define CM_TWAIT1 0x00000002 /* FM i/o cycle, 0: 48, 1: 64 PCICLKs */
#define CM_TWAIT0 0x00000001 /* i/o cycle, 0: 4, 1: 6 PCICLKs */
#define CM_REG_TDMA_POSITION 0x1C
#define CM_TDMA_CNT_MASK 0xFFFF0000 /* current byte/word count */
#define CM_TDMA_ADR_MASK 0x0000FFFF /* current address */
/* byte */
#define CM_REG_MIXER0 0x20
#define CM_REG_SBVR 0x20 /* write: sb16 version */
#define CM_REG_DEV 0x20 /* read: hardware device version */
#define CM_REG_MIXER21 0x21
#define CM_UNKNOWN_21_MASK 0x78 /* ? */
#define CM_X_ADPCM 0x04 /* SB16 ADPCM enable */
#define CM_PROINV 0x02 /* SBPro left/right channel switching */
#define CM_X_SB16 0x01 /* SB16 compatible */
#define CM_REG_SB16_DATA 0x22
#define CM_REG_SB16_ADDR 0x23
#define CM_REFFREQ_XIN (315*1000*1000)/22 /* 14.31818 Mhz reference clock frequency pin XIN */
#define CM_ADCMULT_XIN 512 /* Guessed (487 best for 44.1kHz, not for 88/176kHz) */
#define CM_TOLERANCE_RATE 0.001 /* Tolerance sample rate pitch (1000ppm) */
#define CM_MAXIMUM_RATE 80000000 /* Note more than 80MHz */
#define CM_REG_MIXER1 0x24
#define CM_FMMUTE 0x80 /* mute FM */
#define CM_FMMUTE_SHIFT 7
#define CM_WSMUTE 0x40 /* mute PCM */
#define CM_WSMUTE_SHIFT 6
#define CM_REAR2LIN 0x20 /* lin-in -> rear line out */
#define CM_REAR2LIN_SHIFT 5
#define CM_REAR2FRONT 0x10 /* exchange rear/front */
#define CM_REAR2FRONT_SHIFT 4
#define CM_WAVEINL 0x08 /* digital wave rec. left chan */
#define CM_WAVEINL_SHIFT 3
#define CM_WAVEINR 0x04 /* digical wave rec. right */
#define CM_WAVEINR_SHIFT 2
#define CM_X3DEN 0x02 /* 3D surround enable */
#define CM_X3DEN_SHIFT 1
#define CM_CDPLAY 0x01 /* enable SPDIF/IN PCM -> DAC */
#define CM_CDPLAY_SHIFT 0
#define CM_REG_MIXER2 0x25
#define CM_RAUXREN 0x80 /* AUX right capture */
#define CM_RAUXREN_SHIFT 7
#define CM_RAUXLEN 0x40 /* AUX left capture */
#define CM_RAUXLEN_SHIFT 6
#define CM_VAUXRM 0x20 /* AUX right mute */
#define CM_VAUXRM_SHIFT 5
#define CM_VAUXLM 0x10 /* AUX left mute */
#define CM_VAUXLM_SHIFT 4
#define CM_VADMIC_MASK 0x0e /* mic gain level (0-3) << 1 */
#define CM_VADMIC_SHIFT 1
#define CM_MICGAINZ 0x01 /* mic boost */
#define CM_MICGAINZ_SHIFT 0
#define CM_REG_MIXER3 0x24
#define CM_REG_AUX_VOL 0x26
#define CM_VAUXL_MASK 0xf0
#define CM_VAUXR_MASK 0x0f
#define CM_REG_MISC 0x27
#define CM_UNKNOWN_27_MASK 0xd8 /* ? */
#define CM_XGPO1 0x20
// #define CM_XGPBIO 0x04
#define CM_MIC_CENTER_LFE 0x04 /* mic as center/lfe out? (model 039 or later?) */
#define CM_SPDIF_INVERSE 0x04 /* spdif input phase inverse (model 037) */
#define CM_SPDVALID 0x02 /* spdif input valid check */
#define CM_DMAUTO 0x01 /* SB16 DMA auto detect */
#define CM_REG_AC97 0x28 /* hmmm.. do we have ac97 link? */
/*
* For CMI-8338 (0x28 - 0x2b) .. is this valid for CMI-8738
* or identical with AC97 codec?
*/
#define CM_REG_EXTERN_CODEC CM_REG_AC97
/*
* MPU401 pci port index address 0x40 - 0x4f (CMI-8738 spec ver. 0.6)
*/
#define CM_REG_MPU_PCI 0x40
/*
* FM pci port index address 0x50 - 0x5f (CMI-8738 spec ver. 0.6)
*/
#define CM_REG_FM_PCI 0x50
/*
* access from SB-mixer port
*/
#define CM_REG_EXTENT_IND 0xf0
#define CM_VPHONE_MASK 0xe0 /* Phone volume control (0-3) << 5 */
#define CM_VPHONE_SHIFT 5
#define CM_VPHOM 0x10 /* Phone mute control */
#define CM_VSPKM 0x08 /* Speaker mute control, default high */
#define CM_RLOOPREN 0x04 /* Rec. R-channel enable */
#define CM_RLOOPLEN 0x02 /* Rec. L-channel enable */
#define CM_VADMIC3 0x01 /* Mic record boost */
/*
* CMI-8338 spec ver 0.5 (this is not valid for CMI-8738):
* the 8 registers 0xf8 - 0xff are used for programming m/n counter by the PLL
* unit (readonly?).
*/
#define CM_REG_PLL 0xf8
/*
* extended registers
*/
#define CM_REG_CH0_FRAME1 0x80 /* write: base address */
#define CM_REG_CH0_FRAME2 0x84 /* read: current address */
#define CM_REG_CH1_FRAME1 0x88 /* 0-15: count of samples at bus master; buffer size */
#define CM_REG_CH1_FRAME2 0x8C /* 16-31: count of samples at codec; fragment size */
#define CM_REG_EXT_MISC 0x90
#define CM_ADC48K44K 0x10000000 /* ADC parameters group, 0: 44k, 1: 48k */
#define CM_CHB3D8C 0x00200000 /* 7.1 channels support */
#define CM_SPD32FMT 0x00100000 /* SPDIF/IN 32k sample rate */
#define CM_ADC2SPDIF 0x00080000 /* ADC output to SPDIF/OUT */
#define CM_SHAREADC 0x00040000 /* DAC in ADC as Center/LFE */
#define CM_REALTCMP 0x00020000 /* monitor the CMPL/CMPR of ADC */
#define CM_INVLRCK 0x00010000 /* invert ZVPORT's LRCK */
#define CM_UNKNOWN_90_MASK 0x0000FFFF /* ? */
/*
* size of i/o region
*/
#define CM_EXTENT_CODEC 0x100
#define CM_EXTENT_MIDI 0x2
#define CM_EXTENT_SYNTH 0x4
/*
* channels for playback / capture
*/
#define CM_CH_PLAY 0
#define CM_CH_CAPT 1
/*
* flags to check device open/close
*/
#define CM_OPEN_NONE 0
#define CM_OPEN_CH_MASK 0x01
#define CM_OPEN_DAC 0x10
#define CM_OPEN_ADC 0x20
#define CM_OPEN_SPDIF 0x40
#define CM_OPEN_MCHAN 0x80
#define CM_OPEN_PLAYBACK (CM_CH_PLAY | CM_OPEN_DAC)
#define CM_OPEN_PLAYBACK2 (CM_CH_CAPT | CM_OPEN_DAC)
#define CM_OPEN_PLAYBACK_MULTI (CM_CH_PLAY | CM_OPEN_DAC | CM_OPEN_MCHAN)
#define CM_OPEN_CAPTURE (CM_CH_CAPT | CM_OPEN_ADC)
#define CM_OPEN_SPDIF_PLAYBACK (CM_CH_PLAY | CM_OPEN_DAC | CM_OPEN_SPDIF)
#define CM_OPEN_SPDIF_CAPTURE (CM_CH_CAPT | CM_OPEN_ADC | CM_OPEN_SPDIF)
#if CM_CH_PLAY == 1
#define CM_PLAYBACK_SRATE_176K CM_CH1_SRATE_176K
#define CM_PLAYBACK_SPDF CM_SPDF_1
#define CM_CAPTURE_SPDF CM_SPDF_0
#else
#define CM_PLAYBACK_SRATE_176K CM_CH0_SRATE_176K
#define CM_PLAYBACK_SPDF CM_SPDF_0
#define CM_CAPTURE_SPDF CM_SPDF_1
#endif
/*
* driver data
*/
struct cmipci_pcm {
struct snd_pcm_substream *substream;
u8 running; /* dac/adc running? */
u8 fmt; /* format bits */
u8 is_dac;
u8 needs_silencing;
unsigned int dma_size; /* in frames */
unsigned int shift;
unsigned int ch; /* channel (0/1) */
unsigned int offset; /* physical address of the buffer */
};
/* mixer elements toggled/resumed during ac3 playback */
struct cmipci_mixer_auto_switches {
const char *name; /* switch to toggle */
int toggle_on; /* value to change when ac3 mode */
};
static const struct cmipci_mixer_auto_switches cm_saved_mixer[] = {
{"PCM Playback Switch", 0},
{"IEC958 Output Switch", 1},
{"IEC958 Mix Analog", 0},
// {"IEC958 Out To DAC", 1}, // no longer used
{"IEC958 Loop", 0},
};
#define CM_SAVED_MIXERS ARRAY_SIZE(cm_saved_mixer)
struct cmipci {
struct snd_card *card;
struct pci_dev *pci;
unsigned int device; /* device ID */
int irq;
unsigned long iobase;
unsigned int ctrl; /* FUNCTRL0 current value */
struct snd_pcm *pcm; /* DAC/ADC PCM */
struct snd_pcm *pcm2; /* 2nd DAC */
struct snd_pcm *pcm_spdif; /* SPDIF */
int chip_version;
int max_channels;
unsigned int can_ac3_sw: 1;
unsigned int can_ac3_hw: 1;
unsigned int can_multi_ch: 1;
unsigned int can_96k: 1; /* samplerate above 48k */
unsigned int do_soft_ac3: 1;
unsigned int spdif_playback_avail: 1; /* spdif ready? */
unsigned int spdif_playback_enabled: 1; /* spdif switch enabled? */
int spdif_counter; /* for software AC3 */
unsigned int dig_status;
unsigned int dig_pcm_status;
struct snd_pcm_hardware *hw_info[3]; /* for playbacks */
int opened[2]; /* open mode */
struct mutex open_mutex;
unsigned int mixer_insensitive: 1;
struct snd_kcontrol *mixer_res_ctl[CM_SAVED_MIXERS];
int mixer_res_status[CM_SAVED_MIXERS];
struct cmipci_pcm channel[2]; /* ch0 - DAC, ch1 - ADC or 2nd DAC */
/* external MIDI */
struct snd_rawmidi *rmidi;
#ifdef SUPPORT_JOYSTICK
struct gameport *gameport;
#endif
spinlock_t reg_lock;
#ifdef CONFIG_PM
unsigned int saved_regs[0x20];
unsigned char saved_mixers[0x20];
#endif
};
/* read/write operations for dword register */
static inline void snd_cmipci_write(struct cmipci *cm, unsigned int cmd, unsigned int data)
{
outl(data, cm->iobase + cmd);
}
static inline unsigned int snd_cmipci_read(struct cmipci *cm, unsigned int cmd)
{
return inl(cm->iobase + cmd);
}
/* read/write operations for word register */
static inline void snd_cmipci_write_w(struct cmipci *cm, unsigned int cmd, unsigned short data)
{
outw(data, cm->iobase + cmd);
}
static inline unsigned short snd_cmipci_read_w(struct cmipci *cm, unsigned int cmd)
{
return inw(cm->iobase + cmd);
}
/* read/write operations for byte register */
static inline void snd_cmipci_write_b(struct cmipci *cm, unsigned int cmd, unsigned char data)
{
outb(data, cm->iobase + cmd);
}
static inline unsigned char snd_cmipci_read_b(struct cmipci *cm, unsigned int cmd)
{
return inb(cm->iobase + cmd);
}
/* bit operations for dword register */
static int snd_cmipci_set_bit(struct cmipci *cm, unsigned int cmd, unsigned int flag)
{
unsigned int val, oval;
val = oval = inl(cm->iobase + cmd);
val |= flag;
if (val == oval)
return 0;
outl(val, cm->iobase + cmd);
return 1;
}
static int snd_cmipci_clear_bit(struct cmipci *cm, unsigned int cmd, unsigned int flag)
{
unsigned int val, oval;
val = oval = inl(cm->iobase + cmd);
val &= ~flag;
if (val == oval)
return 0;
outl(val, cm->iobase + cmd);
return 1;
}
/* bit operations for byte register */
static int snd_cmipci_set_bit_b(struct cmipci *cm, unsigned int cmd, unsigned char flag)
{
unsigned char val, oval;
val = oval = inb(cm->iobase + cmd);
val |= flag;
if (val == oval)
return 0;
outb(val, cm->iobase + cmd);
return 1;
}
static int snd_cmipci_clear_bit_b(struct cmipci *cm, unsigned int cmd, unsigned char flag)
{
unsigned char val, oval;
val = oval = inb(cm->iobase + cmd);
val &= ~flag;
if (val == oval)
return 0;
outb(val, cm->iobase + cmd);
return 1;
}
/*
* PCM interface
*/
/*
* calculate frequency
*/
static unsigned int rates[] = { 5512, 11025, 22050, 44100, 8000, 16000, 32000, 48000 };
static unsigned int snd_cmipci_rate_freq(unsigned int rate)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(rates); i++) {
if (rates[i] == rate)
return i;
}
snd_BUG();
return 0;
}
#ifdef USE_VAR48KRATE
/*
* Determine PLL values for frequency setup, maybe the CMI8338 (CMI8738???)
* does it this way .. maybe not. Never get any information from C-Media about
* that <werner@suse.de>.
*/
static int snd_cmipci_pll_rmn(unsigned int rate, unsigned int adcmult, int *r, int *m, int *n)
{
unsigned int delta, tolerance;
int xm, xn, xr;
for (*r = 0; rate < CM_MAXIMUM_RATE/adcmult; *r += (1<<5))
rate <<= 1;
*n = -1;
if (*r > 0xff)
goto out;
tolerance = rate*CM_TOLERANCE_RATE;
for (xn = (1+2); xn < (0x1f+2); xn++) {
for (xm = (1+2); xm < (0xff+2); xm++) {
xr = ((CM_REFFREQ_XIN/adcmult) * xm) / xn;
if (xr < rate)
delta = rate - xr;
else
delta = xr - rate;
/*
* If we found one, remember this,
* and try to find a closer one
*/
if (delta < tolerance) {
tolerance = delta;
*m = xm - 2;
*n = xn - 2;
}
}
}
out:
return (*n > -1);
}
/*
* Program pll register bits, I assume that the 8 registers 0xf8 up to 0xff
* are mapped onto the 8 ADC/DAC sampling frequency which can be chosen
* at the register CM_REG_FUNCTRL1 (0x04).
* Problem: other ways are also possible (any information about that?)
*/
static void snd_cmipci_set_pll(struct cmipci *cm, unsigned int rate, unsigned int slot)
{
unsigned int reg = CM_REG_PLL + slot;
/*
* Guess that this programs at reg. 0x04 the pos 15:13/12:10
* for DSFC/ASFC (000 up to 111).
*/
/* FIXME: Init (Do we've to set an other register first before programming?) */
/* FIXME: Is this correct? Or shouldn't the m/n/r values be used for that? */
snd_cmipci_write_b(cm, reg, rate>>8);
snd_cmipci_write_b(cm, reg, rate&0xff);
/* FIXME: Setup (Do we've to set an other register first to enable this?) */
}
#endif /* USE_VAR48KRATE */
static int snd_cmipci_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_cmipci_playback2_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
if (params_channels(hw_params) > 2) {
mutex_lock(&cm->open_mutex);
if (cm->opened[CM_CH_PLAY]) {
mutex_unlock(&cm->open_mutex);
return -EBUSY;
}
/* reserve the channel A */
cm->opened[CM_CH_PLAY] = CM_OPEN_PLAYBACK_MULTI;
mutex_unlock(&cm->open_mutex);
}
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static void snd_cmipci_ch_reset(struct cmipci *cm, int ch)
{
int reset = CM_RST_CH0 << (cm->channel[ch].ch);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | reset);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~reset);
udelay(10);
}
static int snd_cmipci_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
/*
*/
static unsigned int hw_channels[] = {1, 2, 4, 6, 8};
static struct snd_pcm_hw_constraint_list hw_constraints_channels_4 = {
.count = 3,
.list = hw_channels,
.mask = 0,
};
static struct snd_pcm_hw_constraint_list hw_constraints_channels_6 = {
.count = 4,
.list = hw_channels,
.mask = 0,
};
static struct snd_pcm_hw_constraint_list hw_constraints_channels_8 = {
.count = 5,
.list = hw_channels,
.mask = 0,
};
static int set_dac_channels(struct cmipci *cm, struct cmipci_pcm *rec, int channels)
{
if (channels > 2) {
if (!cm->can_multi_ch || !rec->ch)
return -EINVAL;
if (rec->fmt != 0x03) /* stereo 16bit only */
return -EINVAL;
}
if (cm->can_multi_ch) {
spin_lock_irq(&cm->reg_lock);
if (channels > 2) {
snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_NXCHG);
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
} else {
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_NXCHG);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
}
if (channels == 8)
snd_cmipci_set_bit(cm, CM_REG_EXT_MISC, CM_CHB3D8C);
else
snd_cmipci_clear_bit(cm, CM_REG_EXT_MISC, CM_CHB3D8C);
if (channels == 6) {
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
} else {
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
}
if (channels == 4)
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
else
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
spin_unlock_irq(&cm->reg_lock);
}
return 0;
}
/*
* prepare playback/capture channel
* channel to be used must have been set in rec->ch.
*/
static int snd_cmipci_pcm_prepare(struct cmipci *cm, struct cmipci_pcm *rec,
struct snd_pcm_substream *substream)
{
unsigned int reg, freq, freq_ext, val;
unsigned int period_size;
struct snd_pcm_runtime *runtime = substream->runtime;
rec->fmt = 0;
rec->shift = 0;
if (snd_pcm_format_width(runtime->format) >= 16) {
rec->fmt |= 0x02;
if (snd_pcm_format_width(runtime->format) > 16)
rec->shift++; /* 24/32bit */
}
if (runtime->channels > 1)
rec->fmt |= 0x01;
if (rec->is_dac && set_dac_channels(cm, rec, runtime->channels) < 0) {
snd_printd("cannot set dac channels\n");
return -EINVAL;
}
rec->offset = runtime->dma_addr;
/* buffer and period sizes in frame */
rec->dma_size = runtime->buffer_size << rec->shift;
period_size = runtime->period_size << rec->shift;
if (runtime->channels > 2) {
/* multi-channels */
rec->dma_size = (rec->dma_size * runtime->channels) / 2;
period_size = (period_size * runtime->channels) / 2;
}
spin_lock_irq(&cm->reg_lock);
/* set buffer address */
reg = rec->ch ? CM_REG_CH1_FRAME1 : CM_REG_CH0_FRAME1;
snd_cmipci_write(cm, reg, rec->offset);
/* program sample counts */
reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
snd_cmipci_write_w(cm, reg, rec->dma_size - 1);
snd_cmipci_write_w(cm, reg + 2, period_size - 1);
/* set adc/dac flag */
val = rec->ch ? CM_CHADC1 : CM_CHADC0;
if (rec->is_dac)
cm->ctrl &= ~val;
else
cm->ctrl |= val;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
//snd_printd("cmipci: functrl0 = %08x\n", cm->ctrl);
/* set sample rate */
freq = 0;
freq_ext = 0;
if (runtime->rate > 48000)
switch (runtime->rate) {
case 88200: freq_ext = CM_CH0_SRATE_88K; break;
case 96000: freq_ext = CM_CH0_SRATE_96K; break;
case 128000: freq_ext = CM_CH0_SRATE_128K; break;
default: snd_BUG(); break;
}
else
freq = snd_cmipci_rate_freq(runtime->rate);
val = snd_cmipci_read(cm, CM_REG_FUNCTRL1);
if (rec->ch) {
val &= ~CM_DSFC_MASK;
val |= (freq << CM_DSFC_SHIFT) & CM_DSFC_MASK;
} else {
val &= ~CM_ASFC_MASK;
val |= (freq << CM_ASFC_SHIFT) & CM_ASFC_MASK;
}
snd_cmipci_write(cm, CM_REG_FUNCTRL1, val);
//snd_printd("cmipci: functrl1 = %08x\n", val);
/* set format */
val = snd_cmipci_read(cm, CM_REG_CHFORMAT);
if (rec->ch) {
val &= ~CM_CH1FMT_MASK;
val |= rec->fmt << CM_CH1FMT_SHIFT;
} else {
val &= ~CM_CH0FMT_MASK;
val |= rec->fmt << CM_CH0FMT_SHIFT;
}
if (cm->can_96k) {
val &= ~(CM_CH0_SRATE_MASK << (rec->ch * 2));
val |= freq_ext << (rec->ch * 2);
}
snd_cmipci_write(cm, CM_REG_CHFORMAT, val);
//snd_printd("cmipci: chformat = %08x\n", val);
if (!rec->is_dac && cm->chip_version) {
if (runtime->rate > 44100)
snd_cmipci_set_bit(cm, CM_REG_EXT_MISC, CM_ADC48K44K);
else
snd_cmipci_clear_bit(cm, CM_REG_EXT_MISC, CM_ADC48K44K);
}
rec->running = 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
/*
* PCM trigger/stop
*/
static int snd_cmipci_pcm_trigger(struct cmipci *cm, struct cmipci_pcm *rec,
int cmd)
{
unsigned int inthld, chen, reset, pause;
int result = 0;
inthld = CM_CH0_INT_EN << rec->ch;
chen = CM_CHEN0 << rec->ch;
reset = CM_RST_CH0 << rec->ch;
pause = CM_PAUSE0 << rec->ch;
spin_lock(&cm->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
rec->running = 1;
/* set interrupt */
snd_cmipci_set_bit(cm, CM_REG_INT_HLDCLR, inthld);
cm->ctrl |= chen;
/* enable channel */
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
//snd_printd("cmipci: functrl0 = %08x\n", cm->ctrl);
break;
case SNDRV_PCM_TRIGGER_STOP:
rec->running = 0;
/* disable interrupt */
snd_cmipci_clear_bit(cm, CM_REG_INT_HLDCLR, inthld);
/* reset */
cm->ctrl &= ~chen;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | reset);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~reset);
rec->needs_silencing = rec->is_dac;
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
cm->ctrl |= pause;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
cm->ctrl &= ~pause;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&cm->reg_lock);
return result;
}
/*
* return the current pointer
*/
static snd_pcm_uframes_t snd_cmipci_pcm_pointer(struct cmipci *cm, struct cmipci_pcm *rec,
struct snd_pcm_substream *substream)
{
size_t ptr;
unsigned int reg, rem, tries;
if (!rec->running)
return 0;
#if 1 // this seems better..
reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
for (tries = 0; tries < 3; tries++) {
rem = snd_cmipci_read_w(cm, reg);
if (rem < rec->dma_size)
goto ok;
}
printk(KERN_ERR "cmipci: invalid PCM pointer: %#x\n", rem);
return SNDRV_PCM_POS_XRUN;
ok:
ptr = (rec->dma_size - (rem + 1)) >> rec->shift;
#else
reg = rec->ch ? CM_REG_CH1_FRAME1 : CM_REG_CH0_FRAME1;
ptr = snd_cmipci_read(cm, reg) - rec->offset;
ptr = bytes_to_frames(substream->runtime, ptr);
#endif
if (substream->runtime->channels > 2)
ptr = (ptr * 2) / substream->runtime->channels;
return ptr;
}
/*
* playback
*/
static int snd_cmipci_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_trigger(cm, &cm->channel[CM_CH_PLAY], cmd);
}
static snd_pcm_uframes_t snd_cmipci_playback_pointer(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_pointer(cm, &cm->channel[CM_CH_PLAY], substream);
}
/*
* capture
*/
static int snd_cmipci_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_trigger(cm, &cm->channel[CM_CH_CAPT], cmd);
}
static snd_pcm_uframes_t snd_cmipci_capture_pointer(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_pointer(cm, &cm->channel[CM_CH_CAPT], substream);
}
/*
* hw preparation for spdif
*/
static int snd_cmipci_spdif_default_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_cmipci_spdif_default_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
ucontrol->value.iec958.status[i] = (chip->dig_status >> (i * 8)) & 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cmipci_spdif_default_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i, change;
unsigned int val;
val = 0;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
val |= (unsigned int)ucontrol->value.iec958.status[i] << (i * 8);
change = val != chip->dig_status;
chip->dig_status = val;
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_cmipci_spdif_default __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = snd_cmipci_spdif_default_info,
.get = snd_cmipci_spdif_default_get,
.put = snd_cmipci_spdif_default_put
};
static int snd_cmipci_spdif_mask_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_cmipci_spdif_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.iec958.status[0] = 0xff;
ucontrol->value.iec958.status[1] = 0xff;
ucontrol->value.iec958.status[2] = 0xff;
ucontrol->value.iec958.status[3] = 0xff;
return 0;
}
static struct snd_kcontrol_new snd_cmipci_spdif_mask __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
.info = snd_cmipci_spdif_mask_info,
.get = snd_cmipci_spdif_mask_get,
};
static int snd_cmipci_spdif_stream_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_cmipci_spdif_stream_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
ucontrol->value.iec958.status[i] = (chip->dig_pcm_status >> (i * 8)) & 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cmipci_spdif_stream_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int i, change;
unsigned int val;
val = 0;
spin_lock_irq(&chip->reg_lock);
for (i = 0; i < 4; i++)
val |= (unsigned int)ucontrol->value.iec958.status[i] << (i * 8);
change = val != chip->dig_pcm_status;
chip->dig_pcm_status = val;
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_cmipci_spdif_stream __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
.info = snd_cmipci_spdif_stream_info,
.get = snd_cmipci_spdif_stream_get,
.put = snd_cmipci_spdif_stream_put
};
/*
*/
/* save mixer setting and mute for AC3 playback */
static int save_mixer_state(struct cmipci *cm)
{
if (! cm->mixer_insensitive) {
struct snd_ctl_elem_value *val;
unsigned int i;
val = kmalloc(sizeof(*val), GFP_ATOMIC);
if (!val)
return -ENOMEM;
for (i = 0; i < CM_SAVED_MIXERS; i++) {
struct snd_kcontrol *ctl = cm->mixer_res_ctl[i];
if (ctl) {
int event;
memset(val, 0, sizeof(*val));
ctl->get(ctl, val);
cm->mixer_res_status[i] = val->value.integer.value[0];
val->value.integer.value[0] = cm_saved_mixer[i].toggle_on;
event = SNDRV_CTL_EVENT_MASK_INFO;
if (cm->mixer_res_status[i] != val->value.integer.value[0]) {
ctl->put(ctl, val); /* toggle */
event |= SNDRV_CTL_EVENT_MASK_VALUE;
}
ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(cm->card, event, &ctl->id);
}
}
kfree(val);
cm->mixer_insensitive = 1;
}
return 0;
}
/* restore the previously saved mixer status */
static void restore_mixer_state(struct cmipci *cm)
{
if (cm->mixer_insensitive) {
struct snd_ctl_elem_value *val;
unsigned int i;
val = kmalloc(sizeof(*val), GFP_KERNEL);
if (!val)
return;
cm->mixer_insensitive = 0; /* at first clear this;
otherwise the changes will be ignored */
for (i = 0; i < CM_SAVED_MIXERS; i++) {
struct snd_kcontrol *ctl = cm->mixer_res_ctl[i];
if (ctl) {
int event;
memset(val, 0, sizeof(*val));
ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
ctl->get(ctl, val);
event = SNDRV_CTL_EVENT_MASK_INFO;
if (val->value.integer.value[0] != cm->mixer_res_status[i]) {
val->value.integer.value[0] = cm->mixer_res_status[i];
ctl->put(ctl, val);
event |= SNDRV_CTL_EVENT_MASK_VALUE;
}
snd_ctl_notify(cm->card, event, &ctl->id);
}
}
kfree(val);
}
}
/* spinlock held! */
static void setup_ac3(struct cmipci *cm, struct snd_pcm_substream *subs, int do_ac3, int rate)
{
if (do_ac3) {
/* AC3EN for 037 */
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_AC3EN1);
/* AC3EN for 039 */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_AC3EN2);
if (cm->can_ac3_hw) {
/* SPD24SEL for 037, 0x02 */
/* SPD24SEL for 039, 0x20, but cannot be set */
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
} else { /* can_ac3_sw */
/* SPD32SEL for 037 & 039, 0x20 */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
/* set 176K sample rate to fix 033 HW bug */
if (cm->chip_version == 33) {
if (rate >= 48000) {
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
} else {
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
}
}
}
} else {
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_AC3EN1);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_AC3EN2);
if (cm->can_ac3_hw) {
/* chip model >= 37 */
if (snd_pcm_format_width(subs->runtime->format) > 16) {
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
} else {
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
}
} else {
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
}
}
}
static int setup_spdif_playback(struct cmipci *cm, struct snd_pcm_substream *subs, int up, int do_ac3)
{
int rate, err;
rate = subs->runtime->rate;
if (up && do_ac3)
if ((err = save_mixer_state(cm)) < 0)
return err;
spin_lock_irq(&cm->reg_lock);
cm->spdif_playback_avail = up;
if (up) {
/* they are controlled via "IEC958 Output Switch" */
/* snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT); */
/* snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_SPDO2DAC); */
if (cm->spdif_playback_enabled)
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
setup_ac3(cm, subs, do_ac3, rate);
if (rate == 48000 || rate == 96000)
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K | CM_SPDF_AC97);
else
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K | CM_SPDF_AC97);
if (rate > 48000)
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
else
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
} else {
/* they are controlled via "IEC958 Output Switch" */
/* snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT); */
/* snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_SPDO2DAC); */
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
setup_ac3(cm, subs, 0, 0);
}
spin_unlock_irq(&cm->reg_lock);
return 0;
}
/*
* preparation
*/
/* playback - enable spdif only on the certain condition */
static int snd_cmipci_playback_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
int rate = substream->runtime->rate;
int err, do_spdif, do_ac3 = 0;
do_spdif = (rate >= 44100 && rate <= 96000 &&
substream->runtime->format == SNDRV_PCM_FORMAT_S16_LE &&
substream->runtime->channels == 2);
if (do_spdif && cm->can_ac3_hw)
do_ac3 = cm->dig_pcm_status & IEC958_AES0_NONAUDIO;
if ((err = setup_spdif_playback(cm, substream, do_spdif, do_ac3)) < 0)
return err;
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_PLAY], substream);
}
/* playback (via device #2) - enable spdif always */
static int snd_cmipci_playback_spdif_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
int err, do_ac3;
if (cm->can_ac3_hw)
do_ac3 = cm->dig_pcm_status & IEC958_AES0_NONAUDIO;
else
do_ac3 = 1; /* doesn't matter */
if ((err = setup_spdif_playback(cm, substream, 1, do_ac3)) < 0)
return err;
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_PLAY], substream);
}
/*
* Apparently, the samples last played on channel A stay in some buffer, even
* after the channel is reset, and get added to the data for the rear DACs when
* playing a multichannel stream on channel B. This is likely to generate
* wraparounds and thus distortions.
* To avoid this, we play at least one zero sample after the actual stream has
* stopped.
*/
static void snd_cmipci_silence_hack(struct cmipci *cm, struct cmipci_pcm *rec)
{
struct snd_pcm_runtime *runtime = rec->substream->runtime;
unsigned int reg, val;
if (rec->needs_silencing && runtime && runtime->dma_area) {
/* set up a small silence buffer */
memset(runtime->dma_area, 0, PAGE_SIZE);
reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
val = ((PAGE_SIZE / 4) - 1) | (((PAGE_SIZE / 4) / 2 - 1) << 16);
snd_cmipci_write(cm, reg, val);
/* configure for 16 bits, 2 channels, 8 kHz */
if (runtime->channels > 2)
set_dac_channels(cm, rec, 2);
spin_lock_irq(&cm->reg_lock);
val = snd_cmipci_read(cm, CM_REG_FUNCTRL1);
val &= ~(CM_ASFC_MASK << (rec->ch * 3));
val |= (4 << CM_ASFC_SHIFT) << (rec->ch * 3);
snd_cmipci_write(cm, CM_REG_FUNCTRL1, val);
val = snd_cmipci_read(cm, CM_REG_CHFORMAT);
val &= ~(CM_CH0FMT_MASK << (rec->ch * 2));
val |= (3 << CM_CH0FMT_SHIFT) << (rec->ch * 2);
if (cm->can_96k)
val &= ~(CM_CH0_SRATE_MASK << (rec->ch * 2));
snd_cmipci_write(cm, CM_REG_CHFORMAT, val);
/* start stream (we don't need interrupts) */
cm->ctrl |= CM_CHEN0 << rec->ch;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
spin_unlock_irq(&cm->reg_lock);
msleep(1);
/* stop and reset stream */
spin_lock_irq(&cm->reg_lock);
cm->ctrl &= ~(CM_CHEN0 << rec->ch);
val = CM_RST_CH0 << rec->ch;
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | val);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~val);
spin_unlock_irq(&cm->reg_lock);
rec->needs_silencing = 0;
}
}
static int snd_cmipci_playback_hw_free(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
setup_spdif_playback(cm, substream, 0, 0);
restore_mixer_state(cm);
snd_cmipci_silence_hack(cm, &cm->channel[0]);
return snd_cmipci_hw_free(substream);
}
static int snd_cmipci_playback2_hw_free(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
snd_cmipci_silence_hack(cm, &cm->channel[1]);
return snd_cmipci_hw_free(substream);
}
/* capture */
static int snd_cmipci_capture_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_CAPT], substream);
}
/* capture with spdif (via device #2) */
static int snd_cmipci_capture_spdif_prepare(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
spin_lock_irq(&cm->reg_lock);
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_CAPTURE_SPDF);
if (cm->can_96k) {
if (substream->runtime->rate > 48000)
snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
else
snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_DBLSPDS);
}
if (snd_pcm_format_width(substream->runtime->format) > 16)
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
else
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
spin_unlock_irq(&cm->reg_lock);
return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_CAPT], substream);
}
static int snd_cmipci_capture_spdif_hw_free(struct snd_pcm_substream *subs)
{
struct cmipci *cm = snd_pcm_substream_chip(subs);
spin_lock_irq(&cm->reg_lock);
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_CAPTURE_SPDF);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
spin_unlock_irq(&cm->reg_lock);
return snd_cmipci_hw_free(subs);
}
/*
* interrupt handler
*/
static irqreturn_t snd_cmipci_interrupt(int irq, void *dev_id)
{
struct cmipci *cm = dev_id;
unsigned int status, mask = 0;
/* fastpath out, to ease interrupt sharing */
status = snd_cmipci_read(cm, CM_REG_INT_STATUS);
if (!(status & CM_INTR))
return IRQ_NONE;
/* acknowledge interrupt */
spin_lock(&cm->reg_lock);
if (status & CM_CHINT0)
mask |= CM_CH0_INT_EN;
if (status & CM_CHINT1)
mask |= CM_CH1_INT_EN;
snd_cmipci_clear_bit(cm, CM_REG_INT_HLDCLR, mask);
snd_cmipci_set_bit(cm, CM_REG_INT_HLDCLR, mask);
spin_unlock(&cm->reg_lock);
if (cm->rmidi && (status & CM_UARTINT))
snd_mpu401_uart_interrupt(irq, cm->rmidi->private_data);
if (cm->pcm) {
if ((status & CM_CHINT0) && cm->channel[0].running)
snd_pcm_period_elapsed(cm->channel[0].substream);
if ((status & CM_CHINT1) && cm->channel[1].running)
snd_pcm_period_elapsed(cm->channel[1].substream);
}
return IRQ_HANDLED;
}
/*
* h/w infos
*/
/* playback on channel A */
static struct snd_pcm_hardware snd_cmipci_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* capture on channel B */
static struct snd_pcm_hardware snd_cmipci_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* playback on channel B - stereo 16bit only? */
static struct snd_pcm_hardware snd_cmipci_playback2 =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* spdif playback on channel A */
static struct snd_pcm_hardware snd_cmipci_playback_spdif =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* spdif playback on channel A (32bit, IEC958 subframes) */
static struct snd_pcm_hardware snd_cmipci_playback_iec958_subframe =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
/* spdif capture on channel B */
static struct snd_pcm_hardware snd_cmipci_capture_spdif =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
static unsigned int rate_constraints[] = { 5512, 8000, 11025, 16000, 22050,
32000, 44100, 48000, 88200, 96000, 128000 };
static struct snd_pcm_hw_constraint_list hw_constraints_rates = {
.count = ARRAY_SIZE(rate_constraints),
.list = rate_constraints,
.mask = 0,
};
/*
* check device open/close
*/
static int open_device_check(struct cmipci *cm, int mode, struct snd_pcm_substream *subs)
{
int ch = mode & CM_OPEN_CH_MASK;
/* FIXME: a file should wait until the device becomes free
* when it's opened on blocking mode. however, since the current
* pcm framework doesn't pass file pointer before actually opened,
* we can't know whether blocking mode or not in open callback..
*/
mutex_lock(&cm->open_mutex);
if (cm->opened[ch]) {
mutex_unlock(&cm->open_mutex);
return -EBUSY;
}
cm->opened[ch] = mode;
cm->channel[ch].substream = subs;
if (! (mode & CM_OPEN_DAC)) {
/* disable dual DAC mode */
cm->channel[ch].is_dac = 0;
spin_lock_irq(&cm->reg_lock);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC);
spin_unlock_irq(&cm->reg_lock);
}
mutex_unlock(&cm->open_mutex);
return 0;
}
static void close_device_check(struct cmipci *cm, int mode)
{
int ch = mode & CM_OPEN_CH_MASK;
mutex_lock(&cm->open_mutex);
if (cm->opened[ch] == mode) {
if (cm->channel[ch].substream) {
snd_cmipci_ch_reset(cm, ch);
cm->channel[ch].running = 0;
cm->channel[ch].substream = NULL;
}
cm->opened[ch] = 0;
if (! cm->channel[ch].is_dac) {
/* enable dual DAC mode again */
cm->channel[ch].is_dac = 1;
spin_lock_irq(&cm->reg_lock);
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC);
spin_unlock_irq(&cm->reg_lock);
}
}
mutex_unlock(&cm->open_mutex);
}
/*
*/
static int snd_cmipci_playback_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_PLAYBACK, substream)) < 0)
return err;
runtime->hw = snd_cmipci_playback;
if (cm->chip_version == 68) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
} else if (cm->chip_version == 55) {
err = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates);
if (err < 0)
return err;
runtime->hw.rates |= SNDRV_PCM_RATE_KNOT;
runtime->hw.rate_max = 128000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
cm->dig_pcm_status = cm->dig_status;
return 0;
}
static int snd_cmipci_capture_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_CAPTURE, substream)) < 0)
return err;
runtime->hw = snd_cmipci_capture;
if (cm->chip_version == 68) { // 8768 only supports 44k/48k recording
runtime->hw.rate_min = 41000;
runtime->hw.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000;
} else if (cm->chip_version == 55) {
err = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates);
if (err < 0)
return err;
runtime->hw.rates |= SNDRV_PCM_RATE_KNOT;
runtime->hw.rate_max = 128000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
return 0;
}
static int snd_cmipci_playback2_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_PLAYBACK2, substream)) < 0) /* use channel B */
return err;
runtime->hw = snd_cmipci_playback2;
mutex_lock(&cm->open_mutex);
if (! cm->opened[CM_CH_PLAY]) {
if (cm->can_multi_ch) {
runtime->hw.channels_max = cm->max_channels;
if (cm->max_channels == 4)
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_4);
else if (cm->max_channels == 6)
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_6);
else if (cm->max_channels == 8)
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_8);
}
}
mutex_unlock(&cm->open_mutex);
if (cm->chip_version == 68) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
} else if (cm->chip_version == 55) {
err = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates);
if (err < 0)
return err;
runtime->hw.rates |= SNDRV_PCM_RATE_KNOT;
runtime->hw.rate_max = 128000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
return 0;
}
static int snd_cmipci_playback_spdif_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_SPDIF_PLAYBACK, substream)) < 0) /* use channel A */
return err;
if (cm->can_ac3_hw) {
runtime->hw = snd_cmipci_playback_spdif;
if (cm->chip_version >= 37) {
runtime->hw.formats |= SNDRV_PCM_FMTBIT_S32_LE;
snd_pcm_hw_constraint_msbits(runtime, 0, 32, 24);
}
if (cm->can_96k) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
}
} else {
runtime->hw = snd_cmipci_playback_iec958_subframe;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x40000);
cm->dig_pcm_status = cm->dig_status;
return 0;
}
static int snd_cmipci_capture_spdif_open(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if ((err = open_device_check(cm, CM_OPEN_SPDIF_CAPTURE, substream)) < 0) /* use channel B */
return err;
runtime->hw = snd_cmipci_capture_spdif;
if (cm->can_96k && !(cm->chip_version == 68)) {
runtime->hw.rates |= SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000;
runtime->hw.rate_max = 96000;
}
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x40000);
return 0;
}
/*
*/
static int snd_cmipci_playback_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_PLAYBACK);
return 0;
}
static int snd_cmipci_capture_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_CAPTURE);
return 0;
}
static int snd_cmipci_playback2_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_PLAYBACK2);
close_device_check(cm, CM_OPEN_PLAYBACK_MULTI);
return 0;
}
static int snd_cmipci_playback_spdif_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_SPDIF_PLAYBACK);
return 0;
}
static int snd_cmipci_capture_spdif_close(struct snd_pcm_substream *substream)
{
struct cmipci *cm = snd_pcm_substream_chip(substream);
close_device_check(cm, CM_OPEN_SPDIF_CAPTURE);
return 0;
}
/*
*/
static struct snd_pcm_ops snd_cmipci_playback_ops = {
.open = snd_cmipci_playback_open,
.close = snd_cmipci_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_playback_hw_free,
.prepare = snd_cmipci_playback_prepare,
.trigger = snd_cmipci_playback_trigger,
.pointer = snd_cmipci_playback_pointer,
};
static struct snd_pcm_ops snd_cmipci_capture_ops = {
.open = snd_cmipci_capture_open,
.close = snd_cmipci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_hw_free,
.prepare = snd_cmipci_capture_prepare,
.trigger = snd_cmipci_capture_trigger,
.pointer = snd_cmipci_capture_pointer,
};
static struct snd_pcm_ops snd_cmipci_playback2_ops = {
.open = snd_cmipci_playback2_open,
.close = snd_cmipci_playback2_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_playback2_hw_params,
.hw_free = snd_cmipci_playback2_hw_free,
.prepare = snd_cmipci_capture_prepare, /* channel B */
.trigger = snd_cmipci_capture_trigger, /* channel B */
.pointer = snd_cmipci_capture_pointer, /* channel B */
};
static struct snd_pcm_ops snd_cmipci_playback_spdif_ops = {
.open = snd_cmipci_playback_spdif_open,
.close = snd_cmipci_playback_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_playback_hw_free,
.prepare = snd_cmipci_playback_spdif_prepare, /* set up rate */
.trigger = snd_cmipci_playback_trigger,
.pointer = snd_cmipci_playback_pointer,
};
static struct snd_pcm_ops snd_cmipci_capture_spdif_ops = {
.open = snd_cmipci_capture_spdif_open,
.close = snd_cmipci_capture_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cmipci_hw_params,
.hw_free = snd_cmipci_capture_spdif_hw_free,
.prepare = snd_cmipci_capture_spdif_prepare,
.trigger = snd_cmipci_capture_trigger,
.pointer = snd_cmipci_capture_pointer,
};
/*
*/
static int __devinit snd_cmipci_pcm_new(struct cmipci *cm, int device)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cmipci_capture_ops);
pcm->private_data = cm;
pcm->info_flags = 0;
strcpy(pcm->name, "C-Media PCI DAC/ADC");
cm->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
return 0;
}
static int __devinit snd_cmipci_pcm2_new(struct cmipci *cm, int device)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 0, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback2_ops);
pcm->private_data = cm;
pcm->info_flags = 0;
strcpy(pcm->name, "C-Media PCI 2nd DAC");
cm->pcm2 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
return 0;
}
static int __devinit snd_cmipci_pcm_spdif_new(struct cmipci *cm, int device)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_spdif_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cmipci_capture_spdif_ops);
pcm->private_data = cm;
pcm->info_flags = 0;
strcpy(pcm->name, "C-Media PCI IEC958");
cm->pcm_spdif = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
return 0;
}
/*
* mixer interface:
* - CM8338/8738 has a compatible mixer interface with SB16, but
* lack of some elements like tone control, i/o gain and AGC.
* - Access to native registers:
* - A 3D switch
* - Output mute switches
*/
static void snd_cmipci_mixer_write(struct cmipci *s, unsigned char idx, unsigned char data)
{
outb(idx, s->iobase + CM_REG_SB16_ADDR);
outb(data, s->iobase + CM_REG_SB16_DATA);
}
static unsigned char snd_cmipci_mixer_read(struct cmipci *s, unsigned char idx)
{
unsigned char v;
outb(idx, s->iobase + CM_REG_SB16_ADDR);
v = inb(s->iobase + CM_REG_SB16_DATA);
return v;
}
/*
* general mixer element
*/
struct cmipci_sb_reg {
unsigned int left_reg, right_reg;
unsigned int left_shift, right_shift;
unsigned int mask;
unsigned int invert: 1;
unsigned int stereo: 1;
};
#define COMPOSE_SB_REG(lreg,rreg,lshift,rshift,mask,invert,stereo) \
((lreg) | ((rreg) << 8) | (lshift << 16) | (rshift << 19) | (mask << 24) | (invert << 22) | (stereo << 23))
#define CMIPCI_DOUBLE(xname, left_reg, right_reg, left_shift, right_shift, mask, invert, stereo) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_volume, \
.get = snd_cmipci_get_volume, .put = snd_cmipci_put_volume, \
.private_value = COMPOSE_SB_REG(left_reg, right_reg, left_shift, right_shift, mask, invert, stereo), \
}
#define CMIPCI_SB_VOL_STEREO(xname,reg,shift,mask) CMIPCI_DOUBLE(xname, reg, reg+1, shift, shift, mask, 0, 1)
#define CMIPCI_SB_VOL_MONO(xname,reg,shift,mask) CMIPCI_DOUBLE(xname, reg, reg, shift, shift, mask, 0, 0)
#define CMIPCI_SB_SW_STEREO(xname,lshift,rshift) CMIPCI_DOUBLE(xname, SB_DSP4_OUTPUT_SW, SB_DSP4_OUTPUT_SW, lshift, rshift, 1, 0, 1)
#define CMIPCI_SB_SW_MONO(xname,shift) CMIPCI_DOUBLE(xname, SB_DSP4_OUTPUT_SW, SB_DSP4_OUTPUT_SW, shift, shift, 1, 0, 0)
static void cmipci_sb_reg_decode(struct cmipci_sb_reg *r, unsigned long val)
{
r->left_reg = val & 0xff;
r->right_reg = (val >> 8) & 0xff;
r->left_shift = (val >> 16) & 0x07;
r->right_shift = (val >> 19) & 0x07;
r->invert = (val >> 22) & 1;
r->stereo = (val >> 23) & 1;
r->mask = (val >> 24) & 0xff;
}
static int snd_cmipci_info_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct cmipci_sb_reg reg;
cmipci_sb_reg_decode(®, kcontrol->private_value);
uinfo->type = reg.mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = reg.stereo + 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = reg.mask;
return 0;
}
static int snd_cmipci_get_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int val;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
val = (snd_cmipci_mixer_read(cm, reg.left_reg) >> reg.left_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[0] = val;
if (reg.stereo) {
val = (snd_cmipci_mixer_read(cm, reg.right_reg) >> reg.right_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[1] = val;
}
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_put_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int change;
int left, right, oleft, oright;
cmipci_sb_reg_decode(®, kcontrol->private_value);
left = ucontrol->value.integer.value[0] & reg.mask;
if (reg.invert)
left = reg.mask - left;
left <<= reg.left_shift;
if (reg.stereo) {
right = ucontrol->value.integer.value[1] & reg.mask;
if (reg.invert)
right = reg.mask - right;
right <<= reg.right_shift;
} else
right = 0;
spin_lock_irq(&cm->reg_lock);
oleft = snd_cmipci_mixer_read(cm, reg.left_reg);
left |= oleft & ~(reg.mask << reg.left_shift);
change = left != oleft;
if (reg.stereo) {
if (reg.left_reg != reg.right_reg) {
snd_cmipci_mixer_write(cm, reg.left_reg, left);
oright = snd_cmipci_mixer_read(cm, reg.right_reg);
} else
oright = left;
right |= oright & ~(reg.mask << reg.right_shift);
change |= right != oright;
snd_cmipci_mixer_write(cm, reg.right_reg, right);
} else
snd_cmipci_mixer_write(cm, reg.left_reg, left);
spin_unlock_irq(&cm->reg_lock);
return change;
}
/*
* input route (left,right) -> (left,right)
*/
#define CMIPCI_SB_INPUT_SW(xname, left_shift, right_shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_input_sw, \
.get = snd_cmipci_get_input_sw, .put = snd_cmipci_put_input_sw, \
.private_value = COMPOSE_SB_REG(SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT, left_shift, right_shift, 1, 0, 1), \
}
static int snd_cmipci_info_input_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 4;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
static int snd_cmipci_get_input_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int val1, val2;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
val1 = snd_cmipci_mixer_read(cm, reg.left_reg);
val2 = snd_cmipci_mixer_read(cm, reg.right_reg);
spin_unlock_irq(&cm->reg_lock);
ucontrol->value.integer.value[0] = (val1 >> reg.left_shift) & 1;
ucontrol->value.integer.value[1] = (val2 >> reg.left_shift) & 1;
ucontrol->value.integer.value[2] = (val1 >> reg.right_shift) & 1;
ucontrol->value.integer.value[3] = (val2 >> reg.right_shift) & 1;
return 0;
}
static int snd_cmipci_put_input_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
int change;
int val1, val2, oval1, oval2;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
oval1 = snd_cmipci_mixer_read(cm, reg.left_reg);
oval2 = snd_cmipci_mixer_read(cm, reg.right_reg);
val1 = oval1 & ~((1 << reg.left_shift) | (1 << reg.right_shift));
val2 = oval2 & ~((1 << reg.left_shift) | (1 << reg.right_shift));
val1 |= (ucontrol->value.integer.value[0] & 1) << reg.left_shift;
val2 |= (ucontrol->value.integer.value[1] & 1) << reg.left_shift;
val1 |= (ucontrol->value.integer.value[2] & 1) << reg.right_shift;
val2 |= (ucontrol->value.integer.value[3] & 1) << reg.right_shift;
change = val1 != oval1 || val2 != oval2;
snd_cmipci_mixer_write(cm, reg.left_reg, val1);
snd_cmipci_mixer_write(cm, reg.right_reg, val2);
spin_unlock_irq(&cm->reg_lock);
return change;
}
/*
* native mixer switches/volumes
*/
#define CMIPCI_MIXER_SW_STEREO(xname, reg, lshift, rshift, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, lshift, rshift, 1, invert, 1), \
}
#define CMIPCI_MIXER_SW_MONO(xname, reg, shift, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, shift, shift, 1, invert, 0), \
}
#define CMIPCI_MIXER_VOL_STEREO(xname, reg, lshift, rshift, mask) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, lshift, rshift, mask, 0, 1), \
}
#define CMIPCI_MIXER_VOL_MONO(xname, reg, shift, mask) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_cmipci_info_native_mixer, \
.get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
.private_value = COMPOSE_SB_REG(reg, reg, shift, shift, mask, 0, 0), \
}
static int snd_cmipci_info_native_mixer(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct cmipci_sb_reg reg;
cmipci_sb_reg_decode(®, kcontrol->private_value);
uinfo->type = reg.mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = reg.stereo + 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = reg.mask;
return 0;
}
static int snd_cmipci_get_native_mixer(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
unsigned char oreg, val;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
oreg = inb(cm->iobase + reg.left_reg);
val = (oreg >> reg.left_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[0] = val;
if (reg.stereo) {
val = (oreg >> reg.right_shift) & reg.mask;
if (reg.invert)
val = reg.mask - val;
ucontrol->value.integer.value[1] = val;
}
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_put_native_mixer(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
struct cmipci_sb_reg reg;
unsigned char oreg, nreg, val;
cmipci_sb_reg_decode(®, kcontrol->private_value);
spin_lock_irq(&cm->reg_lock);
oreg = inb(cm->iobase + reg.left_reg);
val = ucontrol->value.integer.value[0] & reg.mask;
if (reg.invert)
val = reg.mask - val;
nreg = oreg & ~(reg.mask << reg.left_shift);
nreg |= (val << reg.left_shift);
if (reg.stereo) {
val = ucontrol->value.integer.value[1] & reg.mask;
if (reg.invert)
val = reg.mask - val;
nreg &= ~(reg.mask << reg.right_shift);
nreg |= (val << reg.right_shift);
}
outb(nreg, cm->iobase + reg.left_reg);
spin_unlock_irq(&cm->reg_lock);
return (nreg != oreg);
}
/*
* special case - check mixer sensitivity
*/
static int snd_cmipci_get_native_mixer_sensitive(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
//struct cmipci *cm = snd_kcontrol_chip(kcontrol);
return snd_cmipci_get_native_mixer(kcontrol, ucontrol);
}
static int snd_cmipci_put_native_mixer_sensitive(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
if (cm->mixer_insensitive) {
/* ignored */
return 0;
}
return snd_cmipci_put_native_mixer(kcontrol, ucontrol);
}
static struct snd_kcontrol_new snd_cmipci_mixers[] __devinitdata = {
CMIPCI_SB_VOL_STEREO("Master Playback Volume", SB_DSP4_MASTER_DEV, 3, 31),
CMIPCI_MIXER_SW_MONO("3D Control - Switch", CM_REG_MIXER1, CM_X3DEN_SHIFT, 0),
CMIPCI_SB_VOL_STEREO("PCM Playback Volume", SB_DSP4_PCM_DEV, 3, 31),
//CMIPCI_MIXER_SW_MONO("PCM Playback Switch", CM_REG_MIXER1, CM_WSMUTE_SHIFT, 1),
{ /* switch with sensitivity */
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Switch",
.info = snd_cmipci_info_native_mixer,
.get = snd_cmipci_get_native_mixer_sensitive,
.put = snd_cmipci_put_native_mixer_sensitive,
.private_value = COMPOSE_SB_REG(CM_REG_MIXER1, CM_REG_MIXER1, CM_WSMUTE_SHIFT, CM_WSMUTE_SHIFT, 1, 1, 0),
},
CMIPCI_MIXER_SW_STEREO("PCM Capture Switch", CM_REG_MIXER1, CM_WAVEINL_SHIFT, CM_WAVEINR_SHIFT, 0),
CMIPCI_SB_VOL_STEREO("Synth Playback Volume", SB_DSP4_SYNTH_DEV, 3, 31),
CMIPCI_MIXER_SW_MONO("Synth Playback Switch", CM_REG_MIXER1, CM_FMMUTE_SHIFT, 1),
CMIPCI_SB_INPUT_SW("Synth Capture Route", 6, 5),
CMIPCI_SB_VOL_STEREO("CD Playback Volume", SB_DSP4_CD_DEV, 3, 31),
CMIPCI_SB_SW_STEREO("CD Playback Switch", 2, 1),
CMIPCI_SB_INPUT_SW("CD Capture Route", 2, 1),
CMIPCI_SB_VOL_STEREO("Line Playback Volume", SB_DSP4_LINE_DEV, 3, 31),
CMIPCI_SB_SW_STEREO("Line Playback Switch", 4, 3),
CMIPCI_SB_INPUT_SW("Line Capture Route", 4, 3),
CMIPCI_SB_VOL_MONO("Mic Playback Volume", SB_DSP4_MIC_DEV, 3, 31),
CMIPCI_SB_SW_MONO("Mic Playback Switch", 0),
CMIPCI_DOUBLE("Mic Capture Switch", SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT, 0, 0, 1, 0, 0),
CMIPCI_SB_VOL_MONO("Beep Playback Volume", SB_DSP4_SPEAKER_DEV, 6, 3),
CMIPCI_MIXER_VOL_STEREO("Aux Playback Volume", CM_REG_AUX_VOL, 4, 0, 15),
CMIPCI_MIXER_SW_STEREO("Aux Playback Switch", CM_REG_MIXER2, CM_VAUXLM_SHIFT, CM_VAUXRM_SHIFT, 0),
CMIPCI_MIXER_SW_STEREO("Aux Capture Switch", CM_REG_MIXER2, CM_RAUXLEN_SHIFT, CM_RAUXREN_SHIFT, 0),
CMIPCI_MIXER_SW_MONO("Mic Boost Playback Switch", CM_REG_MIXER2, CM_MICGAINZ_SHIFT, 1),
CMIPCI_MIXER_VOL_MONO("Mic Capture Volume", CM_REG_MIXER2, CM_VADMIC_SHIFT, 7),
CMIPCI_SB_VOL_MONO("Phone Playback Volume", CM_REG_EXTENT_IND, 5, 7),
CMIPCI_DOUBLE("Phone Playback Switch", CM_REG_EXTENT_IND, CM_REG_EXTENT_IND, 4, 4, 1, 0, 0),
CMIPCI_DOUBLE("Beep Playback Switch", CM_REG_EXTENT_IND, CM_REG_EXTENT_IND, 3, 3, 1, 0, 0),
CMIPCI_DOUBLE("Mic Boost Capture Switch", CM_REG_EXTENT_IND, CM_REG_EXTENT_IND, 0, 0, 1, 0, 0),
};
/*
* other switches
*/
struct cmipci_switch_args {
int reg; /* register index */
unsigned int mask; /* mask bits */
unsigned int mask_on; /* mask bits to turn on */
unsigned int is_byte: 1; /* byte access? */
unsigned int ac3_sensitive: 1; /* access forbidden during
* non-audio operation?
*/
};
#define snd_cmipci_uswitch_info snd_ctl_boolean_mono_info
static int _snd_cmipci_uswitch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol,
struct cmipci_switch_args *args)
{
unsigned int val;
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&cm->reg_lock);
if (args->ac3_sensitive && cm->mixer_insensitive) {
ucontrol->value.integer.value[0] = 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
if (args->is_byte)
val = inb(cm->iobase + args->reg);
else
val = snd_cmipci_read(cm, args->reg);
ucontrol->value.integer.value[0] = ((val & args->mask) == args->mask_on) ? 1 : 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_uswitch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci_switch_args *args;
args = (struct cmipci_switch_args *)kcontrol->private_value;
if (snd_BUG_ON(!args))
return -EINVAL;
return _snd_cmipci_uswitch_get(kcontrol, ucontrol, args);
}
static int _snd_cmipci_uswitch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol,
struct cmipci_switch_args *args)
{
unsigned int val;
int change;
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&cm->reg_lock);
if (args->ac3_sensitive && cm->mixer_insensitive) {
/* ignored */
spin_unlock_irq(&cm->reg_lock);
return 0;
}
if (args->is_byte)
val = inb(cm->iobase + args->reg);
else
val = snd_cmipci_read(cm, args->reg);
change = (val & args->mask) != (ucontrol->value.integer.value[0] ?
args->mask_on : (args->mask & ~args->mask_on));
if (change) {
val &= ~args->mask;
if (ucontrol->value.integer.value[0])
val |= args->mask_on;
else
val |= (args->mask & ~args->mask_on);
if (args->is_byte)
outb((unsigned char)val, cm->iobase + args->reg);
else
snd_cmipci_write(cm, args->reg, val);
}
spin_unlock_irq(&cm->reg_lock);
return change;
}
static int snd_cmipci_uswitch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci_switch_args *args;
args = (struct cmipci_switch_args *)kcontrol->private_value;
if (snd_BUG_ON(!args))
return -EINVAL;
return _snd_cmipci_uswitch_put(kcontrol, ucontrol, args);
}
#define DEFINE_SWITCH_ARG(sname, xreg, xmask, xmask_on, xis_byte, xac3) \
static struct cmipci_switch_args cmipci_switch_arg_##sname = { \
.reg = xreg, \
.mask = xmask, \
.mask_on = xmask_on, \
.is_byte = xis_byte, \
.ac3_sensitive = xac3, \
}
#define DEFINE_BIT_SWITCH_ARG(sname, xreg, xmask, xis_byte, xac3) \
DEFINE_SWITCH_ARG(sname, xreg, xmask, xmask, xis_byte, xac3)
#if 0 /* these will be controlled in pcm device */
DEFINE_BIT_SWITCH_ARG(spdif_in, CM_REG_FUNCTRL1, CM_SPDF_1, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_out, CM_REG_FUNCTRL1, CM_SPDF_0, 0, 0);
#endif
DEFINE_BIT_SWITCH_ARG(spdif_in_sel1, CM_REG_CHFORMAT, CM_SPDIF_SELECT1, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_in_sel2, CM_REG_MISC_CTRL, CM_SPDIF_SELECT2, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_enable, CM_REG_LEGACY_CTRL, CM_ENSPDOUT, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdo2dac, CM_REG_FUNCTRL1, CM_SPDO2DAC, 0, 1);
DEFINE_BIT_SWITCH_ARG(spdi_valid, CM_REG_MISC, CM_SPDVALID, 1, 0);
DEFINE_BIT_SWITCH_ARG(spdif_copyright, CM_REG_LEGACY_CTRL, CM_SPDCOPYRHT, 0, 0);
DEFINE_BIT_SWITCH_ARG(spdif_dac_out, CM_REG_LEGACY_CTRL, CM_DAC2SPDO, 0, 1);
DEFINE_SWITCH_ARG(spdo_5v, CM_REG_MISC_CTRL, CM_SPDO5V, 0, 0, 0); /* inverse: 0 = 5V */
// DEFINE_BIT_SWITCH_ARG(spdo_48k, CM_REG_MISC_CTRL, CM_SPDF_AC97|CM_SPDIF48K, 0, 1);
DEFINE_BIT_SWITCH_ARG(spdif_loop, CM_REG_FUNCTRL1, CM_SPDFLOOP, 0, 1);
DEFINE_BIT_SWITCH_ARG(spdi_monitor, CM_REG_MIXER1, CM_CDPLAY, 1, 0);
/* DEFINE_BIT_SWITCH_ARG(spdi_phase, CM_REG_CHFORMAT, CM_SPDIF_INVERSE, 0, 0); */
DEFINE_BIT_SWITCH_ARG(spdi_phase, CM_REG_MISC, CM_SPDIF_INVERSE, 1, 0);
DEFINE_BIT_SWITCH_ARG(spdi_phase2, CM_REG_CHFORMAT, CM_SPDIF_INVERSE2, 0, 0);
#if CM_CH_PLAY == 1
DEFINE_SWITCH_ARG(exchange_dac, CM_REG_MISC_CTRL, CM_XCHGDAC, 0, 0, 0); /* reversed */
#else
DEFINE_SWITCH_ARG(exchange_dac, CM_REG_MISC_CTRL, CM_XCHGDAC, CM_XCHGDAC, 0, 0);
#endif
DEFINE_BIT_SWITCH_ARG(fourch, CM_REG_MISC_CTRL, CM_N4SPK3D, 0, 0);
// DEFINE_BIT_SWITCH_ARG(line_rear, CM_REG_MIXER1, CM_REAR2LIN, 1, 0);
// DEFINE_BIT_SWITCH_ARG(line_bass, CM_REG_LEGACY_CTRL, CM_CENTR2LIN|CM_BASE2LIN, 0, 0);
// DEFINE_BIT_SWITCH_ARG(joystick, CM_REG_FUNCTRL1, CM_JYSTK_EN, 0, 0); /* now module option */
DEFINE_SWITCH_ARG(modem, CM_REG_MISC_CTRL, CM_FLINKON|CM_FLINKOFF, CM_FLINKON, 0, 0);
#define DEFINE_SWITCH(sname, stype, sarg) \
{ .name = sname, \
.iface = stype, \
.info = snd_cmipci_uswitch_info, \
.get = snd_cmipci_uswitch_get, \
.put = snd_cmipci_uswitch_put, \
.private_value = (unsigned long)&cmipci_switch_arg_##sarg,\
}
#define DEFINE_CARD_SWITCH(sname, sarg) DEFINE_SWITCH(sname, SNDRV_CTL_ELEM_IFACE_CARD, sarg)
#define DEFINE_MIXER_SWITCH(sname, sarg) DEFINE_SWITCH(sname, SNDRV_CTL_ELEM_IFACE_MIXER, sarg)
/*
* callbacks for spdif output switch
* needs toggle two registers..
*/
static int snd_cmipci_spdout_enable_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int changed;
changed = _snd_cmipci_uswitch_get(kcontrol, ucontrol, &cmipci_switch_arg_spdif_enable);
changed |= _snd_cmipci_uswitch_get(kcontrol, ucontrol, &cmipci_switch_arg_spdo2dac);
return changed;
}
static int snd_cmipci_spdout_enable_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *chip = snd_kcontrol_chip(kcontrol);
int changed;
changed = _snd_cmipci_uswitch_put(kcontrol, ucontrol, &cmipci_switch_arg_spdif_enable);
changed |= _snd_cmipci_uswitch_put(kcontrol, ucontrol, &cmipci_switch_arg_spdo2dac);
if (changed) {
if (ucontrol->value.integer.value[0]) {
if (chip->spdif_playback_avail)
snd_cmipci_set_bit(chip, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
} else {
if (chip->spdif_playback_avail)
snd_cmipci_clear_bit(chip, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
}
}
chip->spdif_playback_enabled = ucontrol->value.integer.value[0];
return changed;
}
static int snd_cmipci_line_in_mode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
static const char *const texts[3] = {
"Line-In", "Rear Output", "Bass Output"
};
return snd_ctl_enum_info(uinfo, 1,
cm->chip_version >= 39 ? 3 : 2, texts);
}
static inline unsigned int get_line_in_mode(struct cmipci *cm)
{
unsigned int val;
if (cm->chip_version >= 39) {
val = snd_cmipci_read(cm, CM_REG_LEGACY_CTRL);
if (val & (CM_CENTR2LIN | CM_BASE2LIN))
return 2;
}
val = snd_cmipci_read_b(cm, CM_REG_MIXER1);
if (val & CM_REAR2LIN)
return 1;
return 0;
}
static int snd_cmipci_line_in_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&cm->reg_lock);
ucontrol->value.enumerated.item[0] = get_line_in_mode(cm);
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_line_in_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
int change;
spin_lock_irq(&cm->reg_lock);
if (ucontrol->value.enumerated.item[0] == 2)
change = snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_CENTR2LIN | CM_BASE2LIN);
else
change = snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_CENTR2LIN | CM_BASE2LIN);
if (ucontrol->value.enumerated.item[0] == 1)
change |= snd_cmipci_set_bit_b(cm, CM_REG_MIXER1, CM_REAR2LIN);
else
change |= snd_cmipci_clear_bit_b(cm, CM_REG_MIXER1, CM_REAR2LIN);
spin_unlock_irq(&cm->reg_lock);
return change;
}
static int snd_cmipci_mic_in_mode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *const texts[2] = { "Mic-In", "Center/LFE Output" };
return snd_ctl_enum_info(uinfo, 1, 2, texts);
}
static int snd_cmipci_mic_in_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
/* same bit as spdi_phase */
spin_lock_irq(&cm->reg_lock);
ucontrol->value.enumerated.item[0] =
(snd_cmipci_read_b(cm, CM_REG_MISC) & CM_SPDIF_INVERSE) ? 1 : 0;
spin_unlock_irq(&cm->reg_lock);
return 0;
}
static int snd_cmipci_mic_in_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cmipci *cm = snd_kcontrol_chip(kcontrol);
int change;
spin_lock_irq(&cm->reg_lock);
if (ucontrol->value.enumerated.item[0])
change = snd_cmipci_set_bit_b(cm, CM_REG_MISC, CM_SPDIF_INVERSE);
else
change = snd_cmipci_clear_bit_b(cm, CM_REG_MISC, CM_SPDIF_INVERSE);
spin_unlock_irq(&cm->reg_lock);
return change;
}
/* both for CM8338/8738 */
static struct snd_kcontrol_new snd_cmipci_mixer_switches[] __devinitdata = {
DEFINE_MIXER_SWITCH("Four Channel Mode", fourch),
{
.name = "Line-In Mode",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_cmipci_line_in_mode_info,
.get = snd_cmipci_line_in_mode_get,
.put = snd_cmipci_line_in_mode_put,
},
};
/* for non-multichannel chips */
static struct snd_kcontrol_new snd_cmipci_nomulti_switch __devinitdata =
DEFINE_MIXER_SWITCH("Exchange DAC", exchange_dac);
/* only for CM8738 */
static struct snd_kcontrol_new snd_cmipci_8738_mixer_switches[] __devinitdata = {
#if 0 /* controlled in pcm device */
DEFINE_MIXER_SWITCH("IEC958 In Record", spdif_in),
DEFINE_MIXER_SWITCH("IEC958 Out", spdif_out),
DEFINE_MIXER_SWITCH("IEC958 Out To DAC", spdo2dac),
#endif
// DEFINE_MIXER_SWITCH("IEC958 Output Switch", spdif_enable),
{ .name = "IEC958 Output Switch",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_cmipci_uswitch_info,
.get = snd_cmipci_spdout_enable_get,
.put = snd_cmipci_spdout_enable_put,
},
DEFINE_MIXER_SWITCH("IEC958 In Valid", spdi_valid),
DEFINE_MIXER_SWITCH("IEC958 Copyright", spdif_copyright),
DEFINE_MIXER_SWITCH("IEC958 5V", spdo_5v),
// DEFINE_MIXER_SWITCH("IEC958 In/Out 48KHz", spdo_48k),
DEFINE_MIXER_SWITCH("IEC958 Loop", spdif_loop),
DEFINE_MIXER_SWITCH("IEC958 In Monitor", spdi_monitor),
};
/* only for model 033/037 */
static struct snd_kcontrol_new snd_cmipci_old_mixer_switches[] __devinitdata = {
DEFINE_MIXER_SWITCH("IEC958 Mix Analog", spdif_dac_out),
DEFINE_MIXER_SWITCH("IEC958 In Phase Inverse", spdi_phase),
DEFINE_MIXER_SWITCH("IEC958 In Select", spdif_in_sel1),
};
/* only for model 039 or later */
static struct snd_kcontrol_new snd_cmipci_extra_mixer_switches[] __devinitdata = {
DEFINE_MIXER_SWITCH("IEC958 In Select", spdif_in_sel2),
DEFINE_MIXER_SWITCH("IEC958 In Phase Inverse", spdi_phase2),
{
.name = "Mic-In Mode",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_cmipci_mic_in_mode_info,
.get = snd_cmipci_mic_in_mode_get,
.put = snd_cmipci_mic_in_mode_put,
}
};
/* card control switches */
static struct snd_kcontrol_new snd_cmipci_modem_switch __devinitdata =
DEFINE_CARD_SWITCH("Modem", modem);
static int __devinit snd_cmipci_mixer_new(struct cmipci *cm, int pcm_spdif_device)
{
struct snd_card *card;
struct snd_kcontrol_new *sw;
struct snd_kcontrol *kctl;
unsigned int idx;
int err;
if (snd_BUG_ON(!cm || !cm->card))
return -EINVAL;
card = cm->card;
strcpy(card->mixername, "CMedia PCI");
spin_lock_irq(&cm->reg_lock);
snd_cmipci_mixer_write(cm, 0x00, 0x00); /* mixer reset */
spin_unlock_irq(&cm->reg_lock);
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_mixers); idx++) {
if (cm->chip_version == 68) { // 8768 has no PCM volume
if (!strcmp(snd_cmipci_mixers[idx].name,
"PCM Playback Volume"))
continue;
}
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_cmipci_mixers[idx], cm))) < 0)
return err;
}
/* mixer switches */
sw = snd_cmipci_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
if (! cm->can_multi_ch) {
err = snd_ctl_add(cm->card, snd_ctl_new1(&snd_cmipci_nomulti_switch, cm));
if (err < 0)
return err;
}
if (cm->device == PCI_DEVICE_ID_CMEDIA_CM8738 ||
cm->device == PCI_DEVICE_ID_CMEDIA_CM8738B) {
sw = snd_cmipci_8738_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_8738_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
if (cm->can_ac3_hw) {
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_default, cm))) < 0)
return err;
kctl->id.device = pcm_spdif_device;
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_mask, cm))) < 0)
return err;
kctl->id.device = pcm_spdif_device;
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_stream, cm))) < 0)
return err;
kctl->id.device = pcm_spdif_device;
}
if (cm->chip_version <= 37) {
sw = snd_cmipci_old_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_old_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
}
}
if (cm->chip_version >= 39) {
sw = snd_cmipci_extra_mixer_switches;
for (idx = 0; idx < ARRAY_SIZE(snd_cmipci_extra_mixer_switches); idx++, sw++) {
err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
if (err < 0)
return err;
}
}
/* card switches */
/*
* newer chips don't have the register bits to force modem link
* detection; the bit that was FLINKON now mutes CH1
*/
if (cm->chip_version < 39) {
err = snd_ctl_add(cm->card,
snd_ctl_new1(&snd_cmipci_modem_switch, cm));
if (err < 0)
return err;
}
for (idx = 0; idx < CM_SAVED_MIXERS; idx++) {
struct snd_ctl_elem_id elem_id;
struct snd_kcontrol *ctl;
memset(&elem_id, 0, sizeof(elem_id));
elem_id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
strcpy(elem_id.name, cm_saved_mixer[idx].name);
ctl = snd_ctl_find_id(cm->card, &elem_id);
if (ctl)
cm->mixer_res_ctl[idx] = ctl;
}
return 0;
}
/*
* proc interface
*/
#ifdef CONFIG_PROC_FS
static void snd_cmipci_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct cmipci *cm = entry->private_data;
int i, v;
snd_iprintf(buffer, "%s\n", cm->card->longname);
for (i = 0; i < 0x94; i++) {
if (i == 0x28)
i = 0x90;
v = inb(cm->iobase + i);
if (i % 4 == 0)
snd_iprintf(buffer, "\n%02x:", i);
snd_iprintf(buffer, " %02x", v);
}
snd_iprintf(buffer, "\n");
}
static void __devinit snd_cmipci_proc_init(struct cmipci *cm)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(cm->card, "cmipci", &entry))
snd_info_set_text_ops(entry, cm, snd_cmipci_proc_read);
}
#else /* !CONFIG_PROC_FS */
static inline void snd_cmipci_proc_init(struct cmipci *cm) {}
#endif
static DEFINE_PCI_DEVICE_TABLE(snd_cmipci_ids) = {
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338A), 0},
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338B), 0},
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738), 0},
{PCI_VDEVICE(CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738B), 0},
{PCI_VDEVICE(AL, PCI_DEVICE_ID_CMEDIA_CM8738), 0},
{0,},
};
/*
* check chip version and capabilities
* driver name is modified according to the chip model
*/
static void __devinit query_chip(struct cmipci *cm)
{
unsigned int detect;
/* check reg 0Ch, bit 24-31 */
detect = snd_cmipci_read(cm, CM_REG_INT_HLDCLR) & CM_CHIP_MASK2;
if (! detect) {
/* check reg 08h, bit 24-28 */
detect = snd_cmipci_read(cm, CM_REG_CHFORMAT) & CM_CHIP_MASK1;
switch (detect) {
case 0:
cm->chip_version = 33;
if (cm->do_soft_ac3)
cm->can_ac3_sw = 1;
else
cm->can_ac3_hw = 1;
break;
case CM_CHIP_037:
cm->chip_version = 37;
cm->can_ac3_hw = 1;
break;
default:
cm->chip_version = 39;
cm->can_ac3_hw = 1;
break;
}
cm->max_channels = 2;
} else {
if (detect & CM_CHIP_039) {
cm->chip_version = 39;
if (detect & CM_CHIP_039_6CH) /* 4 or 6 channels */
cm->max_channels = 6;
else
cm->max_channels = 4;
} else if (detect & CM_CHIP_8768) {
cm->chip_version = 68;
cm->max_channels = 8;
cm->can_96k = 1;
} else {
cm->chip_version = 55;
cm->max_channels = 6;
cm->can_96k = 1;
}
cm->can_ac3_hw = 1;
cm->can_multi_ch = 1;
}
}
#ifdef SUPPORT_JOYSTICK
static int __devinit snd_cmipci_create_gameport(struct cmipci *cm, int dev)
{
static int ports[] = { 0x201, 0x200, 0 }; /* FIXME: majority is 0x201? */
struct gameport *gp;
struct resource *r = NULL;
int i, io_port = 0;
if (joystick_port[dev] == 0)
return -ENODEV;
if (joystick_port[dev] == 1) { /* auto-detect */
for (i = 0; ports[i]; i++) {
io_port = ports[i];
r = request_region(io_port, 1, "CMIPCI gameport");
if (r)
break;
}
} else {
io_port = joystick_port[dev];
r = request_region(io_port, 1, "CMIPCI gameport");
}
if (!r) {
printk(KERN_WARNING "cmipci: cannot reserve joystick ports\n");
return -EBUSY;
}
cm->gameport = gp = gameport_allocate_port();
if (!gp) {
printk(KERN_ERR "cmipci: cannot allocate memory for gameport\n");
release_and_free_resource(r);
return -ENOMEM;
}
gameport_set_name(gp, "C-Media Gameport");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(cm->pci));
gameport_set_dev_parent(gp, &cm->pci->dev);
gp->io = io_port;
gameport_set_port_data(gp, r);
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
gameport_register_port(cm->gameport);
return 0;
}
static void snd_cmipci_free_gameport(struct cmipci *cm)
{
if (cm->gameport) {
struct resource *r = gameport_get_port_data(cm->gameport);
gameport_unregister_port(cm->gameport);
cm->gameport = NULL;
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
release_and_free_resource(r);
}
}
#else
static inline int snd_cmipci_create_gameport(struct cmipci *cm, int dev) { return -ENOSYS; }
static inline void snd_cmipci_free_gameport(struct cmipci *cm) { }
#endif
static int snd_cmipci_free(struct cmipci *cm)
{
if (cm->irq >= 0) {
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT);
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0); /* disable ints */
snd_cmipci_ch_reset(cm, CM_CH_PLAY);
snd_cmipci_ch_reset(cm, CM_CH_CAPT);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, 0); /* disable channels */
snd_cmipci_write(cm, CM_REG_FUNCTRL1, 0);
/* reset mixer */
snd_cmipci_mixer_write(cm, 0, 0);
free_irq(cm->irq, cm);
}
snd_cmipci_free_gameport(cm);
pci_release_regions(cm->pci);
pci_disable_device(cm->pci);
kfree(cm);
return 0;
}
static int snd_cmipci_dev_free(struct snd_device *device)
{
struct cmipci *cm = device->device_data;
return snd_cmipci_free(cm);
}
static int __devinit snd_cmipci_create_fm(struct cmipci *cm, long fm_port)
{
long iosynth;
unsigned int val;
struct snd_opl3 *opl3;
int err;
if (!fm_port)
goto disable_fm;
if (cm->chip_version >= 39) {
/* first try FM regs in PCI port range */
iosynth = cm->iobase + CM_REG_FM_PCI;
err = snd_opl3_create(cm->card, iosynth, iosynth + 2,
OPL3_HW_OPL3, 1, &opl3);
} else {
err = -EIO;
}
if (err < 0) {
/* then try legacy ports */
val = snd_cmipci_read(cm, CM_REG_LEGACY_CTRL) & ~CM_FMSEL_MASK;
iosynth = fm_port;
switch (iosynth) {
case 0x3E8: val |= CM_FMSEL_3E8; break;
case 0x3E0: val |= CM_FMSEL_3E0; break;
case 0x3C8: val |= CM_FMSEL_3C8; break;
case 0x388: val |= CM_FMSEL_388; break;
default:
goto disable_fm;
}
snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val);
/* enable FM */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
if (snd_opl3_create(cm->card, iosynth, iosynth + 2,
OPL3_HW_OPL3, 0, &opl3) < 0) {
printk(KERN_ERR "cmipci: no OPL device at %#lx, "
"skipping...\n", iosynth);
goto disable_fm;
}
}
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
printk(KERN_ERR "cmipci: cannot create OPL3 hwdep\n");
return err;
}
return 0;
disable_fm:
snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_FMSEL_MASK);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
return 0;
}
static int __devinit snd_cmipci_create(struct snd_card *card, struct pci_dev *pci,
int dev, struct cmipci **rcmipci)
{
struct cmipci *cm;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_cmipci_dev_free,
};
unsigned int val;
long iomidi = 0;
int integrated_midi = 0;
char modelstr[16];
int pcm_index, pcm_spdif_index;
static DEFINE_PCI_DEVICE_TABLE(intel_82437vx) = {
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437VX) },
{ },
};
*rcmipci = NULL;
if ((err = pci_enable_device(pci)) < 0)
return err;
cm = kzalloc(sizeof(*cm), GFP_KERNEL);
if (cm == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&cm->reg_lock);
mutex_init(&cm->open_mutex);
cm->device = pci->device;
cm->card = card;
cm->pci = pci;
cm->irq = -1;
cm->channel[0].ch = 0;
cm->channel[1].ch = 1;
cm->channel[0].is_dac = cm->channel[1].is_dac = 1; /* dual DAC mode */
if ((err = pci_request_regions(pci, card->driver)) < 0) {
kfree(cm);
pci_disable_device(pci);
return err;
}
cm->iobase = pci_resource_start(pci, 0);
if (request_irq(pci->irq, snd_cmipci_interrupt,
IRQF_SHARED, KBUILD_MODNAME, cm)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_cmipci_free(cm);
return -EBUSY;
}
cm->irq = pci->irq;
pci_set_master(cm->pci);
/*
* check chip version, max channels and capabilities
*/
cm->chip_version = 0;
cm->max_channels = 2;
cm->do_soft_ac3 = soft_ac3[dev];
if (pci->device != PCI_DEVICE_ID_CMEDIA_CM8338A &&
pci->device != PCI_DEVICE_ID_CMEDIA_CM8338B)
query_chip(cm);
/* added -MCx suffix for chip supporting multi-channels */
if (cm->can_multi_ch)
sprintf(cm->card->driver + strlen(cm->card->driver),
"-MC%d", cm->max_channels);
else if (cm->can_ac3_sw)
strcpy(cm->card->driver + strlen(cm->card->driver), "-SWIEC");
cm->dig_status = SNDRV_PCM_DEFAULT_CON_SPDIF;
cm->dig_pcm_status = SNDRV_PCM_DEFAULT_CON_SPDIF;
#if CM_CH_PLAY == 1
cm->ctrl = CM_CHADC0; /* default FUNCNTRL0 */
#else
cm->ctrl = CM_CHADC1; /* default FUNCNTRL0 */
#endif
/* initialize codec registers */
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_RESET);
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_RESET);
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0); /* disable ints */
snd_cmipci_ch_reset(cm, CM_CH_PLAY);
snd_cmipci_ch_reset(cm, CM_CH_CAPT);
snd_cmipci_write(cm, CM_REG_FUNCTRL0, 0); /* disable channels */
snd_cmipci_write(cm, CM_REG_FUNCTRL1, 0);
snd_cmipci_write(cm, CM_REG_CHFORMAT, 0);
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC|CM_N4SPK3D);
#if CM_CH_PLAY == 1
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
#else
snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
#endif
if (cm->chip_version) {
snd_cmipci_write_b(cm, CM_REG_EXT_MISC, 0x20); /* magic */
snd_cmipci_write_b(cm, CM_REG_EXT_MISC + 1, 0x09); /* more magic */
}
/* Set Bus Master Request */
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_BREQ);
/* Assume TX and compatible chip set (Autodetection required for VX chip sets) */
switch (pci->device) {
case PCI_DEVICE_ID_CMEDIA_CM8738:
case PCI_DEVICE_ID_CMEDIA_CM8738B:
if (!pci_dev_present(intel_82437vx))
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_TXVX);
break;
default:
break;
}
if (cm->chip_version < 68) {
val = pci->device < 0x110 ? 8338 : 8738;
} else {
switch (snd_cmipci_read_b(cm, CM_REG_INT_HLDCLR + 3) & 0x03) {
case 0:
val = 8769;
break;
case 2:
val = 8762;
break;
default:
switch ((pci->subsystem_vendor << 16) |
pci->subsystem_device) {
case 0x13f69761:
case 0x584d3741:
case 0x584d3751:
case 0x584d3761:
case 0x584d3771:
case 0x72848384:
val = 8770;
break;
default:
val = 8768;
break;
}
}
}
sprintf(card->shortname, "C-Media CMI%d", val);
if (cm->chip_version < 68)
sprintf(modelstr, " (model %d)", cm->chip_version);
else
modelstr[0] = '\0';
sprintf(card->longname, "%s%s at %#lx, irq %i",
card->shortname, modelstr, cm->iobase, cm->irq);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, cm, &ops)) < 0) {
snd_cmipci_free(cm);
return err;
}
if (cm->chip_version >= 39) {
val = snd_cmipci_read_b(cm, CM_REG_MPU_PCI + 1);
if (val != 0x00 && val != 0xff) {
iomidi = cm->iobase + CM_REG_MPU_PCI;
integrated_midi = 1;
}
}
if (!integrated_midi) {
val = 0;
iomidi = mpu_port[dev];
switch (iomidi) {
case 0x320: val = CM_VMPU_320; break;
case 0x310: val = CM_VMPU_310; break;
case 0x300: val = CM_VMPU_300; break;
case 0x330: val = CM_VMPU_330; break;
default:
iomidi = 0; break;
}
if (iomidi > 0) {
snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val);
/* enable UART */
snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_UART_EN);
if (inb(iomidi + 1) == 0xff) {
snd_printk(KERN_ERR "cannot enable MPU-401 port"
" at %#lx\n", iomidi);
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1,
CM_UART_EN);
iomidi = 0;
}
}
}
if (cm->chip_version < 68) {
err = snd_cmipci_create_fm(cm, fm_port[dev]);
if (err < 0)
return err;
}
/* reset mixer */
snd_cmipci_mixer_write(cm, 0, 0);
snd_cmipci_proc_init(cm);
/* create pcm devices */
pcm_index = pcm_spdif_index = 0;
if ((err = snd_cmipci_pcm_new(cm, pcm_index)) < 0)
return err;
pcm_index++;
if ((err = snd_cmipci_pcm2_new(cm, pcm_index)) < 0)
return err;
pcm_index++;
if (cm->can_ac3_hw || cm->can_ac3_sw) {
pcm_spdif_index = pcm_index;
if ((err = snd_cmipci_pcm_spdif_new(cm, pcm_index)) < 0)
return err;
}
/* create mixer interface & switches */
if ((err = snd_cmipci_mixer_new(cm, pcm_spdif_index)) < 0)
return err;
if (iomidi > 0) {
if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_CMIPCI,
iomidi,
(integrated_midi ?
MPU401_INFO_INTEGRATED : 0) |
MPU401_INFO_IRQ_HOOK,
-1, &cm->rmidi)) < 0) {
printk(KERN_ERR "cmipci: no UART401 device at 0x%lx\n", iomidi);
}
}
#ifdef USE_VAR48KRATE
for (val = 0; val < ARRAY_SIZE(rates); val++)
snd_cmipci_set_pll(cm, rates[val], val);
/*
* (Re-)Enable external switch spdo_48k
*/
snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K|CM_SPDF_AC97);
#endif /* USE_VAR48KRATE */
if (snd_cmipci_create_gameport(cm, dev) < 0)
snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
snd_card_set_dev(card, &pci->dev);
*rcmipci = cm;
return 0;
}
/*
*/
MODULE_DEVICE_TABLE(pci, snd_cmipci_ids);
static int __devinit snd_cmipci_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct cmipci *cm;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (! enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
switch (pci->device) {
case PCI_DEVICE_ID_CMEDIA_CM8738:
case PCI_DEVICE_ID_CMEDIA_CM8738B:
strcpy(card->driver, "CMI8738");
break;
case PCI_DEVICE_ID_CMEDIA_CM8338A:
case PCI_DEVICE_ID_CMEDIA_CM8338B:
strcpy(card->driver, "CMI8338");
break;
default:
strcpy(card->driver, "CMIPCI");
break;
}
if ((err = snd_cmipci_create(card, pci, dev, &cm)) < 0) {
snd_card_free(card);
return err;
}
card->private_data = cm;
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void __devexit snd_cmipci_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
#ifdef CONFIG_PM
/*
* power management
*/
static unsigned char saved_regs[] = {
CM_REG_FUNCTRL1, CM_REG_CHFORMAT, CM_REG_LEGACY_CTRL, CM_REG_MISC_CTRL,
CM_REG_MIXER0, CM_REG_MIXER1, CM_REG_MIXER2, CM_REG_MIXER3, CM_REG_PLL,
CM_REG_CH0_FRAME1, CM_REG_CH0_FRAME2,
CM_REG_CH1_FRAME1, CM_REG_CH1_FRAME2, CM_REG_EXT_MISC,
CM_REG_INT_STATUS, CM_REG_INT_HLDCLR, CM_REG_FUNCTRL0,
};
static unsigned char saved_mixers[] = {
SB_DSP4_MASTER_DEV, SB_DSP4_MASTER_DEV + 1,
SB_DSP4_PCM_DEV, SB_DSP4_PCM_DEV + 1,
SB_DSP4_SYNTH_DEV, SB_DSP4_SYNTH_DEV + 1,
SB_DSP4_CD_DEV, SB_DSP4_CD_DEV + 1,
SB_DSP4_LINE_DEV, SB_DSP4_LINE_DEV + 1,
SB_DSP4_MIC_DEV, SB_DSP4_SPEAKER_DEV,
CM_REG_EXTENT_IND, SB_DSP4_OUTPUT_SW,
SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT,
};
static int snd_cmipci_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct cmipci *cm = card->private_data;
int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(cm->pcm);
snd_pcm_suspend_all(cm->pcm2);
snd_pcm_suspend_all(cm->pcm_spdif);
/* save registers */
for (i = 0; i < ARRAY_SIZE(saved_regs); i++)
cm->saved_regs[i] = snd_cmipci_read(cm, saved_regs[i]);
for (i = 0; i < ARRAY_SIZE(saved_mixers); i++)
cm->saved_mixers[i] = snd_cmipci_mixer_read(cm, saved_mixers[i]);
/* disable ints */
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int snd_cmipci_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct cmipci *cm = card->private_data;
int i;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "cmipci: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
/* reset / initialize to a sane state */
snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0);
snd_cmipci_ch_reset(cm, CM_CH_PLAY);
snd_cmipci_ch_reset(cm, CM_CH_CAPT);
snd_cmipci_mixer_write(cm, 0, 0);
/* restore registers */
for (i = 0; i < ARRAY_SIZE(saved_regs); i++)
snd_cmipci_write(cm, saved_regs[i], cm->saved_regs[i]);
for (i = 0; i < ARRAY_SIZE(saved_mixers); i++)
snd_cmipci_mixer_write(cm, saved_mixers[i], cm->saved_mixers[i]);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver driver = {
.name = KBUILD_MODNAME,
.id_table = snd_cmipci_ids,
.probe = snd_cmipci_probe,
.remove = __devexit_p(snd_cmipci_remove),
#ifdef CONFIG_PM
.suspend = snd_cmipci_suspend,
.resume = snd_cmipci_resume,
#endif
};
static int __init alsa_card_cmipci_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_cmipci_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_cmipci_init)
module_exit(alsa_card_cmipci_exit)
| gpl-2.0 |
uliamo/android_kernel_zte_quantum | drivers/acpi/acpica/rsio.c | 5150 | 9211 | /*******************************************************************************
*
* Module Name: rsio - IO and DMA resource descriptors
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acresrc.h"
#define _COMPONENT ACPI_RESOURCES
ACPI_MODULE_NAME("rsio")
/*******************************************************************************
*
* acpi_rs_convert_io
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_convert_io[5] = {
{ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_IO,
ACPI_RS_SIZE(struct acpi_resource_io),
ACPI_RSC_TABLE_SIZE(acpi_rs_convert_io)},
{ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_IO,
sizeof(struct aml_resource_io),
0},
/* Decode flag */
{ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET(data.io.io_decode),
AML_OFFSET(io.flags),
0},
/*
* These fields are contiguous in both the source and destination:
* Address Alignment
* Length
* Minimum Base Address
* Maximum Base Address
*/
{ACPI_RSC_MOVE8, ACPI_RS_OFFSET(data.io.alignment),
AML_OFFSET(io.alignment),
2},
{ACPI_RSC_MOVE16, ACPI_RS_OFFSET(data.io.minimum),
AML_OFFSET(io.minimum),
2}
};
/*******************************************************************************
*
* acpi_rs_convert_fixed_io
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_convert_fixed_io[4] = {
{ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_FIXED_IO,
ACPI_RS_SIZE(struct acpi_resource_fixed_io),
ACPI_RSC_TABLE_SIZE(acpi_rs_convert_fixed_io)},
{ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_FIXED_IO,
sizeof(struct aml_resource_fixed_io),
0},
/*
* These fields are contiguous in both the source and destination:
* Base Address
* Length
*/
{ACPI_RSC_MOVE8, ACPI_RS_OFFSET(data.fixed_io.address_length),
AML_OFFSET(fixed_io.address_length),
1},
{ACPI_RSC_MOVE16, ACPI_RS_OFFSET(data.fixed_io.address),
AML_OFFSET(fixed_io.address),
1}
};
/*******************************************************************************
*
* acpi_rs_convert_generic_reg
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_convert_generic_reg[4] = {
{ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_GENERIC_REGISTER,
ACPI_RS_SIZE(struct acpi_resource_generic_register),
ACPI_RSC_TABLE_SIZE(acpi_rs_convert_generic_reg)},
{ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_GENERIC_REGISTER,
sizeof(struct aml_resource_generic_register),
0},
/*
* These fields are contiguous in both the source and destination:
* Address Space ID
* Register Bit Width
* Register Bit Offset
* Access Size
*/
{ACPI_RSC_MOVE8, ACPI_RS_OFFSET(data.generic_reg.space_id),
AML_OFFSET(generic_reg.address_space_id),
4},
/* Get the Register Address */
{ACPI_RSC_MOVE64, ACPI_RS_OFFSET(data.generic_reg.address),
AML_OFFSET(generic_reg.address),
1}
};
/*******************************************************************************
*
* acpi_rs_convert_end_dpf
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_convert_end_dpf[2] = {
{ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_END_DEPENDENT,
ACPI_RS_SIZE_MIN,
ACPI_RSC_TABLE_SIZE(acpi_rs_convert_end_dpf)},
{ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_END_DEPENDENT,
sizeof(struct aml_resource_end_dependent),
0}
};
/*******************************************************************************
*
* acpi_rs_convert_end_tag
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_convert_end_tag[2] = {
{ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_END_TAG,
ACPI_RS_SIZE_MIN,
ACPI_RSC_TABLE_SIZE(acpi_rs_convert_end_tag)},
/*
* Note: The checksum field is set to zero, meaning that the resource
* data is treated as if the checksum operation succeeded.
* (ACPI Spec 1.0b Section 6.4.2.8)
*/
{ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_END_TAG,
sizeof(struct aml_resource_end_tag),
0}
};
/*******************************************************************************
*
* acpi_rs_get_start_dpf
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_get_start_dpf[6] = {
{ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_START_DEPENDENT,
ACPI_RS_SIZE(struct acpi_resource_start_dependent),
ACPI_RSC_TABLE_SIZE(acpi_rs_get_start_dpf)},
/* Defaults for Compatibility and Performance priorities */
{ACPI_RSC_SET8, ACPI_RS_OFFSET(data.start_dpf.compatibility_priority),
ACPI_ACCEPTABLE_CONFIGURATION,
2},
/* Get the descriptor length (0 or 1 for Start Dpf descriptor) */
{ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET(data.start_dpf.descriptor_length),
AML_OFFSET(start_dpf.descriptor_type),
0},
/* All done if there is no flag byte present in the descriptor */
{ACPI_RSC_EXIT_NE, ACPI_RSC_COMPARE_AML_LENGTH, 0, 1},
/* Flag byte is present, get the flags */
{ACPI_RSC_2BITFLAG,
ACPI_RS_OFFSET(data.start_dpf.compatibility_priority),
AML_OFFSET(start_dpf.flags),
0},
{ACPI_RSC_2BITFLAG,
ACPI_RS_OFFSET(data.start_dpf.performance_robustness),
AML_OFFSET(start_dpf.flags),
2}
};
/*******************************************************************************
*
* acpi_rs_set_start_dpf
*
******************************************************************************/
struct acpi_rsconvert_info acpi_rs_set_start_dpf[10] = {
/* Start with a default descriptor of length 1 */
{ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_START_DEPENDENT,
sizeof(struct aml_resource_start_dependent),
ACPI_RSC_TABLE_SIZE(acpi_rs_set_start_dpf)},
/* Set the default flag values */
{ACPI_RSC_2BITFLAG,
ACPI_RS_OFFSET(data.start_dpf.compatibility_priority),
AML_OFFSET(start_dpf.flags),
0},
{ACPI_RSC_2BITFLAG,
ACPI_RS_OFFSET(data.start_dpf.performance_robustness),
AML_OFFSET(start_dpf.flags),
2},
/*
* All done if the output descriptor length is required to be 1
* (i.e., optimization to 0 bytes cannot be attempted)
*/
{ACPI_RSC_EXIT_EQ, ACPI_RSC_COMPARE_VALUE,
ACPI_RS_OFFSET(data.start_dpf.descriptor_length),
1},
/* Set length to 0 bytes (no flags byte) */
{ACPI_RSC_LENGTH, 0, 0,
sizeof(struct aml_resource_start_dependent_noprio)},
/*
* All done if the output descriptor length is required to be 0.
*
* TBD: Perhaps we should check for error if input flags are not
* compatible with a 0-byte descriptor.
*/
{ACPI_RSC_EXIT_EQ, ACPI_RSC_COMPARE_VALUE,
ACPI_RS_OFFSET(data.start_dpf.descriptor_length),
0},
/* Reset length to 1 byte (descriptor with flags byte) */
{ACPI_RSC_LENGTH, 0, 0, sizeof(struct aml_resource_start_dependent)},
/*
* All done if flags byte is necessary -- if either priority value
* is not ACPI_ACCEPTABLE_CONFIGURATION
*/
{ACPI_RSC_EXIT_NE, ACPI_RSC_COMPARE_VALUE,
ACPI_RS_OFFSET(data.start_dpf.compatibility_priority),
ACPI_ACCEPTABLE_CONFIGURATION},
{ACPI_RSC_EXIT_NE, ACPI_RSC_COMPARE_VALUE,
ACPI_RS_OFFSET(data.start_dpf.performance_robustness),
ACPI_ACCEPTABLE_CONFIGURATION},
/* Flag byte is not necessary */
{ACPI_RSC_LENGTH, 0, 0,
sizeof(struct aml_resource_start_dependent_noprio)}
};
| gpl-2.0 |
languitar/android_kernel_lge_hammerhead | drivers/input/mouse/logips2pp.c | 7198 | 11714 | /*
* Logitech PS/2++ mouse driver
*
* Copyright (c) 1999-2003 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2003 Eric Wong <eric@yhbt.net>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include "psmouse.h"
#include "logips2pp.h"
/* Logitech mouse types */
#define PS2PP_KIND_WHEEL 1
#define PS2PP_KIND_MX 2
#define PS2PP_KIND_TP3 3
#define PS2PP_KIND_TRACKMAN 4
/* Logitech mouse features */
#define PS2PP_WHEEL 0x01
#define PS2PP_HWHEEL 0x02
#define PS2PP_SIDE_BTN 0x04
#define PS2PP_EXTRA_BTN 0x08
#define PS2PP_TASK_BTN 0x10
#define PS2PP_NAV_BTN 0x20
struct ps2pp_info {
u8 model;
u8 kind;
u16 features;
};
/*
* Process a PS2++ or PS2T++ packet.
*/
static psmouse_ret_t ps2pp_process_byte(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
if (psmouse->pktcnt < 3)
return PSMOUSE_GOOD_DATA;
/*
* Full packet accumulated, process it
*/
if ((packet[0] & 0x48) == 0x48 && (packet[1] & 0x02) == 0x02) {
/* Logitech extended packet */
switch ((packet[1] >> 4) | (packet[0] & 0x30)) {
case 0x0d: /* Mouse extra info */
input_report_rel(dev, packet[2] & 0x80 ? REL_HWHEEL : REL_WHEEL,
(int) (packet[2] & 8) - (int) (packet[2] & 7));
input_report_key(dev, BTN_SIDE, (packet[2] >> 4) & 1);
input_report_key(dev, BTN_EXTRA, (packet[2] >> 5) & 1);
break;
case 0x0e: /* buttons 4, 5, 6, 7, 8, 9, 10 info */
input_report_key(dev, BTN_SIDE, (packet[2]) & 1);
input_report_key(dev, BTN_EXTRA, (packet[2] >> 1) & 1);
input_report_key(dev, BTN_BACK, (packet[2] >> 3) & 1);
input_report_key(dev, BTN_FORWARD, (packet[2] >> 4) & 1);
input_report_key(dev, BTN_TASK, (packet[2] >> 2) & 1);
break;
case 0x0f: /* TouchPad extra info */
input_report_rel(dev, packet[2] & 0x08 ? REL_HWHEEL : REL_WHEEL,
(int) ((packet[2] >> 4) & 8) - (int) ((packet[2] >> 4) & 7));
packet[0] = packet[2] | 0x08;
break;
default:
psmouse_dbg(psmouse,
"Received PS2++ packet #%x, but don't know how to handle.\n",
(packet[1] >> 4) | (packet[0] & 0x30));
break;
}
} else {
/* Standard PS/2 motion data */
input_report_rel(dev, REL_X, packet[1] ? (int) packet[1] - (int) ((packet[0] << 4) & 0x100) : 0);
input_report_rel(dev, REL_Y, packet[2] ? (int) ((packet[0] << 3) & 0x100) - (int) packet[2] : 0);
}
input_report_key(dev, BTN_LEFT, packet[0] & 1);
input_report_key(dev, BTN_MIDDLE, (packet[0] >> 2) & 1);
input_report_key(dev, BTN_RIGHT, (packet[0] >> 1) & 1);
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
/*
* ps2pp_cmd() sends a PS2++ command, sliced into two bit
* pieces through the SETRES command. This is needed to send extended
* commands to mice on notebooks that try to understand the PS/2 protocol
* Ugly.
*/
static int ps2pp_cmd(struct psmouse *psmouse, unsigned char *param, unsigned char command)
{
if (psmouse_sliced_command(psmouse, command))
return -1;
if (ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_POLL | 0x0300))
return -1;
return 0;
}
/*
* SmartScroll / CruiseControl for some newer Logitech mice Defaults to
* enabled if we do nothing to it. Of course I put this in because I want it
* disabled :P
* 1 - enabled (if previously disabled, also default)
* 0 - disabled
*/
static void ps2pp_set_smartscroll(struct psmouse *psmouse, bool smartscroll)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
ps2pp_cmd(psmouse, param, 0x32);
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
param[0] = smartscroll;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
}
static ssize_t ps2pp_attr_show_smartscroll(struct psmouse *psmouse,
void *data, char *buf)
{
return sprintf(buf, "%d\n", psmouse->smartscroll);
}
static ssize_t ps2pp_attr_set_smartscroll(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
ps2pp_set_smartscroll(psmouse, value);
psmouse->smartscroll = value;
return count;
}
PSMOUSE_DEFINE_ATTR(smartscroll, S_IWUSR | S_IRUGO, NULL,
ps2pp_attr_show_smartscroll, ps2pp_attr_set_smartscroll);
/*
* Support 800 dpi resolution _only_ if the user wants it (there are good
* reasons to not use it even if the mouse supports it, and of course there are
* also good reasons to use it, let the user decide).
*/
static void ps2pp_set_resolution(struct psmouse *psmouse, unsigned int resolution)
{
if (resolution > 400) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param = 3;
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, ¶m, PSMOUSE_CMD_SETRES);
psmouse->resolution = 800;
} else
psmouse_set_resolution(psmouse, resolution);
}
static void ps2pp_disconnect(struct psmouse *psmouse)
{
device_remove_file(&psmouse->ps2dev.serio->dev, &psmouse_attr_smartscroll.dattr);
}
static const struct ps2pp_info *get_model_info(unsigned char model)
{
static const struct ps2pp_info ps2pp_list[] = {
{ 1, 0, 0 }, /* Simple 2-button mouse */
{ 12, 0, PS2PP_SIDE_BTN},
{ 13, 0, 0 },
{ 15, PS2PP_KIND_MX, /* MX1000 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 40, 0, PS2PP_SIDE_BTN },
{ 41, 0, PS2PP_SIDE_BTN },
{ 42, 0, PS2PP_SIDE_BTN },
{ 43, 0, PS2PP_SIDE_BTN },
{ 50, 0, 0 },
{ 51, 0, 0 },
{ 52, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 53, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 56, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL }, /* Cordless MouseMan Wheel */
{ 61, PS2PP_KIND_MX, /* MX700 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 66, PS2PP_KIND_MX, /* MX3100 reciver */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 72, PS2PP_KIND_TRACKMAN, 0 }, /* T-CH11: TrackMan Marble */
{ 73, PS2PP_KIND_TRACKMAN, PS2PP_SIDE_BTN }, /* TrackMan FX */
{ 75, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 76, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 79, PS2PP_KIND_TRACKMAN, PS2PP_WHEEL }, /* TrackMan with wheel */
{ 80, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 81, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 83, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 85, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 86, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 87, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 88, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 96, 0, 0 },
{ 97, PS2PP_KIND_TP3, PS2PP_WHEEL | PS2PP_HWHEEL },
{ 99, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 100, PS2PP_KIND_MX, /* MX510 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 111, PS2PP_KIND_MX, PS2PP_WHEEL | PS2PP_SIDE_BTN }, /* MX300 reports task button as side */
{ 112, PS2PP_KIND_MX, /* MX500 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 114, PS2PP_KIND_MX, /* MX310 */
PS2PP_WHEEL | PS2PP_SIDE_BTN |
PS2PP_TASK_BTN | PS2PP_EXTRA_BTN }
};
int i;
for (i = 0; i < ARRAY_SIZE(ps2pp_list); i++)
if (model == ps2pp_list[i].model)
return &ps2pp_list[i];
return NULL;
}
/*
* Set up input device's properties based on the detected mouse model.
*/
static void ps2pp_set_model_properties(struct psmouse *psmouse,
const struct ps2pp_info *model_info,
bool using_ps2pp)
{
struct input_dev *input_dev = psmouse->dev;
if (model_info->features & PS2PP_SIDE_BTN)
__set_bit(BTN_SIDE, input_dev->keybit);
if (model_info->features & PS2PP_EXTRA_BTN)
__set_bit(BTN_EXTRA, input_dev->keybit);
if (model_info->features & PS2PP_TASK_BTN)
__set_bit(BTN_TASK, input_dev->keybit);
if (model_info->features & PS2PP_NAV_BTN) {
__set_bit(BTN_FORWARD, input_dev->keybit);
__set_bit(BTN_BACK, input_dev->keybit);
}
if (model_info->features & PS2PP_WHEEL)
__set_bit(REL_WHEEL, input_dev->relbit);
if (model_info->features & PS2PP_HWHEEL)
__set_bit(REL_HWHEEL, input_dev->relbit);
switch (model_info->kind) {
case PS2PP_KIND_WHEEL:
psmouse->name = "Wheel Mouse";
break;
case PS2PP_KIND_MX:
psmouse->name = "MX Mouse";
break;
case PS2PP_KIND_TP3:
psmouse->name = "TouchPad 3";
break;
case PS2PP_KIND_TRACKMAN:
psmouse->name = "TrackMan";
break;
default:
/*
* Set name to "Mouse" only when using PS2++,
* otherwise let other protocols define suitable
* name
*/
if (using_ps2pp)
psmouse->name = "Mouse";
break;
}
}
/*
* Logitech magic init. Detect whether the mouse is a Logitech one
* and its exact model and try turning on extended protocol for ones
* that support it.
*/
int ps2pp_init(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
unsigned char model, buttons;
const struct ps2pp_info *model_info;
bool use_ps2pp = false;
int error;
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
param[1] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO);
model = ((param[0] >> 4) & 0x07) | ((param[0] << 3) & 0x78);
buttons = param[1];
if (!model || !buttons)
return -1;
model_info = get_model_info(model);
if (model_info) {
/*
* Do Logitech PS2++ / PS2T++ magic init.
*/
if (model_info->kind == PS2PP_KIND_TP3) { /* Touch Pad 3 */
/* Unprotect RAM */
param[0] = 0x11; param[1] = 0x04; param[2] = 0x68;
ps2_command(ps2dev, param, 0x30d1);
/* Enable features */
param[0] = 0x11; param[1] = 0x05; param[2] = 0x0b;
ps2_command(ps2dev, param, 0x30d1);
/* Enable PS2++ */
param[0] = 0x11; param[1] = 0x09; param[2] = 0xc3;
ps2_command(ps2dev, param, 0x30d1);
param[0] = 0;
if (!ps2_command(ps2dev, param, 0x13d1) &&
param[0] == 0x06 && param[1] == 0x00 && param[2] == 0x14) {
use_ps2pp = true;
}
} else {
param[0] = param[1] = param[2] = 0;
ps2pp_cmd(psmouse, param, 0x39); /* Magic knock */
ps2pp_cmd(psmouse, param, 0xDB);
if ((param[0] & 0x78) == 0x48 &&
(param[1] & 0xf3) == 0xc2 &&
(param[2] & 0x03) == ((param[1] >> 2) & 3)) {
ps2pp_set_smartscroll(psmouse, false);
use_ps2pp = true;
}
}
} else {
psmouse_warn(psmouse, "Detected unknown Logitech mouse model %d\n", model);
}
if (set_properties) {
psmouse->vendor = "Logitech";
psmouse->model = model;
if (use_ps2pp) {
psmouse->protocol_handler = ps2pp_process_byte;
psmouse->pktsize = 3;
if (model_info->kind != PS2PP_KIND_TP3) {
psmouse->set_resolution = ps2pp_set_resolution;
psmouse->disconnect = ps2pp_disconnect;
error = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_smartscroll.dattr);
if (error) {
psmouse_err(psmouse,
"failed to create smartscroll sysfs attribute, error: %d\n",
error);
return -1;
}
}
}
if (buttons >= 3)
__set_bit(BTN_MIDDLE, psmouse->dev->keybit);
if (model_info)
ps2pp_set_model_properties(psmouse, model_info, use_ps2pp);
}
return use_ps2pp ? 0 : -1;
}
| gpl-2.0 |
elektroschmock/android_kernel_google_msm | drivers/char/apm-emulation.c | 7454 | 17812 | /*
* bios-less APM driver for ARM Linux
* Jamey Hicks <jamey@crl.dec.com>
* adapted from the APM BIOS driver for Linux by Stephen Rothwell (sfr@linuxcare.com)
*
* APM 1.2 Reference:
* Intel Corporation, Microsoft Corporation. Advanced Power Management
* (APM) BIOS Interface Specification, Revision 1.2, February 1996.
*
* This document is available from Microsoft at:
* http://www.microsoft.com/whdc/archive/amp_12.mspx
*/
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/miscdevice.h>
#include <linux/apm_bios.h>
#include <linux/capability.h>
#include <linux/sched.h>
#include <linux/suspend.h>
#include <linux/apm-emulation.h>
#include <linux/freezer.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/completion.h>
#include <linux/kthread.h>
#include <linux/delay.h>
/*
* The apm_bios device is one of the misc char devices.
* This is its minor number.
*/
#define APM_MINOR_DEV 134
/*
* One option can be changed at boot time as follows:
* apm=on/off enable/disable APM
*/
/*
* Maximum number of events stored
*/
#define APM_MAX_EVENTS 16
struct apm_queue {
unsigned int event_head;
unsigned int event_tail;
apm_event_t events[APM_MAX_EVENTS];
};
/*
* thread states (for threads using a writable /dev/apm_bios fd):
*
* SUSPEND_NONE: nothing happening
* SUSPEND_PENDING: suspend event queued for thread and pending to be read
* SUSPEND_READ: suspend event read, pending acknowledgement
* SUSPEND_ACKED: acknowledgement received from thread (via ioctl),
* waiting for resume
* SUSPEND_ACKTO: acknowledgement timeout
* SUSPEND_DONE: thread had acked suspend and is now notified of
* resume
*
* SUSPEND_WAIT: this thread invoked suspend and is waiting for resume
*
* A thread migrates in one of three paths:
* NONE -1-> PENDING -2-> READ -3-> ACKED -4-> DONE -5-> NONE
* -6-> ACKTO -7-> NONE
* NONE -8-> WAIT -9-> NONE
*
* While in PENDING or READ, the thread is accounted for in the
* suspend_acks_pending counter.
*
* The transitions are invoked as follows:
* 1: suspend event is signalled from the core PM code
* 2: the suspend event is read from the fd by the userspace thread
* 3: userspace thread issues the APM_IOC_SUSPEND ioctl (as ack)
* 4: core PM code signals that we have resumed
* 5: APM_IOC_SUSPEND ioctl returns
*
* 6: the notifier invoked from the core PM code timed out waiting
* for all relevant threds to enter ACKED state and puts those
* that haven't into ACKTO
* 7: those threads issue APM_IOC_SUSPEND ioctl too late,
* get an error
*
* 8: userspace thread issues the APM_IOC_SUSPEND ioctl (to suspend),
* ioctl code invokes pm_suspend()
* 9: pm_suspend() returns indicating resume
*/
enum apm_suspend_state {
SUSPEND_NONE,
SUSPEND_PENDING,
SUSPEND_READ,
SUSPEND_ACKED,
SUSPEND_ACKTO,
SUSPEND_WAIT,
SUSPEND_DONE,
};
/*
* The per-file APM data
*/
struct apm_user {
struct list_head list;
unsigned int suser: 1;
unsigned int writer: 1;
unsigned int reader: 1;
int suspend_result;
enum apm_suspend_state suspend_state;
struct apm_queue queue;
};
/*
* Local variables
*/
static atomic_t suspend_acks_pending = ATOMIC_INIT(0);
static atomic_t userspace_notification_inhibit = ATOMIC_INIT(0);
static int apm_disabled;
static struct task_struct *kapmd_tsk;
static DECLARE_WAIT_QUEUE_HEAD(apm_waitqueue);
static DECLARE_WAIT_QUEUE_HEAD(apm_suspend_waitqueue);
/*
* This is a list of everyone who has opened /dev/apm_bios
*/
static DECLARE_RWSEM(user_list_lock);
static LIST_HEAD(apm_user_list);
/*
* kapmd info. kapmd provides us a process context to handle
* "APM" events within - specifically necessary if we're going
* to be suspending the system.
*/
static DECLARE_WAIT_QUEUE_HEAD(kapmd_wait);
static DEFINE_SPINLOCK(kapmd_queue_lock);
static struct apm_queue kapmd_queue;
static DEFINE_MUTEX(state_lock);
static const char driver_version[] = "1.13"; /* no spaces */
/*
* Compatibility cruft until the IPAQ people move over to the new
* interface.
*/
static void __apm_get_power_status(struct apm_power_info *info)
{
}
/*
* This allows machines to provide their own "apm get power status" function.
*/
void (*apm_get_power_status)(struct apm_power_info *) = __apm_get_power_status;
EXPORT_SYMBOL(apm_get_power_status);
/*
* APM event queue management.
*/
static inline int queue_empty(struct apm_queue *q)
{
return q->event_head == q->event_tail;
}
static inline apm_event_t queue_get_event(struct apm_queue *q)
{
q->event_tail = (q->event_tail + 1) % APM_MAX_EVENTS;
return q->events[q->event_tail];
}
static void queue_add_event(struct apm_queue *q, apm_event_t event)
{
q->event_head = (q->event_head + 1) % APM_MAX_EVENTS;
if (q->event_head == q->event_tail) {
static int notified;
if (notified++ == 0)
printk(KERN_ERR "apm: an event queue overflowed\n");
q->event_tail = (q->event_tail + 1) % APM_MAX_EVENTS;
}
q->events[q->event_head] = event;
}
static void queue_event(apm_event_t event)
{
struct apm_user *as;
down_read(&user_list_lock);
list_for_each_entry(as, &apm_user_list, list) {
if (as->reader)
queue_add_event(&as->queue, event);
}
up_read(&user_list_lock);
wake_up_interruptible(&apm_waitqueue);
}
static ssize_t apm_read(struct file *fp, char __user *buf, size_t count, loff_t *ppos)
{
struct apm_user *as = fp->private_data;
apm_event_t event;
int i = count, ret = 0;
if (count < sizeof(apm_event_t))
return -EINVAL;
if (queue_empty(&as->queue) && fp->f_flags & O_NONBLOCK)
return -EAGAIN;
wait_event_interruptible(apm_waitqueue, !queue_empty(&as->queue));
while ((i >= sizeof(event)) && !queue_empty(&as->queue)) {
event = queue_get_event(&as->queue);
ret = -EFAULT;
if (copy_to_user(buf, &event, sizeof(event)))
break;
mutex_lock(&state_lock);
if (as->suspend_state == SUSPEND_PENDING &&
(event == APM_SYS_SUSPEND || event == APM_USER_SUSPEND))
as->suspend_state = SUSPEND_READ;
mutex_unlock(&state_lock);
buf += sizeof(event);
i -= sizeof(event);
}
if (i < count)
ret = count - i;
return ret;
}
static unsigned int apm_poll(struct file *fp, poll_table * wait)
{
struct apm_user *as = fp->private_data;
poll_wait(fp, &apm_waitqueue, wait);
return queue_empty(&as->queue) ? 0 : POLLIN | POLLRDNORM;
}
/*
* apm_ioctl - handle APM ioctl
*
* APM_IOC_SUSPEND
* This IOCTL is overloaded, and performs two functions. It is used to:
* - initiate a suspend
* - acknowledge a suspend read from /dev/apm_bios.
* Only when everyone who has opened /dev/apm_bios with write permission
* has acknowledge does the actual suspend happen.
*/
static long
apm_ioctl(struct file *filp, u_int cmd, u_long arg)
{
struct apm_user *as = filp->private_data;
int err = -EINVAL;
if (!as->suser || !as->writer)
return -EPERM;
switch (cmd) {
case APM_IOC_SUSPEND:
mutex_lock(&state_lock);
as->suspend_result = -EINTR;
switch (as->suspend_state) {
case SUSPEND_READ:
/*
* If we read a suspend command from /dev/apm_bios,
* then the corresponding APM_IOC_SUSPEND ioctl is
* interpreted as an acknowledge.
*/
as->suspend_state = SUSPEND_ACKED;
atomic_dec(&suspend_acks_pending);
mutex_unlock(&state_lock);
/*
* suspend_acks_pending changed, the notifier needs to
* be woken up for this
*/
wake_up(&apm_suspend_waitqueue);
/*
* Wait for the suspend/resume to complete. If there
* are pending acknowledges, we wait here for them.
* wait_event_freezable() is interruptible and pending
* signal can cause busy looping. We aren't doing
* anything critical, chill a bit on each iteration.
*/
while (wait_event_freezable(apm_suspend_waitqueue,
as->suspend_state != SUSPEND_ACKED))
msleep(10);
break;
case SUSPEND_ACKTO:
as->suspend_result = -ETIMEDOUT;
mutex_unlock(&state_lock);
break;
default:
as->suspend_state = SUSPEND_WAIT;
mutex_unlock(&state_lock);
/*
* Otherwise it is a request to suspend the system.
* Just invoke pm_suspend(), we'll handle it from
* there via the notifier.
*/
as->suspend_result = pm_suspend(PM_SUSPEND_MEM);
}
mutex_lock(&state_lock);
err = as->suspend_result;
as->suspend_state = SUSPEND_NONE;
mutex_unlock(&state_lock);
break;
}
return err;
}
static int apm_release(struct inode * inode, struct file * filp)
{
struct apm_user *as = filp->private_data;
filp->private_data = NULL;
down_write(&user_list_lock);
list_del(&as->list);
up_write(&user_list_lock);
/*
* We are now unhooked from the chain. As far as new
* events are concerned, we no longer exist.
*/
mutex_lock(&state_lock);
if (as->suspend_state == SUSPEND_PENDING ||
as->suspend_state == SUSPEND_READ)
atomic_dec(&suspend_acks_pending);
mutex_unlock(&state_lock);
wake_up(&apm_suspend_waitqueue);
kfree(as);
return 0;
}
static int apm_open(struct inode * inode, struct file * filp)
{
struct apm_user *as;
as = kzalloc(sizeof(*as), GFP_KERNEL);
if (as) {
/*
* XXX - this is a tiny bit broken, when we consider BSD
* process accounting. If the device is opened by root, we
* instantly flag that we used superuser privs. Who knows,
* we might close the device immediately without doing a
* privileged operation -- cevans
*/
as->suser = capable(CAP_SYS_ADMIN);
as->writer = (filp->f_mode & FMODE_WRITE) == FMODE_WRITE;
as->reader = (filp->f_mode & FMODE_READ) == FMODE_READ;
down_write(&user_list_lock);
list_add(&as->list, &apm_user_list);
up_write(&user_list_lock);
filp->private_data = as;
}
return as ? 0 : -ENOMEM;
}
static const struct file_operations apm_bios_fops = {
.owner = THIS_MODULE,
.read = apm_read,
.poll = apm_poll,
.unlocked_ioctl = apm_ioctl,
.open = apm_open,
.release = apm_release,
.llseek = noop_llseek,
};
static struct miscdevice apm_device = {
.minor = APM_MINOR_DEV,
.name = "apm_bios",
.fops = &apm_bios_fops
};
#ifdef CONFIG_PROC_FS
/*
* Arguments, with symbols from linux/apm_bios.h.
*
* 0) Linux driver version (this will change if format changes)
* 1) APM BIOS Version. Usually 1.0, 1.1 or 1.2.
* 2) APM flags from APM Installation Check (0x00):
* bit 0: APM_16_BIT_SUPPORT
* bit 1: APM_32_BIT_SUPPORT
* bit 2: APM_IDLE_SLOWS_CLOCK
* bit 3: APM_BIOS_DISABLED
* bit 4: APM_BIOS_DISENGAGED
* 3) AC line status
* 0x00: Off-line
* 0x01: On-line
* 0x02: On backup power (BIOS >= 1.1 only)
* 0xff: Unknown
* 4) Battery status
* 0x00: High
* 0x01: Low
* 0x02: Critical
* 0x03: Charging
* 0x04: Selected battery not present (BIOS >= 1.2 only)
* 0xff: Unknown
* 5) Battery flag
* bit 0: High
* bit 1: Low
* bit 2: Critical
* bit 3: Charging
* bit 7: No system battery
* 0xff: Unknown
* 6) Remaining battery life (percentage of charge):
* 0-100: valid
* -1: Unknown
* 7) Remaining battery life (time units):
* Number of remaining minutes or seconds
* -1: Unknown
* 8) min = minutes; sec = seconds
*/
static int proc_apm_show(struct seq_file *m, void *v)
{
struct apm_power_info info;
char *units;
info.ac_line_status = 0xff;
info.battery_status = 0xff;
info.battery_flag = 0xff;
info.battery_life = -1;
info.time = -1;
info.units = -1;
if (apm_get_power_status)
apm_get_power_status(&info);
switch (info.units) {
default: units = "?"; break;
case 0: units = "min"; break;
case 1: units = "sec"; break;
}
seq_printf(m, "%s 1.2 0x%02x 0x%02x 0x%02x 0x%02x %d%% %d %s\n",
driver_version, APM_32_BIT_SUPPORT,
info.ac_line_status, info.battery_status,
info.battery_flag, info.battery_life,
info.time, units);
return 0;
}
static int proc_apm_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_apm_show, NULL);
}
static const struct file_operations apm_proc_fops = {
.owner = THIS_MODULE,
.open = proc_apm_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
static int kapmd(void *arg)
{
do {
apm_event_t event;
wait_event_interruptible(kapmd_wait,
!queue_empty(&kapmd_queue) || kthread_should_stop());
if (kthread_should_stop())
break;
spin_lock_irq(&kapmd_queue_lock);
event = 0;
if (!queue_empty(&kapmd_queue))
event = queue_get_event(&kapmd_queue);
spin_unlock_irq(&kapmd_queue_lock);
switch (event) {
case 0:
break;
case APM_LOW_BATTERY:
case APM_POWER_STATUS_CHANGE:
queue_event(event);
break;
case APM_USER_SUSPEND:
case APM_SYS_SUSPEND:
pm_suspend(PM_SUSPEND_MEM);
break;
case APM_CRITICAL_SUSPEND:
atomic_inc(&userspace_notification_inhibit);
pm_suspend(PM_SUSPEND_MEM);
atomic_dec(&userspace_notification_inhibit);
break;
}
} while (1);
return 0;
}
static int apm_suspend_notifier(struct notifier_block *nb,
unsigned long event,
void *dummy)
{
struct apm_user *as;
int err;
/* short-cut emergency suspends */
if (atomic_read(&userspace_notification_inhibit))
return NOTIFY_DONE;
switch (event) {
case PM_SUSPEND_PREPARE:
/*
* Queue an event to all "writer" users that we want
* to suspend and need their ack.
*/
mutex_lock(&state_lock);
down_read(&user_list_lock);
list_for_each_entry(as, &apm_user_list, list) {
if (as->suspend_state != SUSPEND_WAIT && as->reader &&
as->writer && as->suser) {
as->suspend_state = SUSPEND_PENDING;
atomic_inc(&suspend_acks_pending);
queue_add_event(&as->queue, APM_USER_SUSPEND);
}
}
up_read(&user_list_lock);
mutex_unlock(&state_lock);
wake_up_interruptible(&apm_waitqueue);
/*
* Wait for the the suspend_acks_pending variable to drop to
* zero, meaning everybody acked the suspend event (or the
* process was killed.)
*
* If the app won't answer within a short while we assume it
* locked up and ignore it.
*/
err = wait_event_interruptible_timeout(
apm_suspend_waitqueue,
atomic_read(&suspend_acks_pending) == 0,
5*HZ);
/* timed out */
if (err == 0) {
/*
* Move anybody who timed out to "ack timeout" state.
*
* We could time out and the userspace does the ACK
* right after we time out but before we enter the
* locked section here, but that's fine.
*/
mutex_lock(&state_lock);
down_read(&user_list_lock);
list_for_each_entry(as, &apm_user_list, list) {
if (as->suspend_state == SUSPEND_PENDING ||
as->suspend_state == SUSPEND_READ) {
as->suspend_state = SUSPEND_ACKTO;
atomic_dec(&suspend_acks_pending);
}
}
up_read(&user_list_lock);
mutex_unlock(&state_lock);
}
/* let suspend proceed */
if (err >= 0)
return NOTIFY_OK;
/* interrupted by signal */
return notifier_from_errno(err);
case PM_POST_SUSPEND:
/*
* Anyone on the APM queues will think we're still suspended.
* Send a message so everyone knows we're now awake again.
*/
queue_event(APM_NORMAL_RESUME);
/*
* Finally, wake up anyone who is sleeping on the suspend.
*/
mutex_lock(&state_lock);
down_read(&user_list_lock);
list_for_each_entry(as, &apm_user_list, list) {
if (as->suspend_state == SUSPEND_ACKED) {
/*
* TODO: maybe grab error code, needs core
* changes to push the error to the notifier
* chain (could use the second parameter if
* implemented)
*/
as->suspend_result = 0;
as->suspend_state = SUSPEND_DONE;
}
}
up_read(&user_list_lock);
mutex_unlock(&state_lock);
wake_up(&apm_suspend_waitqueue);
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
static struct notifier_block apm_notif_block = {
.notifier_call = apm_suspend_notifier,
};
static int __init apm_init(void)
{
int ret;
if (apm_disabled) {
printk(KERN_NOTICE "apm: disabled on user request.\n");
return -ENODEV;
}
kapmd_tsk = kthread_create(kapmd, NULL, "kapmd");
if (IS_ERR(kapmd_tsk)) {
ret = PTR_ERR(kapmd_tsk);
kapmd_tsk = NULL;
goto out;
}
wake_up_process(kapmd_tsk);
#ifdef CONFIG_PROC_FS
proc_create("apm", 0, NULL, &apm_proc_fops);
#endif
ret = misc_register(&apm_device);
if (ret)
goto out_stop;
ret = register_pm_notifier(&apm_notif_block);
if (ret)
goto out_unregister;
return 0;
out_unregister:
misc_deregister(&apm_device);
out_stop:
remove_proc_entry("apm", NULL);
kthread_stop(kapmd_tsk);
out:
return ret;
}
static void __exit apm_exit(void)
{
unregister_pm_notifier(&apm_notif_block);
misc_deregister(&apm_device);
remove_proc_entry("apm", NULL);
kthread_stop(kapmd_tsk);
}
module_init(apm_init);
module_exit(apm_exit);
MODULE_AUTHOR("Stephen Rothwell");
MODULE_DESCRIPTION("Advanced Power Management");
MODULE_LICENSE("GPL");
#ifndef MODULE
static int __init apm_setup(char *str)
{
while ((str != NULL) && (*str != '\0')) {
if (strncmp(str, "off", 3) == 0)
apm_disabled = 1;
if (strncmp(str, "on", 2) == 0)
apm_disabled = 0;
str = strchr(str, ',');
if (str != NULL)
str += strspn(str, ", \t");
}
return 1;
}
__setup("apm=", apm_setup);
#endif
/**
* apm_queue_event - queue an APM event for kapmd
* @event: APM event
*
* Queue an APM event for kapmd to process and ultimately take the
* appropriate action. Only a subset of events are handled:
* %APM_LOW_BATTERY
* %APM_POWER_STATUS_CHANGE
* %APM_USER_SUSPEND
* %APM_SYS_SUSPEND
* %APM_CRITICAL_SUSPEND
*/
void apm_queue_event(apm_event_t event)
{
unsigned long flags;
spin_lock_irqsave(&kapmd_queue_lock, flags);
queue_add_event(&kapmd_queue, event);
spin_unlock_irqrestore(&kapmd_queue_lock, flags);
wake_up_interruptible(&kapmd_wait);
}
EXPORT_SYMBOL(apm_queue_event);
| gpl-2.0 |
andrewoko-odion/linux | arch/m68k/mac/macints.c | 8734 | 8348 | /*
* Macintosh interrupts
*
* General design:
* In contrary to the Amiga and Atari platforms, the Mac hardware seems to
* exclusively use the autovector interrupts (the 'generic level0-level7'
* interrupts with exception vectors 0x19-0x1f). The following interrupt levels
* are used:
* 1 - VIA1
* - slot 0: one second interrupt (CA2)
* - slot 1: VBlank (CA1)
* - slot 2: ADB data ready (SR full)
* - slot 3: ADB data (CB2)
* - slot 4: ADB clock (CB1)
* - slot 5: timer 2
* - slot 6: timer 1
* - slot 7: status of IRQ; signals 'any enabled int.'
*
* 2 - VIA2 or RBV
* - slot 0: SCSI DRQ (CA2)
* - slot 1: NUBUS IRQ (CA1) need to read port A to find which
* - slot 2: /EXP IRQ (only on IIci)
* - slot 3: SCSI IRQ (CB2)
* - slot 4: ASC IRQ (CB1)
* - slot 5: timer 2 (not on IIci)
* - slot 6: timer 1 (not on IIci)
* - slot 7: status of IRQ; signals 'any enabled int.'
*
* Levels 3-6 vary by machine type. For VIA or RBV Macintoshes:
*
* 3 - unused (?)
*
* 4 - SCC
*
* 5 - unused (?)
* [serial errors or special conditions seem to raise level 6
* interrupts on some models (LC4xx?)]
*
* 6 - off switch (?)
*
* Machines with Quadra-like VIA hardware, except PSC and PMU machines, support
* an alternate interrupt mapping, as used by A/UX. It spreads ethernet and
* sound out to their own autovector IRQs and gives VIA1 a higher priority:
*
* 1 - unused (?)
*
* 3 - on-board SONIC
*
* 5 - Apple Sound Chip (ASC)
*
* 6 - VIA1
*
* For OSS Macintoshes (IIfx only), we apply an interrupt mapping similar to
* the Quadra (A/UX) mapping:
*
* 1 - ISM IOP (ADB)
*
* 2 - SCSI
*
* 3 - NuBus
*
* 4 - SCC IOP
*
* 6 - VIA1
*
* For PSC Macintoshes (660AV, 840AV):
*
* 3 - PSC level 3
* - slot 0: MACE
*
* 4 - PSC level 4
* - slot 1: SCC channel A interrupt
* - slot 2: SCC channel B interrupt
* - slot 3: MACE DMA
*
* 5 - PSC level 5
*
* 6 - PSC level 6
*
* Finally we have good 'ole level 7, the non-maskable interrupt:
*
* 7 - NMI (programmer's switch on the back of some Macs)
* Also RAM parity error on models which support it (IIc, IIfx?)
*
* The current interrupt logic looks something like this:
*
* - We install dispatchers for the autovector interrupts (1-7). These
* dispatchers are responsible for querying the hardware (the
* VIA/RBV/OSS/PSC chips) to determine the actual interrupt source. Using
* this information a machspec interrupt number is generated by placing the
* index of the interrupt hardware into the low three bits and the original
* autovector interrupt number in the upper 5 bits. The handlers for the
* resulting machspec interrupt are then called.
*
* - Nubus is a special case because its interrupts are hidden behind two
* layers of hardware. Nubus interrupts come in as index 1 on VIA #2,
* which translates to IRQ number 17. In this spot we install _another_
* dispatcher. This dispatcher finds the interrupting slot number (9-F) and
* then forms a new machspec interrupt number as above with the slot number
* minus 9 in the low three bits and the pseudo-level 7 in the upper five
* bits. The handlers for this new machspec interrupt number are then
* called. This puts Nubus interrupts into the range 56-62.
*
* - The Baboon interrupts (used on some PowerBooks) are an even more special
* case. They're hidden behind the Nubus slot $C interrupt thus adding a
* third layer of indirection. Why oh why did the Apple engineers do that?
*
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/macintosh.h>
#include <asm/macints.h>
#include <asm/mac_via.h>
#include <asm/mac_psc.h>
#include <asm/mac_oss.h>
#include <asm/mac_iop.h>
#include <asm/mac_baboon.h>
#include <asm/hwtest.h>
#include <asm/irq_regs.h>
#define SHUTUP_SONIC
/*
* console_loglevel determines NMI handler function
*/
irqreturn_t mac_nmi_handler(int, void *);
irqreturn_t mac_debug_handler(int, void *);
/* #define DEBUG_MACINTS */
static unsigned int mac_irq_startup(struct irq_data *);
static void mac_irq_shutdown(struct irq_data *);
static struct irq_chip mac_irq_chip = {
.name = "mac",
.irq_enable = mac_irq_enable,
.irq_disable = mac_irq_disable,
.irq_startup = mac_irq_startup,
.irq_shutdown = mac_irq_shutdown,
};
void __init mac_init_IRQ(void)
{
#ifdef DEBUG_MACINTS
printk("mac_init_IRQ(): Setting things up...\n");
#endif
m68k_setup_irq_controller(&mac_irq_chip, handle_simple_irq, IRQ_USER,
NUM_MAC_SOURCES - IRQ_USER);
/* Make sure the SONIC interrupt is cleared or things get ugly */
#ifdef SHUTUP_SONIC
printk("Killing onboard sonic... ");
/* This address should hopefully be mapped already */
if (hwreg_present((void*)(0x50f0a000))) {
*(long *)(0x50f0a014) = 0x7fffL;
*(long *)(0x50f0a010) = 0L;
}
printk("Done.\n");
#endif /* SHUTUP_SONIC */
/*
* Now register the handlers for the master IRQ handlers
* at levels 1-7. Most of the work is done elsewhere.
*/
if (oss_present)
oss_register_interrupts();
else
via_register_interrupts();
if (psc_present)
psc_register_interrupts();
if (baboon_present)
baboon_register_interrupts();
iop_register_interrupts();
if (request_irq(IRQ_AUTO_7, mac_nmi_handler, 0, "NMI",
mac_nmi_handler))
pr_err("Couldn't register NMI\n");
#ifdef DEBUG_MACINTS
printk("mac_init_IRQ(): Done!\n");
#endif
}
/*
* mac_irq_enable - enable an interrupt source
* mac_irq_disable - disable an interrupt source
*
* These routines are just dispatchers to the VIA/OSS/PSC routines.
*/
void mac_irq_enable(struct irq_data *data)
{
int irq = data->irq;
int irq_src = IRQ_SRC(irq);
switch(irq_src) {
case 1:
case 2:
case 7:
if (oss_present)
oss_irq_enable(irq);
else
via_irq_enable(irq);
break;
case 3:
case 4:
case 5:
case 6:
if (psc_present)
psc_irq_enable(irq);
else if (oss_present)
oss_irq_enable(irq);
break;
case 8:
if (baboon_present)
baboon_irq_enable(irq);
break;
}
}
void mac_irq_disable(struct irq_data *data)
{
int irq = data->irq;
int irq_src = IRQ_SRC(irq);
switch(irq_src) {
case 1:
case 2:
case 7:
if (oss_present)
oss_irq_disable(irq);
else
via_irq_disable(irq);
break;
case 3:
case 4:
case 5:
case 6:
if (psc_present)
psc_irq_disable(irq);
else if (oss_present)
oss_irq_disable(irq);
break;
case 8:
if (baboon_present)
baboon_irq_disable(irq);
break;
}
}
static unsigned int mac_irq_startup(struct irq_data *data)
{
int irq = data->irq;
if (IRQ_SRC(irq) == 7 && !oss_present)
via_nubus_irq_startup(irq);
else
mac_irq_enable(data);
return 0;
}
static void mac_irq_shutdown(struct irq_data *data)
{
int irq = data->irq;
if (IRQ_SRC(irq) == 7 && !oss_present)
via_nubus_irq_shutdown(irq);
else
mac_irq_disable(data);
}
static int num_debug[8];
irqreturn_t mac_debug_handler(int irq, void *dev_id)
{
if (num_debug[irq] < 10) {
printk("DEBUG: Unexpected IRQ %d\n", irq);
num_debug[irq]++;
}
return IRQ_HANDLED;
}
static int in_nmi;
static volatile int nmi_hold;
irqreturn_t mac_nmi_handler(int irq, void *dev_id)
{
int i;
/*
* generate debug output on NMI switch if 'debug' kernel option given
* (only works with Penguin!)
*/
in_nmi++;
for (i=0; i<100; i++)
udelay(1000);
if (in_nmi == 1) {
nmi_hold = 1;
printk("... pausing, press NMI to resume ...");
} else {
printk(" ok!\n");
nmi_hold = 0;
}
barrier();
while (nmi_hold == 1)
udelay(1000);
if (console_loglevel >= 8) {
#if 0
struct pt_regs *fp = get_irq_regs();
show_state();
printk("PC: %08lx\nSR: %04x SP: %p\n", fp->pc, fp->sr, fp);
printk("d0: %08lx d1: %08lx d2: %08lx d3: %08lx\n",
fp->d0, fp->d1, fp->d2, fp->d3);
printk("d4: %08lx d5: %08lx a0: %08lx a1: %08lx\n",
fp->d4, fp->d5, fp->a0, fp->a1);
if (STACK_MAGIC != *(unsigned long *)current->kernel_stack_page)
printk("Corrupted stack page\n");
printk("Process %s (pid: %d, stackpage=%08lx)\n",
current->comm, current->pid, current->kernel_stack_page);
if (intr_count == 1)
dump_stack((struct frame *)fp);
#else
/* printk("NMI "); */
#endif
}
in_nmi--;
return IRQ_HANDLED;
}
| gpl-2.0 |
sycolon/lge_g3_kernel | drivers/parisc/asp.c | 13854 | 3607 | /*
* ASP Device Driver
*
* (c) Copyright 2000 The Puffin Group Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* by Helge Deller <deller@gmx.de>
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/types.h>
#include <asm/io.h>
#include <asm/led.h>
#include "gsc.h"
#define ASP_GSC_IRQ 3 /* hardcoded interrupt for GSC */
#define ASP_VER_OFFSET 0x20 /* offset of ASP version */
#define ASP_LED_ADDR 0xf0800020
#define VIPER_INT_WORD 0xFFFBF088 /* addr of viper interrupt word */
static struct gsc_asic asp;
static void asp_choose_irq(struct parisc_device *dev, void *ctrl)
{
int irq;
switch (dev->id.sversion) {
case 0x71: irq = 9; break; /* SCSI */
case 0x72: irq = 8; break; /* LAN */
case 0x73: irq = 1; break; /* HIL */
case 0x74: irq = 7; break; /* Centronics */
case 0x75: irq = (dev->hw_path == 4) ? 5 : 6; break; /* RS232 */
case 0x76: irq = 10; break; /* EISA BA */
case 0x77: irq = 11; break; /* Graphics1 */
case 0x7a: irq = 13; break; /* Audio (Bushmaster) */
case 0x7b: irq = 13; break; /* Audio (Scorpio) */
case 0x7c: irq = 3; break; /* FW SCSI */
case 0x7d: irq = 4; break; /* FDDI */
case 0x7f: irq = 13; break; /* Audio (Outfield) */
default: return; /* Unknown */
}
gsc_asic_assign_irq(ctrl, irq, &dev->irq);
switch (dev->id.sversion) {
case 0x73: irq = 2; break; /* i8042 High-priority */
case 0x76: irq = 0; break; /* EISA BA */
default: return; /* Other */
}
gsc_asic_assign_irq(ctrl, irq, &dev->aux_irq);
}
/* There are two register ranges we're interested in. Interrupt /
* Status / LED are at 0xf080xxxx and Asp special registers are at
* 0xf082fxxx. PDC only tells us that Asp is at 0xf082f000, so for
* the purposes of interrupt handling, we have to tell other bits of
* the kernel to look at the other registers.
*/
#define ASP_INTERRUPT_ADDR 0xf0800000
static int __init asp_init_chip(struct parisc_device *dev)
{
struct gsc_irq gsc_irq;
int ret;
asp.version = gsc_readb(dev->hpa.start + ASP_VER_OFFSET) & 0xf;
asp.name = (asp.version == 1) ? "Asp" : "Cutoff";
asp.hpa = ASP_INTERRUPT_ADDR;
printk(KERN_INFO "%s version %d at 0x%lx found.\n",
asp.name, asp.version, (unsigned long)dev->hpa.start);
/* the IRQ ASP should use */
ret = -EBUSY;
dev->irq = gsc_claim_irq(&gsc_irq, ASP_GSC_IRQ);
if (dev->irq < 0) {
printk(KERN_ERR "%s(): cannot get GSC irq\n", __func__);
goto out;
}
asp.eim = ((u32) gsc_irq.txn_addr) | gsc_irq.txn_data;
ret = request_irq(gsc_irq.irq, gsc_asic_intr, 0, "asp", &asp);
if (ret < 0)
goto out;
/* Program VIPER to interrupt on the ASP irq */
gsc_writel((1 << (31 - ASP_GSC_IRQ)),VIPER_INT_WORD);
/* Done init'ing, register this driver */
ret = gsc_common_setup(dev, &asp);
if (ret)
goto out;
gsc_fixup_irqs(dev, &asp, asp_choose_irq);
/* Mongoose is a sibling of Asp, not a child... */
gsc_fixup_irqs(parisc_parent(dev), &asp, asp_choose_irq);
/* initialize the chassis LEDs */
#ifdef CONFIG_CHASSIS_LCD_LED
register_led_driver(DISPLAY_MODEL_OLD_ASP, LED_CMD_REG_NONE,
ASP_LED_ADDR);
#endif
out:
return ret;
}
static struct parisc_device_id asp_tbl[] = {
{ HPHW_BA, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00070 },
{ 0, }
};
struct parisc_driver asp_driver = {
.name = "asp",
.id_table = asp_tbl,
.probe = asp_init_chip,
};
| gpl-2.0 |
pitichai/pi2 | sound/core/oss/io.c | 14622 | 4433 | /*
* PCM I/O Plug-In Interface
* Copyright (c) 1999 by Jaroslav Kysela <perex@perex.cz>
*
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/time.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "pcm_plugin.h"
#define pcm_write(plug,buf,count) snd_pcm_oss_write3(plug,buf,count,1)
#define pcm_writev(plug,vec,count) snd_pcm_oss_writev3(plug,vec,count,1)
#define pcm_read(plug,buf,count) snd_pcm_oss_read3(plug,buf,count,1)
#define pcm_readv(plug,vec,count) snd_pcm_oss_readv3(plug,vec,count,1)
/*
* Basic io plugin
*/
static snd_pcm_sframes_t io_playback_transfer(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames)
{
if (snd_BUG_ON(!plugin))
return -ENXIO;
if (snd_BUG_ON(!src_channels))
return -ENXIO;
if (plugin->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED) {
return pcm_write(plugin->plug, src_channels->area.addr, frames);
} else {
int channel, channels = plugin->dst_format.channels;
void **bufs = (void**)plugin->extra_data;
if (snd_BUG_ON(!bufs))
return -ENXIO;
for (channel = 0; channel < channels; channel++) {
if (src_channels[channel].enabled)
bufs[channel] = src_channels[channel].area.addr;
else
bufs[channel] = NULL;
}
return pcm_writev(plugin->plug, bufs, frames);
}
}
static snd_pcm_sframes_t io_capture_transfer(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames)
{
if (snd_BUG_ON(!plugin))
return -ENXIO;
if (snd_BUG_ON(!dst_channels))
return -ENXIO;
if (plugin->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED) {
return pcm_read(plugin->plug, dst_channels->area.addr, frames);
} else {
int channel, channels = plugin->dst_format.channels;
void **bufs = (void**)plugin->extra_data;
if (snd_BUG_ON(!bufs))
return -ENXIO;
for (channel = 0; channel < channels; channel++) {
if (dst_channels[channel].enabled)
bufs[channel] = dst_channels[channel].area.addr;
else
bufs[channel] = NULL;
}
return pcm_readv(plugin->plug, bufs, frames);
}
return 0;
}
static snd_pcm_sframes_t io_src_channels(struct snd_pcm_plugin *plugin,
snd_pcm_uframes_t frames,
struct snd_pcm_plugin_channel **channels)
{
int err;
unsigned int channel;
struct snd_pcm_plugin_channel *v;
err = snd_pcm_plugin_client_channels(plugin, frames, &v);
if (err < 0)
return err;
*channels = v;
if (plugin->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED) {
for (channel = 0; channel < plugin->src_format.channels; ++channel, ++v)
v->wanted = 1;
}
return frames;
}
int snd_pcm_plugin_build_io(struct snd_pcm_substream *plug,
struct snd_pcm_hw_params *params,
struct snd_pcm_plugin **r_plugin)
{
int err;
struct snd_pcm_plugin_format format;
struct snd_pcm_plugin *plugin;
if (snd_BUG_ON(!r_plugin))
return -ENXIO;
*r_plugin = NULL;
if (snd_BUG_ON(!plug || !params))
return -ENXIO;
format.format = params_format(params);
format.rate = params_rate(params);
format.channels = params_channels(params);
err = snd_pcm_plugin_build(plug, "I/O io",
&format, &format,
sizeof(void *) * format.channels,
&plugin);
if (err < 0)
return err;
plugin->access = params_access(params);
if (snd_pcm_plug_stream(plug) == SNDRV_PCM_STREAM_PLAYBACK) {
plugin->transfer = io_playback_transfer;
if (plugin->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED)
plugin->client_channels = io_src_channels;
} else {
plugin->transfer = io_capture_transfer;
}
*r_plugin = plugin;
return 0;
}
| gpl-2.0 |
cybojenix/android_kernel_nvidia_kalamata | drivers/cpuidle/governors/menu.c | 31 | 12754 | /*
* menu.c - the menu idle governor
*
* Copyright (C) 2006-2007 Adam Belay <abelay@novell.com>
* Copyright (C) 2009 Intel Corporation
* Author:
* Arjan van de Ven <arjan@linux.intel.com>
*
* This code is licenced under the GPL version 2 as described
* in the COPYING file that acompanies the Linux Kernel.
*/
#include <linux/kernel.h>
#include <linux/cpuidle.h>
#include <linux/pm_qos.h>
#include <linux/time.h>
#include <linux/ktime.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/sched.h>
#include <linux/math64.h>
#include <linux/module.h>
#define BUCKETS 12
#define INTERVALS 8
#define RESOLUTION 1024
#define DECAY 8
#define MAX_INTERESTING 50000
#define STDDEV_THRESH 400
/*
* Concepts and ideas behind the menu governor
*
* For the menu governor, there are 3 decision factors for picking a C
* state:
* 1) Energy break even point
* 2) Performance impact
* 3) Latency tolerance (from pmqos infrastructure)
* These these three factors are treated independently.
*
* Energy break even point
* -----------------------
* C state entry and exit have an energy cost, and a certain amount of time in
* the C state is required to actually break even on this cost. CPUIDLE
* provides us this duration in the "target_residency" field. So all that we
* need is a good prediction of how long we'll be idle. Like the traditional
* menu governor, we start with the actual known "next timer event" time.
*
* Since there are other source of wakeups (interrupts for example) than
* the next timer event, this estimation is rather optimistic. To get a
* more realistic estimate, a correction factor is applied to the estimate,
* that is based on historic behavior. For example, if in the past the actual
* duration always was 50% of the next timer tick, the correction factor will
* be 0.5.
*
* menu uses a running average for this correction factor, however it uses a
* set of factors, not just a single factor. This stems from the realization
* that the ratio is dependent on the order of magnitude of the expected
* duration; if we expect 500 milliseconds of idle time the likelihood of
* getting an interrupt very early is much higher than if we expect 50 micro
* seconds of idle time. A second independent factor that has big impact on
* the actual factor is if there is (disk) IO outstanding or not.
* (as a special twist, we consider every sleep longer than 50 milliseconds
* as perfect; there are no power gains for sleeping longer than this)
*
* For these two reasons we keep an array of 12 independent factors, that gets
* indexed based on the magnitude of the expected duration as well as the
* "is IO outstanding" property.
*
* Repeatable-interval-detector
* ----------------------------
* There are some cases where "next timer" is a completely unusable predictor:
* Those cases where the interval is fixed, for example due to hardware
* interrupt mitigation, but also due to fixed transfer rate devices such as
* mice.
* For this, we use a different predictor: We track the duration of the last 8
* intervals and if the stand deviation of these 8 intervals is below a
* threshold value, we use the average of these intervals as prediction.
*
* Limiting Performance Impact
* ---------------------------
* C states, especially those with large exit latencies, can have a real
* noticeable impact on workloads, which is not acceptable for most sysadmins,
* and in addition, less performance has a power price of its own.
*
* As a general rule of thumb, menu assumes that the following heuristic
* holds:
* The busier the system, the less impact of C states is acceptable
*
* This rule-of-thumb is implemented using a performance-multiplier:
* If the exit latency times the performance multiplier is longer than
* the predicted duration, the C state is not considered a candidate
* for selection due to a too high performance impact. So the higher
* this multiplier is, the longer we need to be idle to pick a deep C
* state, and thus the less likely a busy CPU will hit such a deep
* C state.
*
* Two factors are used in determing this multiplier:
* a value of 10 is added for each point of "per cpu load average" we have.
* a value of 5 points is added for each process that is waiting for
* IO on this CPU.
* (these values are experimentally determined)
*
* The load average factor gives a longer term (few seconds) input to the
* decision, while the iowait value gives a cpu local instantanious input.
* The iowait factor may look low, but realize that this is also already
* represented in the system load average.
*
*/
struct menu_device {
int last_state_idx;
int needs_update;
unsigned int expected_us;
u64 predicted_us;
unsigned int exit_us;
unsigned int bucket;
u64 correction_factor[BUCKETS];
u32 intervals[INTERVALS];
int interval_ptr;
};
#define LOAD_INT(x) ((x) >> FSHIFT)
#define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
#if 0
/* see comment above -- google code commented out */
static int get_loadavg(void)
{
unsigned long this = this_cpu_load();
return LOAD_INT(this) * 10 + LOAD_FRAC(this) / 10;
}
#endif
static inline int which_bucket(unsigned int duration)
{
int bucket = 0;
/*
* We keep two groups of stats; one with no
* IO pending, one without.
* This allows us to calculate
* E(duration)|iowait
*/
if (nr_iowait_cpu(smp_processor_id()))
bucket = BUCKETS/2;
if (duration < 10)
return bucket;
if (duration < 100)
return bucket + 1;
if (duration < 1000)
return bucket + 2;
if (duration < 10000)
return bucket + 3;
if (duration < 100000)
return bucket + 4;
return bucket + 5;
}
/*
* Return a multiplier for the exit latency that is intended
* to take performance requirements into account.
* The more performance critical we estimate the system
* to be, the higher this multiplier, and thus the higher
* the barrier to go to an expensive C state.
*/
static inline int performance_multiplier(void)
{
int mult = 1;
/* for higher loadavg, we are more reluctant */
/*
* this doesn't work as intended - it is almost always 0, but can
* sometimes, depending on workload, spike very high into the hundreds
* even when the average cpu load is under 10%.
*/
/* mult += 2 * get_loadavg(); */
/* for IO wait tasks (per cpu!) we add 5x each */
mult += 10 * nr_iowait_cpu(smp_processor_id());
return mult;
}
static DEFINE_PER_CPU(struct menu_device, menu_devices);
static void menu_update(struct cpuidle_device *dev);
/* This implements DIV_ROUND_CLOSEST but avoids 64 bit division */
static u64 div_round64(u64 dividend, u32 divisor)
{
return div_u64(dividend + (divisor / 2), divisor);
}
/*
* Try detecting repeating patterns by keeping track of the last 8
* intervals, and checking if the standard deviation of that set
* of points is below a threshold. If it is... then use the
* average of these 8 points as the estimated value.
*/
static void detect_repeating_patterns(struct menu_device *data)
{
int i;
uint64_t avg = 0;
uint64_t stddev = 0; /* contains the square of the std deviation */
/* first calculate average and standard deviation of the past */
for (i = 0; i < INTERVALS; i++)
avg += data->intervals[i];
avg = avg / INTERVALS;
/* if the avg is beyond the known next tick, it's worthless */
if (avg > data->expected_us)
return;
for (i = 0; i < INTERVALS; i++)
stddev += (data->intervals[i] - avg) *
(data->intervals[i] - avg);
stddev = stddev / INTERVALS;
/*
* now.. if stddev is small.. then assume we have a
* repeating pattern and predict we keep doing this.
*/
if (avg && stddev < STDDEV_THRESH)
data->predicted_us = avg;
}
/**
* menu_select - selects the next idle state to enter
* @dev: the CPU
*/
static int menu_select(struct cpuidle_device *dev)
{
struct menu_device *data = &__get_cpu_var(menu_devices);
int latency_req = pm_qos_request(PM_QOS_CPU_DMA_LATENCY);
int power_usage = INT_MAX;
int i;
int multiplier;
struct timespec t;
if (data->needs_update) {
menu_update(dev);
data->needs_update = 0;
}
data->last_state_idx = 0;
data->exit_us = 0;
/* Special case when user has set very strict latency requirement */
if (unlikely(latency_req == 0))
return 0;
/* determine the expected residency time, round up */
t = ktime_to_timespec(tick_nohz_get_sleep_length());
data->expected_us =
t.tv_sec * USEC_PER_SEC + t.tv_nsec / NSEC_PER_USEC;
data->bucket = which_bucket(data->expected_us);
multiplier = performance_multiplier();
/*
* if the correction factor is 0 (eg first time init or cpu hotplug
* etc), we actually want to start out with a unity factor.
*/
if (data->correction_factor[data->bucket] == 0)
data->correction_factor[data->bucket] = RESOLUTION * DECAY;
/* Make sure to round up for half microseconds */
data->predicted_us = div_round64(data->expected_us * data->correction_factor[data->bucket],
RESOLUTION * DECAY);
detect_repeating_patterns(data);
/*
* We want to default to C1 (hlt), not to busy polling
* unless the timer is happening really really soon.
*/
if (data->expected_us > 5 &&
!dev->states[CPUIDLE_DRIVER_STATE_START].disabled)
data->last_state_idx = CPUIDLE_DRIVER_STATE_START;
/*
* Find the idle state with the lowest power while satisfying
* our constraints.
*/
for (i = CPUIDLE_DRIVER_STATE_START; i < dev->state_count; i++) {
struct cpuidle_state *s = &dev->states[i];
if (s->disabled)
continue;
if (s->target_residency > data->predicted_us)
continue;
if (s->exit_latency > latency_req)
continue;
if (s->exit_latency * multiplier > data->predicted_us)
continue;
if (s->power_usage < power_usage) {
power_usage = s->power_usage;
data->last_state_idx = i;
data->exit_us = s->exit_latency;
}
}
return data->last_state_idx;
}
/**
* menu_reflect - records that data structures need update
* @dev: the CPU
* @index: the index of actual entered state
*
* NOTE: it's important to be fast here because this operation will add to
* the overall exit latency.
*/
static void menu_reflect(struct cpuidle_device *dev, int index)
{
struct menu_device *data = &__get_cpu_var(menu_devices);
data->last_state_idx = index;
if (index >= 0)
data->needs_update = 1;
}
/**
* menu_update - attempts to guess what happened after entry
* @dev: the CPU
*/
static void menu_update(struct cpuidle_device *dev)
{
struct menu_device *data = &__get_cpu_var(menu_devices);
int last_idx = data->last_state_idx;
unsigned int last_idle_us = cpuidle_get_last_residency(dev);
struct cpuidle_state *target = &dev->states[last_idx];
unsigned int measured_us;
u64 new_factor;
/*
* Ugh, this idle state doesn't support residency measurements, so we
* are basically lost in the dark. As a compromise, assume we slept
* for the whole expected time.
*/
if (unlikely(!(target->flags & CPUIDLE_FLAG_TIME_VALID)))
last_idle_us = data->expected_us;
measured_us = last_idle_us;
/*
* We correct for the exit latency; we are assuming here that the
* exit latency happens after the event that we're interested in.
*/
if (measured_us > data->exit_us)
measured_us -= data->exit_us;
/* update our correction ratio */
new_factor = data->correction_factor[data->bucket]
* (DECAY - 1) / DECAY;
if (data->expected_us > 0 && measured_us < MAX_INTERESTING)
new_factor += RESOLUTION * measured_us / data->expected_us;
else
/*
* we were idle so long that we count it as a perfect
* prediction
*/
new_factor += RESOLUTION;
/*
* We don't want 0 as factor; we always want at least
* a tiny bit of estimated time.
*/
if (new_factor == 0)
new_factor = 1;
data->correction_factor[data->bucket] = new_factor;
/* update the repeating-pattern data */
data->intervals[data->interval_ptr++] = last_idle_us;
if (data->interval_ptr >= INTERVALS)
data->interval_ptr = 0;
}
/**
* menu_enable_device - scans a CPU's states and does setup
* @dev: the CPU
*/
static int menu_enable_device(struct cpuidle_device *dev)
{
struct menu_device *data = &per_cpu(menu_devices, dev->cpu);
memset(data, 0, sizeof(struct menu_device));
return 0;
}
static struct cpuidle_governor menu_governor = {
.name = "menu",
.rating = 20,
.enable = menu_enable_device,
.select = menu_select,
.reflect = menu_reflect,
.owner = THIS_MODULE,
};
/**
* init_menu - initializes the governor
*/
static int __init init_menu(void)
{
return cpuidle_register_governor(&menu_governor);
}
/**
* exit_menu - exits the governor
*/
static void __exit exit_menu(void)
{
cpuidle_unregister_governor(&menu_governor);
}
MODULE_LICENSE("GPL");
module_init(init_menu);
module_exit(exit_menu);
| gpl-2.0 |
kinsamanka/linux | drivers/media/video/gspca/sunplus.c | 287 | 29751 | /*
* Sunplus spca504(abc) spca533 spca536 library
* Copyright (C) 2005 Michel Xhaard mxhaard@magic.fr
*
* V4L2 by Jean-Francois Moine <http://moinejf.free.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "sunplus"
#include "gspca.h"
#include "jpeg.h"
MODULE_AUTHOR("Michel Xhaard <mxhaard@users.sourceforge.net>");
MODULE_DESCRIPTION("GSPCA/SPCA5xx USB Camera Driver");
MODULE_LICENSE("GPL");
#define QUALITY 85
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
bool autogain;
u8 bridge;
#define BRIDGE_SPCA504 0
#define BRIDGE_SPCA504B 1
#define BRIDGE_SPCA504C 2
#define BRIDGE_SPCA533 3
#define BRIDGE_SPCA536 4
u8 subtype;
#define AiptekMiniPenCam13 1
#define LogitechClickSmart420 2
#define LogitechClickSmart820 3
#define MegapixV4 4
#define MegaImageVI 5
u8 jpeg_hdr[JPEG_HDR_SZ];
};
static const struct v4l2_pix_format vga_mode[] = {
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
};
static const struct v4l2_pix_format custom_mode[] = {
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{464, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 464,
.sizeimage = 464 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
};
static const struct v4l2_pix_format vga_mode2[] = {
{176, 144, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 4},
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 3},
{352, 288, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
};
#define SPCA50X_OFFSET_DATA 10
#define SPCA504_PCCAM600_OFFSET_SNAPSHOT 3
#define SPCA504_PCCAM600_OFFSET_COMPRESS 4
#define SPCA504_PCCAM600_OFFSET_MODE 5
#define SPCA504_PCCAM600_OFFSET_DATA 14
/* Frame packet header offsets for the spca533 */
#define SPCA533_OFFSET_DATA 16
#define SPCA533_OFFSET_FRAMSEQ 15
/* Frame packet header offsets for the spca536 */
#define SPCA536_OFFSET_DATA 4
#define SPCA536_OFFSET_FRAMSEQ 1
struct cmd {
u8 req;
u16 val;
u16 idx;
};
/* Initialisation data for the Creative PC-CAM 600 */
static const struct cmd spca504_pccam600_init_data[] = {
/* {0xa0, 0x0000, 0x0503}, * capture mode */
{0x00, 0x0000, 0x2000},
{0x00, 0x0013, 0x2301},
{0x00, 0x0003, 0x2000},
{0x00, 0x0001, 0x21ac},
{0x00, 0x0001, 0x21a6},
{0x00, 0x0000, 0x21a7}, /* brightness */
{0x00, 0x0020, 0x21a8}, /* contrast */
{0x00, 0x0001, 0x21ac}, /* sat/hue */
{0x00, 0x0000, 0x21ad}, /* hue */
{0x00, 0x001a, 0x21ae}, /* saturation */
{0x00, 0x0002, 0x21a3}, /* gamma */
{0x30, 0x0154, 0x0008},
{0x30, 0x0004, 0x0006},
{0x30, 0x0258, 0x0009},
{0x30, 0x0004, 0x0000},
{0x30, 0x0093, 0x0004},
{0x30, 0x0066, 0x0005},
{0x00, 0x0000, 0x2000},
{0x00, 0x0013, 0x2301},
{0x00, 0x0003, 0x2000},
{0x00, 0x0013, 0x2301},
{0x00, 0x0003, 0x2000},
};
/* Creative PC-CAM 600 specific open data, sent before using the
* generic initialisation data from spca504_open_data.
*/
static const struct cmd spca504_pccam600_open_data[] = {
{0x00, 0x0001, 0x2501},
{0x20, 0x0500, 0x0001}, /* snapshot mode */
{0x00, 0x0003, 0x2880},
{0x00, 0x0001, 0x2881},
};
/* Initialisation data for the logitech clicksmart 420 */
static const struct cmd spca504A_clicksmart420_init_data[] = {
/* {0xa0, 0x0000, 0x0503}, * capture mode */
{0x00, 0x0000, 0x2000},
{0x00, 0x0013, 0x2301},
{0x00, 0x0003, 0x2000},
{0x00, 0x0001, 0x21ac},
{0x00, 0x0001, 0x21a6},
{0x00, 0x0000, 0x21a7}, /* brightness */
{0x00, 0x0020, 0x21a8}, /* contrast */
{0x00, 0x0001, 0x21ac}, /* sat/hue */
{0x00, 0x0000, 0x21ad}, /* hue */
{0x00, 0x001a, 0x21ae}, /* saturation */
{0x00, 0x0002, 0x21a3}, /* gamma */
{0x30, 0x0004, 0x000a},
{0xb0, 0x0001, 0x0000},
{0xa1, 0x0080, 0x0001},
{0x30, 0x0049, 0x0000},
{0x30, 0x0060, 0x0005},
{0x0c, 0x0004, 0x0000},
{0x00, 0x0000, 0x0000},
{0x00, 0x0000, 0x2000},
{0x00, 0x0013, 0x2301},
{0x00, 0x0003, 0x2000},
};
/* clicksmart 420 open data ? */
static const struct cmd spca504A_clicksmart420_open_data[] = {
{0x00, 0x0001, 0x2501},
{0x20, 0x0502, 0x0000},
{0x06, 0x0000, 0x0000},
{0x00, 0x0004, 0x2880},
{0x00, 0x0001, 0x2881},
{0xa0, 0x0000, 0x0503},
};
static const u8 qtable_creative_pccam[2][64] = {
{ /* Q-table Y-components */
0x05, 0x03, 0x03, 0x05, 0x07, 0x0c, 0x0f, 0x12,
0x04, 0x04, 0x04, 0x06, 0x08, 0x11, 0x12, 0x11,
0x04, 0x04, 0x05, 0x07, 0x0c, 0x11, 0x15, 0x11,
0x04, 0x05, 0x07, 0x09, 0x0f, 0x1a, 0x18, 0x13,
0x05, 0x07, 0x0b, 0x11, 0x14, 0x21, 0x1f, 0x17,
0x07, 0x0b, 0x11, 0x13, 0x18, 0x1f, 0x22, 0x1c,
0x0f, 0x13, 0x17, 0x1a, 0x1f, 0x24, 0x24, 0x1e,
0x16, 0x1c, 0x1d, 0x1d, 0x22, 0x1e, 0x1f, 0x1e},
{ /* Q-table C-components */
0x05, 0x05, 0x07, 0x0e, 0x1e, 0x1e, 0x1e, 0x1e,
0x05, 0x06, 0x08, 0x14, 0x1e, 0x1e, 0x1e, 0x1e,
0x07, 0x08, 0x11, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x0e, 0x14, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e}
};
/* FIXME: This Q-table is identical to the Creative PC-CAM one,
* except for one byte. Possibly a typo?
* NWG: 18/05/2003.
*/
static const u8 qtable_spca504_default[2][64] = {
{ /* Q-table Y-components */
0x05, 0x03, 0x03, 0x05, 0x07, 0x0c, 0x0f, 0x12,
0x04, 0x04, 0x04, 0x06, 0x08, 0x11, 0x12, 0x11,
0x04, 0x04, 0x05, 0x07, 0x0c, 0x11, 0x15, 0x11,
0x04, 0x05, 0x07, 0x09, 0x0f, 0x1a, 0x18, 0x13,
0x05, 0x07, 0x0b, 0x11, 0x14, 0x21, 0x1f, 0x17,
0x07, 0x0b, 0x11, 0x13, 0x18, 0x1f, 0x22, 0x1c,
0x0f, 0x13, 0x17, 0x1a, 0x1f, 0x24, 0x24, 0x1e,
0x16, 0x1c, 0x1d, 0x1d, 0x1d /* 0x22 */ , 0x1e, 0x1f, 0x1e,
},
{ /* Q-table C-components */
0x05, 0x05, 0x07, 0x0e, 0x1e, 0x1e, 0x1e, 0x1e,
0x05, 0x06, 0x08, 0x14, 0x1e, 0x1e, 0x1e, 0x1e,
0x07, 0x08, 0x11, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x0e, 0x14, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e}
};
/* read <len> bytes to gspca_dev->usb_buf */
static void reg_r(struct gspca_dev *gspca_dev,
u8 req,
u16 index,
u16 len)
{
int ret;
#ifdef GSPCA_DEBUG
if (len > USB_BUF_SZ) {
pr_err("reg_r: buffer overflow\n");
return;
}
#endif
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(gspca_dev->dev,
usb_rcvctrlpipe(gspca_dev->dev, 0),
req,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, /* value */
index,
len ? gspca_dev->usb_buf : NULL, len,
500);
if (ret < 0) {
pr_err("reg_r err %d\n", ret);
gspca_dev->usb_err = ret;
}
}
/* write one byte */
static void reg_w_1(struct gspca_dev *gspca_dev,
u8 req,
u16 value,
u16 index,
u16 byte)
{
int ret;
if (gspca_dev->usb_err < 0)
return;
gspca_dev->usb_buf[0] = byte;
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
req,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index,
gspca_dev->usb_buf, 1,
500);
if (ret < 0) {
pr_err("reg_w_1 err %d\n", ret);
gspca_dev->usb_err = ret;
}
}
/* write req / index / value */
static void reg_w_riv(struct gspca_dev *gspca_dev,
u8 req, u16 index, u16 value)
{
struct usb_device *dev = gspca_dev->dev;
int ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(dev,
usb_sndctrlpipe(dev, 0),
req,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, NULL, 0, 500);
if (ret < 0) {
pr_err("reg_w_riv err %d\n", ret);
gspca_dev->usb_err = ret;
return;
}
PDEBUG(D_USBO, "reg_w_riv: 0x%02x,0x%04x:0x%04x",
req, index, value);
}
static void write_vector(struct gspca_dev *gspca_dev,
const struct cmd *data, int ncmds)
{
while (--ncmds >= 0) {
reg_w_riv(gspca_dev, data->req, data->idx, data->val);
data++;
}
}
static void setup_qtable(struct gspca_dev *gspca_dev,
const u8 qtable[2][64])
{
int i;
/* loop over y components */
for (i = 0; i < 64; i++)
reg_w_riv(gspca_dev, 0x00, 0x2800 + i, qtable[0][i]);
/* loop over c components */
for (i = 0; i < 64; i++)
reg_w_riv(gspca_dev, 0x00, 0x2840 + i, qtable[1][i]);
}
static void spca504_acknowledged_command(struct gspca_dev *gspca_dev,
u8 req, u16 idx, u16 val)
{
reg_w_riv(gspca_dev, req, idx, val);
reg_r(gspca_dev, 0x01, 0x0001, 1);
PDEBUG(D_FRAM, "before wait 0x%04x", gspca_dev->usb_buf[0]);
reg_w_riv(gspca_dev, req, idx, val);
msleep(200);
reg_r(gspca_dev, 0x01, 0x0001, 1);
PDEBUG(D_FRAM, "after wait 0x%04x", gspca_dev->usb_buf[0]);
}
#ifdef GSPCA_DEBUG
static void spca504_read_info(struct gspca_dev *gspca_dev)
{
int i;
u8 info[6];
for (i = 0; i < 6; i++) {
reg_r(gspca_dev, 0, i, 1);
info[i] = gspca_dev->usb_buf[0];
}
PDEBUG(D_STREAM,
"Read info: %d %d %d %d %d %d."
" Should be 1,0,2,2,0,0",
info[0], info[1], info[2],
info[3], info[4], info[5]);
}
#endif
static void spca504A_acknowledged_command(struct gspca_dev *gspca_dev,
u8 req,
u16 idx, u16 val, u8 endcode, u8 count)
{
u16 status;
reg_w_riv(gspca_dev, req, idx, val);
reg_r(gspca_dev, 0x01, 0x0001, 1);
if (gspca_dev->usb_err < 0)
return;
PDEBUG(D_FRAM, "Status 0x%02x Need 0x%02x",
gspca_dev->usb_buf[0], endcode);
if (!count)
return;
count = 200;
while (--count > 0) {
msleep(10);
/* gsmart mini2 write a each wait setting 1 ms is enough */
/* reg_w_riv(gspca_dev, req, idx, val); */
reg_r(gspca_dev, 0x01, 0x0001, 1);
status = gspca_dev->usb_buf[0];
if (status == endcode) {
PDEBUG(D_FRAM, "status 0x%04x after wait %d",
status, 200 - count);
break;
}
}
}
static void spca504B_PollingDataReady(struct gspca_dev *gspca_dev)
{
int count = 10;
while (--count > 0) {
reg_r(gspca_dev, 0x21, 0, 1);
if ((gspca_dev->usb_buf[0] & 0x01) == 0)
break;
msleep(10);
}
}
static void spca504B_WaitCmdStatus(struct gspca_dev *gspca_dev)
{
int count = 50;
while (--count > 0) {
reg_r(gspca_dev, 0x21, 1, 1);
if (gspca_dev->usb_buf[0] != 0) {
reg_w_1(gspca_dev, 0x21, 0, 1, 0);
reg_r(gspca_dev, 0x21, 1, 1);
spca504B_PollingDataReady(gspca_dev);
break;
}
msleep(10);
}
}
#ifdef GSPCA_DEBUG
static void spca50x_GetFirmware(struct gspca_dev *gspca_dev)
{
u8 *data;
data = gspca_dev->usb_buf;
reg_r(gspca_dev, 0x20, 0, 5);
PDEBUG(D_STREAM, "FirmWare: %d %d %d %d %d",
data[0], data[1], data[2], data[3], data[4]);
reg_r(gspca_dev, 0x23, 0, 64);
reg_r(gspca_dev, 0x23, 1, 64);
}
#endif
static void spca504B_SetSizeType(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 Size;
Size = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv;
switch (sd->bridge) {
case BRIDGE_SPCA533:
reg_w_riv(gspca_dev, 0x31, 0, 0);
spca504B_WaitCmdStatus(gspca_dev);
spca504B_PollingDataReady(gspca_dev);
#ifdef GSPCA_DEBUG
spca50x_GetFirmware(gspca_dev);
#endif
reg_w_1(gspca_dev, 0x24, 0, 8, 2); /* type */
reg_r(gspca_dev, 0x24, 8, 1);
reg_w_1(gspca_dev, 0x25, 0, 4, Size);
reg_r(gspca_dev, 0x25, 4, 1); /* size */
spca504B_PollingDataReady(gspca_dev);
/* Init the cam width height with some values get on init ? */
reg_w_riv(gspca_dev, 0x31, 0x0004, 0x00);
spca504B_WaitCmdStatus(gspca_dev);
spca504B_PollingDataReady(gspca_dev);
break;
default:
/* case BRIDGE_SPCA504B: */
/* case BRIDGE_SPCA536: */
reg_w_1(gspca_dev, 0x25, 0, 4, Size);
reg_r(gspca_dev, 0x25, 4, 1); /* size */
reg_w_1(gspca_dev, 0x27, 0, 0, 6);
reg_r(gspca_dev, 0x27, 0, 1); /* type */
spca504B_PollingDataReady(gspca_dev);
break;
case BRIDGE_SPCA504:
Size += 3;
if (sd->subtype == AiptekMiniPenCam13) {
/* spca504a aiptek */
spca504A_acknowledged_command(gspca_dev,
0x08, Size, 0,
0x80 | (Size & 0x0f), 1);
spca504A_acknowledged_command(gspca_dev,
1, 3, 0, 0x9f, 0);
} else {
spca504_acknowledged_command(gspca_dev, 0x08, Size, 0);
}
break;
case BRIDGE_SPCA504C:
/* capture mode */
reg_w_riv(gspca_dev, 0xa0, (0x0500 | (Size & 0x0f)), 0x00);
reg_w_riv(gspca_dev, 0x20, 0x01, 0x0500 | (Size & 0x0f));
break;
}
}
static void spca504_wait_status(struct gspca_dev *gspca_dev)
{
int cnt;
cnt = 256;
while (--cnt > 0) {
/* With this we get the status, when return 0 it's all ok */
reg_r(gspca_dev, 0x06, 0x00, 1);
if (gspca_dev->usb_buf[0] == 0)
return;
msleep(10);
}
}
static void spca504B_setQtable(struct gspca_dev *gspca_dev)
{
reg_w_1(gspca_dev, 0x26, 0, 0, 3);
reg_r(gspca_dev, 0x26, 0, 1);
spca504B_PollingDataReady(gspca_dev);
}
static void setbrightness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
u16 reg;
reg = sd->bridge == BRIDGE_SPCA536 ? 0x20f0 : 0x21a7;
reg_w_riv(gspca_dev, 0x00, reg, val);
}
static void setcontrast(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
u16 reg;
reg = sd->bridge == BRIDGE_SPCA536 ? 0x20f1 : 0x21a8;
reg_w_riv(gspca_dev, 0x00, reg, val);
}
static void setcolors(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
u16 reg;
reg = sd->bridge == BRIDGE_SPCA536 ? 0x20f6 : 0x21ae;
reg_w_riv(gspca_dev, 0x00, reg, val);
}
static void init_ctl_reg(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int pollreg = 1;
switch (sd->bridge) {
case BRIDGE_SPCA504:
case BRIDGE_SPCA504C:
pollreg = 0;
/* fall thru */
default:
/* case BRIDGE_SPCA533: */
/* case BRIDGE_SPCA504B: */
reg_w_riv(gspca_dev, 0, 0x21ad, 0x00); /* hue */
reg_w_riv(gspca_dev, 0, 0x21ac, 0x01); /* sat/hue */
reg_w_riv(gspca_dev, 0, 0x21a3, 0x00); /* gamma */
break;
case BRIDGE_SPCA536:
reg_w_riv(gspca_dev, 0, 0x20f5, 0x40);
reg_w_riv(gspca_dev, 0, 0x20f4, 0x01);
reg_w_riv(gspca_dev, 0, 0x2089, 0x00);
break;
}
if (pollreg)
spca504B_PollingDataReady(gspca_dev);
}
/* this function is called at probe time */
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;
sd->bridge = id->driver_info >> 8;
sd->subtype = id->driver_info;
if (sd->subtype == AiptekMiniPenCam13) {
/* try to get the firmware as some cam answer 2.0.1.2.2
* and should be a spca504b then overwrite that setting */
reg_r(gspca_dev, 0x20, 0, 1);
switch (gspca_dev->usb_buf[0]) {
case 1:
break; /* (right bridge/subtype) */
case 2:
sd->bridge = BRIDGE_SPCA504B;
sd->subtype = 0;
break;
default:
return -ENODEV;
}
}
switch (sd->bridge) {
default:
/* case BRIDGE_SPCA504B: */
/* case BRIDGE_SPCA504: */
/* case BRIDGE_SPCA536: */
cam->cam_mode = vga_mode;
cam->nmodes = ARRAY_SIZE(vga_mode);
break;
case BRIDGE_SPCA533:
cam->cam_mode = custom_mode;
if (sd->subtype == MegaImageVI) /* 320x240 only */
cam->nmodes = ARRAY_SIZE(custom_mode) - 1;
else
cam->nmodes = ARRAY_SIZE(custom_mode);
break;
case BRIDGE_SPCA504C:
cam->cam_mode = vga_mode2;
cam->nmodes = ARRAY_SIZE(vga_mode2);
break;
}
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->bridge) {
case BRIDGE_SPCA504B:
reg_w_riv(gspca_dev, 0x1d, 0x00, 0);
reg_w_riv(gspca_dev, 0x00, 0x2306, 0x01);
reg_w_riv(gspca_dev, 0x00, 0x0d04, 0x00);
reg_w_riv(gspca_dev, 0x00, 0x2000, 0x00);
reg_w_riv(gspca_dev, 0x00, 0x2301, 0x13);
reg_w_riv(gspca_dev, 0x00, 0x2306, 0x00);
/* fall thru */
case BRIDGE_SPCA533:
spca504B_PollingDataReady(gspca_dev);
#ifdef GSPCA_DEBUG
spca50x_GetFirmware(gspca_dev);
#endif
break;
case BRIDGE_SPCA536:
#ifdef GSPCA_DEBUG
spca50x_GetFirmware(gspca_dev);
#endif
reg_r(gspca_dev, 0x00, 0x5002, 1);
reg_w_1(gspca_dev, 0x24, 0, 0, 0);
reg_r(gspca_dev, 0x24, 0, 1);
spca504B_PollingDataReady(gspca_dev);
reg_w_riv(gspca_dev, 0x34, 0, 0);
spca504B_WaitCmdStatus(gspca_dev);
break;
case BRIDGE_SPCA504C: /* pccam600 */
PDEBUG(D_STREAM, "Opening SPCA504 (PC-CAM 600)");
reg_w_riv(gspca_dev, 0xe0, 0x0000, 0x0000);
reg_w_riv(gspca_dev, 0xe0, 0x0000, 0x0001); /* reset */
spca504_wait_status(gspca_dev);
if (sd->subtype == LogitechClickSmart420)
write_vector(gspca_dev,
spca504A_clicksmart420_open_data,
ARRAY_SIZE(spca504A_clicksmart420_open_data));
else
write_vector(gspca_dev, spca504_pccam600_open_data,
ARRAY_SIZE(spca504_pccam600_open_data));
setup_qtable(gspca_dev, qtable_creative_pccam);
break;
default:
/* case BRIDGE_SPCA504: */
PDEBUG(D_STREAM, "Opening SPCA504");
if (sd->subtype == AiptekMiniPenCam13) {
#ifdef GSPCA_DEBUG
spca504_read_info(gspca_dev);
#endif
/* Set AE AWB Banding Type 3-> 50Hz 2-> 60Hz */
spca504A_acknowledged_command(gspca_dev, 0x24,
8, 3, 0x9e, 1);
/* Twice sequential need status 0xff->0x9e->0x9d */
spca504A_acknowledged_command(gspca_dev, 0x24,
8, 3, 0x9e, 0);
spca504A_acknowledged_command(gspca_dev, 0x24,
0, 0, 0x9d, 1);
/******************************/
/* spca504a aiptek */
spca504A_acknowledged_command(gspca_dev, 0x08,
6, 0, 0x86, 1);
/* reg_write (dev, 0, 0x2000, 0); */
/* reg_write (dev, 0, 0x2883, 1); */
/* spca504A_acknowledged_command (gspca_dev, 0x08,
6, 0, 0x86, 1); */
/* spca504A_acknowledged_command (gspca_dev, 0x24,
0, 0, 0x9D, 1); */
reg_w_riv(gspca_dev, 0x00, 0x270c, 0x05);
/* L92 sno1t.txt */
reg_w_riv(gspca_dev, 0x00, 0x2310, 0x05);
spca504A_acknowledged_command(gspca_dev, 0x01,
0x0f, 0, 0xff, 0);
}
/* setup qtable */
reg_w_riv(gspca_dev, 0, 0x2000, 0);
reg_w_riv(gspca_dev, 0, 0x2883, 1);
setup_qtable(gspca_dev, qtable_spca504_default);
break;
}
return gspca_dev->usb_err;
}
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int enable;
/* create the JPEG header */
jpeg_define(sd->jpeg_hdr, gspca_dev->height, gspca_dev->width,
0x22); /* JPEG 411 */
jpeg_set_qual(sd->jpeg_hdr, QUALITY);
if (sd->bridge == BRIDGE_SPCA504B)
spca504B_setQtable(gspca_dev);
spca504B_SetSizeType(gspca_dev);
switch (sd->bridge) {
default:
/* case BRIDGE_SPCA504B: */
/* case BRIDGE_SPCA533: */
/* case BRIDGE_SPCA536: */
switch (sd->subtype) {
case MegapixV4:
case LogitechClickSmart820:
case MegaImageVI:
reg_w_riv(gspca_dev, 0xf0, 0, 0);
spca504B_WaitCmdStatus(gspca_dev);
reg_r(gspca_dev, 0xf0, 4, 0);
spca504B_WaitCmdStatus(gspca_dev);
break;
default:
reg_w_riv(gspca_dev, 0x31, 0x0004, 0x00);
spca504B_WaitCmdStatus(gspca_dev);
spca504B_PollingDataReady(gspca_dev);
break;
}
break;
case BRIDGE_SPCA504:
if (sd->subtype == AiptekMiniPenCam13) {
#ifdef GSPCA_DEBUG
spca504_read_info(gspca_dev);
#endif
/* Set AE AWB Banding Type 3-> 50Hz 2-> 60Hz */
spca504A_acknowledged_command(gspca_dev, 0x24,
8, 3, 0x9e, 1);
/* Twice sequential need status 0xff->0x9e->0x9d */
spca504A_acknowledged_command(gspca_dev, 0x24,
8, 3, 0x9e, 0);
spca504A_acknowledged_command(gspca_dev, 0x24,
0, 0, 0x9d, 1);
} else {
spca504_acknowledged_command(gspca_dev, 0x24, 8, 3);
#ifdef GSPCA_DEBUG
spca504_read_info(gspca_dev);
#endif
spca504_acknowledged_command(gspca_dev, 0x24, 8, 3);
spca504_acknowledged_command(gspca_dev, 0x24, 0, 0);
}
spca504B_SetSizeType(gspca_dev);
reg_w_riv(gspca_dev, 0x00, 0x270c, 0x05);
/* L92 sno1t.txt */
reg_w_riv(gspca_dev, 0x00, 0x2310, 0x05);
break;
case BRIDGE_SPCA504C:
if (sd->subtype == LogitechClickSmart420) {
write_vector(gspca_dev,
spca504A_clicksmart420_init_data,
ARRAY_SIZE(spca504A_clicksmart420_init_data));
} else {
write_vector(gspca_dev, spca504_pccam600_init_data,
ARRAY_SIZE(spca504_pccam600_init_data));
}
enable = (sd->autogain ? 0x04 : 0x01);
reg_w_riv(gspca_dev, 0x0c, 0x0000, enable);
/* auto exposure */
reg_w_riv(gspca_dev, 0xb0, 0x0000, enable);
/* auto whiteness */
/* set default exposure compensation and whiteness balance */
reg_w_riv(gspca_dev, 0x30, 0x0001, 800); /* ~ 20 fps */
reg_w_riv(gspca_dev, 0x30, 0x0002, 1600);
spca504B_SetSizeType(gspca_dev);
break;
}
init_ctl_reg(gspca_dev);
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->bridge) {
default:
/* case BRIDGE_SPCA533: */
/* case BRIDGE_SPCA536: */
/* case BRIDGE_SPCA504B: */
reg_w_riv(gspca_dev, 0x31, 0, 0);
spca504B_WaitCmdStatus(gspca_dev);
spca504B_PollingDataReady(gspca_dev);
break;
case BRIDGE_SPCA504:
case BRIDGE_SPCA504C:
reg_w_riv(gspca_dev, 0x00, 0x2000, 0x0000);
if (sd->subtype == AiptekMiniPenCam13) {
/* spca504a aiptek */
/* spca504A_acknowledged_command(gspca_dev, 0x08,
6, 0, 0x86, 1); */
spca504A_acknowledged_command(gspca_dev, 0x24,
0x00, 0x00, 0x9d, 1);
spca504A_acknowledged_command(gspca_dev, 0x01,
0x0f, 0x00, 0xff, 1);
} else {
spca504_acknowledged_command(gspca_dev, 0x24, 0, 0);
reg_w_riv(gspca_dev, 0x01, 0x000f, 0x0000);
}
break;
}
}
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;
int i, sof = 0;
static u8 ffd9[] = {0xff, 0xd9};
/* frames are jpeg 4.1.1 without 0xff escape */
switch (sd->bridge) {
case BRIDGE_SPCA533:
if (data[0] == 0xff) {
if (data[1] != 0x01) { /* drop packet */
/* gspca_dev->last_packet_type = DISCARD_PACKET; */
return;
}
sof = 1;
data += SPCA533_OFFSET_DATA;
len -= SPCA533_OFFSET_DATA;
} else {
data += 1;
len -= 1;
}
break;
case BRIDGE_SPCA536:
if (data[0] == 0xff) {
sof = 1;
data += SPCA536_OFFSET_DATA;
len -= SPCA536_OFFSET_DATA;
} else {
data += 2;
len -= 2;
}
break;
default:
/* case BRIDGE_SPCA504: */
/* case BRIDGE_SPCA504B: */
switch (data[0]) {
case 0xfe: /* start of frame */
sof = 1;
data += SPCA50X_OFFSET_DATA;
len -= SPCA50X_OFFSET_DATA;
break;
case 0xff: /* drop packet */
/* gspca_dev->last_packet_type = DISCARD_PACKET; */
return;
default:
data += 1;
len -= 1;
break;
}
break;
case BRIDGE_SPCA504C:
switch (data[0]) {
case 0xfe: /* start of frame */
sof = 1;
data += SPCA504_PCCAM600_OFFSET_DATA;
len -= SPCA504_PCCAM600_OFFSET_DATA;
break;
case 0xff: /* drop packet */
/* gspca_dev->last_packet_type = DISCARD_PACKET; */
return;
default:
data += 1;
len -= 1;
break;
}
break;
}
if (sof) { /* start of frame */
gspca_frame_add(gspca_dev, LAST_PACKET,
ffd9, 2);
/* put the JPEG header in the new frame */
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
}
/* add 0x00 after 0xff */
i = 0;
do {
if (data[i] == 0xff) {
gspca_frame_add(gspca_dev, INTER_PACKET,
data, i + 1);
len -= i;
data += i;
*data = 0x00;
i = 0;
}
i++;
} while (i < len);
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (!gspca_dev->streaming)
return 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
setbrightness(gspca_dev, ctrl->val);
break;
case V4L2_CID_CONTRAST:
setcontrast(gspca_dev, ctrl->val);
break;
case V4L2_CID_SATURATION:
setcolors(gspca_dev, ctrl->val);
break;
case V4L2_CID_AUTOGAIN:
sd->autogain = ctrl->val;
break;
}
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.s_ctrl = sd_s_ctrl,
};
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 4);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BRIGHTNESS, -128, 127, 1, 0);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_CONTRAST, 0, 255, 1, 0x20);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_SATURATION, 0, 255, 1, 0x1a);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
if (hdl->error) {
pr_err("Could not initialize controls\n");
return hdl->error;
}
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.stopN = sd_stopN,
.pkt_scan = sd_pkt_scan,
};
/* -- module initialisation -- */
#define BS(bridge, subtype) \
.driver_info = (BRIDGE_ ## bridge << 8) \
| (subtype)
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x041e, 0x400b), BS(SPCA504C, 0)},
{USB_DEVICE(0x041e, 0x4012), BS(SPCA504C, 0)},
{USB_DEVICE(0x041e, 0x4013), BS(SPCA504C, 0)},
{USB_DEVICE(0x0458, 0x7006), BS(SPCA504B, 0)},
{USB_DEVICE(0x0461, 0x0821), BS(SPCA533, 0)},
{USB_DEVICE(0x046d, 0x0905), BS(SPCA533, LogitechClickSmart820)},
{USB_DEVICE(0x046d, 0x0960), BS(SPCA504C, LogitechClickSmart420)},
{USB_DEVICE(0x0471, 0x0322), BS(SPCA504B, 0)},
{USB_DEVICE(0x04a5, 0x3003), BS(SPCA504B, 0)},
{USB_DEVICE(0x04a5, 0x3008), BS(SPCA533, 0)},
{USB_DEVICE(0x04a5, 0x300a), BS(SPCA533, 0)},
{USB_DEVICE(0x04f1, 0x1001), BS(SPCA504B, 0)},
{USB_DEVICE(0x04fc, 0x500c), BS(SPCA504B, 0)},
{USB_DEVICE(0x04fc, 0x504a), BS(SPCA504, AiptekMiniPenCam13)},
{USB_DEVICE(0x04fc, 0x504b), BS(SPCA504B, 0)},
{USB_DEVICE(0x04fc, 0x5330), BS(SPCA533, 0)},
{USB_DEVICE(0x04fc, 0x5360), BS(SPCA536, 0)},
{USB_DEVICE(0x04fc, 0xffff), BS(SPCA504B, 0)},
{USB_DEVICE(0x052b, 0x1507), BS(SPCA533, MegapixV4)},
{USB_DEVICE(0x052b, 0x1513), BS(SPCA533, MegapixV4)},
{USB_DEVICE(0x052b, 0x1803), BS(SPCA533, MegaImageVI)},
{USB_DEVICE(0x0546, 0x3155), BS(SPCA533, 0)},
{USB_DEVICE(0x0546, 0x3191), BS(SPCA504B, 0)},
{USB_DEVICE(0x0546, 0x3273), BS(SPCA504B, 0)},
{USB_DEVICE(0x055f, 0xc211), BS(SPCA536, 0)},
{USB_DEVICE(0x055f, 0xc230), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc232), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc360), BS(SPCA536, 0)},
{USB_DEVICE(0x055f, 0xc420), BS(SPCA504, 0)},
{USB_DEVICE(0x055f, 0xc430), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc440), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc520), BS(SPCA504, 0)},
{USB_DEVICE(0x055f, 0xc530), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc540), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc630), BS(SPCA533, 0)},
{USB_DEVICE(0x055f, 0xc650), BS(SPCA533, 0)},
{USB_DEVICE(0x05da, 0x1018), BS(SPCA504B, 0)},
{USB_DEVICE(0x06d6, 0x0031), BS(SPCA533, 0)},
{USB_DEVICE(0x0733, 0x1311), BS(SPCA533, 0)},
{USB_DEVICE(0x0733, 0x1314), BS(SPCA533, 0)},
{USB_DEVICE(0x0733, 0x2211), BS(SPCA533, 0)},
{USB_DEVICE(0x0733, 0x2221), BS(SPCA533, 0)},
{USB_DEVICE(0x0733, 0x3261), BS(SPCA536, 0)},
{USB_DEVICE(0x0733, 0x3281), BS(SPCA536, 0)},
{USB_DEVICE(0x08ca, 0x0104), BS(SPCA533, 0)},
{USB_DEVICE(0x08ca, 0x0106), BS(SPCA533, 0)},
{USB_DEVICE(0x08ca, 0x2008), BS(SPCA504B, 0)},
{USB_DEVICE(0x08ca, 0x2010), BS(SPCA533, 0)},
{USB_DEVICE(0x08ca, 0x2016), BS(SPCA504B, 0)},
{USB_DEVICE(0x08ca, 0x2018), BS(SPCA504B, 0)},
{USB_DEVICE(0x08ca, 0x2020), BS(SPCA533, 0)},
{USB_DEVICE(0x08ca, 0x2022), BS(SPCA533, 0)},
{USB_DEVICE(0x08ca, 0x2024), BS(SPCA536, 0)},
{USB_DEVICE(0x08ca, 0x2028), BS(SPCA533, 0)},
{USB_DEVICE(0x08ca, 0x2040), BS(SPCA536, 0)},
{USB_DEVICE(0x08ca, 0x2042), BS(SPCA536, 0)},
{USB_DEVICE(0x08ca, 0x2050), BS(SPCA536, 0)},
{USB_DEVICE(0x08ca, 0x2060), BS(SPCA536, 0)},
{USB_DEVICE(0x0d64, 0x0303), BS(SPCA536, 0)},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int 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,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| gpl-2.0 |
nel82/android_zenfone4_kernel | fs/jbd2/journal.c | 1055 | 75216 | /*
* linux/fs/jbd2/journal.c
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1998
*
* Copyright 1998 Red Hat corp --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Generic filesystem journal-writing code; part of the ext2fs
* journaling system.
*
* This file manages journals: areas of disk reserved for logging
* transactional updates. This includes the kernel journaling thread
* which is responsible for scheduling updates to the log.
*
* We do not actually manage the physical storage of the journal in this
* file: that is left to a per-journal policy function, which allows us
* to store the journal within a filesystem-specified area for ext2
* journaling (ext2 can use a reserved inode for storing the log).
*/
#include <linux/module.h>
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/freezer.h>
#include <linux/pagemap.h>
#include <linux/kthread.h>
#include <linux/poison.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/math64.h>
#include <linux/hash.h>
#include <linux/log2.h>
#include <linux/vmalloc.h>
#include <linux/backing-dev.h>
#include <linux/bitops.h>
#include <linux/ratelimit.h>
#define CREATE_TRACE_POINTS
#include <trace/events/jbd2.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#ifdef CONFIG_JBD2_DEBUG
ushort jbd2_journal_enable_debug __read_mostly;
EXPORT_SYMBOL(jbd2_journal_enable_debug);
module_param_named(jbd2_debug, jbd2_journal_enable_debug, ushort, 0644);
MODULE_PARM_DESC(jbd2_debug, "Debugging level for jbd2");
#endif
EXPORT_SYMBOL(jbd2_journal_extend);
EXPORT_SYMBOL(jbd2_journal_stop);
EXPORT_SYMBOL(jbd2_journal_lock_updates);
EXPORT_SYMBOL(jbd2_journal_unlock_updates);
EXPORT_SYMBOL(jbd2_journal_get_write_access);
EXPORT_SYMBOL(jbd2_journal_get_create_access);
EXPORT_SYMBOL(jbd2_journal_get_undo_access);
EXPORT_SYMBOL(jbd2_journal_set_triggers);
EXPORT_SYMBOL(jbd2_journal_dirty_metadata);
EXPORT_SYMBOL(jbd2_journal_forget);
#if 0
EXPORT_SYMBOL(journal_sync_buffer);
#endif
EXPORT_SYMBOL(jbd2_journal_flush);
EXPORT_SYMBOL(jbd2_journal_revoke);
EXPORT_SYMBOL(jbd2_journal_init_dev);
EXPORT_SYMBOL(jbd2_journal_init_inode);
EXPORT_SYMBOL(jbd2_journal_check_used_features);
EXPORT_SYMBOL(jbd2_journal_check_available_features);
EXPORT_SYMBOL(jbd2_journal_set_features);
EXPORT_SYMBOL(jbd2_journal_load);
EXPORT_SYMBOL(jbd2_journal_destroy);
EXPORT_SYMBOL(jbd2_journal_abort);
EXPORT_SYMBOL(jbd2_journal_errno);
EXPORT_SYMBOL(jbd2_journal_ack_err);
EXPORT_SYMBOL(jbd2_journal_clear_err);
EXPORT_SYMBOL(jbd2_log_wait_commit);
EXPORT_SYMBOL(jbd2_log_start_commit);
EXPORT_SYMBOL(jbd2_journal_start_commit);
EXPORT_SYMBOL(jbd2_journal_force_commit_nested);
EXPORT_SYMBOL(jbd2_journal_wipe);
EXPORT_SYMBOL(jbd2_journal_blocks_per_page);
EXPORT_SYMBOL(jbd2_journal_invalidatepage);
EXPORT_SYMBOL(jbd2_journal_try_to_free_buffers);
EXPORT_SYMBOL(jbd2_journal_force_commit);
EXPORT_SYMBOL(jbd2_journal_file_inode);
EXPORT_SYMBOL(jbd2_journal_init_jbd_inode);
EXPORT_SYMBOL(jbd2_journal_release_jbd_inode);
EXPORT_SYMBOL(jbd2_journal_begin_ordered_truncate);
EXPORT_SYMBOL(jbd2_inode_cache);
static void __journal_abort_soft (journal_t *journal, int errno);
static int jbd2_journal_create_slab(size_t slab_size);
/* Checksumming functions */
int jbd2_verify_csum_type(journal_t *j, journal_superblock_t *sb)
{
if (!JBD2_HAS_INCOMPAT_FEATURE(j, JBD2_FEATURE_INCOMPAT_CSUM_V2))
return 1;
return sb->s_checksum_type == JBD2_CRC32C_CHKSUM;
}
static __u32 jbd2_superblock_csum(journal_t *j, journal_superblock_t *sb)
{
__u32 csum, old_csum;
old_csum = sb->s_checksum;
sb->s_checksum = 0;
csum = jbd2_chksum(j, ~0, (char *)sb, sizeof(journal_superblock_t));
sb->s_checksum = old_csum;
return cpu_to_be32(csum);
}
int jbd2_superblock_csum_verify(journal_t *j, journal_superblock_t *sb)
{
if (!JBD2_HAS_INCOMPAT_FEATURE(j, JBD2_FEATURE_INCOMPAT_CSUM_V2))
return 1;
return sb->s_checksum == jbd2_superblock_csum(j, sb);
}
void jbd2_superblock_csum_set(journal_t *j, journal_superblock_t *sb)
{
if (!JBD2_HAS_INCOMPAT_FEATURE(j, JBD2_FEATURE_INCOMPAT_CSUM_V2))
return;
sb->s_checksum = jbd2_superblock_csum(j, sb);
}
/*
* Helper function used to manage commit timeouts
*/
static void commit_timeout(unsigned long __data)
{
struct task_struct * p = (struct task_struct *) __data;
wake_up_process(p);
}
/*
* kjournald2: The main thread function used to manage a logging device
* journal.
*
* This kernel thread is responsible for two things:
*
* 1) COMMIT: Every so often we need to commit the current state of the
* filesystem to disk. The journal thread is responsible for writing
* all of the metadata buffers to disk.
*
* 2) CHECKPOINT: We cannot reuse a used section of the log file until all
* of the data in that part of the log has been rewritten elsewhere on
* the disk. Flushing these old buffers to reclaim space in the log is
* known as checkpointing, and this thread is responsible for that job.
*/
static int kjournald2(void *arg)
{
journal_t *journal = arg;
transaction_t *transaction;
/*
* Set up an interval timer which can be used to trigger a commit wakeup
* after the commit interval expires
*/
setup_timer(&journal->j_commit_timer, commit_timeout,
(unsigned long)current);
set_freezable();
/* Record that the journal thread is running */
journal->j_task = current;
wake_up(&journal->j_wait_done_commit);
/*
* And now, wait forever for commit wakeup events.
*/
write_lock(&journal->j_state_lock);
loop:
if (journal->j_flags & JBD2_UNMOUNT)
goto end_loop;
jbd_debug(1, "commit_sequence=%d, commit_request=%d\n",
journal->j_commit_sequence, journal->j_commit_request);
if (journal->j_commit_sequence != journal->j_commit_request) {
jbd_debug(1, "OK, requests differ\n");
write_unlock(&journal->j_state_lock);
del_timer_sync(&journal->j_commit_timer);
jbd2_journal_commit_transaction(journal);
write_lock(&journal->j_state_lock);
goto loop;
}
wake_up(&journal->j_wait_done_commit);
if (freezing(current)) {
/*
* The simpler the better. Flushing journal isn't a
* good idea, because that depends on threads that may
* be already stopped.
*/
jbd_debug(1, "Now suspending kjournald2\n");
write_unlock(&journal->j_state_lock);
try_to_freeze();
write_lock(&journal->j_state_lock);
} else {
/*
* We assume on resume that commits are already there,
* so we don't sleep
*/
DEFINE_WAIT(wait);
int should_sleep = 1;
prepare_to_wait(&journal->j_wait_commit, &wait,
TASK_INTERRUPTIBLE);
if (journal->j_commit_sequence != journal->j_commit_request)
should_sleep = 0;
transaction = journal->j_running_transaction;
if (transaction && time_after_eq(jiffies,
transaction->t_expires))
should_sleep = 0;
if (journal->j_flags & JBD2_UNMOUNT)
should_sleep = 0;
if (should_sleep) {
write_unlock(&journal->j_state_lock);
schedule();
write_lock(&journal->j_state_lock);
}
finish_wait(&journal->j_wait_commit, &wait);
}
jbd_debug(1, "kjournald2 wakes\n");
/*
* Were we woken up by a commit wakeup event?
*/
transaction = journal->j_running_transaction;
if (transaction && time_after_eq(jiffies, transaction->t_expires)) {
journal->j_commit_request = transaction->t_tid;
jbd_debug(1, "woke because of timeout\n");
}
goto loop;
end_loop:
write_unlock(&journal->j_state_lock);
del_timer_sync(&journal->j_commit_timer);
journal->j_task = NULL;
wake_up(&journal->j_wait_done_commit);
jbd_debug(1, "Journal thread exiting.\n");
return 0;
}
static int jbd2_journal_start_thread(journal_t *journal)
{
struct task_struct *t;
t = kthread_run(kjournald2, journal, "jbd2/%s",
journal->j_devname);
if (IS_ERR(t))
return PTR_ERR(t);
wait_event(journal->j_wait_done_commit, journal->j_task != NULL);
return 0;
}
static void journal_kill_thread(journal_t *journal)
{
write_lock(&journal->j_state_lock);
journal->j_flags |= JBD2_UNMOUNT;
while (journal->j_task) {
wake_up(&journal->j_wait_commit);
write_unlock(&journal->j_state_lock);
wait_event(journal->j_wait_done_commit, journal->j_task == NULL);
write_lock(&journal->j_state_lock);
}
write_unlock(&journal->j_state_lock);
}
/*
* jbd2_journal_write_metadata_buffer: write a metadata buffer to the journal.
*
* Writes a metadata buffer to a given disk block. The actual IO is not
* performed but a new buffer_head is constructed which labels the data
* to be written with the correct destination disk block.
*
* Any magic-number escaping which needs to be done will cause a
* copy-out here. If the buffer happens to start with the
* JBD2_MAGIC_NUMBER, then we can't write it to the log directly: the
* magic number is only written to the log for descripter blocks. In
* this case, we copy the data and replace the first word with 0, and we
* return a result code which indicates that this buffer needs to be
* marked as an escaped buffer in the corresponding log descriptor
* block. The missing word can then be restored when the block is read
* during recovery.
*
* If the source buffer has already been modified by a new transaction
* since we took the last commit snapshot, we use the frozen copy of
* that data for IO. If we end up using the existing buffer_head's data
* for the write, then we *have* to lock the buffer to prevent anyone
* else from using and possibly modifying it while the IO is in
* progress.
*
* The function returns a pointer to the buffer_heads to be used for IO.
*
* We assume that the journal has already been locked in this function.
*
* Return value:
* <0: Error
* >=0: Finished OK
*
* On success:
* Bit 0 set == escape performed on the data
* Bit 1 set == buffer copy-out performed (kfree the data after IO)
*/
int jbd2_journal_write_metadata_buffer(transaction_t *transaction,
struct journal_head *jh_in,
struct journal_head **jh_out,
unsigned long long blocknr)
{
int need_copy_out = 0;
int done_copy_out = 0;
int do_escape = 0;
char *mapped_data;
struct buffer_head *new_bh;
struct journal_head *new_jh;
struct page *new_page;
unsigned int new_offset;
struct buffer_head *bh_in = jh2bh(jh_in);
journal_t *journal = transaction->t_journal;
/*
* The buffer really shouldn't be locked: only the current committing
* transaction is allowed to write it, so nobody else is allowed
* to do any IO.
*
* akpm: except if we're journalling data, and write() output is
* also part of a shared mapping, and another thread has
* decided to launch a writepage() against this buffer.
*/
J_ASSERT_BH(bh_in, buffer_jbddirty(bh_in));
retry_alloc:
new_bh = alloc_buffer_head(GFP_NOFS);
if (!new_bh) {
/*
* Failure is not an option, but __GFP_NOFAIL is going
* away; so we retry ourselves here.
*/
congestion_wait(BLK_RW_ASYNC, HZ/50);
goto retry_alloc;
}
/* keep subsequent assertions sane */
atomic_set(&new_bh->b_count, 1);
new_jh = jbd2_journal_add_journal_head(new_bh); /* This sleeps */
/*
* If a new transaction has already done a buffer copy-out, then
* we use that version of the data for the commit.
*/
jbd_lock_bh_state(bh_in);
repeat:
if (jh_in->b_frozen_data) {
done_copy_out = 1;
new_page = virt_to_page(jh_in->b_frozen_data);
new_offset = offset_in_page(jh_in->b_frozen_data);
} else {
new_page = jh2bh(jh_in)->b_page;
new_offset = offset_in_page(jh2bh(jh_in)->b_data);
}
mapped_data = kmap_atomic(new_page);
/*
* Fire data frozen trigger if data already wasn't frozen. Do this
* before checking for escaping, as the trigger may modify the magic
* offset. If a copy-out happens afterwards, it will have the correct
* data in the buffer.
*/
if (!done_copy_out)
jbd2_buffer_frozen_trigger(jh_in, mapped_data + new_offset,
jh_in->b_triggers);
/*
* Check for escaping
*/
if (*((__be32 *)(mapped_data + new_offset)) ==
cpu_to_be32(JBD2_MAGIC_NUMBER)) {
need_copy_out = 1;
do_escape = 1;
}
kunmap_atomic(mapped_data);
/*
* Do we need to do a data copy?
*/
if (need_copy_out && !done_copy_out) {
char *tmp;
jbd_unlock_bh_state(bh_in);
tmp = jbd2_alloc(bh_in->b_size, GFP_NOFS);
if (!tmp) {
jbd2_journal_put_journal_head(new_jh);
return -ENOMEM;
}
jbd_lock_bh_state(bh_in);
if (jh_in->b_frozen_data) {
jbd2_free(tmp, bh_in->b_size);
goto repeat;
}
jh_in->b_frozen_data = tmp;
mapped_data = kmap_atomic(new_page);
memcpy(tmp, mapped_data + new_offset, jh2bh(jh_in)->b_size);
kunmap_atomic(mapped_data);
new_page = virt_to_page(tmp);
new_offset = offset_in_page(tmp);
done_copy_out = 1;
/*
* This isn't strictly necessary, as we're using frozen
* data for the escaping, but it keeps consistency with
* b_frozen_data usage.
*/
jh_in->b_frozen_triggers = jh_in->b_triggers;
}
/*
* Did we need to do an escaping? Now we've done all the
* copying, we can finally do so.
*/
if (do_escape) {
mapped_data = kmap_atomic(new_page);
*((unsigned int *)(mapped_data + new_offset)) = 0;
kunmap_atomic(mapped_data);
}
set_bh_page(new_bh, new_page, new_offset);
new_jh->b_transaction = NULL;
new_bh->b_size = jh2bh(jh_in)->b_size;
new_bh->b_bdev = transaction->t_journal->j_dev;
new_bh->b_blocknr = blocknr;
set_buffer_mapped(new_bh);
set_buffer_dirty(new_bh);
*jh_out = new_jh;
/*
* The to-be-written buffer needs to get moved to the io queue,
* and the original buffer whose contents we are shadowing or
* copying is moved to the transaction's shadow queue.
*/
JBUFFER_TRACE(jh_in, "file as BJ_Shadow");
spin_lock(&journal->j_list_lock);
__jbd2_journal_file_buffer(jh_in, transaction, BJ_Shadow);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh_in);
JBUFFER_TRACE(new_jh, "file as BJ_IO");
jbd2_journal_file_buffer(new_jh, transaction, BJ_IO);
return do_escape | (done_copy_out << 1);
}
/*
* Allocation code for the journal file. Manage the space left in the
* journal, so that we can begin checkpointing when appropriate.
*/
/*
* __jbd2_log_space_left: Return the number of free blocks left in the journal.
*
* Called with the journal already locked.
*
* Called under j_state_lock
*/
int __jbd2_log_space_left(journal_t *journal)
{
int left = journal->j_free;
/* assert_spin_locked(&journal->j_state_lock); */
/*
* Be pessimistic here about the number of those free blocks which
* might be required for log descriptor control blocks.
*/
#define MIN_LOG_RESERVED_BLOCKS 32 /* Allow for rounding errors */
left -= MIN_LOG_RESERVED_BLOCKS;
if (left <= 0)
return 0;
left -= (left >> 3);
return left;
}
/*
* Called with j_state_lock locked for writing.
* Returns true if a transaction commit was started.
*/
int __jbd2_log_start_commit(journal_t *journal, tid_t target)
{
/* Return if the txn has already requested to be committed */
if (journal->j_commit_request == target)
return 0;
/*
* The only transaction we can possibly wait upon is the
* currently running transaction (if it exists). Otherwise,
* the target tid must be an old one.
*/
if (journal->j_running_transaction &&
journal->j_running_transaction->t_tid == target) {
/*
* We want a new commit: OK, mark the request and wakeup the
* commit thread. We do _not_ do the commit ourselves.
*/
journal->j_commit_request = target;
jbd_debug(1, "JBD2: requesting commit %d/%d\n",
journal->j_commit_request,
journal->j_commit_sequence);
journal->j_running_transaction->t_requested = jiffies;
wake_up(&journal->j_wait_commit);
return 1;
} else if (!tid_geq(journal->j_commit_request, target))
/* This should never happen, but if it does, preserve
the evidence before kjournald goes into a loop and
increments j_commit_sequence beyond all recognition. */
WARN_ONCE(1, "JBD2: bad log_start_commit: %u %u %u %u\n",
journal->j_commit_request,
journal->j_commit_sequence,
target, journal->j_running_transaction ?
journal->j_running_transaction->t_tid : 0);
return 0;
}
int jbd2_log_start_commit(journal_t *journal, tid_t tid)
{
int ret;
write_lock(&journal->j_state_lock);
ret = __jbd2_log_start_commit(journal, tid);
write_unlock(&journal->j_state_lock);
return ret;
}
/*
* Force and wait upon a commit if the calling process is not within
* transaction. This is used for forcing out undo-protected data which contains
* bitmaps, when the fs is running out of space.
*
* We can only force the running transaction if we don't have an active handle;
* otherwise, we will deadlock.
*
* Returns true if a transaction was started.
*/
int jbd2_journal_force_commit_nested(journal_t *journal)
{
transaction_t *transaction = NULL;
tid_t tid;
int need_to_start = 0;
read_lock(&journal->j_state_lock);
if (journal->j_running_transaction && !current->journal_info) {
transaction = journal->j_running_transaction;
if (!tid_geq(journal->j_commit_request, transaction->t_tid))
need_to_start = 1;
} else if (journal->j_committing_transaction)
transaction = journal->j_committing_transaction;
if (!transaction) {
read_unlock(&journal->j_state_lock);
return 0; /* Nothing to retry */
}
tid = transaction->t_tid;
read_unlock(&journal->j_state_lock);
if (need_to_start)
jbd2_log_start_commit(journal, tid);
jbd2_log_wait_commit(journal, tid);
return 1;
}
/*
* Start a commit of the current running transaction (if any). Returns true
* if a transaction is going to be committed (or is currently already
* committing), and fills its tid in at *ptid
*/
int jbd2_journal_start_commit(journal_t *journal, tid_t *ptid)
{
int ret = 0;
write_lock(&journal->j_state_lock);
if (journal->j_running_transaction) {
tid_t tid = journal->j_running_transaction->t_tid;
__jbd2_log_start_commit(journal, tid);
/* There's a running transaction and we've just made sure
* it's commit has been scheduled. */
if (ptid)
*ptid = tid;
ret = 1;
} else if (journal->j_committing_transaction) {
/*
* If commit has been started, then we have to wait for
* completion of that transaction.
*/
if (ptid)
*ptid = journal->j_committing_transaction->t_tid;
ret = 1;
}
write_unlock(&journal->j_state_lock);
return ret;
}
/*
* Return 1 if a given transaction has not yet sent barrier request
* connected with a transaction commit. If 0 is returned, transaction
* may or may not have sent the barrier. Used to avoid sending barrier
* twice in common cases.
*/
int jbd2_trans_will_send_data_barrier(journal_t *journal, tid_t tid)
{
int ret = 0;
transaction_t *commit_trans;
if (!(journal->j_flags & JBD2_BARRIER))
return 0;
read_lock(&journal->j_state_lock);
/* Transaction already committed? */
if (tid_geq(journal->j_commit_sequence, tid))
goto out;
commit_trans = journal->j_committing_transaction;
if (!commit_trans || commit_trans->t_tid != tid) {
ret = 1;
goto out;
}
/*
* Transaction is being committed and we already proceeded to
* submitting a flush to fs partition?
*/
if (journal->j_fs_dev != journal->j_dev) {
if (!commit_trans->t_need_data_flush ||
commit_trans->t_state >= T_COMMIT_DFLUSH)
goto out;
} else {
if (commit_trans->t_state >= T_COMMIT_JFLUSH)
goto out;
}
ret = 1;
out:
read_unlock(&journal->j_state_lock);
return ret;
}
EXPORT_SYMBOL(jbd2_trans_will_send_data_barrier);
/*
* Wait for a specified commit to complete.
* The caller may not hold the journal lock.
*/
int jbd2_log_wait_commit(journal_t *journal, tid_t tid)
{
int err = 0;
read_lock(&journal->j_state_lock);
#ifdef CONFIG_JBD2_DEBUG
if (!tid_geq(journal->j_commit_request, tid)) {
printk(KERN_EMERG
"%s: error: j_commit_request=%d, tid=%d\n",
__func__, journal->j_commit_request, tid);
}
#endif
while (tid_gt(tid, journal->j_commit_sequence)) {
jbd_debug(1, "JBD2: want %d, j_commit_sequence=%d\n",
tid, journal->j_commit_sequence);
wake_up(&journal->j_wait_commit);
read_unlock(&journal->j_state_lock);
wait_event(journal->j_wait_done_commit,
!tid_gt(tid, journal->j_commit_sequence));
read_lock(&journal->j_state_lock);
}
read_unlock(&journal->j_state_lock);
if (unlikely(is_journal_aborted(journal))) {
printk(KERN_EMERG "journal commit I/O error\n");
err = -EIO;
}
return err;
}
/*
* When this function returns the transaction corresponding to tid
* will be completed. If the transaction has currently running, start
* committing that transaction before waiting for it to complete. If
* the transaction id is stale, it is by definition already completed,
* so just return SUCCESS.
*/
int jbd2_complete_transaction(journal_t *journal, tid_t tid)
{
int need_to_wait = 1;
read_lock(&journal->j_state_lock);
if (journal->j_running_transaction &&
journal->j_running_transaction->t_tid == tid) {
if (journal->j_commit_request != tid) {
/* transaction not yet started, so request it */
read_unlock(&journal->j_state_lock);
jbd2_log_start_commit(journal, tid);
goto wait_commit;
}
} else if (!(journal->j_committing_transaction &&
journal->j_committing_transaction->t_tid == tid))
need_to_wait = 0;
read_unlock(&journal->j_state_lock);
if (!need_to_wait)
return 0;
wait_commit:
return jbd2_log_wait_commit(journal, tid);
}
EXPORT_SYMBOL(jbd2_complete_transaction);
/*
* Log buffer allocation routines:
*/
int jbd2_journal_next_log_block(journal_t *journal, unsigned long long *retp)
{
unsigned long blocknr;
write_lock(&journal->j_state_lock);
J_ASSERT(journal->j_free > 1);
blocknr = journal->j_head;
journal->j_head++;
journal->j_free--;
if (journal->j_head == journal->j_last)
journal->j_head = journal->j_first;
write_unlock(&journal->j_state_lock);
return jbd2_journal_bmap(journal, blocknr, retp);
}
/*
* Conversion of logical to physical block numbers for the journal
*
* On external journals the journal blocks are identity-mapped, so
* this is a no-op. If needed, we can use j_blk_offset - everything is
* ready.
*/
int jbd2_journal_bmap(journal_t *journal, unsigned long blocknr,
unsigned long long *retp)
{
int err = 0;
unsigned long long ret;
if (journal->j_inode) {
ret = bmap(journal->j_inode, blocknr);
if (ret)
*retp = ret;
else {
printk(KERN_ALERT "%s: journal block not found "
"at offset %lu on %s\n",
__func__, blocknr, journal->j_devname);
err = -EIO;
__journal_abort_soft(journal, err);
}
} else {
*retp = blocknr; /* +journal->j_blk_offset */
}
return err;
}
/*
* We play buffer_head aliasing tricks to write data/metadata blocks to
* the journal without copying their contents, but for journal
* descriptor blocks we do need to generate bona fide buffers.
*
* After the caller of jbd2_journal_get_descriptor_buffer() has finished modifying
* the buffer's contents they really should run flush_dcache_page(bh->b_page).
* But we don't bother doing that, so there will be coherency problems with
* mmaps of blockdevs which hold live JBD-controlled filesystems.
*/
struct journal_head *jbd2_journal_get_descriptor_buffer(journal_t *journal)
{
struct buffer_head *bh;
unsigned long long blocknr;
int err;
err = jbd2_journal_next_log_block(journal, &blocknr);
if (err)
return NULL;
bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
if (!bh)
return NULL;
lock_buffer(bh);
memset(bh->b_data, 0, journal->j_blocksize);
set_buffer_uptodate(bh);
unlock_buffer(bh);
BUFFER_TRACE(bh, "return this buffer");
return jbd2_journal_add_journal_head(bh);
}
/*
* Return tid of the oldest transaction in the journal and block in the journal
* where the transaction starts.
*
* If the journal is now empty, return which will be the next transaction ID
* we will write and where will that transaction start.
*
* The return value is 0 if journal tail cannot be pushed any further, 1 if
* it can.
*/
int jbd2_journal_get_log_tail(journal_t *journal, tid_t *tid,
unsigned long *block)
{
transaction_t *transaction;
int ret;
read_lock(&journal->j_state_lock);
spin_lock(&journal->j_list_lock);
transaction = journal->j_checkpoint_transactions;
if (transaction) {
*tid = transaction->t_tid;
*block = transaction->t_log_start;
} else if ((transaction = journal->j_committing_transaction) != NULL) {
*tid = transaction->t_tid;
*block = transaction->t_log_start;
} else if ((transaction = journal->j_running_transaction) != NULL) {
*tid = transaction->t_tid;
*block = journal->j_head;
} else {
*tid = journal->j_transaction_sequence;
*block = journal->j_head;
}
ret = tid_gt(*tid, journal->j_tail_sequence);
spin_unlock(&journal->j_list_lock);
read_unlock(&journal->j_state_lock);
return ret;
}
/*
* Update information in journal structure and in on disk journal superblock
* about log tail. This function does not check whether information passed in
* really pushes log tail further. It's responsibility of the caller to make
* sure provided log tail information is valid (e.g. by holding
* j_checkpoint_mutex all the time between computing log tail and calling this
* function as is the case with jbd2_cleanup_journal_tail()).
*
* Requires j_checkpoint_mutex
*/
void __jbd2_update_log_tail(journal_t *journal, tid_t tid, unsigned long block)
{
unsigned long freed;
BUG_ON(!mutex_is_locked(&journal->j_checkpoint_mutex));
/*
* We cannot afford for write to remain in drive's caches since as
* soon as we update j_tail, next transaction can start reusing journal
* space and if we lose sb update during power failure we'd replay
* old transaction with possibly newly overwritten data.
*/
jbd2_journal_update_sb_log_tail(journal, tid, block, WRITE_FUA);
write_lock(&journal->j_state_lock);
freed = block - journal->j_tail;
if (block < journal->j_tail)
freed += journal->j_last - journal->j_first;
trace_jbd2_update_log_tail(journal, tid, block, freed);
jbd_debug(1,
"Cleaning journal tail from %d to %d (offset %lu), "
"freeing %lu\n",
journal->j_tail_sequence, tid, block, freed);
journal->j_free += freed;
journal->j_tail_sequence = tid;
journal->j_tail = block;
write_unlock(&journal->j_state_lock);
}
/*
* This is a variaon of __jbd2_update_log_tail which checks for validity of
* provided log tail and locks j_checkpoint_mutex. So it is safe against races
* with other threads updating log tail.
*/
void jbd2_update_log_tail(journal_t *journal, tid_t tid, unsigned long block)
{
mutex_lock(&journal->j_checkpoint_mutex);
if (tid_gt(tid, journal->j_tail_sequence))
__jbd2_update_log_tail(journal, tid, block);
mutex_unlock(&journal->j_checkpoint_mutex);
}
struct jbd2_stats_proc_session {
journal_t *journal;
struct transaction_stats_s *stats;
int start;
int max;
};
static void *jbd2_seq_info_start(struct seq_file *seq, loff_t *pos)
{
return *pos ? NULL : SEQ_START_TOKEN;
}
static void *jbd2_seq_info_next(struct seq_file *seq, void *v, loff_t *pos)
{
return NULL;
}
static int jbd2_seq_info_show(struct seq_file *seq, void *v)
{
struct jbd2_stats_proc_session *s = seq->private;
if (v != SEQ_START_TOKEN)
return 0;
seq_printf(seq, "%lu transactions (%lu requested), "
"each up to %u blocks\n",
s->stats->ts_tid, s->stats->ts_requested,
s->journal->j_max_transaction_buffers);
if (s->stats->ts_tid == 0)
return 0;
seq_printf(seq, "average: \n %ums waiting for transaction\n",
jiffies_to_msecs(s->stats->run.rs_wait / s->stats->ts_tid));
seq_printf(seq, " %ums request delay\n",
(s->stats->ts_requested == 0) ? 0 :
jiffies_to_msecs(s->stats->run.rs_request_delay /
s->stats->ts_requested));
seq_printf(seq, " %ums running transaction\n",
jiffies_to_msecs(s->stats->run.rs_running / s->stats->ts_tid));
seq_printf(seq, " %ums transaction was being locked\n",
jiffies_to_msecs(s->stats->run.rs_locked / s->stats->ts_tid));
seq_printf(seq, " %ums flushing data (in ordered mode)\n",
jiffies_to_msecs(s->stats->run.rs_flushing / s->stats->ts_tid));
seq_printf(seq, " %ums logging transaction\n",
jiffies_to_msecs(s->stats->run.rs_logging / s->stats->ts_tid));
seq_printf(seq, " %lluus average transaction commit time\n",
div_u64(s->journal->j_average_commit_time, 1000));
seq_printf(seq, " %lu handles per transaction\n",
s->stats->run.rs_handle_count / s->stats->ts_tid);
seq_printf(seq, " %lu blocks per transaction\n",
s->stats->run.rs_blocks / s->stats->ts_tid);
seq_printf(seq, " %lu logged blocks per transaction\n",
s->stats->run.rs_blocks_logged / s->stats->ts_tid);
return 0;
}
static void jbd2_seq_info_stop(struct seq_file *seq, void *v)
{
}
static const struct seq_operations jbd2_seq_info_ops = {
.start = jbd2_seq_info_start,
.next = jbd2_seq_info_next,
.stop = jbd2_seq_info_stop,
.show = jbd2_seq_info_show,
};
static int jbd2_seq_info_open(struct inode *inode, struct file *file)
{
journal_t *journal = PDE_DATA(inode);
struct jbd2_stats_proc_session *s;
int rc, size;
s = kmalloc(sizeof(*s), GFP_KERNEL);
if (s == NULL)
return -ENOMEM;
size = sizeof(struct transaction_stats_s);
s->stats = kmalloc(size, GFP_KERNEL);
if (s->stats == NULL) {
kfree(s);
return -ENOMEM;
}
spin_lock(&journal->j_history_lock);
memcpy(s->stats, &journal->j_stats, size);
s->journal = journal;
spin_unlock(&journal->j_history_lock);
rc = seq_open(file, &jbd2_seq_info_ops);
if (rc == 0) {
struct seq_file *m = file->private_data;
m->private = s;
} else {
kfree(s->stats);
kfree(s);
}
return rc;
}
static int jbd2_seq_info_release(struct inode *inode, struct file *file)
{
struct seq_file *seq = file->private_data;
struct jbd2_stats_proc_session *s = seq->private;
kfree(s->stats);
kfree(s);
return seq_release(inode, file);
}
static const struct file_operations jbd2_seq_info_fops = {
.owner = THIS_MODULE,
.open = jbd2_seq_info_open,
.read = seq_read,
.llseek = seq_lseek,
.release = jbd2_seq_info_release,
};
static struct proc_dir_entry *proc_jbd2_stats;
static void jbd2_stats_proc_init(journal_t *journal)
{
journal->j_proc_entry = proc_mkdir(journal->j_devname, proc_jbd2_stats);
if (journal->j_proc_entry) {
proc_create_data("info", S_IRUGO, journal->j_proc_entry,
&jbd2_seq_info_fops, journal);
}
}
static void jbd2_stats_proc_exit(journal_t *journal)
{
remove_proc_entry("info", journal->j_proc_entry);
remove_proc_entry(journal->j_devname, proc_jbd2_stats);
}
/*
* Management for journal control blocks: functions to create and
* destroy journal_t structures, and to initialise and read existing
* journal blocks from disk. */
/* First: create and setup a journal_t object in memory. We initialise
* very few fields yet: that has to wait until we have created the
* journal structures from from scratch, or loaded them from disk. */
static journal_t * journal_init_common (void)
{
journal_t *journal;
int err;
journal = kzalloc(sizeof(*journal), GFP_KERNEL);
if (!journal)
return NULL;
init_waitqueue_head(&journal->j_wait_transaction_locked);
init_waitqueue_head(&journal->j_wait_logspace);
init_waitqueue_head(&journal->j_wait_done_commit);
init_waitqueue_head(&journal->j_wait_checkpoint);
init_waitqueue_head(&journal->j_wait_commit);
init_waitqueue_head(&journal->j_wait_updates);
mutex_init(&journal->j_barrier);
mutex_init(&journal->j_checkpoint_mutex);
spin_lock_init(&journal->j_revoke_lock);
spin_lock_init(&journal->j_list_lock);
rwlock_init(&journal->j_state_lock);
journal->j_commit_interval = (HZ * JBD2_DEFAULT_MAX_COMMIT_AGE);
journal->j_min_batch_time = 0;
journal->j_max_batch_time = 15000; /* 15ms */
/* The journal is marked for error until we succeed with recovery! */
journal->j_flags = JBD2_ABORT;
/* Set up a default-sized revoke table for the new mount. */
err = jbd2_journal_init_revoke(journal, JOURNAL_REVOKE_DEFAULT_HASH);
if (err) {
kfree(journal);
return NULL;
}
spin_lock_init(&journal->j_history_lock);
return journal;
}
/* jbd2_journal_init_dev and jbd2_journal_init_inode:
*
* Create a journal structure assigned some fixed set of disk blocks to
* the journal. We don't actually touch those disk blocks yet, but we
* need to set up all of the mapping information to tell the journaling
* system where the journal blocks are.
*
*/
/**
* journal_t * jbd2_journal_init_dev() - creates and initialises a journal structure
* @bdev: Block device on which to create the journal
* @fs_dev: Device which hold journalled filesystem for this journal.
* @start: Block nr Start of journal.
* @len: Length of the journal in blocks.
* @blocksize: blocksize of journalling device
*
* Returns: a newly created journal_t *
*
* jbd2_journal_init_dev creates a journal which maps a fixed contiguous
* range of blocks on an arbitrary block device.
*
*/
journal_t * jbd2_journal_init_dev(struct block_device *bdev,
struct block_device *fs_dev,
unsigned long long start, int len, int blocksize)
{
journal_t *journal = journal_init_common();
struct buffer_head *bh;
char *p;
int n;
if (!journal)
return NULL;
/* journal descriptor can store up to n blocks -bzzz */
journal->j_blocksize = blocksize;
journal->j_dev = bdev;
journal->j_fs_dev = fs_dev;
journal->j_blk_offset = start;
journal->j_maxlen = len;
bdevname(journal->j_dev, journal->j_devname);
p = journal->j_devname;
while ((p = strchr(p, '/')))
*p = '!';
jbd2_stats_proc_init(journal);
n = journal->j_blocksize / sizeof(journal_block_tag_t);
journal->j_wbufsize = n;
journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
if (!journal->j_wbuf) {
printk(KERN_ERR "%s: Can't allocate bhs for commit thread\n",
__func__);
goto out_err;
}
bh = __getblk(journal->j_dev, start, journal->j_blocksize);
if (!bh) {
printk(KERN_ERR
"%s: Cannot get buffer for journal superblock\n",
__func__);
goto out_err;
}
journal->j_sb_buffer = bh;
journal->j_superblock = (journal_superblock_t *)bh->b_data;
return journal;
out_err:
kfree(journal->j_wbuf);
jbd2_stats_proc_exit(journal);
kfree(journal);
return NULL;
}
/**
* journal_t * jbd2_journal_init_inode () - creates a journal which maps to a inode.
* @inode: An inode to create the journal in
*
* jbd2_journal_init_inode creates a journal which maps an on-disk inode as
* the journal. The inode must exist already, must support bmap() and
* must have all data blocks preallocated.
*/
journal_t * jbd2_journal_init_inode (struct inode *inode)
{
struct buffer_head *bh;
journal_t *journal = journal_init_common();
char *p;
int err;
int n;
unsigned long long blocknr;
if (!journal)
return NULL;
journal->j_dev = journal->j_fs_dev = inode->i_sb->s_bdev;
journal->j_inode = inode;
bdevname(journal->j_dev, journal->j_devname);
p = journal->j_devname;
while ((p = strchr(p, '/')))
*p = '!';
p = journal->j_devname + strlen(journal->j_devname);
sprintf(p, "-%lu", journal->j_inode->i_ino);
jbd_debug(1,
"journal %p: inode %s/%ld, size %Ld, bits %d, blksize %ld\n",
journal, inode->i_sb->s_id, inode->i_ino,
(long long) inode->i_size,
inode->i_sb->s_blocksize_bits, inode->i_sb->s_blocksize);
journal->j_maxlen = inode->i_size >> inode->i_sb->s_blocksize_bits;
journal->j_blocksize = inode->i_sb->s_blocksize;
jbd2_stats_proc_init(journal);
/* journal descriptor can store up to n blocks -bzzz */
n = journal->j_blocksize / sizeof(journal_block_tag_t);
journal->j_wbufsize = n;
journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
if (!journal->j_wbuf) {
printk(KERN_ERR "%s: Can't allocate bhs for commit thread\n",
__func__);
goto out_err;
}
err = jbd2_journal_bmap(journal, 0, &blocknr);
/* If that failed, give up */
if (err) {
printk(KERN_ERR "%s: Cannot locate journal superblock\n",
__func__);
goto out_err;
}
bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
if (!bh) {
printk(KERN_ERR
"%s: Cannot get buffer for journal superblock\n",
__func__);
goto out_err;
}
journal->j_sb_buffer = bh;
journal->j_superblock = (journal_superblock_t *)bh->b_data;
return journal;
out_err:
kfree(journal->j_wbuf);
jbd2_stats_proc_exit(journal);
kfree(journal);
return NULL;
}
/*
* If the journal init or create aborts, we need to mark the journal
* superblock as being NULL to prevent the journal destroy from writing
* back a bogus superblock.
*/
static void journal_fail_superblock (journal_t *journal)
{
struct buffer_head *bh = journal->j_sb_buffer;
brelse(bh);
journal->j_sb_buffer = NULL;
}
/*
* Given a journal_t structure, initialise the various fields for
* startup of a new journaling session. We use this both when creating
* a journal, and after recovering an old journal to reset it for
* subsequent use.
*/
static int journal_reset(journal_t *journal)
{
journal_superblock_t *sb = journal->j_superblock;
unsigned long long first, last;
first = be32_to_cpu(sb->s_first);
last = be32_to_cpu(sb->s_maxlen);
if (first + JBD2_MIN_JOURNAL_BLOCKS > last + 1) {
printk(KERN_ERR "JBD2: Journal too short (blocks %llu-%llu).\n",
first, last);
journal_fail_superblock(journal);
return -EINVAL;
}
journal->j_first = first;
journal->j_last = last;
journal->j_head = first;
journal->j_tail = first;
journal->j_free = last - first;
journal->j_tail_sequence = journal->j_transaction_sequence;
journal->j_commit_sequence = journal->j_transaction_sequence - 1;
journal->j_commit_request = journal->j_commit_sequence;
journal->j_max_transaction_buffers = journal->j_maxlen / 4;
/*
* As a special case, if the on-disk copy is already marked as needing
* no recovery (s_start == 0), then we can safely defer the superblock
* update until the next commit by setting JBD2_FLUSHED. This avoids
* attempting a write to a potential-readonly device.
*/
if (sb->s_start == 0) {
jbd_debug(1, "JBD2: Skipping superblock update on recovered sb "
"(start %ld, seq %d, errno %d)\n",
journal->j_tail, journal->j_tail_sequence,
journal->j_errno);
journal->j_flags |= JBD2_FLUSHED;
} else {
/* Lock here to make assertions happy... */
mutex_lock(&journal->j_checkpoint_mutex);
/*
* Update log tail information. We use WRITE_FUA since new
* transaction will start reusing journal space and so we
* must make sure information about current log tail is on
* disk before that.
*/
jbd2_journal_update_sb_log_tail(journal,
journal->j_tail_sequence,
journal->j_tail,
WRITE_FUA);
mutex_unlock(&journal->j_checkpoint_mutex);
}
return jbd2_journal_start_thread(journal);
}
static void jbd2_write_superblock(journal_t *journal, int write_op)
{
struct buffer_head *bh = journal->j_sb_buffer;
journal_superblock_t *sb = journal->j_superblock;
int ret;
trace_jbd2_write_superblock(journal, write_op);
if (!(journal->j_flags & JBD2_BARRIER))
write_op &= ~(REQ_FUA | REQ_FLUSH);
lock_buffer(bh);
if (buffer_write_io_error(bh)) {
/*
* Oh, dear. A previous attempt to write the journal
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
printk(KERN_ERR "JBD2: previous I/O error detected "
"for journal superblock update for %s.\n",
journal->j_devname);
clear_buffer_write_io_error(bh);
set_buffer_uptodate(bh);
}
jbd2_superblock_csum_set(journal, sb);
get_bh(bh);
bh->b_end_io = end_buffer_write_sync;
ret = submit_bh(write_op, bh);
wait_on_buffer(bh);
if (buffer_write_io_error(bh)) {
clear_buffer_write_io_error(bh);
set_buffer_uptodate(bh);
ret = -EIO;
}
if (ret) {
printk(KERN_ERR "JBD2: Error %d detected when updating "
"journal superblock for %s.\n", ret,
journal->j_devname);
}
}
/**
* jbd2_journal_update_sb_log_tail() - Update log tail in journal sb on disk.
* @journal: The journal to update.
* @tail_tid: TID of the new transaction at the tail of the log
* @tail_block: The first block of the transaction at the tail of the log
* @write_op: With which operation should we write the journal sb
*
* Update a journal's superblock information about log tail and write it to
* disk, waiting for the IO to complete.
*/
void jbd2_journal_update_sb_log_tail(journal_t *journal, tid_t tail_tid,
unsigned long tail_block, int write_op)
{
journal_superblock_t *sb = journal->j_superblock;
BUG_ON(!mutex_is_locked(&journal->j_checkpoint_mutex));
jbd_debug(1, "JBD2: updating superblock (start %lu, seq %u)\n",
tail_block, tail_tid);
sb->s_sequence = cpu_to_be32(tail_tid);
sb->s_start = cpu_to_be32(tail_block);
jbd2_write_superblock(journal, write_op);
/* Log is no longer empty */
write_lock(&journal->j_state_lock);
WARN_ON(!sb->s_sequence);
journal->j_flags &= ~JBD2_FLUSHED;
write_unlock(&journal->j_state_lock);
}
/**
* jbd2_mark_journal_empty() - Mark on disk journal as empty.
* @journal: The journal to update.
*
* Update a journal's dynamic superblock fields to show that journal is empty.
* Write updated superblock to disk waiting for IO to complete.
*/
static void jbd2_mark_journal_empty(journal_t *journal)
{
journal_superblock_t *sb = journal->j_superblock;
BUG_ON(!mutex_is_locked(&journal->j_checkpoint_mutex));
read_lock(&journal->j_state_lock);
/* Is it already empty? */
if (sb->s_start == 0) {
read_unlock(&journal->j_state_lock);
return;
}
jbd_debug(1, "JBD2: Marking journal as empty (seq %d)\n",
journal->j_tail_sequence);
sb->s_sequence = cpu_to_be32(journal->j_tail_sequence);
sb->s_start = cpu_to_be32(0);
read_unlock(&journal->j_state_lock);
jbd2_write_superblock(journal, WRITE_FUA);
/* Log is no longer empty */
write_lock(&journal->j_state_lock);
journal->j_flags |= JBD2_FLUSHED;
write_unlock(&journal->j_state_lock);
}
/**
* jbd2_journal_update_sb_errno() - Update error in the journal.
* @journal: The journal to update.
*
* Update a journal's errno. Write updated superblock to disk waiting for IO
* to complete.
*/
void jbd2_journal_update_sb_errno(journal_t *journal)
{
journal_superblock_t *sb = journal->j_superblock;
read_lock(&journal->j_state_lock);
jbd_debug(1, "JBD2: updating superblock error (errno %d)\n",
journal->j_errno);
sb->s_errno = cpu_to_be32(journal->j_errno);
read_unlock(&journal->j_state_lock);
jbd2_write_superblock(journal, WRITE_SYNC);
}
EXPORT_SYMBOL(jbd2_journal_update_sb_errno);
/*
* Read the superblock for a given journal, performing initial
* validation of the format.
*/
static int journal_get_superblock(journal_t *journal)
{
struct buffer_head *bh;
journal_superblock_t *sb;
int err = -EIO;
bh = journal->j_sb_buffer;
J_ASSERT(bh != NULL);
if (!buffer_uptodate(bh)) {
ll_rw_block(READ, 1, &bh);
wait_on_buffer(bh);
if (!buffer_uptodate(bh)) {
printk(KERN_ERR
"JBD2: IO error reading journal superblock\n");
goto out;
}
}
if (buffer_verified(bh))
return 0;
sb = journal->j_superblock;
err = -EINVAL;
if (sb->s_header.h_magic != cpu_to_be32(JBD2_MAGIC_NUMBER) ||
sb->s_blocksize != cpu_to_be32(journal->j_blocksize)) {
printk(KERN_WARNING "JBD2: no valid journal superblock found\n");
goto out;
}
switch(be32_to_cpu(sb->s_header.h_blocktype)) {
case JBD2_SUPERBLOCK_V1:
journal->j_format_version = 1;
break;
case JBD2_SUPERBLOCK_V2:
journal->j_format_version = 2;
break;
default:
printk(KERN_WARNING "JBD2: unrecognised superblock format ID\n");
goto out;
}
if (be32_to_cpu(sb->s_maxlen) < journal->j_maxlen)
journal->j_maxlen = be32_to_cpu(sb->s_maxlen);
else if (be32_to_cpu(sb->s_maxlen) > journal->j_maxlen) {
printk(KERN_WARNING "JBD2: journal file too short\n");
goto out;
}
if (be32_to_cpu(sb->s_first) == 0 ||
be32_to_cpu(sb->s_first) >= journal->j_maxlen) {
printk(KERN_WARNING
"JBD2: Invalid start block of journal: %u\n",
be32_to_cpu(sb->s_first));
goto out;
}
if (JBD2_HAS_COMPAT_FEATURE(journal, JBD2_FEATURE_COMPAT_CHECKSUM) &&
JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_CSUM_V2)) {
/* Can't have checksum v1 and v2 on at the same time! */
printk(KERN_ERR "JBD: Can't enable checksumming v1 and v2 "
"at the same time!\n");
goto out;
}
if (!jbd2_verify_csum_type(journal, sb)) {
printk(KERN_ERR "JBD: Unknown checksum type\n");
goto out;
}
/* Load the checksum driver */
if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_CSUM_V2)) {
journal->j_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(journal->j_chksum_driver)) {
printk(KERN_ERR "JBD: Cannot load crc32c driver.\n");
err = PTR_ERR(journal->j_chksum_driver);
journal->j_chksum_driver = NULL;
goto out;
}
}
/* Check superblock checksum */
if (!jbd2_superblock_csum_verify(journal, sb)) {
printk(KERN_ERR "JBD: journal checksum error\n");
goto out;
}
/* Precompute checksum seed for all metadata */
if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_CSUM_V2))
journal->j_csum_seed = jbd2_chksum(journal, ~0, sb->s_uuid,
sizeof(sb->s_uuid));
set_buffer_verified(bh);
return 0;
out:
journal_fail_superblock(journal);
return err;
}
/*
* Load the on-disk journal superblock and read the key fields into the
* journal_t.
*/
static int load_superblock(journal_t *journal)
{
int err;
journal_superblock_t *sb;
err = journal_get_superblock(journal);
if (err)
return err;
sb = journal->j_superblock;
journal->j_tail_sequence = be32_to_cpu(sb->s_sequence);
journal->j_tail = be32_to_cpu(sb->s_start);
journal->j_first = be32_to_cpu(sb->s_first);
journal->j_last = be32_to_cpu(sb->s_maxlen);
journal->j_errno = be32_to_cpu(sb->s_errno);
return 0;
}
/**
* int jbd2_journal_load() - Read journal from disk.
* @journal: Journal to act on.
*
* Given a journal_t structure which tells us which disk blocks contain
* a journal, read the journal from disk to initialise the in-memory
* structures.
*/
int jbd2_journal_load(journal_t *journal)
{
int err;
journal_superblock_t *sb;
err = load_superblock(journal);
if (err)
return err;
sb = journal->j_superblock;
/* If this is a V2 superblock, then we have to check the
* features flags on it. */
if (journal->j_format_version >= 2) {
if ((sb->s_feature_ro_compat &
~cpu_to_be32(JBD2_KNOWN_ROCOMPAT_FEATURES)) ||
(sb->s_feature_incompat &
~cpu_to_be32(JBD2_KNOWN_INCOMPAT_FEATURES))) {
printk(KERN_WARNING
"JBD2: Unrecognised features on journal\n");
return -EINVAL;
}
}
/*
* Create a slab for this blocksize
*/
err = jbd2_journal_create_slab(be32_to_cpu(sb->s_blocksize));
if (err)
return err;
/* Let the recovery code check whether it needs to recover any
* data from the journal. */
if (jbd2_journal_recover(journal))
goto recovery_error;
if (journal->j_failed_commit) {
printk(KERN_ERR "JBD2: journal transaction %u on %s "
"is corrupt.\n", journal->j_failed_commit,
journal->j_devname);
return -EIO;
}
/* OK, we've finished with the dynamic journal bits:
* reinitialise the dynamic contents of the superblock in memory
* and reset them on disk. */
if (journal_reset(journal))
goto recovery_error;
journal->j_flags &= ~JBD2_ABORT;
journal->j_flags |= JBD2_LOADED;
return 0;
recovery_error:
printk(KERN_WARNING "JBD2: recovery failed\n");
return -EIO;
}
/**
* void jbd2_journal_destroy() - Release a journal_t structure.
* @journal: Journal to act on.
*
* Release a journal_t structure once it is no longer in use by the
* journaled object.
* Return <0 if we couldn't clean up the journal.
*/
int jbd2_journal_destroy(journal_t *journal)
{
int err = 0;
/* Wait for the commit thread to wake up and die. */
journal_kill_thread(journal);
/* Force a final log commit */
if (journal->j_running_transaction)
jbd2_journal_commit_transaction(journal);
/* Force any old transactions to disk */
/* Totally anal locking here... */
spin_lock(&journal->j_list_lock);
while (journal->j_checkpoint_transactions != NULL) {
spin_unlock(&journal->j_list_lock);
mutex_lock(&journal->j_checkpoint_mutex);
jbd2_log_do_checkpoint(journal);
mutex_unlock(&journal->j_checkpoint_mutex);
spin_lock(&journal->j_list_lock);
}
J_ASSERT(journal->j_running_transaction == NULL);
J_ASSERT(journal->j_committing_transaction == NULL);
J_ASSERT(journal->j_checkpoint_transactions == NULL);
spin_unlock(&journal->j_list_lock);
if (journal->j_sb_buffer) {
if (!is_journal_aborted(journal)) {
mutex_lock(&journal->j_checkpoint_mutex);
jbd2_mark_journal_empty(journal);
mutex_unlock(&journal->j_checkpoint_mutex);
} else
err = -EIO;
brelse(journal->j_sb_buffer);
}
if (journal->j_proc_entry)
jbd2_stats_proc_exit(journal);
if (journal->j_inode)
iput(journal->j_inode);
if (journal->j_revoke)
jbd2_journal_destroy_revoke(journal);
if (journal->j_chksum_driver)
crypto_free_shash(journal->j_chksum_driver);
kfree(journal->j_wbuf);
kfree(journal);
return err;
}
/**
*int jbd2_journal_check_used_features () - Check if features specified are used.
* @journal: Journal to check.
* @compat: bitmask of compatible features
* @ro: bitmask of features that force read-only mount
* @incompat: bitmask of incompatible features
*
* Check whether the journal uses all of a given set of
* features. Return true (non-zero) if it does.
**/
int jbd2_journal_check_used_features (journal_t *journal, unsigned long compat,
unsigned long ro, unsigned long incompat)
{
journal_superblock_t *sb;
if (!compat && !ro && !incompat)
return 1;
/* Load journal superblock if it is not loaded yet. */
if (journal->j_format_version == 0 &&
journal_get_superblock(journal) != 0)
return 0;
if (journal->j_format_version == 1)
return 0;
sb = journal->j_superblock;
if (((be32_to_cpu(sb->s_feature_compat) & compat) == compat) &&
((be32_to_cpu(sb->s_feature_ro_compat) & ro) == ro) &&
((be32_to_cpu(sb->s_feature_incompat) & incompat) == incompat))
return 1;
return 0;
}
/**
* int jbd2_journal_check_available_features() - Check feature set in journalling layer
* @journal: Journal to check.
* @compat: bitmask of compatible features
* @ro: bitmask of features that force read-only mount
* @incompat: bitmask of incompatible features
*
* Check whether the journaling code supports the use of
* all of a given set of features on this journal. Return true
* (non-zero) if it can. */
int jbd2_journal_check_available_features (journal_t *journal, unsigned long compat,
unsigned long ro, unsigned long incompat)
{
if (!compat && !ro && !incompat)
return 1;
/* We can support any known requested features iff the
* superblock is in version 2. Otherwise we fail to support any
* extended sb features. */
if (journal->j_format_version != 2)
return 0;
if ((compat & JBD2_KNOWN_COMPAT_FEATURES) == compat &&
(ro & JBD2_KNOWN_ROCOMPAT_FEATURES) == ro &&
(incompat & JBD2_KNOWN_INCOMPAT_FEATURES) == incompat)
return 1;
return 0;
}
/**
* int jbd2_journal_set_features () - Mark a given journal feature in the superblock
* @journal: Journal to act on.
* @compat: bitmask of compatible features
* @ro: bitmask of features that force read-only mount
* @incompat: bitmask of incompatible features
*
* Mark a given journal feature as present on the
* superblock. Returns true if the requested features could be set.
*
*/
int jbd2_journal_set_features (journal_t *journal, unsigned long compat,
unsigned long ro, unsigned long incompat)
{
#define INCOMPAT_FEATURE_ON(f) \
((incompat & (f)) && !(sb->s_feature_incompat & cpu_to_be32(f)))
#define COMPAT_FEATURE_ON(f) \
((compat & (f)) && !(sb->s_feature_compat & cpu_to_be32(f)))
journal_superblock_t *sb;
if (jbd2_journal_check_used_features(journal, compat, ro, incompat))
return 1;
if (!jbd2_journal_check_available_features(journal, compat, ro, incompat))
return 0;
/* Asking for checksumming v2 and v1? Only give them v2. */
if (incompat & JBD2_FEATURE_INCOMPAT_CSUM_V2 &&
compat & JBD2_FEATURE_COMPAT_CHECKSUM)
compat &= ~JBD2_FEATURE_COMPAT_CHECKSUM;
jbd_debug(1, "Setting new features 0x%lx/0x%lx/0x%lx\n",
compat, ro, incompat);
sb = journal->j_superblock;
/* If enabling v2 checksums, update superblock */
if (INCOMPAT_FEATURE_ON(JBD2_FEATURE_INCOMPAT_CSUM_V2)) {
sb->s_checksum_type = JBD2_CRC32C_CHKSUM;
sb->s_feature_compat &=
~cpu_to_be32(JBD2_FEATURE_COMPAT_CHECKSUM);
/* Load the checksum driver */
if (journal->j_chksum_driver == NULL) {
journal->j_chksum_driver = crypto_alloc_shash("crc32c",
0, 0);
if (IS_ERR(journal->j_chksum_driver)) {
printk(KERN_ERR "JBD: Cannot load crc32c "
"driver.\n");
journal->j_chksum_driver = NULL;
return 0;
}
}
/* Precompute checksum seed for all metadata */
if (JBD2_HAS_INCOMPAT_FEATURE(journal,
JBD2_FEATURE_INCOMPAT_CSUM_V2))
journal->j_csum_seed = jbd2_chksum(journal, ~0,
sb->s_uuid,
sizeof(sb->s_uuid));
}
/* If enabling v1 checksums, downgrade superblock */
if (COMPAT_FEATURE_ON(JBD2_FEATURE_COMPAT_CHECKSUM))
sb->s_feature_incompat &=
~cpu_to_be32(JBD2_FEATURE_INCOMPAT_CSUM_V2);
sb->s_feature_compat |= cpu_to_be32(compat);
sb->s_feature_ro_compat |= cpu_to_be32(ro);
sb->s_feature_incompat |= cpu_to_be32(incompat);
return 1;
#undef COMPAT_FEATURE_ON
#undef INCOMPAT_FEATURE_ON
}
/*
* jbd2_journal_clear_features () - Clear a given journal feature in the
* superblock
* @journal: Journal to act on.
* @compat: bitmask of compatible features
* @ro: bitmask of features that force read-only mount
* @incompat: bitmask of incompatible features
*
* Clear a given journal feature as present on the
* superblock.
*/
void jbd2_journal_clear_features(journal_t *journal, unsigned long compat,
unsigned long ro, unsigned long incompat)
{
journal_superblock_t *sb;
jbd_debug(1, "Clear features 0x%lx/0x%lx/0x%lx\n",
compat, ro, incompat);
sb = journal->j_superblock;
sb->s_feature_compat &= ~cpu_to_be32(compat);
sb->s_feature_ro_compat &= ~cpu_to_be32(ro);
sb->s_feature_incompat &= ~cpu_to_be32(incompat);
}
EXPORT_SYMBOL(jbd2_journal_clear_features);
/**
* int jbd2_journal_flush () - Flush journal
* @journal: Journal to act on.
*
* Flush all data for a given journal to disk and empty the journal.
* Filesystems can use this when remounting readonly to ensure that
* recovery does not need to happen on remount.
*/
int jbd2_journal_flush(journal_t *journal)
{
int err = 0;
transaction_t *transaction = NULL;
write_lock(&journal->j_state_lock);
/* Force everything buffered to the log... */
if (journal->j_running_transaction) {
transaction = journal->j_running_transaction;
__jbd2_log_start_commit(journal, transaction->t_tid);
} else if (journal->j_committing_transaction)
transaction = journal->j_committing_transaction;
/* Wait for the log commit to complete... */
if (transaction) {
tid_t tid = transaction->t_tid;
write_unlock(&journal->j_state_lock);
jbd2_log_wait_commit(journal, tid);
} else {
write_unlock(&journal->j_state_lock);
}
/* ...and flush everything in the log out to disk. */
spin_lock(&journal->j_list_lock);
while (!err && journal->j_checkpoint_transactions != NULL) {
spin_unlock(&journal->j_list_lock);
mutex_lock(&journal->j_checkpoint_mutex);
err = jbd2_log_do_checkpoint(journal);
mutex_unlock(&journal->j_checkpoint_mutex);
spin_lock(&journal->j_list_lock);
}
spin_unlock(&journal->j_list_lock);
if (is_journal_aborted(journal))
return -EIO;
mutex_lock(&journal->j_checkpoint_mutex);
jbd2_cleanup_journal_tail(journal);
/* Finally, mark the journal as really needing no recovery.
* This sets s_start==0 in the underlying superblock, which is
* the magic code for a fully-recovered superblock. Any future
* commits of data to the journal will restore the current
* s_start value. */
jbd2_mark_journal_empty(journal);
mutex_unlock(&journal->j_checkpoint_mutex);
write_lock(&journal->j_state_lock);
J_ASSERT(!journal->j_running_transaction);
J_ASSERT(!journal->j_committing_transaction);
J_ASSERT(!journal->j_checkpoint_transactions);
J_ASSERT(journal->j_head == journal->j_tail);
J_ASSERT(journal->j_tail_sequence == journal->j_transaction_sequence);
write_unlock(&journal->j_state_lock);
return 0;
}
/**
* int jbd2_journal_wipe() - Wipe journal contents
* @journal: Journal to act on.
* @write: flag (see below)
*
* Wipe out all of the contents of a journal, safely. This will produce
* a warning if the journal contains any valid recovery information.
* Must be called between journal_init_*() and jbd2_journal_load().
*
* If 'write' is non-zero, then we wipe out the journal on disk; otherwise
* we merely suppress recovery.
*/
int jbd2_journal_wipe(journal_t *journal, int write)
{
int err = 0;
J_ASSERT (!(journal->j_flags & JBD2_LOADED));
err = load_superblock(journal);
if (err)
return err;
if (!journal->j_tail)
goto no_recovery;
printk(KERN_WARNING "JBD2: %s recovery information on journal\n",
write ? "Clearing" : "Ignoring");
err = jbd2_journal_skip_recovery(journal);
if (write) {
/* Lock to make assertions happy... */
mutex_lock(&journal->j_checkpoint_mutex);
jbd2_mark_journal_empty(journal);
mutex_unlock(&journal->j_checkpoint_mutex);
}
no_recovery:
return err;
}
/*
* Journal abort has very specific semantics, which we describe
* for journal abort.
*
* Two internal functions, which provide abort to the jbd layer
* itself are here.
*/
/*
* Quick version for internal journal use (doesn't lock the journal).
* Aborts hard --- we mark the abort as occurred, but do _nothing_ else,
* and don't attempt to make any other journal updates.
*/
void __jbd2_journal_abort_hard(journal_t *journal)
{
transaction_t *transaction;
if (journal->j_flags & JBD2_ABORT)
return;
printk(KERN_ERR "Aborting journal on device %s.\n",
journal->j_devname);
write_lock(&journal->j_state_lock);
journal->j_flags |= JBD2_ABORT;
transaction = journal->j_running_transaction;
if (transaction)
__jbd2_log_start_commit(journal, transaction->t_tid);
write_unlock(&journal->j_state_lock);
}
/* Soft abort: record the abort error status in the journal superblock,
* but don't do any other IO. */
static void __journal_abort_soft (journal_t *journal, int errno)
{
if (journal->j_flags & JBD2_ABORT)
return;
if (!journal->j_errno)
journal->j_errno = errno;
__jbd2_journal_abort_hard(journal);
if (errno)
jbd2_journal_update_sb_errno(journal);
}
/**
* void jbd2_journal_abort () - Shutdown the journal immediately.
* @journal: the journal to shutdown.
* @errno: an error number to record in the journal indicating
* the reason for the shutdown.
*
* Perform a complete, immediate shutdown of the ENTIRE
* journal (not of a single transaction). This operation cannot be
* undone without closing and reopening the journal.
*
* The jbd2_journal_abort function is intended to support higher level error
* recovery mechanisms such as the ext2/ext3 remount-readonly error
* mode.
*
* Journal abort has very specific semantics. Any existing dirty,
* unjournaled buffers in the main filesystem will still be written to
* disk by bdflush, but the journaling mechanism will be suspended
* immediately and no further transaction commits will be honoured.
*
* Any dirty, journaled buffers will be written back to disk without
* hitting the journal. Atomicity cannot be guaranteed on an aborted
* filesystem, but we _do_ attempt to leave as much data as possible
* behind for fsck to use for cleanup.
*
* Any attempt to get a new transaction handle on a journal which is in
* ABORT state will just result in an -EROFS error return. A
* jbd2_journal_stop on an existing handle will return -EIO if we have
* entered abort state during the update.
*
* Recursive transactions are not disturbed by journal abort until the
* final jbd2_journal_stop, which will receive the -EIO error.
*
* Finally, the jbd2_journal_abort call allows the caller to supply an errno
* which will be recorded (if possible) in the journal superblock. This
* allows a client to record failure conditions in the middle of a
* transaction without having to complete the transaction to record the
* failure to disk. ext3_error, for example, now uses this
* functionality.
*
* Errors which originate from within the journaling layer will NOT
* supply an errno; a null errno implies that absolutely no further
* writes are done to the journal (unless there are any already in
* progress).
*
*/
void jbd2_journal_abort(journal_t *journal, int errno)
{
__journal_abort_soft(journal, errno);
}
/**
* int jbd2_journal_errno () - returns the journal's error state.
* @journal: journal to examine.
*
* This is the errno number set with jbd2_journal_abort(), the last
* time the journal was mounted - if the journal was stopped
* without calling abort this will be 0.
*
* If the journal has been aborted on this mount time -EROFS will
* be returned.
*/
int jbd2_journal_errno(journal_t *journal)
{
int err;
read_lock(&journal->j_state_lock);
if (journal->j_flags & JBD2_ABORT)
err = -EROFS;
else
err = journal->j_errno;
read_unlock(&journal->j_state_lock);
return err;
}
/**
* int jbd2_journal_clear_err () - clears the journal's error state
* @journal: journal to act on.
*
* An error must be cleared or acked to take a FS out of readonly
* mode.
*/
int jbd2_journal_clear_err(journal_t *journal)
{
int err = 0;
write_lock(&journal->j_state_lock);
if (journal->j_flags & JBD2_ABORT)
err = -EROFS;
else
journal->j_errno = 0;
write_unlock(&journal->j_state_lock);
return err;
}
/**
* void jbd2_journal_ack_err() - Ack journal err.
* @journal: journal to act on.
*
* An error must be cleared or acked to take a FS out of readonly
* mode.
*/
void jbd2_journal_ack_err(journal_t *journal)
{
write_lock(&journal->j_state_lock);
if (journal->j_errno)
journal->j_flags |= JBD2_ACK_ERR;
write_unlock(&journal->j_state_lock);
}
int jbd2_journal_blocks_per_page(struct inode *inode)
{
return 1 << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
}
/*
* helper functions to deal with 32 or 64bit block numbers.
*/
size_t journal_tag_bytes(journal_t *journal)
{
journal_block_tag_t tag;
size_t x = 0;
if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_CSUM_V2))
x += sizeof(tag.t_checksum);
if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_64BIT))
return x + JBD2_TAG_SIZE64;
else
return x + JBD2_TAG_SIZE32;
}
/*
* JBD memory management
*
* These functions are used to allocate block-sized chunks of memory
* used for making copies of buffer_head data. Very often it will be
* page-sized chunks of data, but sometimes it will be in
* sub-page-size chunks. (For example, 16k pages on Power systems
* with a 4k block file system.) For blocks smaller than a page, we
* use a SLAB allocator. There are slab caches for each block size,
* which are allocated at mount time, if necessary, and we only free
* (all of) the slab caches when/if the jbd2 module is unloaded. For
* this reason we don't need to a mutex to protect access to
* jbd2_slab[] allocating or releasing memory; only in
* jbd2_journal_create_slab().
*/
#define JBD2_MAX_SLABS 8
static struct kmem_cache *jbd2_slab[JBD2_MAX_SLABS];
static const char *jbd2_slab_names[JBD2_MAX_SLABS] = {
"jbd2_1k", "jbd2_2k", "jbd2_4k", "jbd2_8k",
"jbd2_16k", "jbd2_32k", "jbd2_64k", "jbd2_128k"
};
static void jbd2_journal_destroy_slabs(void)
{
int i;
for (i = 0; i < JBD2_MAX_SLABS; i++) {
if (jbd2_slab[i])
kmem_cache_destroy(jbd2_slab[i]);
jbd2_slab[i] = NULL;
}
}
static int jbd2_journal_create_slab(size_t size)
{
static DEFINE_MUTEX(jbd2_slab_create_mutex);
int i = order_base_2(size) - 10;
size_t slab_size;
if (size == PAGE_SIZE)
return 0;
if (i >= JBD2_MAX_SLABS)
return -EINVAL;
if (unlikely(i < 0))
i = 0;
mutex_lock(&jbd2_slab_create_mutex);
if (jbd2_slab[i]) {
mutex_unlock(&jbd2_slab_create_mutex);
return 0; /* Already created */
}
slab_size = 1 << (i+10);
jbd2_slab[i] = kmem_cache_create(jbd2_slab_names[i], slab_size,
slab_size, 0, NULL);
mutex_unlock(&jbd2_slab_create_mutex);
if (!jbd2_slab[i]) {
printk(KERN_EMERG "JBD2: no memory for jbd2_slab cache\n");
return -ENOMEM;
}
return 0;
}
static struct kmem_cache *get_slab(size_t size)
{
int i = order_base_2(size) - 10;
BUG_ON(i >= JBD2_MAX_SLABS);
if (unlikely(i < 0))
i = 0;
BUG_ON(jbd2_slab[i] == NULL);
return jbd2_slab[i];
}
void *jbd2_alloc(size_t size, gfp_t flags)
{
void *ptr;
BUG_ON(size & (size-1)); /* Must be a power of 2 */
flags |= __GFP_REPEAT;
if (size == PAGE_SIZE)
ptr = (void *)__get_free_pages(flags, 0);
else if (size > PAGE_SIZE) {
int order = get_order(size);
if (order < 3)
ptr = (void *)__get_free_pages(flags, order);
else
ptr = vmalloc(size);
} else
ptr = kmem_cache_alloc(get_slab(size), flags);
/* Check alignment; SLUB has gotten this wrong in the past,
* and this can lead to user data corruption! */
BUG_ON(((unsigned long) ptr) & (size-1));
return ptr;
}
void jbd2_free(void *ptr, size_t size)
{
if (size == PAGE_SIZE) {
free_pages((unsigned long)ptr, 0);
return;
}
if (size > PAGE_SIZE) {
int order = get_order(size);
if (order < 3)
free_pages((unsigned long)ptr, order);
else
vfree(ptr);
return;
}
kmem_cache_free(get_slab(size), ptr);
};
/*
* Journal_head storage management
*/
static struct kmem_cache *jbd2_journal_head_cache;
#ifdef CONFIG_JBD2_DEBUG
static atomic_t nr_journal_heads = ATOMIC_INIT(0);
#endif
static int jbd2_journal_init_journal_head_cache(void)
{
int retval;
J_ASSERT(jbd2_journal_head_cache == NULL);
jbd2_journal_head_cache = kmem_cache_create("jbd2_journal_head",
sizeof(struct journal_head),
0, /* offset */
SLAB_TEMPORARY, /* flags */
NULL); /* ctor */
retval = 0;
if (!jbd2_journal_head_cache) {
retval = -ENOMEM;
printk(KERN_EMERG "JBD2: no memory for journal_head cache\n");
}
return retval;
}
static void jbd2_journal_destroy_journal_head_cache(void)
{
if (jbd2_journal_head_cache) {
kmem_cache_destroy(jbd2_journal_head_cache);
jbd2_journal_head_cache = NULL;
}
}
/*
* journal_head splicing and dicing
*/
static struct journal_head *journal_alloc_journal_head(void)
{
struct journal_head *ret;
#ifdef CONFIG_JBD2_DEBUG
atomic_inc(&nr_journal_heads);
#endif
ret = kmem_cache_alloc(jbd2_journal_head_cache, GFP_NOFS);
if (!ret) {
jbd_debug(1, "out of memory for journal_head\n");
pr_notice_ratelimited("ENOMEM in %s, retrying.\n", __func__);
while (!ret) {
yield();
ret = kmem_cache_alloc(jbd2_journal_head_cache, GFP_NOFS);
}
}
return ret;
}
static void journal_free_journal_head(struct journal_head *jh)
{
#ifdef CONFIG_JBD2_DEBUG
atomic_dec(&nr_journal_heads);
memset(jh, JBD2_POISON_FREE, sizeof(*jh));
#endif
kmem_cache_free(jbd2_journal_head_cache, jh);
}
/*
* A journal_head is attached to a buffer_head whenever JBD has an
* interest in the buffer.
*
* Whenever a buffer has an attached journal_head, its ->b_state:BH_JBD bit
* is set. This bit is tested in core kernel code where we need to take
* JBD-specific actions. Testing the zeroness of ->b_private is not reliable
* there.
*
* When a buffer has its BH_JBD bit set, its ->b_count is elevated by one.
*
* When a buffer has its BH_JBD bit set it is immune from being released by
* core kernel code, mainly via ->b_count.
*
* A journal_head is detached from its buffer_head when the journal_head's
* b_jcount reaches zero. Running transaction (b_transaction) and checkpoint
* transaction (b_cp_transaction) hold their references to b_jcount.
*
* Various places in the kernel want to attach a journal_head to a buffer_head
* _before_ attaching the journal_head to a transaction. To protect the
* journal_head in this situation, jbd2_journal_add_journal_head elevates the
* journal_head's b_jcount refcount by one. The caller must call
* jbd2_journal_put_journal_head() to undo this.
*
* So the typical usage would be:
*
* (Attach a journal_head if needed. Increments b_jcount)
* struct journal_head *jh = jbd2_journal_add_journal_head(bh);
* ...
* (Get another reference for transaction)
* jbd2_journal_grab_journal_head(bh);
* jh->b_transaction = xxx;
* (Put original reference)
* jbd2_journal_put_journal_head(jh);
*/
/*
* Give a buffer_head a journal_head.
*
* May sleep.
*/
struct journal_head *jbd2_journal_add_journal_head(struct buffer_head *bh)
{
struct journal_head *jh;
struct journal_head *new_jh = NULL;
repeat:
if (!buffer_jbd(bh)) {
new_jh = journal_alloc_journal_head();
memset(new_jh, 0, sizeof(*new_jh));
}
jbd_lock_bh_journal_head(bh);
if (buffer_jbd(bh)) {
jh = bh2jh(bh);
} else {
J_ASSERT_BH(bh,
(atomic_read(&bh->b_count) > 0) ||
(bh->b_page && bh->b_page->mapping));
if (!new_jh) {
jbd_unlock_bh_journal_head(bh);
goto repeat;
}
jh = new_jh;
new_jh = NULL; /* We consumed it */
set_buffer_jbd(bh);
bh->b_private = jh;
jh->b_bh = bh;
get_bh(bh);
BUFFER_TRACE(bh, "added journal_head");
}
jh->b_jcount++;
jbd_unlock_bh_journal_head(bh);
if (new_jh)
journal_free_journal_head(new_jh);
return bh->b_private;
}
/*
* Grab a ref against this buffer_head's journal_head. If it ended up not
* having a journal_head, return NULL
*/
struct journal_head *jbd2_journal_grab_journal_head(struct buffer_head *bh)
{
struct journal_head *jh = NULL;
jbd_lock_bh_journal_head(bh);
if (buffer_jbd(bh)) {
jh = bh2jh(bh);
jh->b_jcount++;
}
jbd_unlock_bh_journal_head(bh);
return jh;
}
static void __journal_remove_journal_head(struct buffer_head *bh)
{
struct journal_head *jh = bh2jh(bh);
J_ASSERT_JH(jh, jh->b_jcount >= 0);
J_ASSERT_JH(jh, jh->b_transaction == NULL);
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
J_ASSERT_JH(jh, jh->b_cp_transaction == NULL);
J_ASSERT_JH(jh, jh->b_jlist == BJ_None);
J_ASSERT_BH(bh, buffer_jbd(bh));
J_ASSERT_BH(bh, jh2bh(jh) == bh);
BUFFER_TRACE(bh, "remove journal_head");
if (jh->b_frozen_data) {
printk(KERN_WARNING "%s: freeing b_frozen_data\n", __func__);
jbd2_free(jh->b_frozen_data, bh->b_size);
}
if (jh->b_committed_data) {
printk(KERN_WARNING "%s: freeing b_committed_data\n", __func__);
jbd2_free(jh->b_committed_data, bh->b_size);
}
bh->b_private = NULL;
jh->b_bh = NULL; /* debug, really */
clear_buffer_jbd(bh);
journal_free_journal_head(jh);
}
/*
* Drop a reference on the passed journal_head. If it fell to zero then
* release the journal_head from the buffer_head.
*/
void jbd2_journal_put_journal_head(struct journal_head *jh)
{
struct buffer_head *bh = jh2bh(jh);
jbd_lock_bh_journal_head(bh);
J_ASSERT_JH(jh, jh->b_jcount > 0);
--jh->b_jcount;
if (!jh->b_jcount) {
__journal_remove_journal_head(bh);
jbd_unlock_bh_journal_head(bh);
__brelse(bh);
} else
jbd_unlock_bh_journal_head(bh);
}
/*
* Initialize jbd inode head
*/
void jbd2_journal_init_jbd_inode(struct jbd2_inode *jinode, struct inode *inode)
{
jinode->i_transaction = NULL;
jinode->i_next_transaction = NULL;
jinode->i_vfs_inode = inode;
jinode->i_flags = 0;
INIT_LIST_HEAD(&jinode->i_list);
}
/*
* Function to be called before we start removing inode from memory (i.e.,
* clear_inode() is a fine place to be called from). It removes inode from
* transaction's lists.
*/
void jbd2_journal_release_jbd_inode(journal_t *journal,
struct jbd2_inode *jinode)
{
if (!journal)
return;
restart:
spin_lock(&journal->j_list_lock);
/* Is commit writing out inode - we have to wait */
if (test_bit(__JI_COMMIT_RUNNING, &jinode->i_flags)) {
wait_queue_head_t *wq;
DEFINE_WAIT_BIT(wait, &jinode->i_flags, __JI_COMMIT_RUNNING);
wq = bit_waitqueue(&jinode->i_flags, __JI_COMMIT_RUNNING);
prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
spin_unlock(&journal->j_list_lock);
schedule();
finish_wait(wq, &wait.wait);
goto restart;
}
if (jinode->i_transaction) {
list_del(&jinode->i_list);
jinode->i_transaction = NULL;
}
spin_unlock(&journal->j_list_lock);
}
#ifdef CONFIG_PROC_FS
#define JBD2_STATS_PROC_NAME "fs/jbd2"
static void __init jbd2_create_jbd_stats_proc_entry(void)
{
proc_jbd2_stats = proc_mkdir(JBD2_STATS_PROC_NAME, NULL);
}
static void __exit jbd2_remove_jbd_stats_proc_entry(void)
{
if (proc_jbd2_stats)
remove_proc_entry(JBD2_STATS_PROC_NAME, NULL);
}
#else
#define jbd2_create_jbd_stats_proc_entry() do {} while (0)
#define jbd2_remove_jbd_stats_proc_entry() do {} while (0)
#endif
struct kmem_cache *jbd2_handle_cache, *jbd2_inode_cache;
static int __init jbd2_journal_init_handle_cache(void)
{
jbd2_handle_cache = KMEM_CACHE(jbd2_journal_handle, SLAB_TEMPORARY);
if (jbd2_handle_cache == NULL) {
printk(KERN_EMERG "JBD2: failed to create handle cache\n");
return -ENOMEM;
}
jbd2_inode_cache = KMEM_CACHE(jbd2_inode, 0);
if (jbd2_inode_cache == NULL) {
printk(KERN_EMERG "JBD2: failed to create inode cache\n");
kmem_cache_destroy(jbd2_handle_cache);
return -ENOMEM;
}
return 0;
}
static void jbd2_journal_destroy_handle_cache(void)
{
if (jbd2_handle_cache)
kmem_cache_destroy(jbd2_handle_cache);
if (jbd2_inode_cache)
kmem_cache_destroy(jbd2_inode_cache);
}
/*
* Module startup and shutdown
*/
static int __init journal_init_caches(void)
{
int ret;
ret = jbd2_journal_init_revoke_caches();
if (ret == 0)
ret = jbd2_journal_init_journal_head_cache();
if (ret == 0)
ret = jbd2_journal_init_handle_cache();
if (ret == 0)
ret = jbd2_journal_init_transaction_cache();
return ret;
}
static void jbd2_journal_destroy_caches(void)
{
jbd2_journal_destroy_revoke_caches();
jbd2_journal_destroy_journal_head_cache();
jbd2_journal_destroy_handle_cache();
jbd2_journal_destroy_transaction_cache();
jbd2_journal_destroy_slabs();
}
static int __init journal_init(void)
{
int ret;
BUILD_BUG_ON(sizeof(struct journal_superblock_s) != 1024);
ret = journal_init_caches();
if (ret == 0) {
jbd2_create_jbd_stats_proc_entry();
} else {
jbd2_journal_destroy_caches();
}
return ret;
}
static void __exit journal_exit(void)
{
#ifdef CONFIG_JBD2_DEBUG
int n = atomic_read(&nr_journal_heads);
if (n)
printk(KERN_EMERG "JBD2: leaked %d journal_heads!\n", n);
#endif
jbd2_remove_jbd_stats_proc_entry();
jbd2_journal_destroy_caches();
}
MODULE_LICENSE("GPL");
module_init(journal_init);
module_exit(journal_exit);
| gpl-2.0 |
spiderworthy/linux | drivers/md/dm-era-target.c | 1055 | 39484 | #include "dm.h"
#include "persistent-data/dm-transaction-manager.h"
#include "persistent-data/dm-bitset.h"
#include "persistent-data/dm-space-map.h"
#include <linux/dm-io.h>
#include <linux/dm-kcopyd.h>
#include <linux/init.h>
#include <linux/mempool.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#define DM_MSG_PREFIX "era"
#define SUPERBLOCK_LOCATION 0
#define SUPERBLOCK_MAGIC 2126579579
#define SUPERBLOCK_CSUM_XOR 146538381
#define MIN_ERA_VERSION 1
#define MAX_ERA_VERSION 1
#define INVALID_WRITESET_ROOT SUPERBLOCK_LOCATION
#define MIN_BLOCK_SIZE 8
/*----------------------------------------------------------------
* Writeset
*--------------------------------------------------------------*/
struct writeset_metadata {
uint32_t nr_bits;
dm_block_t root;
};
struct writeset {
struct writeset_metadata md;
/*
* An in core copy of the bits to save constantly doing look ups on
* disk.
*/
unsigned long *bits;
};
/*
* This does not free off the on disk bitset as this will normally be done
* after digesting into the era array.
*/
static void writeset_free(struct writeset *ws)
{
vfree(ws->bits);
}
static int setup_on_disk_bitset(struct dm_disk_bitset *info,
unsigned nr_bits, dm_block_t *root)
{
int r;
r = dm_bitset_empty(info, root);
if (r)
return r;
return dm_bitset_resize(info, *root, 0, nr_bits, false, root);
}
static size_t bitset_size(unsigned nr_bits)
{
return sizeof(unsigned long) * dm_div_up(nr_bits, BITS_PER_LONG);
}
/*
* Allocates memory for the in core bitset.
*/
static int writeset_alloc(struct writeset *ws, dm_block_t nr_blocks)
{
ws->md.nr_bits = nr_blocks;
ws->md.root = INVALID_WRITESET_ROOT;
ws->bits = vzalloc(bitset_size(nr_blocks));
if (!ws->bits) {
DMERR("%s: couldn't allocate in memory bitset", __func__);
return -ENOMEM;
}
return 0;
}
/*
* Wipes the in-core bitset, and creates a new on disk bitset.
*/
static int writeset_init(struct dm_disk_bitset *info, struct writeset *ws)
{
int r;
memset(ws->bits, 0, bitset_size(ws->md.nr_bits));
r = setup_on_disk_bitset(info, ws->md.nr_bits, &ws->md.root);
if (r) {
DMERR("%s: setup_on_disk_bitset failed", __func__);
return r;
}
return 0;
}
static bool writeset_marked(struct writeset *ws, dm_block_t block)
{
return test_bit(block, ws->bits);
}
static int writeset_marked_on_disk(struct dm_disk_bitset *info,
struct writeset_metadata *m, dm_block_t block,
bool *result)
{
dm_block_t old = m->root;
/*
* The bitset was flushed when it was archived, so we know there'll
* be no change to the root.
*/
int r = dm_bitset_test_bit(info, m->root, block, &m->root, result);
if (r) {
DMERR("%s: dm_bitset_test_bit failed", __func__);
return r;
}
BUG_ON(m->root != old);
return r;
}
/*
* Returns < 0 on error, 0 if the bit wasn't previously set, 1 if it was.
*/
static int writeset_test_and_set(struct dm_disk_bitset *info,
struct writeset *ws, uint32_t block)
{
int r;
if (!test_and_set_bit(block, ws->bits)) {
r = dm_bitset_set_bit(info, ws->md.root, block, &ws->md.root);
if (r) {
/* FIXME: fail mode */
return r;
}
return 0;
}
return 1;
}
/*----------------------------------------------------------------
* On disk metadata layout
*--------------------------------------------------------------*/
#define SPACE_MAP_ROOT_SIZE 128
#define UUID_LEN 16
struct writeset_disk {
__le32 nr_bits;
__le64 root;
} __packed;
struct superblock_disk {
__le32 csum;
__le32 flags;
__le64 blocknr;
__u8 uuid[UUID_LEN];
__le64 magic;
__le32 version;
__u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE];
__le32 data_block_size;
__le32 metadata_block_size;
__le32 nr_blocks;
__le32 current_era;
struct writeset_disk current_writeset;
/*
* Only these two fields are valid within the metadata snapshot.
*/
__le64 writeset_tree_root;
__le64 era_array_root;
__le64 metadata_snap;
} __packed;
/*----------------------------------------------------------------
* Superblock validation
*--------------------------------------------------------------*/
static void sb_prepare_for_write(struct dm_block_validator *v,
struct dm_block *b,
size_t sb_block_size)
{
struct superblock_disk *disk = dm_block_data(b);
disk->blocknr = cpu_to_le64(dm_block_location(b));
disk->csum = cpu_to_le32(dm_bm_checksum(&disk->flags,
sb_block_size - sizeof(__le32),
SUPERBLOCK_CSUM_XOR));
}
static int check_metadata_version(struct superblock_disk *disk)
{
uint32_t metadata_version = le32_to_cpu(disk->version);
if (metadata_version < MIN_ERA_VERSION || metadata_version > MAX_ERA_VERSION) {
DMERR("Era metadata version %u found, but only versions between %u and %u supported.",
metadata_version, MIN_ERA_VERSION, MAX_ERA_VERSION);
return -EINVAL;
}
return 0;
}
static int sb_check(struct dm_block_validator *v,
struct dm_block *b,
size_t sb_block_size)
{
struct superblock_disk *disk = dm_block_data(b);
__le32 csum_le;
if (dm_block_location(b) != le64_to_cpu(disk->blocknr)) {
DMERR("sb_check failed: blocknr %llu: wanted %llu",
le64_to_cpu(disk->blocknr),
(unsigned long long)dm_block_location(b));
return -ENOTBLK;
}
if (le64_to_cpu(disk->magic) != SUPERBLOCK_MAGIC) {
DMERR("sb_check failed: magic %llu: wanted %llu",
le64_to_cpu(disk->magic),
(unsigned long long) SUPERBLOCK_MAGIC);
return -EILSEQ;
}
csum_le = cpu_to_le32(dm_bm_checksum(&disk->flags,
sb_block_size - sizeof(__le32),
SUPERBLOCK_CSUM_XOR));
if (csum_le != disk->csum) {
DMERR("sb_check failed: csum %u: wanted %u",
le32_to_cpu(csum_le), le32_to_cpu(disk->csum));
return -EILSEQ;
}
return check_metadata_version(disk);
}
static struct dm_block_validator sb_validator = {
.name = "superblock",
.prepare_for_write = sb_prepare_for_write,
.check = sb_check
};
/*----------------------------------------------------------------
* Low level metadata handling
*--------------------------------------------------------------*/
#define DM_ERA_METADATA_BLOCK_SIZE 4096
#define DM_ERA_METADATA_CACHE_SIZE 64
#define ERA_MAX_CONCURRENT_LOCKS 5
struct era_metadata {
struct block_device *bdev;
struct dm_block_manager *bm;
struct dm_space_map *sm;
struct dm_transaction_manager *tm;
dm_block_t block_size;
uint32_t nr_blocks;
uint32_t current_era;
/*
* We preallocate 2 writesets. When an era rolls over we
* switch between them. This means the allocation is done at
* preresume time, rather than on the io path.
*/
struct writeset writesets[2];
struct writeset *current_writeset;
dm_block_t writeset_tree_root;
dm_block_t era_array_root;
struct dm_disk_bitset bitset_info;
struct dm_btree_info writeset_tree_info;
struct dm_array_info era_array_info;
dm_block_t metadata_snap;
/*
* A flag that is set whenever a writeset has been archived.
*/
bool archived_writesets;
/*
* Reading the space map root can fail, so we read it into this
* buffer before the superblock is locked and updated.
*/
__u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE];
};
static int superblock_read_lock(struct era_metadata *md,
struct dm_block **sblock)
{
return dm_bm_read_lock(md->bm, SUPERBLOCK_LOCATION,
&sb_validator, sblock);
}
static int superblock_lock_zero(struct era_metadata *md,
struct dm_block **sblock)
{
return dm_bm_write_lock_zero(md->bm, SUPERBLOCK_LOCATION,
&sb_validator, sblock);
}
static int superblock_lock(struct era_metadata *md,
struct dm_block **sblock)
{
return dm_bm_write_lock(md->bm, SUPERBLOCK_LOCATION,
&sb_validator, sblock);
}
/* FIXME: duplication with cache and thin */
static int superblock_all_zeroes(struct dm_block_manager *bm, bool *result)
{
int r;
unsigned i;
struct dm_block *b;
__le64 *data_le, zero = cpu_to_le64(0);
unsigned sb_block_size = dm_bm_block_size(bm) / sizeof(__le64);
/*
* We can't use a validator here - it may be all zeroes.
*/
r = dm_bm_read_lock(bm, SUPERBLOCK_LOCATION, NULL, &b);
if (r)
return r;
data_le = dm_block_data(b);
*result = true;
for (i = 0; i < sb_block_size; i++) {
if (data_le[i] != zero) {
*result = false;
break;
}
}
return dm_bm_unlock(b);
}
/*----------------------------------------------------------------*/
static void ws_pack(const struct writeset_metadata *core, struct writeset_disk *disk)
{
disk->nr_bits = cpu_to_le32(core->nr_bits);
disk->root = cpu_to_le64(core->root);
}
static void ws_unpack(const struct writeset_disk *disk, struct writeset_metadata *core)
{
core->nr_bits = le32_to_cpu(disk->nr_bits);
core->root = le64_to_cpu(disk->root);
}
static void ws_inc(void *context, const void *value)
{
struct era_metadata *md = context;
struct writeset_disk ws_d;
dm_block_t b;
memcpy(&ws_d, value, sizeof(ws_d));
b = le64_to_cpu(ws_d.root);
dm_tm_inc(md->tm, b);
}
static void ws_dec(void *context, const void *value)
{
struct era_metadata *md = context;
struct writeset_disk ws_d;
dm_block_t b;
memcpy(&ws_d, value, sizeof(ws_d));
b = le64_to_cpu(ws_d.root);
dm_bitset_del(&md->bitset_info, b);
}
static int ws_eq(void *context, const void *value1, const void *value2)
{
return !memcmp(value1, value2, sizeof(struct writeset_metadata));
}
/*----------------------------------------------------------------*/
static void setup_writeset_tree_info(struct era_metadata *md)
{
struct dm_btree_value_type *vt = &md->writeset_tree_info.value_type;
md->writeset_tree_info.tm = md->tm;
md->writeset_tree_info.levels = 1;
vt->context = md;
vt->size = sizeof(struct writeset_disk);
vt->inc = ws_inc;
vt->dec = ws_dec;
vt->equal = ws_eq;
}
static void setup_era_array_info(struct era_metadata *md)
{
struct dm_btree_value_type vt;
vt.context = NULL;
vt.size = sizeof(__le32);
vt.inc = NULL;
vt.dec = NULL;
vt.equal = NULL;
dm_array_info_init(&md->era_array_info, md->tm, &vt);
}
static void setup_infos(struct era_metadata *md)
{
dm_disk_bitset_init(md->tm, &md->bitset_info);
setup_writeset_tree_info(md);
setup_era_array_info(md);
}
/*----------------------------------------------------------------*/
static int create_fresh_metadata(struct era_metadata *md)
{
int r;
r = dm_tm_create_with_sm(md->bm, SUPERBLOCK_LOCATION,
&md->tm, &md->sm);
if (r < 0) {
DMERR("dm_tm_create_with_sm failed");
return r;
}
setup_infos(md);
r = dm_btree_empty(&md->writeset_tree_info, &md->writeset_tree_root);
if (r) {
DMERR("couldn't create new writeset tree");
goto bad;
}
r = dm_array_empty(&md->era_array_info, &md->era_array_root);
if (r) {
DMERR("couldn't create era array");
goto bad;
}
return 0;
bad:
dm_sm_destroy(md->sm);
dm_tm_destroy(md->tm);
return r;
}
static int save_sm_root(struct era_metadata *md)
{
int r;
size_t metadata_len;
r = dm_sm_root_size(md->sm, &metadata_len);
if (r < 0)
return r;
return dm_sm_copy_root(md->sm, &md->metadata_space_map_root,
metadata_len);
}
static void copy_sm_root(struct era_metadata *md, struct superblock_disk *disk)
{
memcpy(&disk->metadata_space_map_root,
&md->metadata_space_map_root,
sizeof(md->metadata_space_map_root));
}
/*
* Writes a superblock, including the static fields that don't get updated
* with every commit (possible optimisation here). 'md' should be fully
* constructed when this is called.
*/
static void prepare_superblock(struct era_metadata *md, struct superblock_disk *disk)
{
disk->magic = cpu_to_le64(SUPERBLOCK_MAGIC);
disk->flags = cpu_to_le32(0ul);
/* FIXME: can't keep blanking the uuid (uuid is currently unused though) */
memset(disk->uuid, 0, sizeof(disk->uuid));
disk->version = cpu_to_le32(MAX_ERA_VERSION);
copy_sm_root(md, disk);
disk->data_block_size = cpu_to_le32(md->block_size);
disk->metadata_block_size = cpu_to_le32(DM_ERA_METADATA_BLOCK_SIZE >> SECTOR_SHIFT);
disk->nr_blocks = cpu_to_le32(md->nr_blocks);
disk->current_era = cpu_to_le32(md->current_era);
ws_pack(&md->current_writeset->md, &disk->current_writeset);
disk->writeset_tree_root = cpu_to_le64(md->writeset_tree_root);
disk->era_array_root = cpu_to_le64(md->era_array_root);
disk->metadata_snap = cpu_to_le64(md->metadata_snap);
}
static int write_superblock(struct era_metadata *md)
{
int r;
struct dm_block *sblock;
struct superblock_disk *disk;
r = save_sm_root(md);
if (r) {
DMERR("%s: save_sm_root failed", __func__);
return r;
}
r = superblock_lock_zero(md, &sblock);
if (r)
return r;
disk = dm_block_data(sblock);
prepare_superblock(md, disk);
return dm_tm_commit(md->tm, sblock);
}
/*
* Assumes block_size and the infos are set.
*/
static int format_metadata(struct era_metadata *md)
{
int r;
r = create_fresh_metadata(md);
if (r)
return r;
r = write_superblock(md);
if (r) {
dm_sm_destroy(md->sm);
dm_tm_destroy(md->tm);
return r;
}
return 0;
}
static int open_metadata(struct era_metadata *md)
{
int r;
struct dm_block *sblock;
struct superblock_disk *disk;
r = superblock_read_lock(md, &sblock);
if (r) {
DMERR("couldn't read_lock superblock");
return r;
}
disk = dm_block_data(sblock);
r = dm_tm_open_with_sm(md->bm, SUPERBLOCK_LOCATION,
disk->metadata_space_map_root,
sizeof(disk->metadata_space_map_root),
&md->tm, &md->sm);
if (r) {
DMERR("dm_tm_open_with_sm failed");
goto bad;
}
setup_infos(md);
md->block_size = le32_to_cpu(disk->data_block_size);
md->nr_blocks = le32_to_cpu(disk->nr_blocks);
md->current_era = le32_to_cpu(disk->current_era);
md->writeset_tree_root = le64_to_cpu(disk->writeset_tree_root);
md->era_array_root = le64_to_cpu(disk->era_array_root);
md->metadata_snap = le64_to_cpu(disk->metadata_snap);
md->archived_writesets = true;
return dm_bm_unlock(sblock);
bad:
dm_bm_unlock(sblock);
return r;
}
static int open_or_format_metadata(struct era_metadata *md,
bool may_format)
{
int r;
bool unformatted = false;
r = superblock_all_zeroes(md->bm, &unformatted);
if (r)
return r;
if (unformatted)
return may_format ? format_metadata(md) : -EPERM;
return open_metadata(md);
}
static int create_persistent_data_objects(struct era_metadata *md,
bool may_format)
{
int r;
md->bm = dm_block_manager_create(md->bdev, DM_ERA_METADATA_BLOCK_SIZE,
DM_ERA_METADATA_CACHE_SIZE,
ERA_MAX_CONCURRENT_LOCKS);
if (IS_ERR(md->bm)) {
DMERR("could not create block manager");
return PTR_ERR(md->bm);
}
r = open_or_format_metadata(md, may_format);
if (r)
dm_block_manager_destroy(md->bm);
return r;
}
static void destroy_persistent_data_objects(struct era_metadata *md)
{
dm_sm_destroy(md->sm);
dm_tm_destroy(md->tm);
dm_block_manager_destroy(md->bm);
}
/*
* This waits until all era_map threads have picked up the new filter.
*/
static void swap_writeset(struct era_metadata *md, struct writeset *new_writeset)
{
rcu_assign_pointer(md->current_writeset, new_writeset);
synchronize_rcu();
}
/*----------------------------------------------------------------
* Writesets get 'digested' into the main era array.
*
* We're using a coroutine here so the worker thread can do the digestion,
* thus avoiding synchronisation of the metadata. Digesting a whole
* writeset in one go would cause too much latency.
*--------------------------------------------------------------*/
struct digest {
uint32_t era;
unsigned nr_bits, current_bit;
struct writeset_metadata writeset;
__le32 value;
struct dm_disk_bitset info;
int (*step)(struct era_metadata *, struct digest *);
};
static int metadata_digest_lookup_writeset(struct era_metadata *md,
struct digest *d);
static int metadata_digest_remove_writeset(struct era_metadata *md,
struct digest *d)
{
int r;
uint64_t key = d->era;
r = dm_btree_remove(&md->writeset_tree_info, md->writeset_tree_root,
&key, &md->writeset_tree_root);
if (r) {
DMERR("%s: dm_btree_remove failed", __func__);
return r;
}
d->step = metadata_digest_lookup_writeset;
return 0;
}
#define INSERTS_PER_STEP 100
static int metadata_digest_transcribe_writeset(struct era_metadata *md,
struct digest *d)
{
int r;
bool marked;
unsigned b, e = min(d->current_bit + INSERTS_PER_STEP, d->nr_bits);
for (b = d->current_bit; b < e; b++) {
r = writeset_marked_on_disk(&d->info, &d->writeset, b, &marked);
if (r) {
DMERR("%s: writeset_marked_on_disk failed", __func__);
return r;
}
if (!marked)
continue;
__dm_bless_for_disk(&d->value);
r = dm_array_set_value(&md->era_array_info, md->era_array_root,
b, &d->value, &md->era_array_root);
if (r) {
DMERR("%s: dm_array_set_value failed", __func__);
return r;
}
}
if (b == d->nr_bits)
d->step = metadata_digest_remove_writeset;
else
d->current_bit = b;
return 0;
}
static int metadata_digest_lookup_writeset(struct era_metadata *md,
struct digest *d)
{
int r;
uint64_t key;
struct writeset_disk disk;
r = dm_btree_find_lowest_key(&md->writeset_tree_info,
md->writeset_tree_root, &key);
if (r < 0)
return r;
d->era = key;
r = dm_btree_lookup(&md->writeset_tree_info,
md->writeset_tree_root, &key, &disk);
if (r) {
if (r == -ENODATA) {
d->step = NULL;
return 0;
}
DMERR("%s: dm_btree_lookup failed", __func__);
return r;
}
ws_unpack(&disk, &d->writeset);
d->value = cpu_to_le32(key);
d->nr_bits = min(d->writeset.nr_bits, md->nr_blocks);
d->current_bit = 0;
d->step = metadata_digest_transcribe_writeset;
return 0;
}
static int metadata_digest_start(struct era_metadata *md, struct digest *d)
{
if (d->step)
return 0;
memset(d, 0, sizeof(*d));
/*
* We initialise another bitset info to avoid any caching side
* effects with the previous one.
*/
dm_disk_bitset_init(md->tm, &d->info);
d->step = metadata_digest_lookup_writeset;
return 0;
}
/*----------------------------------------------------------------
* High level metadata interface. Target methods should use these, and not
* the lower level ones.
*--------------------------------------------------------------*/
static struct era_metadata *metadata_open(struct block_device *bdev,
sector_t block_size,
bool may_format)
{
int r;
struct era_metadata *md = kzalloc(sizeof(*md), GFP_KERNEL);
if (!md)
return NULL;
md->bdev = bdev;
md->block_size = block_size;
md->writesets[0].md.root = INVALID_WRITESET_ROOT;
md->writesets[1].md.root = INVALID_WRITESET_ROOT;
md->current_writeset = &md->writesets[0];
r = create_persistent_data_objects(md, may_format);
if (r) {
kfree(md);
return ERR_PTR(r);
}
return md;
}
static void metadata_close(struct era_metadata *md)
{
destroy_persistent_data_objects(md);
kfree(md);
}
static bool valid_nr_blocks(dm_block_t n)
{
/*
* dm_bitset restricts us to 2^32. test_bit & co. restrict us
* further to 2^31 - 1
*/
return n < (1ull << 31);
}
static int metadata_resize(struct era_metadata *md, void *arg)
{
int r;
dm_block_t *new_size = arg;
__le32 value;
if (!valid_nr_blocks(*new_size)) {
DMERR("Invalid number of origin blocks %llu",
(unsigned long long) *new_size);
return -EINVAL;
}
writeset_free(&md->writesets[0]);
writeset_free(&md->writesets[1]);
r = writeset_alloc(&md->writesets[0], *new_size);
if (r) {
DMERR("%s: writeset_alloc failed for writeset 0", __func__);
return r;
}
r = writeset_alloc(&md->writesets[1], *new_size);
if (r) {
DMERR("%s: writeset_alloc failed for writeset 1", __func__);
return r;
}
value = cpu_to_le32(0u);
__dm_bless_for_disk(&value);
r = dm_array_resize(&md->era_array_info, md->era_array_root,
md->nr_blocks, *new_size,
&value, &md->era_array_root);
if (r) {
DMERR("%s: dm_array_resize failed", __func__);
return r;
}
md->nr_blocks = *new_size;
return 0;
}
static int metadata_era_archive(struct era_metadata *md)
{
int r;
uint64_t keys[1];
struct writeset_disk value;
r = dm_bitset_flush(&md->bitset_info, md->current_writeset->md.root,
&md->current_writeset->md.root);
if (r) {
DMERR("%s: dm_bitset_flush failed", __func__);
return r;
}
ws_pack(&md->current_writeset->md, &value);
md->current_writeset->md.root = INVALID_WRITESET_ROOT;
keys[0] = md->current_era;
__dm_bless_for_disk(&value);
r = dm_btree_insert(&md->writeset_tree_info, md->writeset_tree_root,
keys, &value, &md->writeset_tree_root);
if (r) {
DMERR("%s: couldn't insert writeset into btree", __func__);
/* FIXME: fail mode */
return r;
}
md->archived_writesets = true;
return 0;
}
static struct writeset *next_writeset(struct era_metadata *md)
{
return (md->current_writeset == &md->writesets[0]) ?
&md->writesets[1] : &md->writesets[0];
}
static int metadata_new_era(struct era_metadata *md)
{
int r;
struct writeset *new_writeset = next_writeset(md);
r = writeset_init(&md->bitset_info, new_writeset);
if (r) {
DMERR("%s: writeset_init failed", __func__);
return r;
}
swap_writeset(md, new_writeset);
md->current_era++;
return 0;
}
static int metadata_era_rollover(struct era_metadata *md)
{
int r;
if (md->current_writeset->md.root != INVALID_WRITESET_ROOT) {
r = metadata_era_archive(md);
if (r) {
DMERR("%s: metadata_archive_era failed", __func__);
/* FIXME: fail mode? */
return r;
}
}
r = metadata_new_era(md);
if (r) {
DMERR("%s: new era failed", __func__);
/* FIXME: fail mode */
return r;
}
return 0;
}
static bool metadata_current_marked(struct era_metadata *md, dm_block_t block)
{
bool r;
struct writeset *ws;
rcu_read_lock();
ws = rcu_dereference(md->current_writeset);
r = writeset_marked(ws, block);
rcu_read_unlock();
return r;
}
static int metadata_commit(struct era_metadata *md)
{
int r;
struct dm_block *sblock;
if (md->current_writeset->md.root != SUPERBLOCK_LOCATION) {
r = dm_bitset_flush(&md->bitset_info, md->current_writeset->md.root,
&md->current_writeset->md.root);
if (r) {
DMERR("%s: bitset flush failed", __func__);
return r;
}
}
r = save_sm_root(md);
if (r) {
DMERR("%s: save_sm_root failed", __func__);
return r;
}
r = dm_tm_pre_commit(md->tm);
if (r) {
DMERR("%s: pre commit failed", __func__);
return r;
}
r = superblock_lock(md, &sblock);
if (r) {
DMERR("%s: superblock lock failed", __func__);
return r;
}
prepare_superblock(md, dm_block_data(sblock));
return dm_tm_commit(md->tm, sblock);
}
static int metadata_checkpoint(struct era_metadata *md)
{
/*
* For now we just rollover, but later I want to put a check in to
* avoid this if the filter is still pretty fresh.
*/
return metadata_era_rollover(md);
}
/*
* Metadata snapshots allow userland to access era data.
*/
static int metadata_take_snap(struct era_metadata *md)
{
int r, inc;
struct dm_block *clone;
if (md->metadata_snap != SUPERBLOCK_LOCATION) {
DMERR("%s: metadata snapshot already exists", __func__);
return -EINVAL;
}
r = metadata_era_rollover(md);
if (r) {
DMERR("%s: era rollover failed", __func__);
return r;
}
r = metadata_commit(md);
if (r) {
DMERR("%s: pre commit failed", __func__);
return r;
}
r = dm_sm_inc_block(md->sm, SUPERBLOCK_LOCATION);
if (r) {
DMERR("%s: couldn't increment superblock", __func__);
return r;
}
r = dm_tm_shadow_block(md->tm, SUPERBLOCK_LOCATION,
&sb_validator, &clone, &inc);
if (r) {
DMERR("%s: couldn't shadow superblock", __func__);
dm_sm_dec_block(md->sm, SUPERBLOCK_LOCATION);
return r;
}
BUG_ON(!inc);
r = dm_sm_inc_block(md->sm, md->writeset_tree_root);
if (r) {
DMERR("%s: couldn't inc writeset tree root", __func__);
dm_tm_unlock(md->tm, clone);
return r;
}
r = dm_sm_inc_block(md->sm, md->era_array_root);
if (r) {
DMERR("%s: couldn't inc era tree root", __func__);
dm_sm_dec_block(md->sm, md->writeset_tree_root);
dm_tm_unlock(md->tm, clone);
return r;
}
md->metadata_snap = dm_block_location(clone);
r = dm_tm_unlock(md->tm, clone);
if (r) {
DMERR("%s: couldn't unlock clone", __func__);
md->metadata_snap = SUPERBLOCK_LOCATION;
return r;
}
return 0;
}
static int metadata_drop_snap(struct era_metadata *md)
{
int r;
dm_block_t location;
struct dm_block *clone;
struct superblock_disk *disk;
if (md->metadata_snap == SUPERBLOCK_LOCATION) {
DMERR("%s: no snap to drop", __func__);
return -EINVAL;
}
r = dm_tm_read_lock(md->tm, md->metadata_snap, &sb_validator, &clone);
if (r) {
DMERR("%s: couldn't read lock superblock clone", __func__);
return r;
}
/*
* Whatever happens now we'll commit with no record of the metadata
* snap.
*/
md->metadata_snap = SUPERBLOCK_LOCATION;
disk = dm_block_data(clone);
r = dm_btree_del(&md->writeset_tree_info,
le64_to_cpu(disk->writeset_tree_root));
if (r) {
DMERR("%s: error deleting writeset tree clone", __func__);
dm_tm_unlock(md->tm, clone);
return r;
}
r = dm_array_del(&md->era_array_info, le64_to_cpu(disk->era_array_root));
if (r) {
DMERR("%s: error deleting era array clone", __func__);
dm_tm_unlock(md->tm, clone);
return r;
}
location = dm_block_location(clone);
dm_tm_unlock(md->tm, clone);
return dm_sm_dec_block(md->sm, location);
}
struct metadata_stats {
dm_block_t used;
dm_block_t total;
dm_block_t snap;
uint32_t era;
};
static int metadata_get_stats(struct era_metadata *md, void *ptr)
{
int r;
struct metadata_stats *s = ptr;
dm_block_t nr_free, nr_total;
r = dm_sm_get_nr_free(md->sm, &nr_free);
if (r) {
DMERR("dm_sm_get_nr_free returned %d", r);
return r;
}
r = dm_sm_get_nr_blocks(md->sm, &nr_total);
if (r) {
DMERR("dm_pool_get_metadata_dev_size returned %d", r);
return r;
}
s->used = nr_total - nr_free;
s->total = nr_total;
s->snap = md->metadata_snap;
s->era = md->current_era;
return 0;
}
/*----------------------------------------------------------------*/
struct era {
struct dm_target *ti;
struct dm_target_callbacks callbacks;
struct dm_dev *metadata_dev;
struct dm_dev *origin_dev;
dm_block_t nr_blocks;
uint32_t sectors_per_block;
int sectors_per_block_shift;
struct era_metadata *md;
struct workqueue_struct *wq;
struct work_struct worker;
spinlock_t deferred_lock;
struct bio_list deferred_bios;
spinlock_t rpc_lock;
struct list_head rpc_calls;
struct digest digest;
atomic_t suspended;
};
struct rpc {
struct list_head list;
int (*fn0)(struct era_metadata *);
int (*fn1)(struct era_metadata *, void *);
void *arg;
int result;
struct completion complete;
};
/*----------------------------------------------------------------
* Remapping.
*---------------------------------------------------------------*/
static bool block_size_is_power_of_two(struct era *era)
{
return era->sectors_per_block_shift >= 0;
}
static dm_block_t get_block(struct era *era, struct bio *bio)
{
sector_t block_nr = bio->bi_iter.bi_sector;
if (!block_size_is_power_of_two(era))
(void) sector_div(block_nr, era->sectors_per_block);
else
block_nr >>= era->sectors_per_block_shift;
return block_nr;
}
static void remap_to_origin(struct era *era, struct bio *bio)
{
bio->bi_bdev = era->origin_dev->bdev;
}
/*----------------------------------------------------------------
* Worker thread
*--------------------------------------------------------------*/
static void wake_worker(struct era *era)
{
if (!atomic_read(&era->suspended))
queue_work(era->wq, &era->worker);
}
static void process_old_eras(struct era *era)
{
int r;
if (!era->digest.step)
return;
r = era->digest.step(era->md, &era->digest);
if (r < 0) {
DMERR("%s: digest step failed, stopping digestion", __func__);
era->digest.step = NULL;
} else if (era->digest.step)
wake_worker(era);
}
static void process_deferred_bios(struct era *era)
{
int r;
struct bio_list deferred_bios, marked_bios;
struct bio *bio;
bool commit_needed = false;
bool failed = false;
bio_list_init(&deferred_bios);
bio_list_init(&marked_bios);
spin_lock(&era->deferred_lock);
bio_list_merge(&deferred_bios, &era->deferred_bios);
bio_list_init(&era->deferred_bios);
spin_unlock(&era->deferred_lock);
while ((bio = bio_list_pop(&deferred_bios))) {
r = writeset_test_and_set(&era->md->bitset_info,
era->md->current_writeset,
get_block(era, bio));
if (r < 0) {
/*
* This is bad news, we need to rollback.
* FIXME: finish.
*/
failed = true;
} else if (r == 0)
commit_needed = true;
bio_list_add(&marked_bios, bio);
}
if (commit_needed) {
r = metadata_commit(era->md);
if (r)
failed = true;
}
if (failed)
while ((bio = bio_list_pop(&marked_bios)))
bio_io_error(bio);
else
while ((bio = bio_list_pop(&marked_bios)))
generic_make_request(bio);
}
static void process_rpc_calls(struct era *era)
{
int r;
bool need_commit = false;
struct list_head calls;
struct rpc *rpc, *tmp;
INIT_LIST_HEAD(&calls);
spin_lock(&era->rpc_lock);
list_splice_init(&era->rpc_calls, &calls);
spin_unlock(&era->rpc_lock);
list_for_each_entry_safe(rpc, tmp, &calls, list) {
rpc->result = rpc->fn0 ? rpc->fn0(era->md) : rpc->fn1(era->md, rpc->arg);
need_commit = true;
}
if (need_commit) {
r = metadata_commit(era->md);
if (r)
list_for_each_entry_safe(rpc, tmp, &calls, list)
rpc->result = r;
}
list_for_each_entry_safe(rpc, tmp, &calls, list)
complete(&rpc->complete);
}
static void kick_off_digest(struct era *era)
{
if (era->md->archived_writesets) {
era->md->archived_writesets = false;
metadata_digest_start(era->md, &era->digest);
}
}
static void do_work(struct work_struct *ws)
{
struct era *era = container_of(ws, struct era, worker);
kick_off_digest(era);
process_old_eras(era);
process_deferred_bios(era);
process_rpc_calls(era);
}
static void defer_bio(struct era *era, struct bio *bio)
{
spin_lock(&era->deferred_lock);
bio_list_add(&era->deferred_bios, bio);
spin_unlock(&era->deferred_lock);
wake_worker(era);
}
/*
* Make an rpc call to the worker to change the metadata.
*/
static int perform_rpc(struct era *era, struct rpc *rpc)
{
rpc->result = 0;
init_completion(&rpc->complete);
spin_lock(&era->rpc_lock);
list_add(&rpc->list, &era->rpc_calls);
spin_unlock(&era->rpc_lock);
wake_worker(era);
wait_for_completion(&rpc->complete);
return rpc->result;
}
static int in_worker0(struct era *era, int (*fn)(struct era_metadata *))
{
struct rpc rpc;
rpc.fn0 = fn;
rpc.fn1 = NULL;
return perform_rpc(era, &rpc);
}
static int in_worker1(struct era *era,
int (*fn)(struct era_metadata *, void *), void *arg)
{
struct rpc rpc;
rpc.fn0 = NULL;
rpc.fn1 = fn;
rpc.arg = arg;
return perform_rpc(era, &rpc);
}
static void start_worker(struct era *era)
{
atomic_set(&era->suspended, 0);
}
static void stop_worker(struct era *era)
{
atomic_set(&era->suspended, 1);
flush_workqueue(era->wq);
}
/*----------------------------------------------------------------
* Target methods
*--------------------------------------------------------------*/
static int dev_is_congested(struct dm_dev *dev, int bdi_bits)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return bdi_congested(&q->backing_dev_info, bdi_bits);
}
static int era_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
{
struct era *era = container_of(cb, struct era, callbacks);
return dev_is_congested(era->origin_dev, bdi_bits);
}
static void era_destroy(struct era *era)
{
if (era->md)
metadata_close(era->md);
if (era->wq)
destroy_workqueue(era->wq);
if (era->origin_dev)
dm_put_device(era->ti, era->origin_dev);
if (era->metadata_dev)
dm_put_device(era->ti, era->metadata_dev);
kfree(era);
}
static dm_block_t calc_nr_blocks(struct era *era)
{
return dm_sector_div_up(era->ti->len, era->sectors_per_block);
}
static bool valid_block_size(dm_block_t block_size)
{
bool greater_than_zero = block_size > 0;
bool multiple_of_min_block_size = (block_size & (MIN_BLOCK_SIZE - 1)) == 0;
return greater_than_zero && multiple_of_min_block_size;
}
/*
* <metadata dev> <data dev> <data block size (sectors)>
*/
static int era_ctr(struct dm_target *ti, unsigned argc, char **argv)
{
int r;
char dummy;
struct era *era;
struct era_metadata *md;
if (argc != 3) {
ti->error = "Invalid argument count";
return -EINVAL;
}
era = kzalloc(sizeof(*era), GFP_KERNEL);
if (!era) {
ti->error = "Error allocating era structure";
return -ENOMEM;
}
era->ti = ti;
r = dm_get_device(ti, argv[0], FMODE_READ | FMODE_WRITE, &era->metadata_dev);
if (r) {
ti->error = "Error opening metadata device";
era_destroy(era);
return -EINVAL;
}
r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &era->origin_dev);
if (r) {
ti->error = "Error opening data device";
era_destroy(era);
return -EINVAL;
}
r = sscanf(argv[2], "%u%c", &era->sectors_per_block, &dummy);
if (r != 1) {
ti->error = "Error parsing block size";
era_destroy(era);
return -EINVAL;
}
r = dm_set_target_max_io_len(ti, era->sectors_per_block);
if (r) {
ti->error = "could not set max io len";
era_destroy(era);
return -EINVAL;
}
if (!valid_block_size(era->sectors_per_block)) {
ti->error = "Invalid block size";
era_destroy(era);
return -EINVAL;
}
if (era->sectors_per_block & (era->sectors_per_block - 1))
era->sectors_per_block_shift = -1;
else
era->sectors_per_block_shift = __ffs(era->sectors_per_block);
md = metadata_open(era->metadata_dev->bdev, era->sectors_per_block, true);
if (IS_ERR(md)) {
ti->error = "Error reading metadata";
era_destroy(era);
return PTR_ERR(md);
}
era->md = md;
era->nr_blocks = calc_nr_blocks(era);
r = metadata_resize(era->md, &era->nr_blocks);
if (r) {
ti->error = "couldn't resize metadata";
era_destroy(era);
return -ENOMEM;
}
era->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
if (!era->wq) {
ti->error = "could not create workqueue for metadata object";
era_destroy(era);
return -ENOMEM;
}
INIT_WORK(&era->worker, do_work);
spin_lock_init(&era->deferred_lock);
bio_list_init(&era->deferred_bios);
spin_lock_init(&era->rpc_lock);
INIT_LIST_HEAD(&era->rpc_calls);
ti->private = era;
ti->num_flush_bios = 1;
ti->flush_supported = true;
ti->num_discard_bios = 1;
ti->discards_supported = true;
era->callbacks.congested_fn = era_is_congested;
dm_table_add_target_callbacks(ti->table, &era->callbacks);
return 0;
}
static void era_dtr(struct dm_target *ti)
{
era_destroy(ti->private);
}
static int era_map(struct dm_target *ti, struct bio *bio)
{
struct era *era = ti->private;
dm_block_t block = get_block(era, bio);
/*
* All bios get remapped to the origin device. We do this now, but
* it may not get issued until later. Depending on whether the
* block is marked in this era.
*/
remap_to_origin(era, bio);
/*
* REQ_FLUSH bios carry no data, so we're not interested in them.
*/
if (!(bio->bi_rw & REQ_FLUSH) &&
(bio_data_dir(bio) == WRITE) &&
!metadata_current_marked(era->md, block)) {
defer_bio(era, bio);
return DM_MAPIO_SUBMITTED;
}
return DM_MAPIO_REMAPPED;
}
static void era_postsuspend(struct dm_target *ti)
{
int r;
struct era *era = ti->private;
r = in_worker0(era, metadata_era_archive);
if (r) {
DMERR("%s: couldn't archive current era", __func__);
/* FIXME: fail mode */
}
stop_worker(era);
}
static int era_preresume(struct dm_target *ti)
{
int r;
struct era *era = ti->private;
dm_block_t new_size = calc_nr_blocks(era);
if (era->nr_blocks != new_size) {
r = in_worker1(era, metadata_resize, &new_size);
if (r)
return r;
era->nr_blocks = new_size;
}
start_worker(era);
r = in_worker0(era, metadata_new_era);
if (r) {
DMERR("%s: metadata_era_rollover failed", __func__);
return r;
}
return 0;
}
/*
* Status format:
*
* <metadata block size> <#used metadata blocks>/<#total metadata blocks>
* <current era> <held metadata root | '-'>
*/
static void era_status(struct dm_target *ti, status_type_t type,
unsigned status_flags, char *result, unsigned maxlen)
{
int r;
struct era *era = ti->private;
ssize_t sz = 0;
struct metadata_stats stats;
char buf[BDEVNAME_SIZE];
switch (type) {
case STATUSTYPE_INFO:
r = in_worker1(era, metadata_get_stats, &stats);
if (r)
goto err;
DMEMIT("%u %llu/%llu %u",
(unsigned) (DM_ERA_METADATA_BLOCK_SIZE >> SECTOR_SHIFT),
(unsigned long long) stats.used,
(unsigned long long) stats.total,
(unsigned) stats.era);
if (stats.snap != SUPERBLOCK_LOCATION)
DMEMIT(" %llu", stats.snap);
else
DMEMIT(" -");
break;
case STATUSTYPE_TABLE:
format_dev_t(buf, era->metadata_dev->bdev->bd_dev);
DMEMIT("%s ", buf);
format_dev_t(buf, era->origin_dev->bdev->bd_dev);
DMEMIT("%s %u", buf, era->sectors_per_block);
break;
}
return;
err:
DMEMIT("Error");
}
static int era_message(struct dm_target *ti, unsigned argc, char **argv)
{
struct era *era = ti->private;
if (argc != 1) {
DMERR("incorrect number of message arguments");
return -EINVAL;
}
if (!strcasecmp(argv[0], "checkpoint"))
return in_worker0(era, metadata_checkpoint);
if (!strcasecmp(argv[0], "take_metadata_snap"))
return in_worker0(era, metadata_take_snap);
if (!strcasecmp(argv[0], "drop_metadata_snap"))
return in_worker0(era, metadata_drop_snap);
DMERR("unsupported message '%s'", argv[0]);
return -EINVAL;
}
static sector_t get_dev_size(struct dm_dev *dev)
{
return i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT;
}
static int era_iterate_devices(struct dm_target *ti,
iterate_devices_callout_fn fn, void *data)
{
struct era *era = ti->private;
return fn(ti, era->origin_dev, 0, get_dev_size(era->origin_dev), data);
}
static int era_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
struct bio_vec *biovec, int max_size)
{
struct era *era = ti->private;
struct request_queue *q = bdev_get_queue(era->origin_dev->bdev);
if (!q->merge_bvec_fn)
return max_size;
bvm->bi_bdev = era->origin_dev->bdev;
return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
}
static void era_io_hints(struct dm_target *ti, struct queue_limits *limits)
{
struct era *era = ti->private;
uint64_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
/*
* If the system-determined stacked limits are compatible with the
* era device's blocksize (io_opt is a factor) do not override them.
*/
if (io_opt_sectors < era->sectors_per_block ||
do_div(io_opt_sectors, era->sectors_per_block)) {
blk_limits_io_min(limits, 0);
blk_limits_io_opt(limits, era->sectors_per_block << SECTOR_SHIFT);
}
}
/*----------------------------------------------------------------*/
static struct target_type era_target = {
.name = "era",
.version = {1, 0, 0},
.module = THIS_MODULE,
.ctr = era_ctr,
.dtr = era_dtr,
.map = era_map,
.postsuspend = era_postsuspend,
.preresume = era_preresume,
.status = era_status,
.message = era_message,
.iterate_devices = era_iterate_devices,
.merge = era_merge,
.io_hints = era_io_hints
};
static int __init dm_era_init(void)
{
int r;
r = dm_register_target(&era_target);
if (r) {
DMERR("era target registration failed: %d", r);
return r;
}
return 0;
}
static void __exit dm_era_exit(void)
{
dm_unregister_target(&era_target);
}
module_init(dm_era_init);
module_exit(dm_era_exit);
MODULE_DESCRIPTION(DM_NAME " era target");
MODULE_AUTHOR("Joe Thornber <ejt@redhat.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
k2wl/5282 | drivers/input/keyboard/pmic8xxx-keypad.c | 1823 | 19863 | /* Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/mfd/pm8xxx/core.h>
#include <linux/mfd/pm8xxx/gpio.h>
#include <linux/input/pmic8xxx-keypad.h>
#define PM8XXX_MAX_ROWS 18
#define PM8XXX_MAX_COLS 8
#define PM8XXX_ROW_SHIFT 3
#define PM8XXX_MATRIX_MAX_SIZE (PM8XXX_MAX_ROWS * PM8XXX_MAX_COLS)
#define PM8XXX_MIN_ROWS 5
#define PM8XXX_MIN_COLS 5
#define MAX_SCAN_DELAY 128
#define MIN_SCAN_DELAY 1
/* in nanoseconds */
#define MAX_ROW_HOLD_DELAY 122000
#define MIN_ROW_HOLD_DELAY 30500
#define MAX_DEBOUNCE_TIME 20
#define MIN_DEBOUNCE_TIME 5
#define KEYP_CTRL 0x148
#define KEYP_CTRL_EVNTS BIT(0)
#define KEYP_CTRL_EVNTS_MASK 0x3
#define KEYP_CTRL_SCAN_COLS_SHIFT 5
#define KEYP_CTRL_SCAN_COLS_MIN 5
#define KEYP_CTRL_SCAN_COLS_BITS 0x3
#define KEYP_CTRL_SCAN_ROWS_SHIFT 2
#define KEYP_CTRL_SCAN_ROWS_MIN 5
#define KEYP_CTRL_SCAN_ROWS_BITS 0x7
#define KEYP_CTRL_KEYP_EN BIT(7)
#define KEYP_SCAN 0x149
#define KEYP_SCAN_READ_STATE BIT(0)
#define KEYP_SCAN_DBOUNCE_SHIFT 1
#define KEYP_SCAN_PAUSE_SHIFT 3
#define KEYP_SCAN_ROW_HOLD_SHIFT 6
#define KEYP_TEST 0x14A
#define KEYP_TEST_CLEAR_RECENT_SCAN BIT(6)
#define KEYP_TEST_CLEAR_OLD_SCAN BIT(5)
#define KEYP_TEST_READ_RESET BIT(4)
#define KEYP_TEST_DTEST_EN BIT(3)
#define KEYP_TEST_ABORT_READ BIT(0)
#define KEYP_TEST_DBG_SELECT_SHIFT 1
/* bits of these registers represent
* '0' for key press
* '1' for key release
*/
#define KEYP_RECENT_DATA 0x14B
#define KEYP_OLD_DATA 0x14C
#define KEYP_CLOCK_FREQ 32768
/**
* struct pmic8xxx_kp - internal keypad data structure
* @pdata - keypad platform data pointer
* @input - input device pointer for keypad
* @key_sense_irq - key press/release irq number
* @key_stuck_irq - key stuck notification irq number
* @keycodes - array to hold the key codes
* @dev - parent device pointer
* @keystate - present key press/release state
* @stuckstate - present state when key stuck irq
* @ctrl_reg - control register value
*/
struct pmic8xxx_kp {
const struct pm8xxx_keypad_platform_data *pdata;
struct input_dev *input;
int key_sense_irq;
int key_stuck_irq;
unsigned short keycodes[PM8XXX_MATRIX_MAX_SIZE];
struct device *dev;
u16 keystate[PM8XXX_MAX_ROWS];
u16 stuckstate[PM8XXX_MAX_ROWS];
u8 ctrl_reg;
};
static int pmic8xxx_kp_write_u8(struct pmic8xxx_kp *kp,
u8 data, u16 reg)
{
int rc;
rc = pm8xxx_writeb(kp->dev->parent, reg, data);
return rc;
}
static int pmic8xxx_kp_read(struct pmic8xxx_kp *kp,
u8 *data, u16 reg, unsigned num_bytes)
{
int rc;
rc = pm8xxx_read_buf(kp->dev->parent, reg, data, num_bytes);
return rc;
}
static int pmic8xxx_kp_read_u8(struct pmic8xxx_kp *kp,
u8 *data, u16 reg)
{
int rc;
rc = pmic8xxx_kp_read(kp, data, reg, 1);
return rc;
}
static u8 pmic8xxx_col_state(struct pmic8xxx_kp *kp, u8 col)
{
/* all keys pressed on that particular row? */
if (col == 0x00)
return 1 << kp->pdata->num_cols;
else
return col & ((1 << kp->pdata->num_cols) - 1);
}
/*
* Synchronous read protocol for RevB0 onwards:
*
* 1. Write '1' to ReadState bit in KEYP_SCAN register
* 2. Wait 2*32KHz clocks, so that HW can successfully enter read mode
* synchronously
* 3. Read rows in old array first if events are more than one
* 4. Read rows in recent array
* 5. Wait 4*32KHz clocks
* 6. Write '0' to ReadState bit of KEYP_SCAN register so that hw can
* synchronously exit read mode.
*/
static int pmic8xxx_chk_sync_read(struct pmic8xxx_kp *kp)
{
int rc;
u8 scan_val;
rc = pmic8xxx_kp_read_u8(kp, &scan_val, KEYP_SCAN);
if (rc < 0) {
dev_err(kp->dev, "Error reading KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
scan_val |= 0x1;
rc = pmic8xxx_kp_write_u8(kp, scan_val, KEYP_SCAN);
if (rc < 0) {
dev_err(kp->dev, "Error writing KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
/* 2 * 32KHz clocks */
udelay((2 * DIV_ROUND_UP(USEC_PER_SEC, KEYP_CLOCK_FREQ)) + 1);
return rc;
}
static int pmic8xxx_kp_read_data(struct pmic8xxx_kp *kp, u16 *state,
u16 data_reg, int read_rows)
{
int rc, row;
u8 new_data[PM8XXX_MAX_ROWS];
rc = pmic8xxx_kp_read(kp, new_data, data_reg, read_rows);
if (rc)
return rc;
for (row = 0; row < kp->pdata->num_rows; row++) {
dev_dbg(kp->dev, "new_data[%d] = %d\n", row,
new_data[row]);
state[row] = pmic8xxx_col_state(kp, new_data[row]);
}
return rc;
}
static int pmic8xxx_kp_read_matrix(struct pmic8xxx_kp *kp, u16 *new_state,
u16 *old_state)
{
int rc, read_rows;
u8 scan_val;
if (kp->pdata->num_rows < PM8XXX_MIN_ROWS)
read_rows = PM8XXX_MIN_ROWS;
else
read_rows = kp->pdata->num_rows;
pmic8xxx_chk_sync_read(kp);
if (old_state) {
rc = pmic8xxx_kp_read_data(kp, old_state, KEYP_OLD_DATA,
read_rows);
if (rc < 0) {
dev_err(kp->dev,
"Error reading KEYP_OLD_DATA, rc=%d\n", rc);
return rc;
}
}
rc = pmic8xxx_kp_read_data(kp, new_state, KEYP_RECENT_DATA,
read_rows);
if (rc < 0) {
dev_err(kp->dev,
"Error reading KEYP_RECENT_DATA, rc=%d\n", rc);
return rc;
}
/* 4 * 32KHz clocks */
udelay((4 * DIV_ROUND_UP(USEC_PER_SEC, KEYP_CLOCK_FREQ)) + 1);
rc = pmic8xxx_kp_read_u8(kp, &scan_val, KEYP_SCAN);
if (rc < 0) {
dev_err(kp->dev, "Error reading KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
scan_val &= 0xFE;
rc = pmic8xxx_kp_write_u8(kp, scan_val, KEYP_SCAN);
if (rc < 0)
dev_err(kp->dev, "Error writing KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
static void __pmic8xxx_kp_scan_matrix(struct pmic8xxx_kp *kp, u16 *new_state,
u16 *old_state)
{
int row, col, code;
for (row = 0; row < kp->pdata->num_rows; row++) {
int bits_changed = new_state[row] ^ old_state[row];
if (!bits_changed)
continue;
for (col = 0; col < kp->pdata->num_cols; col++) {
if (!(bits_changed & (1 << col)))
continue;
dev_dbg(kp->dev, "key [%d:%d] %s\n", row, col,
!(new_state[row] & (1 << col)) ?
"pressed" : "released");
code = MATRIX_SCAN_CODE(row, col, PM8XXX_ROW_SHIFT);
input_event(kp->input, EV_MSC, MSC_SCAN, code);
input_report_key(kp->input,
kp->keycodes[code],
!(new_state[row] & (1 << col)));
input_sync(kp->input);
}
}
}
static bool pmic8xxx_detect_ghost_keys(struct pmic8xxx_kp *kp, u16 *new_state)
{
int row, found_first = -1;
u16 check, row_state;
check = 0;
for (row = 0; row < kp->pdata->num_rows; row++) {
row_state = (~new_state[row]) &
((1 << kp->pdata->num_cols) - 1);
if (hweight16(row_state) > 1) {
if (found_first == -1)
found_first = row;
if (check & row_state) {
dev_dbg(kp->dev, "detected ghost key on row[%d]"
" and row[%d]\n", found_first, row);
return true;
}
}
check |= row_state;
}
return false;
}
static int pmic8xxx_kp_scan_matrix(struct pmic8xxx_kp *kp, unsigned int events)
{
u16 new_state[PM8XXX_MAX_ROWS];
u16 old_state[PM8XXX_MAX_ROWS];
int rc;
switch (events) {
case 0x1:
rc = pmic8xxx_kp_read_matrix(kp, new_state, NULL);
if (rc < 0)
return rc;
/* detecting ghost key is not an error */
if (pmic8xxx_detect_ghost_keys(kp, new_state))
return 0;
__pmic8xxx_kp_scan_matrix(kp, new_state, kp->keystate);
memcpy(kp->keystate, new_state, sizeof(new_state));
break;
case 0x3: /* two events - eventcounter is gray-coded */
rc = pmic8xxx_kp_read_matrix(kp, new_state, old_state);
if (rc < 0)
return rc;
__pmic8xxx_kp_scan_matrix(kp, old_state, kp->keystate);
__pmic8xxx_kp_scan_matrix(kp, new_state, old_state);
memcpy(kp->keystate, new_state, sizeof(new_state));
break;
case 0x2:
dev_dbg(kp->dev, "Some key events were lost\n");
rc = pmic8xxx_kp_read_matrix(kp, new_state, old_state);
if (rc < 0)
return rc;
__pmic8xxx_kp_scan_matrix(kp, old_state, kp->keystate);
__pmic8xxx_kp_scan_matrix(kp, new_state, old_state);
memcpy(kp->keystate, new_state, sizeof(new_state));
break;
default:
rc = -EINVAL;
}
return rc;
}
/*
* NOTE: We are reading recent and old data registers blindly
* whenever key-stuck interrupt happens, because events counter doesn't
* get updated when this interrupt happens due to key stuck doesn't get
* considered as key state change.
*
* We are not using old data register contents after they are being read
* because it might report the key which was pressed before the key being stuck
* as stuck key because it's pressed status is stored in the old data
* register.
*/
static irqreturn_t pmic8xxx_kp_stuck_irq(int irq, void *data)
{
u16 new_state[PM8XXX_MAX_ROWS];
u16 old_state[PM8XXX_MAX_ROWS];
int rc;
struct pmic8xxx_kp *kp = data;
rc = pmic8xxx_kp_read_matrix(kp, new_state, old_state);
if (rc < 0) {
dev_err(kp->dev, "failed to read keypad matrix\n");
return IRQ_HANDLED;
}
__pmic8xxx_kp_scan_matrix(kp, new_state, kp->stuckstate);
return IRQ_HANDLED;
}
static irqreturn_t pmic8xxx_kp_irq(int irq, void *data)
{
struct pmic8xxx_kp *kp = data;
u8 ctrl_val, events;
int rc;
rc = pmic8xxx_kp_read(kp, &ctrl_val, KEYP_CTRL, 1);
if (rc < 0) {
dev_err(kp->dev, "failed to read keyp_ctrl register\n");
return IRQ_HANDLED;
}
events = ctrl_val & KEYP_CTRL_EVNTS_MASK;
rc = pmic8xxx_kp_scan_matrix(kp, events);
if (rc < 0)
dev_err(kp->dev, "failed to scan matrix\n");
return IRQ_HANDLED;
}
static int __devinit pmic8xxx_kpd_init(struct pmic8xxx_kp *kp)
{
int bits, rc, cycles;
u8 scan_val = 0, ctrl_val = 0;
static const u8 row_bits[] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 7,
};
/* Find column bits */
if (kp->pdata->num_cols < KEYP_CTRL_SCAN_COLS_MIN)
bits = 0;
else
bits = kp->pdata->num_cols - KEYP_CTRL_SCAN_COLS_MIN;
ctrl_val = (bits & KEYP_CTRL_SCAN_COLS_BITS) <<
KEYP_CTRL_SCAN_COLS_SHIFT;
/* Find row bits */
if (kp->pdata->num_rows < KEYP_CTRL_SCAN_ROWS_MIN)
bits = 0;
else
bits = row_bits[kp->pdata->num_rows - KEYP_CTRL_SCAN_ROWS_MIN];
ctrl_val |= (bits << KEYP_CTRL_SCAN_ROWS_SHIFT);
rc = pmic8xxx_kp_write_u8(kp, ctrl_val, KEYP_CTRL);
if (rc < 0) {
dev_err(kp->dev, "Error writing KEYP_CTRL reg, rc=%d\n", rc);
return rc;
}
bits = (kp->pdata->debounce_ms / 5) - 1;
scan_val |= (bits << KEYP_SCAN_DBOUNCE_SHIFT);
bits = fls(kp->pdata->scan_delay_ms) - 1;
scan_val |= (bits << KEYP_SCAN_PAUSE_SHIFT);
/* Row hold time is a multiple of 32KHz cycles. */
cycles = (kp->pdata->row_hold_ns * KEYP_CLOCK_FREQ) / NSEC_PER_SEC;
scan_val |= (cycles << KEYP_SCAN_ROW_HOLD_SHIFT);
rc = pmic8xxx_kp_write_u8(kp, scan_val, KEYP_SCAN);
if (rc)
dev_err(kp->dev, "Error writing KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
static int __devinit pmic8xxx_kp_config_gpio(int gpio_start, int num_gpios,
struct pmic8xxx_kp *kp, struct pm_gpio *gpio_config)
{
int rc, i;
if (gpio_start < 0 || num_gpios < 0)
return -EINVAL;
for (i = 0; i < num_gpios; i++) {
rc = pm8xxx_gpio_config(gpio_start + i, gpio_config);
if (rc) {
dev_err(kp->dev, "%s: FAIL pm8xxx_gpio_config():"
"for PM GPIO [%d] rc=%d.\n",
__func__, gpio_start + i, rc);
return rc;
}
}
return 0;
}
static int pmic8xxx_kp_enable(struct pmic8xxx_kp *kp)
{
int rc;
kp->ctrl_reg |= KEYP_CTRL_KEYP_EN;
rc = pmic8xxx_kp_write_u8(kp, kp->ctrl_reg, KEYP_CTRL);
if (rc < 0)
dev_err(kp->dev, "Error writing KEYP_CTRL reg, rc=%d\n", rc);
return rc;
}
static int pmic8xxx_kp_disable(struct pmic8xxx_kp *kp)
{
int rc;
kp->ctrl_reg &= ~KEYP_CTRL_KEYP_EN;
rc = pmic8xxx_kp_write_u8(kp, kp->ctrl_reg, KEYP_CTRL);
if (rc < 0)
return rc;
return rc;
}
static int pmic8xxx_kp_open(struct input_dev *dev)
{
struct pmic8xxx_kp *kp = input_get_drvdata(dev);
return pmic8xxx_kp_enable(kp);
}
static void pmic8xxx_kp_close(struct input_dev *dev)
{
struct pmic8xxx_kp *kp = input_get_drvdata(dev);
pmic8xxx_kp_disable(kp);
}
/*
* keypad controller should be initialized in the following sequence
* only, otherwise it might get into FSM stuck state.
*
* - Initialize keypad control parameters, like no. of rows, columns,
* timing values etc.,
* - configure rows and column gpios pull up/down.
* - set irq edge type.
* - enable the keypad controller.
*/
static int __devinit pmic8xxx_kp_probe(struct platform_device *pdev)
{
const struct pm8xxx_keypad_platform_data *pdata =
dev_get_platdata(&pdev->dev);
const struct matrix_keymap_data *keymap_data;
struct pmic8xxx_kp *kp;
int rc;
u8 ctrl_val;
struct pm_gpio kypd_drv = {
.direction = PM_GPIO_DIR_OUT,
.output_buffer = PM_GPIO_OUT_BUF_OPEN_DRAIN,
.output_value = 0,
.pull = PM_GPIO_PULL_NO,
.vin_sel = PM_GPIO_VIN_S3,
.out_strength = PM_GPIO_STRENGTH_LOW,
.function = PM_GPIO_FUNC_1,
.inv_int_pol = 1,
};
struct pm_gpio kypd_sns = {
.direction = PM_GPIO_DIR_IN,
.pull = PM_GPIO_PULL_UP_31P5,
.vin_sel = PM_GPIO_VIN_S3,
.out_strength = PM_GPIO_STRENGTH_NO,
.function = PM_GPIO_FUNC_NORMAL,
.inv_int_pol = 1,
};
if (!pdata || !pdata->num_cols || !pdata->num_rows ||
pdata->num_cols > PM8XXX_MAX_COLS ||
pdata->num_rows > PM8XXX_MAX_ROWS ||
pdata->num_cols < PM8XXX_MIN_COLS) {
dev_err(&pdev->dev, "invalid platform data\n");
return -EINVAL;
}
if (!pdata->scan_delay_ms ||
pdata->scan_delay_ms > MAX_SCAN_DELAY ||
pdata->scan_delay_ms < MIN_SCAN_DELAY ||
!is_power_of_2(pdata->scan_delay_ms)) {
dev_err(&pdev->dev, "invalid keypad scan time supplied\n");
return -EINVAL;
}
if (!pdata->row_hold_ns ||
pdata->row_hold_ns > MAX_ROW_HOLD_DELAY ||
pdata->row_hold_ns < MIN_ROW_HOLD_DELAY ||
((pdata->row_hold_ns % MIN_ROW_HOLD_DELAY) != 0)) {
dev_err(&pdev->dev, "invalid keypad row hold time supplied\n");
return -EINVAL;
}
if (!pdata->debounce_ms ||
((pdata->debounce_ms % 5) != 0) ||
pdata->debounce_ms > MAX_DEBOUNCE_TIME ||
pdata->debounce_ms < MIN_DEBOUNCE_TIME) {
dev_err(&pdev->dev, "invalid debounce time supplied\n");
return -EINVAL;
}
keymap_data = pdata->keymap_data;
if (!keymap_data) {
dev_err(&pdev->dev, "no keymap data supplied\n");
return -EINVAL;
}
kp = kzalloc(sizeof(*kp), GFP_KERNEL);
if (!kp)
return -ENOMEM;
platform_set_drvdata(pdev, kp);
kp->pdata = pdata;
kp->dev = &pdev->dev;
kp->input = input_allocate_device();
if (!kp->input) {
dev_err(&pdev->dev, "unable to allocate input device\n");
rc = -ENOMEM;
goto err_alloc_device;
}
kp->key_sense_irq = platform_get_irq(pdev, 0);
if (kp->key_sense_irq < 0) {
dev_err(&pdev->dev, "unable to get keypad sense irq\n");
rc = -ENXIO;
goto err_get_irq;
}
kp->key_stuck_irq = platform_get_irq(pdev, 1);
if (kp->key_stuck_irq < 0) {
dev_err(&pdev->dev, "unable to get keypad stuck irq\n");
rc = -ENXIO;
goto err_get_irq;
}
kp->input->name = pdata->input_name ? : "PMIC8XXX keypad";
kp->input->phys = pdata->input_phys_device ? : "pmic8xxx_keypad/input0";
kp->input->dev.parent = &pdev->dev;
kp->input->id.bustype = BUS_I2C;
kp->input->id.version = 0x0001;
kp->input->id.product = 0x0001;
kp->input->id.vendor = 0x0001;
kp->input->evbit[0] = BIT_MASK(EV_KEY);
if (pdata->rep)
__set_bit(EV_REP, kp->input->evbit);
kp->input->keycode = kp->keycodes;
kp->input->keycodemax = PM8XXX_MATRIX_MAX_SIZE;
kp->input->keycodesize = sizeof(kp->keycodes);
kp->input->open = pmic8xxx_kp_open;
kp->input->close = pmic8xxx_kp_close;
matrix_keypad_build_keymap(keymap_data, PM8XXX_ROW_SHIFT,
kp->input->keycode, kp->input->keybit);
input_set_capability(kp->input, EV_MSC, MSC_SCAN);
input_set_drvdata(kp->input, kp);
/* initialize keypad state */
memset(kp->keystate, 0xff, sizeof(kp->keystate));
memset(kp->stuckstate, 0xff, sizeof(kp->stuckstate));
rc = pmic8xxx_kpd_init(kp);
if (rc < 0) {
dev_err(&pdev->dev, "unable to initialize keypad controller\n");
goto err_get_irq;
}
rc = pmic8xxx_kp_config_gpio(pdata->cols_gpio_start,
pdata->num_cols, kp, &kypd_sns);
if (rc < 0) {
dev_err(&pdev->dev, "unable to configure keypad sense lines\n");
goto err_gpio_config;
}
rc = pmic8xxx_kp_config_gpio(pdata->rows_gpio_start,
pdata->num_rows, kp, &kypd_drv);
if (rc < 0) {
dev_err(&pdev->dev, "unable to configure keypad drive lines\n");
goto err_gpio_config;
}
rc = request_any_context_irq(kp->key_sense_irq, pmic8xxx_kp_irq,
IRQF_TRIGGER_RISING, "pmic-keypad", kp);
if (rc < 0) {
dev_err(&pdev->dev, "failed to request keypad sense irq\n");
goto err_get_irq;
}
rc = request_any_context_irq(kp->key_stuck_irq, pmic8xxx_kp_stuck_irq,
IRQF_TRIGGER_RISING, "pmic-keypad-stuck", kp);
if (rc < 0) {
dev_err(&pdev->dev, "failed to request keypad stuck irq\n");
goto err_req_stuck_irq;
}
rc = pmic8xxx_kp_read_u8(kp, &ctrl_val, KEYP_CTRL);
if (rc < 0) {
dev_err(&pdev->dev, "failed to read KEYP_CTRL register\n");
goto err_pmic_reg_read;
}
kp->ctrl_reg = ctrl_val;
rc = input_register_device(kp->input);
if (rc < 0) {
dev_err(&pdev->dev, "unable to register keypad input device\n");
goto err_pmic_reg_read;
}
device_init_wakeup(&pdev->dev, pdata->wakeup);
return 0;
err_pmic_reg_read:
free_irq(kp->key_stuck_irq, NULL);
err_req_stuck_irq:
free_irq(kp->key_sense_irq, NULL);
err_gpio_config:
err_get_irq:
input_free_device(kp->input);
err_alloc_device:
platform_set_drvdata(pdev, NULL);
kfree(kp);
return rc;
}
static int __devexit pmic8xxx_kp_remove(struct platform_device *pdev)
{
struct pmic8xxx_kp *kp = platform_get_drvdata(pdev);
device_init_wakeup(&pdev->dev, 0);
free_irq(kp->key_stuck_irq, NULL);
free_irq(kp->key_sense_irq, NULL);
input_unregister_device(kp->input);
kfree(kp);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int pmic8xxx_kp_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct pmic8xxx_kp *kp = platform_get_drvdata(pdev);
struct input_dev *input_dev = kp->input;
if (device_may_wakeup(dev)) {
enable_irq_wake(kp->key_sense_irq);
} else {
mutex_lock(&input_dev->mutex);
if (input_dev->users)
pmic8xxx_kp_disable(kp);
mutex_unlock(&input_dev->mutex);
}
return 0;
}
static int pmic8xxx_kp_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct pmic8xxx_kp *kp = platform_get_drvdata(pdev);
struct input_dev *input_dev = kp->input;
if (device_may_wakeup(dev)) {
disable_irq_wake(kp->key_sense_irq);
} else {
mutex_lock(&input_dev->mutex);
if (input_dev->users)
pmic8xxx_kp_enable(kp);
mutex_unlock(&input_dev->mutex);
}
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(pm8xxx_kp_pm_ops,
pmic8xxx_kp_suspend, pmic8xxx_kp_resume);
static struct platform_driver pmic8xxx_kp_driver = {
.probe = pmic8xxx_kp_probe,
.remove = __devexit_p(pmic8xxx_kp_remove),
.driver = {
.name = PM8XXX_KEYPAD_DEV_NAME,
.owner = THIS_MODULE,
.pm = &pm8xxx_kp_pm_ops,
},
};
static int __init pmic8xxx_kp_init(void)
{
return platform_driver_register(&pmic8xxx_kp_driver);
}
module_init(pmic8xxx_kp_init);
static void __exit pmic8xxx_kp_exit(void)
{
platform_driver_unregister(&pmic8xxx_kp_driver);
}
module_exit(pmic8xxx_kp_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("PMIC8XXX keypad driver");
MODULE_VERSION("1.0");
MODULE_ALIAS("platform:pmic8xxx_keypad");
MODULE_AUTHOR("Trilok Soni <tsoni@codeaurora.org>");
| gpl-2.0 |
gundal/zerofltetmo | drivers/usb/host/ohci-omap3.c | 2079 | 6505 | /*
* ohci-omap3.c - driver for OHCI on OMAP3 and later processors
*
* Bus Glue for OMAP3 USBHOST 3 port OHCI controller
* This controller is also used in later OMAPs and AM35x chips
*
* Copyright (C) 2007-2010 Texas Instruments, Inc.
* Author: Vikram Pandita <vikram.pandita@ti.com>
* Author: Anand Gadiyar <gadiyar@ti.com>
* Author: Keshava Munegowda <keshava_mgowda@ti.com>
*
* Based on ehci-omap.c and some other ohci glue layers
*
* 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
*
* TODO (last updated Feb 27, 2011):
* - add kernel-doc
*/
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/of.h>
#include <linux/dma-mapping.h>
/*-------------------------------------------------------------------------*/
static int ohci_omap3_init(struct usb_hcd *hcd)
{
dev_dbg(hcd->self.controller, "starting OHCI controller\n");
return ohci_init(hcd_to_ohci(hcd));
}
/*-------------------------------------------------------------------------*/
static int ohci_omap3_start(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
int ret;
/*
* RemoteWakeupConnected has to be set explicitly before
* calling ohci_run. The reset value of RWC is 0.
*/
ohci->hc_control = OHCI_CTRL_RWC;
writel(OHCI_CTRL_RWC, &ohci->regs->control);
ret = ohci_run(ohci);
if (ret < 0) {
dev_err(hcd->self.controller, "can't start\n");
ohci_stop(hcd);
}
return ret;
}
/*-------------------------------------------------------------------------*/
static const struct hc_driver ohci_omap3_hc_driver = {
.description = hcd_name,
.product_desc = "OMAP3 OHCI Host Controller",
.hcd_priv_size = sizeof(struct ohci_hcd),
/*
* generic hardware linkage
*/
.irq = ohci_irq,
.flags = HCD_USB11 | HCD_MEMORY,
/*
* basic lifecycle operations
*/
.reset = ohci_omap3_init,
.start = ohci_omap3_start,
.stop = ohci_stop,
.shutdown = ohci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
/*
* scheduling support
*/
.get_frame_number = ohci_get_frame,
/*
* root hub support
*/
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
/*-------------------------------------------------------------------------*/
/*
* configure so an HC device and id are always provided
* always called with process context; sleeping is OK
*/
/**
* ohci_hcd_omap3_probe - initialize OMAP-based HCDs
*
* Allocates basic resources for this USB host controller, and
* then invokes the start() method for the HCD associated with it
* through the hotplug entry's driver_data.
*/
static int ohci_hcd_omap3_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct usb_hcd *hcd = NULL;
void __iomem *regs = NULL;
struct resource *res;
int ret = -ENODEV;
int irq;
if (usb_disabled())
return -ENODEV;
if (!dev->parent) {
dev_err(dev, "Missing parent device\n");
return -ENODEV;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "OHCI irq failed\n");
return -ENODEV;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "UHH OHCI get resource failed\n");
return -ENOMEM;
}
regs = ioremap(res->start, resource_size(res));
if (!regs) {
dev_err(dev, "UHH OHCI ioremap failed\n");
return -ENOMEM;
}
/*
* Right now device-tree probed devices don't get dma_mask set.
* Since shared usb code relies on it, set it here for now.
* Once we have dma capability bindings this can go away.
*/
if (!dev->dma_mask)
dev->dma_mask = &dev->coherent_dma_mask;
if (!dev->coherent_dma_mask)
dev->coherent_dma_mask = DMA_BIT_MASK(32);
hcd = usb_create_hcd(&ohci_omap3_hc_driver, dev,
dev_name(dev));
if (!hcd) {
dev_err(dev, "usb_create_hcd failed\n");
goto err_io;
}
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
hcd->regs = regs;
pm_runtime_enable(dev);
pm_runtime_get_sync(dev);
ohci_hcd_init(hcd_to_ohci(hcd));
ret = usb_add_hcd(hcd, irq, 0);
if (ret) {
dev_dbg(dev, "failed to add hcd with err %d\n", ret);
goto err_add_hcd;
}
return 0;
err_add_hcd:
pm_runtime_put_sync(dev);
usb_put_hcd(hcd);
err_io:
iounmap(regs);
return ret;
}
/*
* may be called without controller electrically present
* may be called with controller, bus, and devices active
*/
/**
* ohci_hcd_omap3_remove - shutdown processing for OHCI HCDs
* @pdev: USB Host Controller being removed
*
* Reverses the effect of ohci_hcd_omap3_probe(), first invoking
* the HCD's stop() method. It is always called from a thread
* context, normally "rmmod", "apmd", or something similar.
*/
static int ohci_hcd_omap3_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct usb_hcd *hcd = dev_get_drvdata(dev);
iounmap(hcd->regs);
usb_remove_hcd(hcd);
pm_runtime_put_sync(dev);
pm_runtime_disable(dev);
usb_put_hcd(hcd);
return 0;
}
static void ohci_hcd_omap3_shutdown(struct platform_device *pdev)
{
struct usb_hcd *hcd = dev_get_drvdata(&pdev->dev);
if (hcd->driver->shutdown)
hcd->driver->shutdown(hcd);
}
static const struct of_device_id omap_ohci_dt_ids[] = {
{ .compatible = "ti,ohci-omap3" },
{ }
};
MODULE_DEVICE_TABLE(of, omap_ohci_dt_ids);
static struct platform_driver ohci_hcd_omap3_driver = {
.probe = ohci_hcd_omap3_probe,
.remove = ohci_hcd_omap3_remove,
.shutdown = ohci_hcd_omap3_shutdown,
.driver = {
.name = "ohci-omap3",
.of_match_table = of_match_ptr(omap_ohci_dt_ids),
},
};
MODULE_ALIAS("platform:ohci-omap3");
MODULE_AUTHOR("Anand Gadiyar <gadiyar@ti.com>");
| gpl-2.0 |
OwnROM-Devices/android_kernel_samsung_golden | net/tipc/config.c | 3103 | 14905 | /*
* net/tipc/config.c: TIPC configuration management code
*
* Copyright (c) 2002-2006, Ericsson AB
* Copyright (c) 2004-2007, 2010-2011, Wind River Systems
* 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.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "core.h"
#include "port.h"
#include "name_table.h"
#include "config.h"
static u32 config_port_ref;
static DEFINE_SPINLOCK(config_lock);
static const void *req_tlv_area; /* request message TLV area */
static int req_tlv_space; /* request message TLV area size */
static int rep_headroom; /* reply message headroom to use */
struct sk_buff *tipc_cfg_reply_alloc(int payload_size)
{
struct sk_buff *buf;
buf = alloc_skb(rep_headroom + payload_size, GFP_ATOMIC);
if (buf)
skb_reserve(buf, rep_headroom);
return buf;
}
int tipc_cfg_append_tlv(struct sk_buff *buf, int tlv_type,
void *tlv_data, int tlv_data_size)
{
struct tlv_desc *tlv = (struct tlv_desc *)skb_tail_pointer(buf);
int new_tlv_space = TLV_SPACE(tlv_data_size);
if (skb_tailroom(buf) < new_tlv_space)
return 0;
skb_put(buf, new_tlv_space);
tlv->tlv_type = htons(tlv_type);
tlv->tlv_len = htons(TLV_LENGTH(tlv_data_size));
if (tlv_data_size && tlv_data)
memcpy(TLV_DATA(tlv), tlv_data, tlv_data_size);
return 1;
}
static struct sk_buff *tipc_cfg_reply_unsigned_type(u16 tlv_type, u32 value)
{
struct sk_buff *buf;
__be32 value_net;
buf = tipc_cfg_reply_alloc(TLV_SPACE(sizeof(value)));
if (buf) {
value_net = htonl(value);
tipc_cfg_append_tlv(buf, tlv_type, &value_net,
sizeof(value_net));
}
return buf;
}
static struct sk_buff *tipc_cfg_reply_unsigned(u32 value)
{
return tipc_cfg_reply_unsigned_type(TIPC_TLV_UNSIGNED, value);
}
struct sk_buff *tipc_cfg_reply_string_type(u16 tlv_type, char *string)
{
struct sk_buff *buf;
int string_len = strlen(string) + 1;
buf = tipc_cfg_reply_alloc(TLV_SPACE(string_len));
if (buf)
tipc_cfg_append_tlv(buf, tlv_type, string, string_len);
return buf;
}
#define MAX_STATS_INFO 2000
static struct sk_buff *tipc_show_stats(void)
{
struct sk_buff *buf;
struct tlv_desc *rep_tlv;
struct print_buf pb;
int str_len;
u32 value;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_UNSIGNED))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
value = ntohl(*(u32 *)TLV_DATA(req_tlv_area));
if (value != 0)
return tipc_cfg_reply_error_string("unsupported argument");
buf = tipc_cfg_reply_alloc(TLV_SPACE(MAX_STATS_INFO));
if (buf == NULL)
return NULL;
rep_tlv = (struct tlv_desc *)buf->data;
tipc_printbuf_init(&pb, (char *)TLV_DATA(rep_tlv), MAX_STATS_INFO);
tipc_printf(&pb, "TIPC version " TIPC_MOD_VER "\n");
/* Use additional tipc_printf()'s to return more info ... */
str_len = tipc_printbuf_validate(&pb);
skb_put(buf, TLV_SPACE(str_len));
TLV_SET(rep_tlv, TIPC_TLV_ULTRA_STRING, NULL, str_len);
return buf;
}
static struct sk_buff *cfg_enable_bearer(void)
{
struct tipc_bearer_config *args;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_BEARER_CONFIG))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
args = (struct tipc_bearer_config *)TLV_DATA(req_tlv_area);
if (tipc_enable_bearer(args->name,
ntohl(args->disc_domain),
ntohl(args->priority)))
return tipc_cfg_reply_error_string("unable to enable bearer");
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_disable_bearer(void)
{
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_BEARER_NAME))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
if (tipc_disable_bearer((char *)TLV_DATA(req_tlv_area)))
return tipc_cfg_reply_error_string("unable to disable bearer");
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_set_own_addr(void)
{
u32 addr;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_NET_ADDR))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
addr = ntohl(*(__be32 *)TLV_DATA(req_tlv_area));
if (addr == tipc_own_addr)
return tipc_cfg_reply_none();
if (!tipc_addr_node_valid(addr))
return tipc_cfg_reply_error_string(TIPC_CFG_INVALID_VALUE
" (node address)");
if (tipc_mode == TIPC_NET_MODE)
return tipc_cfg_reply_error_string(TIPC_CFG_NOT_SUPPORTED
" (cannot change node address once assigned)");
/*
* Must release all spinlocks before calling start_net() because
* Linux version of TIPC calls eth_media_start() which calls
* register_netdevice_notifier() which may block!
*
* Temporarily releasing the lock should be harmless for non-Linux TIPC,
* but Linux version of eth_media_start() should really be reworked
* so that it can be called with spinlocks held.
*/
spin_unlock_bh(&config_lock);
tipc_core_start_net(addr);
spin_lock_bh(&config_lock);
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_set_remote_mng(void)
{
u32 value;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_UNSIGNED))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
value = ntohl(*(__be32 *)TLV_DATA(req_tlv_area));
tipc_remote_management = (value != 0);
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_set_max_publications(void)
{
u32 value;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_UNSIGNED))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
value = ntohl(*(__be32 *)TLV_DATA(req_tlv_area));
if (value != delimit(value, 1, 65535))
return tipc_cfg_reply_error_string(TIPC_CFG_INVALID_VALUE
" (max publications must be 1-65535)");
tipc_max_publications = value;
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_set_max_subscriptions(void)
{
u32 value;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_UNSIGNED))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
value = ntohl(*(__be32 *)TLV_DATA(req_tlv_area));
if (value != delimit(value, 1, 65535))
return tipc_cfg_reply_error_string(TIPC_CFG_INVALID_VALUE
" (max subscriptions must be 1-65535");
tipc_max_subscriptions = value;
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_set_max_ports(void)
{
u32 value;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_UNSIGNED))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
value = ntohl(*(__be32 *)TLV_DATA(req_tlv_area));
if (value == tipc_max_ports)
return tipc_cfg_reply_none();
if (value != delimit(value, 127, 65535))
return tipc_cfg_reply_error_string(TIPC_CFG_INVALID_VALUE
" (max ports must be 127-65535)");
if (tipc_mode != TIPC_NOT_RUNNING)
return tipc_cfg_reply_error_string(TIPC_CFG_NOT_SUPPORTED
" (cannot change max ports while TIPC is active)");
tipc_max_ports = value;
return tipc_cfg_reply_none();
}
static struct sk_buff *cfg_set_netid(void)
{
u32 value;
if (!TLV_CHECK(req_tlv_area, req_tlv_space, TIPC_TLV_UNSIGNED))
return tipc_cfg_reply_error_string(TIPC_CFG_TLV_ERROR);
value = ntohl(*(__be32 *)TLV_DATA(req_tlv_area));
if (value == tipc_net_id)
return tipc_cfg_reply_none();
if (value != delimit(value, 1, 9999))
return tipc_cfg_reply_error_string(TIPC_CFG_INVALID_VALUE
" (network id must be 1-9999)");
if (tipc_mode == TIPC_NET_MODE)
return tipc_cfg_reply_error_string(TIPC_CFG_NOT_SUPPORTED
" (cannot change network id once TIPC has joined a network)");
tipc_net_id = value;
return tipc_cfg_reply_none();
}
struct sk_buff *tipc_cfg_do_cmd(u32 orig_node, u16 cmd, const void *request_area,
int request_space, int reply_headroom)
{
struct sk_buff *rep_tlv_buf;
spin_lock_bh(&config_lock);
/* Save request and reply details in a well-known location */
req_tlv_area = request_area;
req_tlv_space = request_space;
rep_headroom = reply_headroom;
/* Check command authorization */
if (likely(orig_node == tipc_own_addr)) {
/* command is permitted */
} else if (cmd >= 0x8000) {
rep_tlv_buf = tipc_cfg_reply_error_string(TIPC_CFG_NOT_SUPPORTED
" (cannot be done remotely)");
goto exit;
} else if (!tipc_remote_management) {
rep_tlv_buf = tipc_cfg_reply_error_string(TIPC_CFG_NO_REMOTE);
goto exit;
} else if (cmd >= 0x4000) {
u32 domain = 0;
if ((tipc_nametbl_translate(TIPC_ZM_SRV, 0, &domain) == 0) ||
(domain != orig_node)) {
rep_tlv_buf = tipc_cfg_reply_error_string(TIPC_CFG_NOT_ZONE_MSTR);
goto exit;
}
}
/* Call appropriate processing routine */
switch (cmd) {
case TIPC_CMD_NOOP:
rep_tlv_buf = tipc_cfg_reply_none();
break;
case TIPC_CMD_GET_NODES:
rep_tlv_buf = tipc_node_get_nodes(req_tlv_area, req_tlv_space);
break;
case TIPC_CMD_GET_LINKS:
rep_tlv_buf = tipc_node_get_links(req_tlv_area, req_tlv_space);
break;
case TIPC_CMD_SHOW_LINK_STATS:
rep_tlv_buf = tipc_link_cmd_show_stats(req_tlv_area, req_tlv_space);
break;
case TIPC_CMD_RESET_LINK_STATS:
rep_tlv_buf = tipc_link_cmd_reset_stats(req_tlv_area, req_tlv_space);
break;
case TIPC_CMD_SHOW_NAME_TABLE:
rep_tlv_buf = tipc_nametbl_get(req_tlv_area, req_tlv_space);
break;
case TIPC_CMD_GET_BEARER_NAMES:
rep_tlv_buf = tipc_bearer_get_names();
break;
case TIPC_CMD_GET_MEDIA_NAMES:
rep_tlv_buf = tipc_media_get_names();
break;
case TIPC_CMD_SHOW_PORTS:
rep_tlv_buf = tipc_port_get_ports();
break;
case TIPC_CMD_SET_LOG_SIZE:
rep_tlv_buf = tipc_log_resize_cmd(req_tlv_area, req_tlv_space);
break;
case TIPC_CMD_DUMP_LOG:
rep_tlv_buf = tipc_log_dump();
break;
case TIPC_CMD_SHOW_STATS:
rep_tlv_buf = tipc_show_stats();
break;
case TIPC_CMD_SET_LINK_TOL:
case TIPC_CMD_SET_LINK_PRI:
case TIPC_CMD_SET_LINK_WINDOW:
rep_tlv_buf = tipc_link_cmd_config(req_tlv_area, req_tlv_space, cmd);
break;
case TIPC_CMD_ENABLE_BEARER:
rep_tlv_buf = cfg_enable_bearer();
break;
case TIPC_CMD_DISABLE_BEARER:
rep_tlv_buf = cfg_disable_bearer();
break;
case TIPC_CMD_SET_NODE_ADDR:
rep_tlv_buf = cfg_set_own_addr();
break;
case TIPC_CMD_SET_REMOTE_MNG:
rep_tlv_buf = cfg_set_remote_mng();
break;
case TIPC_CMD_SET_MAX_PORTS:
rep_tlv_buf = cfg_set_max_ports();
break;
case TIPC_CMD_SET_MAX_PUBL:
rep_tlv_buf = cfg_set_max_publications();
break;
case TIPC_CMD_SET_MAX_SUBSCR:
rep_tlv_buf = cfg_set_max_subscriptions();
break;
case TIPC_CMD_SET_NETID:
rep_tlv_buf = cfg_set_netid();
break;
case TIPC_CMD_GET_REMOTE_MNG:
rep_tlv_buf = tipc_cfg_reply_unsigned(tipc_remote_management);
break;
case TIPC_CMD_GET_MAX_PORTS:
rep_tlv_buf = tipc_cfg_reply_unsigned(tipc_max_ports);
break;
case TIPC_CMD_GET_MAX_PUBL:
rep_tlv_buf = tipc_cfg_reply_unsigned(tipc_max_publications);
break;
case TIPC_CMD_GET_MAX_SUBSCR:
rep_tlv_buf = tipc_cfg_reply_unsigned(tipc_max_subscriptions);
break;
case TIPC_CMD_GET_NETID:
rep_tlv_buf = tipc_cfg_reply_unsigned(tipc_net_id);
break;
case TIPC_CMD_NOT_NET_ADMIN:
rep_tlv_buf =
tipc_cfg_reply_error_string(TIPC_CFG_NOT_NET_ADMIN);
break;
case TIPC_CMD_SET_MAX_ZONES:
case TIPC_CMD_GET_MAX_ZONES:
case TIPC_CMD_SET_MAX_SLAVES:
case TIPC_CMD_GET_MAX_SLAVES:
case TIPC_CMD_SET_MAX_CLUSTERS:
case TIPC_CMD_GET_MAX_CLUSTERS:
case TIPC_CMD_SET_MAX_NODES:
case TIPC_CMD_GET_MAX_NODES:
rep_tlv_buf = tipc_cfg_reply_error_string(TIPC_CFG_NOT_SUPPORTED
" (obsolete command)");
break;
default:
rep_tlv_buf = tipc_cfg_reply_error_string(TIPC_CFG_NOT_SUPPORTED
" (unknown command)");
break;
}
/* Return reply buffer */
exit:
spin_unlock_bh(&config_lock);
return rep_tlv_buf;
}
static void cfg_named_msg_event(void *userdata,
u32 port_ref,
struct sk_buff **buf,
const unchar *msg,
u32 size,
u32 importance,
struct tipc_portid const *orig,
struct tipc_name_seq const *dest)
{
struct tipc_cfg_msg_hdr *req_hdr;
struct tipc_cfg_msg_hdr *rep_hdr;
struct sk_buff *rep_buf;
/* Validate configuration message header (ignore invalid message) */
req_hdr = (struct tipc_cfg_msg_hdr *)msg;
if ((size < sizeof(*req_hdr)) ||
(size != TCM_ALIGN(ntohl(req_hdr->tcm_len))) ||
(ntohs(req_hdr->tcm_flags) != TCM_F_REQUEST)) {
warn("Invalid configuration message discarded\n");
return;
}
/* Generate reply for request (if can't, return request) */
rep_buf = tipc_cfg_do_cmd(orig->node,
ntohs(req_hdr->tcm_type),
msg + sizeof(*req_hdr),
size - sizeof(*req_hdr),
BUF_HEADROOM + MAX_H_SIZE + sizeof(*rep_hdr));
if (rep_buf) {
skb_push(rep_buf, sizeof(*rep_hdr));
rep_hdr = (struct tipc_cfg_msg_hdr *)rep_buf->data;
memcpy(rep_hdr, req_hdr, sizeof(*rep_hdr));
rep_hdr->tcm_len = htonl(rep_buf->len);
rep_hdr->tcm_flags &= htons(~TCM_F_REQUEST);
} else {
rep_buf = *buf;
*buf = NULL;
}
/* NEED TO ADD CODE TO HANDLE FAILED SEND (SUCH AS CONGESTION) */
tipc_send_buf2port(port_ref, orig, rep_buf, rep_buf->len);
}
int tipc_cfg_init(void)
{
struct tipc_name_seq seq;
int res;
res = tipc_createport(NULL, TIPC_CRITICAL_IMPORTANCE,
NULL, NULL, NULL,
NULL, cfg_named_msg_event, NULL,
NULL, &config_port_ref);
if (res)
goto failed;
seq.type = TIPC_CFG_SRV;
seq.lower = seq.upper = tipc_own_addr;
res = tipc_nametbl_publish_rsv(config_port_ref, TIPC_ZONE_SCOPE, &seq);
if (res)
goto failed;
return 0;
failed:
err("Unable to create configuration service\n");
return res;
}
void tipc_cfg_stop(void)
{
if (config_port_ref) {
tipc_deleteport(config_port_ref);
config_port_ref = 0;
}
}
| gpl-2.0 |
Dm47021/Android_kernel_f6mt_aosp_jb-rebase | arch/x86/power/cpu.c | 3359 | 6011 | /*
* Suspend support specific for i386/x86-64.
*
* Distribute under GPLv2
*
* Copyright (c) 2007 Rafael J. Wysocki <rjw@sisk.pl>
* Copyright (c) 2002 Pavel Machek <pavel@ucw.cz>
* Copyright (c) 2001 Patrick Mochel <mochel@osdl.org>
*/
#include <linux/suspend.h>
#include <linux/export.h>
#include <linux/smp.h>
#include <asm/pgtable.h>
#include <asm/proto.h>
#include <asm/mtrr.h>
#include <asm/page.h>
#include <asm/mce.h>
#include <asm/xcr.h>
#include <asm/suspend.h>
#include <asm/debugreg.h>
#include <asm/fpu-internal.h> /* pcntxt_mask */
#ifdef CONFIG_X86_32
static struct saved_context saved_context;
unsigned long saved_context_ebx;
unsigned long saved_context_esp, saved_context_ebp;
unsigned long saved_context_esi, saved_context_edi;
unsigned long saved_context_eflags;
#else
/* CONFIG_X86_64 */
struct saved_context saved_context;
#endif
/**
* __save_processor_state - save CPU registers before creating a
* hibernation image and before restoring the memory state from it
* @ctxt - structure to store the registers contents in
*
* NOTE: If there is a CPU register the modification of which by the
* boot kernel (ie. the kernel used for loading the hibernation image)
* might affect the operations of the restored target kernel (ie. the one
* saved in the hibernation image), then its contents must be saved by this
* function. In other words, if kernel A is hibernated and different
* kernel B is used for loading the hibernation image into memory, the
* kernel A's __save_processor_state() function must save all registers
* needed by kernel A, so that it can operate correctly after the resume
* regardless of what kernel B does in the meantime.
*/
static void __save_processor_state(struct saved_context *ctxt)
{
#ifdef CONFIG_X86_32
mtrr_save_fixed_ranges(NULL);
#endif
kernel_fpu_begin();
/*
* descriptor tables
*/
#ifdef CONFIG_X86_32
store_gdt(&ctxt->gdt);
store_idt(&ctxt->idt);
#else
/* CONFIG_X86_64 */
store_gdt((struct desc_ptr *)&ctxt->gdt_limit);
store_idt((struct desc_ptr *)&ctxt->idt_limit);
#endif
store_tr(ctxt->tr);
/* XMM0..XMM15 should be handled by kernel_fpu_begin(). */
/*
* segment registers
*/
#ifdef CONFIG_X86_32
savesegment(es, ctxt->es);
savesegment(fs, ctxt->fs);
savesegment(gs, ctxt->gs);
savesegment(ss, ctxt->ss);
#else
/* CONFIG_X86_64 */
asm volatile ("movw %%ds, %0" : "=m" (ctxt->ds));
asm volatile ("movw %%es, %0" : "=m" (ctxt->es));
asm volatile ("movw %%fs, %0" : "=m" (ctxt->fs));
asm volatile ("movw %%gs, %0" : "=m" (ctxt->gs));
asm volatile ("movw %%ss, %0" : "=m" (ctxt->ss));
rdmsrl(MSR_FS_BASE, ctxt->fs_base);
rdmsrl(MSR_GS_BASE, ctxt->gs_base);
rdmsrl(MSR_KERNEL_GS_BASE, ctxt->gs_kernel_base);
mtrr_save_fixed_ranges(NULL);
rdmsrl(MSR_EFER, ctxt->efer);
#endif
/*
* control registers
*/
ctxt->cr0 = read_cr0();
ctxt->cr2 = read_cr2();
ctxt->cr3 = read_cr3();
#ifdef CONFIG_X86_32
ctxt->cr4 = read_cr4_safe();
#else
/* CONFIG_X86_64 */
ctxt->cr4 = read_cr4();
ctxt->cr8 = read_cr8();
#endif
ctxt->misc_enable_saved = !rdmsrl_safe(MSR_IA32_MISC_ENABLE,
&ctxt->misc_enable);
}
/* Needed by apm.c */
void save_processor_state(void)
{
__save_processor_state(&saved_context);
x86_platform.save_sched_clock_state();
}
#ifdef CONFIG_X86_32
EXPORT_SYMBOL(save_processor_state);
#endif
static void do_fpu_end(void)
{
/*
* Restore FPU regs if necessary.
*/
kernel_fpu_end();
}
static void fix_processor_context(void)
{
int cpu = smp_processor_id();
struct tss_struct *t = &per_cpu(init_tss, cpu);
set_tss_desc(cpu, t); /*
* This just modifies memory; should not be
* necessary. But... This is necessary, because
* 386 hardware has concept of busy TSS or some
* similar stupidity.
*/
#ifdef CONFIG_X86_64
get_cpu_gdt_table(cpu)[GDT_ENTRY_TSS].type = 9;
syscall_init(); /* This sets MSR_*STAR and related */
#endif
load_TR_desc(); /* This does ltr */
load_LDT(¤t->active_mm->context); /* This does lldt */
}
/**
* __restore_processor_state - restore the contents of CPU registers saved
* by __save_processor_state()
* @ctxt - structure to load the registers contents from
*/
static void __restore_processor_state(struct saved_context *ctxt)
{
if (ctxt->misc_enable_saved)
wrmsrl(MSR_IA32_MISC_ENABLE, ctxt->misc_enable);
/*
* control registers
*/
/* cr4 was introduced in the Pentium CPU */
#ifdef CONFIG_X86_32
if (ctxt->cr4)
write_cr4(ctxt->cr4);
#else
/* CONFIG X86_64 */
wrmsrl(MSR_EFER, ctxt->efer);
write_cr8(ctxt->cr8);
write_cr4(ctxt->cr4);
#endif
write_cr3(ctxt->cr3);
write_cr2(ctxt->cr2);
write_cr0(ctxt->cr0);
/*
* now restore the descriptor tables to their proper values
* ltr is done i fix_processor_context().
*/
#ifdef CONFIG_X86_32
load_gdt(&ctxt->gdt);
load_idt(&ctxt->idt);
#else
/* CONFIG_X86_64 */
load_gdt((const struct desc_ptr *)&ctxt->gdt_limit);
load_idt((const struct desc_ptr *)&ctxt->idt_limit);
#endif
/*
* segment registers
*/
#ifdef CONFIG_X86_32
loadsegment(es, ctxt->es);
loadsegment(fs, ctxt->fs);
loadsegment(gs, ctxt->gs);
loadsegment(ss, ctxt->ss);
/*
* sysenter MSRs
*/
if (boot_cpu_has(X86_FEATURE_SEP))
enable_sep_cpu();
#else
/* CONFIG_X86_64 */
asm volatile ("movw %0, %%ds" :: "r" (ctxt->ds));
asm volatile ("movw %0, %%es" :: "r" (ctxt->es));
asm volatile ("movw %0, %%fs" :: "r" (ctxt->fs));
load_gs_index(ctxt->gs);
asm volatile ("movw %0, %%ss" :: "r" (ctxt->ss));
wrmsrl(MSR_FS_BASE, ctxt->fs_base);
wrmsrl(MSR_GS_BASE, ctxt->gs_base);
wrmsrl(MSR_KERNEL_GS_BASE, ctxt->gs_kernel_base);
#endif
/*
* restore XCR0 for xsave capable cpu's.
*/
if (cpu_has_xsave)
xsetbv(XCR_XFEATURE_ENABLED_MASK, pcntxt_mask);
fix_processor_context();
do_fpu_end();
x86_platform.restore_sched_clock_state();
mtrr_bp_restore();
}
/* Needed by apm.c */
void restore_processor_state(void)
{
__restore_processor_state(&saved_context);
}
#ifdef CONFIG_X86_32
EXPORT_SYMBOL(restore_processor_state);
#endif
| gpl-2.0 |
MoKee/android_kernel_samsung_lentislte | fs/ufs/util.c | 4127 | 6184 | /*
* linux/fs/ufs/util.c
*
* Copyright (C) 1998
* Daniel Pirkl <daniel.pirkl@email.cz>
* Charles University, Faculty of Mathematics and Physics
*/
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/buffer_head.h>
#include "ufs_fs.h"
#include "ufs.h"
#include "swab.h"
#include "util.h"
struct ufs_buffer_head * _ubh_bread_ (struct ufs_sb_private_info * uspi,
struct super_block *sb, u64 fragment, u64 size)
{
struct ufs_buffer_head * ubh;
unsigned i, j ;
u64 count = 0;
if (size & ~uspi->s_fmask)
return NULL;
count = size >> uspi->s_fshift;
if (count > UFS_MAXFRAG)
return NULL;
ubh = kmalloc (sizeof (struct ufs_buffer_head), GFP_NOFS);
if (!ubh)
return NULL;
ubh->fragment = fragment;
ubh->count = count;
for (i = 0; i < count; i++)
if (!(ubh->bh[i] = sb_bread(sb, fragment + i)))
goto failed;
for (; i < UFS_MAXFRAG; i++)
ubh->bh[i] = NULL;
return ubh;
failed:
for (j = 0; j < i; j++)
brelse (ubh->bh[j]);
kfree(ubh);
return NULL;
}
struct ufs_buffer_head * ubh_bread_uspi (struct ufs_sb_private_info * uspi,
struct super_block *sb, u64 fragment, u64 size)
{
unsigned i, j;
u64 count = 0;
if (size & ~uspi->s_fmask)
return NULL;
count = size >> uspi->s_fshift;
if (count <= 0 || count > UFS_MAXFRAG)
return NULL;
USPI_UBH(uspi)->fragment = fragment;
USPI_UBH(uspi)->count = count;
for (i = 0; i < count; i++)
if (!(USPI_UBH(uspi)->bh[i] = sb_bread(sb, fragment + i)))
goto failed;
for (; i < UFS_MAXFRAG; i++)
USPI_UBH(uspi)->bh[i] = NULL;
return USPI_UBH(uspi);
failed:
for (j = 0; j < i; j++)
brelse (USPI_UBH(uspi)->bh[j]);
return NULL;
}
void ubh_brelse (struct ufs_buffer_head * ubh)
{
unsigned i;
if (!ubh)
return;
for (i = 0; i < ubh->count; i++)
brelse (ubh->bh[i]);
kfree (ubh);
}
void ubh_brelse_uspi (struct ufs_sb_private_info * uspi)
{
unsigned i;
if (!USPI_UBH(uspi))
return;
for ( i = 0; i < USPI_UBH(uspi)->count; i++ ) {
brelse (USPI_UBH(uspi)->bh[i]);
USPI_UBH(uspi)->bh[i] = NULL;
}
}
void ubh_mark_buffer_dirty (struct ufs_buffer_head * ubh)
{
unsigned i;
if (!ubh)
return;
for ( i = 0; i < ubh->count; i++ )
mark_buffer_dirty (ubh->bh[i]);
}
void ubh_mark_buffer_uptodate (struct ufs_buffer_head * ubh, int flag)
{
unsigned i;
if (!ubh)
return;
if (flag) {
for ( i = 0; i < ubh->count; i++ )
set_buffer_uptodate (ubh->bh[i]);
} else {
for ( i = 0; i < ubh->count; i++ )
clear_buffer_uptodate (ubh->bh[i]);
}
}
void ubh_sync_block(struct ufs_buffer_head *ubh)
{
if (ubh) {
unsigned i;
for (i = 0; i < ubh->count; i++)
write_dirty_buffer(ubh->bh[i], WRITE);
for (i = 0; i < ubh->count; i++)
wait_on_buffer(ubh->bh[i]);
}
}
void ubh_bforget (struct ufs_buffer_head * ubh)
{
unsigned i;
if (!ubh)
return;
for ( i = 0; i < ubh->count; i++ ) if ( ubh->bh[i] )
bforget (ubh->bh[i]);
}
int ubh_buffer_dirty (struct ufs_buffer_head * ubh)
{
unsigned i;
unsigned result = 0;
if (!ubh)
return 0;
for ( i = 0; i < ubh->count; i++ )
result |= buffer_dirty(ubh->bh[i]);
return result;
}
void _ubh_ubhcpymem_(struct ufs_sb_private_info * uspi,
unsigned char * mem, struct ufs_buffer_head * ubh, unsigned size)
{
unsigned len, bhno;
if (size > (ubh->count << uspi->s_fshift))
size = ubh->count << uspi->s_fshift;
bhno = 0;
while (size) {
len = min_t(unsigned int, size, uspi->s_fsize);
memcpy (mem, ubh->bh[bhno]->b_data, len);
mem += uspi->s_fsize;
size -= len;
bhno++;
}
}
void _ubh_memcpyubh_(struct ufs_sb_private_info * uspi,
struct ufs_buffer_head * ubh, unsigned char * mem, unsigned size)
{
unsigned len, bhno;
if (size > (ubh->count << uspi->s_fshift))
size = ubh->count << uspi->s_fshift;
bhno = 0;
while (size) {
len = min_t(unsigned int, size, uspi->s_fsize);
memcpy (ubh->bh[bhno]->b_data, mem, len);
mem += uspi->s_fsize;
size -= len;
bhno++;
}
}
dev_t
ufs_get_inode_dev(struct super_block *sb, struct ufs_inode_info *ufsi)
{
__u32 fs32;
dev_t dev;
if ((UFS_SB(sb)->s_flags & UFS_ST_MASK) == UFS_ST_SUNx86)
fs32 = fs32_to_cpu(sb, ufsi->i_u1.i_data[1]);
else
fs32 = fs32_to_cpu(sb, ufsi->i_u1.i_data[0]);
switch (UFS_SB(sb)->s_flags & UFS_ST_MASK) {
case UFS_ST_SUNx86:
case UFS_ST_SUN:
if ((fs32 & 0xffff0000) == 0 ||
(fs32 & 0xffff0000) == 0xffff0000)
dev = old_decode_dev(fs32 & 0x7fff);
else
dev = MKDEV(sysv_major(fs32), sysv_minor(fs32));
break;
default:
dev = old_decode_dev(fs32);
break;
}
return dev;
}
void
ufs_set_inode_dev(struct super_block *sb, struct ufs_inode_info *ufsi, dev_t dev)
{
__u32 fs32;
switch (UFS_SB(sb)->s_flags & UFS_ST_MASK) {
case UFS_ST_SUNx86:
case UFS_ST_SUN:
fs32 = sysv_encode_dev(dev);
if ((fs32 & 0xffff8000) == 0) {
fs32 = old_encode_dev(dev);
}
break;
default:
fs32 = old_encode_dev(dev);
break;
}
if ((UFS_SB(sb)->s_flags & UFS_ST_MASK) == UFS_ST_SUNx86)
ufsi->i_u1.i_data[1] = cpu_to_fs32(sb, fs32);
else
ufsi->i_u1.i_data[0] = cpu_to_fs32(sb, fs32);
}
/**
* ufs_get_locked_page() - locate, pin and lock a pagecache page, if not exist
* read it from disk.
* @mapping: the address_space to search
* @index: the page index
*
* Locates the desired pagecache page, if not exist we'll read it,
* locks it, increments its reference
* count and returns its address.
*
*/
struct page *ufs_get_locked_page(struct address_space *mapping,
pgoff_t index)
{
struct page *page;
page = find_lock_page(mapping, index);
if (!page) {
page = read_mapping_page(mapping, index, NULL);
if (IS_ERR(page)) {
printk(KERN_ERR "ufs_change_blocknr: "
"read_mapping_page error: ino %lu, index: %lu\n",
mapping->host->i_ino, index);
goto out;
}
lock_page(page);
if (unlikely(page->mapping == NULL)) {
/* Truncate got there first */
unlock_page(page);
page_cache_release(page);
page = NULL;
goto out;
}
if (!PageUptodate(page) || PageError(page)) {
unlock_page(page);
page_cache_release(page);
printk(KERN_ERR "ufs_change_blocknr: "
"can not read page: ino %lu, index: %lu\n",
mapping->host->i_ino, index);
page = ERR_PTR(-EIO);
}
}
out:
return page;
}
| gpl-2.0 |
TeamBAMF/kernel_ics_omap | drivers/usb/storage/cypress_atacb.c | 4127 | 8391 | /*
* Support for emulating SAT (ata pass through) on devices based
* on the Cypress USB/ATA bridge supporting ATACB.
*
* Copyright (c) 2008 Matthieu Castet (castet.matthieu@free.fr)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include <linux/ata.h>
#include "usb.h"
#include "protocol.h"
#include "scsiglue.h"
#include "debug.h"
MODULE_DESCRIPTION("SAT support for Cypress USB/ATA bridges with ATACB");
MODULE_AUTHOR("Matthieu Castet <castet.matthieu@free.fr>");
MODULE_LICENSE("GPL");
/*
* The table of devices
*/
#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
vendorName, productName, useProtocol, useTransport, \
initFunction, flags) \
{ USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
.driver_info = (flags)|(USB_US_TYPE_STOR<<24) }
struct usb_device_id cypress_usb_ids[] = {
# include "unusual_cypress.h"
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, cypress_usb_ids);
#undef UNUSUAL_DEV
/*
* The flags table
*/
#define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
vendor_name, product_name, use_protocol, use_transport, \
init_function, Flags) \
{ \
.vendorName = vendor_name, \
.productName = product_name, \
.useProtocol = use_protocol, \
.useTransport = use_transport, \
.initFunction = init_function, \
}
static struct us_unusual_dev cypress_unusual_dev_list[] = {
# include "unusual_cypress.h"
{ } /* Terminating entry */
};
#undef UNUSUAL_DEV
/*
* ATACB is a protocol used on cypress usb<->ata bridge to
* send raw ATA command over mass storage
* There is a ATACB2 protocol that support LBA48 on newer chip.
* More info that be found on cy7c68310_8.pdf and cy7c68300c_8.pdf
* datasheet from cypress.com.
*/
static void cypress_atacb_passthrough(struct scsi_cmnd *srb, struct us_data *us)
{
unsigned char save_cmnd[MAX_COMMAND_SIZE];
if (likely(srb->cmnd[0] != ATA_16 && srb->cmnd[0] != ATA_12)) {
usb_stor_transparent_scsi_command(srb, us);
return;
}
memcpy(save_cmnd, srb->cmnd, sizeof(save_cmnd));
memset(srb->cmnd, 0, MAX_COMMAND_SIZE);
/* check if we support the command */
if (save_cmnd[1] >> 5) /* MULTIPLE_COUNT */
goto invalid_fld;
/* check protocol */
switch((save_cmnd[1] >> 1) & 0xf) {
case 3: /*no DATA */
case 4: /* PIO in */
case 5: /* PIO out */
break;
default:
goto invalid_fld;
}
/* first build the ATACB command */
srb->cmd_len = 16;
srb->cmnd[0] = 0x24; /* bVSCBSignature : vendor-specific command
this value can change, but most(all ?) manufacturers
keep the cypress default : 0x24 */
srb->cmnd[1] = 0x24; /* bVSCBSubCommand : 0x24 for ATACB */
srb->cmnd[3] = 0xff - 1; /* features, sector count, lba low, lba med
lba high, device, command are valid */
srb->cmnd[4] = 1; /* TransferBlockCount : 512 */
if (save_cmnd[0] == ATA_16) {
srb->cmnd[ 6] = save_cmnd[ 4]; /* features */
srb->cmnd[ 7] = save_cmnd[ 6]; /* sector count */
srb->cmnd[ 8] = save_cmnd[ 8]; /* lba low */
srb->cmnd[ 9] = save_cmnd[10]; /* lba med */
srb->cmnd[10] = save_cmnd[12]; /* lba high */
srb->cmnd[11] = save_cmnd[13]; /* device */
srb->cmnd[12] = save_cmnd[14]; /* command */
if (save_cmnd[1] & 0x01) {/* extended bit set for LBA48 */
/* this could be supported by atacb2 */
if (save_cmnd[3] || save_cmnd[5] || save_cmnd[7] || save_cmnd[9]
|| save_cmnd[11])
goto invalid_fld;
}
}
else { /* ATA12 */
srb->cmnd[ 6] = save_cmnd[3]; /* features */
srb->cmnd[ 7] = save_cmnd[4]; /* sector count */
srb->cmnd[ 8] = save_cmnd[5]; /* lba low */
srb->cmnd[ 9] = save_cmnd[6]; /* lba med */
srb->cmnd[10] = save_cmnd[7]; /* lba high */
srb->cmnd[11] = save_cmnd[8]; /* device */
srb->cmnd[12] = save_cmnd[9]; /* command */
}
/* Filter SET_FEATURES - XFER MODE command */
if ((srb->cmnd[12] == ATA_CMD_SET_FEATURES)
&& (srb->cmnd[6] == SETFEATURES_XFER))
goto invalid_fld;
if (srb->cmnd[12] == ATA_CMD_ID_ATA || srb->cmnd[12] == ATA_CMD_ID_ATAPI)
srb->cmnd[2] |= (1<<7); /* set IdentifyPacketDevice for these cmds */
usb_stor_transparent_scsi_command(srb, us);
/* if the device doesn't support ATACB
*/
if (srb->result == SAM_STAT_CHECK_CONDITION &&
memcmp(srb->sense_buffer, usb_stor_sense_invalidCDB,
sizeof(usb_stor_sense_invalidCDB)) == 0) {
US_DEBUGP("cypress atacb not supported ???\n");
goto end;
}
/* if ck_cond flags is set, and there wasn't critical error,
* build the special sense
*/
if ((srb->result != (DID_ERROR << 16) &&
srb->result != (DID_ABORT << 16)) &&
save_cmnd[2] & 0x20) {
struct scsi_eh_save ses;
unsigned char regs[8];
unsigned char *sb = srb->sense_buffer;
unsigned char *desc = sb + 8;
int tmp_result;
/* build the command for
* reading the ATA registers */
scsi_eh_prep_cmnd(srb, &ses, NULL, 0, sizeof(regs));
/* we use the same command as before, but we set
* the read taskfile bit, for not executing atacb command,
* but reading register selected in srb->cmnd[4]
*/
srb->cmd_len = 16;
srb->cmnd = ses.cmnd;
srb->cmnd[2] = 1;
usb_stor_transparent_scsi_command(srb, us);
memcpy(regs, srb->sense_buffer, sizeof(regs));
tmp_result = srb->result;
scsi_eh_restore_cmnd(srb, &ses);
/* we fail to get registers, report invalid command */
if (tmp_result != SAM_STAT_GOOD)
goto invalid_fld;
/* build the sense */
memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
/* set sk, asc for a good command */
sb[1] = RECOVERED_ERROR;
sb[2] = 0; /* ATA PASS THROUGH INFORMATION AVAILABLE */
sb[3] = 0x1D;
/* XXX we should generate sk, asc, ascq from status and error
* regs
* (see 11.1 Error translation ATA device error to SCSI error
* map, and ata_to_sense_error from libata.)
*/
/* Sense data is current and format is descriptor. */
sb[0] = 0x72;
desc[0] = 0x09; /* ATA_RETURN_DESCRIPTOR */
/* set length of additional sense data */
sb[7] = 14;
desc[1] = 12;
/* Copy registers into sense buffer. */
desc[ 2] = 0x00;
desc[ 3] = regs[1]; /* features */
desc[ 5] = regs[2]; /* sector count */
desc[ 7] = regs[3]; /* lba low */
desc[ 9] = regs[4]; /* lba med */
desc[11] = regs[5]; /* lba high */
desc[12] = regs[6]; /* device */
desc[13] = regs[7]; /* command */
srb->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
}
goto end;
invalid_fld:
srb->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
memcpy(srb->sense_buffer,
usb_stor_sense_invalidCDB,
sizeof(usb_stor_sense_invalidCDB));
end:
memcpy(srb->cmnd, save_cmnd, sizeof(save_cmnd));
if (srb->cmnd[0] == ATA_12)
srb->cmd_len = 12;
}
static int cypress_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct us_data *us;
int result;
result = usb_stor_probe1(&us, intf, id,
(id - cypress_usb_ids) + cypress_unusual_dev_list);
if (result)
return result;
us->protocol_name = "Transparent SCSI with Cypress ATACB";
us->proto_handler = cypress_atacb_passthrough;
result = usb_stor_probe2(us);
return result;
}
static struct usb_driver cypress_driver = {
.name = "ums-cypress",
.probe = cypress_probe,
.disconnect = usb_stor_disconnect,
.suspend = usb_stor_suspend,
.resume = usb_stor_resume,
.reset_resume = usb_stor_reset_resume,
.pre_reset = usb_stor_pre_reset,
.post_reset = usb_stor_post_reset,
.id_table = cypress_usb_ids,
.soft_unbind = 1,
};
static int __init cypress_init(void)
{
return usb_register(&cypress_driver);
}
static void __exit cypress_exit(void)
{
usb_deregister(&cypress_driver);
}
module_init(cypress_init);
module_exit(cypress_exit);
| gpl-2.0 |
zihongli/linux-3.6.0-MIAT | arch/sh/boards/mach-se/7751/setup.c | 4639 | 1341 | /*
* linux/arch/sh/boards/se/7751/setup.c
*
* Copyright (C) 2000 Kazumoto Kojima
*
* Hitachi SolutionEngine Support.
*
* Modified for 7751 Solution Engine by
* Ian da Silva and Jeremy Siegel, 2001.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <asm/machvec.h>
#include <mach-se/mach/se7751.h>
#include <asm/io.h>
#include <asm/heartbeat.h>
static unsigned char heartbeat_bit_pos[] = { 8, 9, 10, 11, 12, 13, 14, 15 };
static struct heartbeat_data heartbeat_data = {
.bit_pos = heartbeat_bit_pos,
.nr_bits = ARRAY_SIZE(heartbeat_bit_pos),
};
static struct resource heartbeat_resources[] = {
[0] = {
.start = PA_LED,
.end = PA_LED,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.dev = {
.platform_data = &heartbeat_data,
},
.num_resources = ARRAY_SIZE(heartbeat_resources),
.resource = heartbeat_resources,
};
static struct platform_device *se7751_devices[] __initdata = {
&heartbeat_device,
};
static int __init se7751_devices_setup(void)
{
return platform_add_devices(se7751_devices, ARRAY_SIZE(se7751_devices));
}
device_initcall(se7751_devices_setup);
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_7751se __initmv = {
.mv_name = "7751 SolutionEngine",
.mv_init_irq = init_7751se_IRQ,
};
| gpl-2.0 |
GioneeDevTeam/android_kernel_gionee_msm8974 | drivers/uio/uio_pdrv_genirq.c | 4895 | 7284 | /*
* drivers/uio/uio_pdrv_genirq.c
*
* Userspace I/O platform driver with generic IRQ handling code.
*
* Copyright (C) 2008 Magnus Damm
*
* Based on uio_pdrv.c by Uwe Kleine-Koenig,
* Copyright (C) 2008 by Digi International 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 version 2 as published by
* the Free Software Foundation.
*/
#include <linux/platform_device.h>
#include <linux/uio_driver.h>
#include <linux/spinlock.h>
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/stringify.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/of_address.h>
#define DRIVER_NAME "uio_pdrv_genirq"
struct uio_pdrv_genirq_platdata {
struct uio_info *uioinfo;
spinlock_t lock;
unsigned long flags;
struct platform_device *pdev;
};
static int uio_pdrv_genirq_open(struct uio_info *info, struct inode *inode)
{
struct uio_pdrv_genirq_platdata *priv = info->priv;
/* Wait until the Runtime PM code has woken up the device */
pm_runtime_get_sync(&priv->pdev->dev);
return 0;
}
static int uio_pdrv_genirq_release(struct uio_info *info, struct inode *inode)
{
struct uio_pdrv_genirq_platdata *priv = info->priv;
/* Tell the Runtime PM code that the device has become idle */
pm_runtime_put_sync(&priv->pdev->dev);
return 0;
}
static irqreturn_t uio_pdrv_genirq_handler(int irq, struct uio_info *dev_info)
{
struct uio_pdrv_genirq_platdata *priv = dev_info->priv;
/* Just disable the interrupt in the interrupt controller, and
* remember the state so we can allow user space to enable it later.
*/
if (!test_and_set_bit(0, &priv->flags))
disable_irq_nosync(irq);
return IRQ_HANDLED;
}
static int uio_pdrv_genirq_irqcontrol(struct uio_info *dev_info, s32 irq_on)
{
struct uio_pdrv_genirq_platdata *priv = dev_info->priv;
unsigned long flags;
/* Allow user space to enable and disable the interrupt
* in the interrupt controller, but keep track of the
* state to prevent per-irq depth damage.
*
* Serialize this operation to support multiple tasks.
*/
spin_lock_irqsave(&priv->lock, flags);
if (irq_on) {
if (test_and_clear_bit(0, &priv->flags))
enable_irq(dev_info->irq);
} else {
if (!test_and_set_bit(0, &priv->flags))
disable_irq(dev_info->irq);
}
spin_unlock_irqrestore(&priv->lock, flags);
return 0;
}
static int uio_pdrv_genirq_probe(struct platform_device *pdev)
{
struct uio_info *uioinfo = pdev->dev.platform_data;
struct uio_pdrv_genirq_platdata *priv;
struct uio_mem *uiomem;
int ret = -EINVAL;
int i;
if (!uioinfo) {
int irq;
/* alloc uioinfo for one device */
uioinfo = kzalloc(sizeof(*uioinfo), GFP_KERNEL);
if (!uioinfo) {
ret = -ENOMEM;
dev_err(&pdev->dev, "unable to kmalloc\n");
goto bad2;
}
uioinfo->name = pdev->dev.of_node->name;
uioinfo->version = "devicetree";
/* Multiple IRQs are not supported */
irq = platform_get_irq(pdev, 0);
if (irq == -ENXIO)
uioinfo->irq = UIO_IRQ_NONE;
else
uioinfo->irq = irq;
}
if (!uioinfo || !uioinfo->name || !uioinfo->version) {
dev_err(&pdev->dev, "missing platform_data\n");
goto bad0;
}
if (uioinfo->handler || uioinfo->irqcontrol ||
uioinfo->irq_flags & IRQF_SHARED) {
dev_err(&pdev->dev, "interrupt configuration error\n");
goto bad0;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
ret = -ENOMEM;
dev_err(&pdev->dev, "unable to kmalloc\n");
goto bad0;
}
priv->uioinfo = uioinfo;
spin_lock_init(&priv->lock);
priv->flags = 0; /* interrupt is enabled to begin with */
priv->pdev = pdev;
uiomem = &uioinfo->mem[0];
for (i = 0; i < pdev->num_resources; ++i) {
struct resource *r = &pdev->resource[i];
if (r->flags != IORESOURCE_MEM)
continue;
if (uiomem >= &uioinfo->mem[MAX_UIO_MAPS]) {
dev_warn(&pdev->dev, "device has more than "
__stringify(MAX_UIO_MAPS)
" I/O memory resources.\n");
break;
}
uiomem->memtype = UIO_MEM_PHYS;
uiomem->addr = r->start;
uiomem->size = resource_size(r);
++uiomem;
}
while (uiomem < &uioinfo->mem[MAX_UIO_MAPS]) {
uiomem->size = 0;
++uiomem;
}
/* This driver requires no hardware specific kernel code to handle
* interrupts. Instead, the interrupt handler simply disables the
* interrupt in the interrupt controller. User space is responsible
* for performing hardware specific acknowledge and re-enabling of
* the interrupt in the interrupt controller.
*
* Interrupt sharing is not supported.
*/
uioinfo->handler = uio_pdrv_genirq_handler;
uioinfo->irqcontrol = uio_pdrv_genirq_irqcontrol;
uioinfo->open = uio_pdrv_genirq_open;
uioinfo->release = uio_pdrv_genirq_release;
uioinfo->priv = priv;
/* Enable Runtime PM for this device:
* The device starts in suspended state to allow the hardware to be
* turned off by default. The Runtime PM bus code should power on the
* hardware and enable clocks at open().
*/
pm_runtime_enable(&pdev->dev);
ret = uio_register_device(&pdev->dev, priv->uioinfo);
if (ret) {
dev_err(&pdev->dev, "unable to register uio device\n");
goto bad1;
}
platform_set_drvdata(pdev, priv);
return 0;
bad1:
kfree(priv);
pm_runtime_disable(&pdev->dev);
bad0:
/* kfree uioinfo for OF */
if (pdev->dev.of_node)
kfree(uioinfo);
bad2:
return ret;
}
static int uio_pdrv_genirq_remove(struct platform_device *pdev)
{
struct uio_pdrv_genirq_platdata *priv = platform_get_drvdata(pdev);
uio_unregister_device(priv->uioinfo);
pm_runtime_disable(&pdev->dev);
priv->uioinfo->handler = NULL;
priv->uioinfo->irqcontrol = NULL;
/* kfree uioinfo for OF */
if (pdev->dev.of_node)
kfree(priv->uioinfo);
kfree(priv);
return 0;
}
static int uio_pdrv_genirq_runtime_nop(struct device *dev)
{
/* Runtime PM callback shared between ->runtime_suspend()
* and ->runtime_resume(). Simply returns success.
*
* In this driver pm_runtime_get_sync() and pm_runtime_put_sync()
* are used at open() and release() time. This allows the
* Runtime PM code to turn off power to the device while the
* device is unused, ie before open() and after release().
*
* This Runtime PM callback does not need to save or restore
* any registers since user space is responsbile for hardware
* register reinitialization after open().
*/
return 0;
}
static const struct dev_pm_ops uio_pdrv_genirq_dev_pm_ops = {
.runtime_suspend = uio_pdrv_genirq_runtime_nop,
.runtime_resume = uio_pdrv_genirq_runtime_nop,
};
#ifdef CONFIG_OF
static const struct of_device_id uio_of_genirq_match[] = {
{ /* empty for now */ },
};
MODULE_DEVICE_TABLE(of, uio_of_genirq_match);
#else
# define uio_of_genirq_match NULL
#endif
static struct platform_driver uio_pdrv_genirq = {
.probe = uio_pdrv_genirq_probe,
.remove = uio_pdrv_genirq_remove,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.pm = &uio_pdrv_genirq_dev_pm_ops,
.of_match_table = uio_of_genirq_match,
},
};
module_platform_driver(uio_pdrv_genirq);
MODULE_AUTHOR("Magnus Damm");
MODULE_DESCRIPTION("Userspace I/O platform driver with generic IRQ handling");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
raden/kencana-kernel | drivers/usb/gadget/m66592-udc.c | 4895 | 44019 | /*
* M66592 UDC (USB gadget)
*
* Copyright (C) 2006-2007 Renesas Solutions Corp.
*
* Author : Yoshihiro Shimoda <yoshihiro.shimoda.uh@renesas.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include "m66592-udc.h"
MODULE_DESCRIPTION("M66592 USB gadget driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yoshihiro Shimoda");
MODULE_ALIAS("platform:m66592_udc");
#define DRIVER_VERSION "21 July 2009"
static const char udc_name[] = "m66592_udc";
static const char *m66592_ep_name[] = {
"ep0", "ep1", "ep2", "ep3", "ep4", "ep5", "ep6", "ep7"
};
static void disable_controller(struct m66592 *m66592);
static void irq_ep0_write(struct m66592_ep *ep, struct m66592_request *req);
static void irq_packet_write(struct m66592_ep *ep, struct m66592_request *req);
static int m66592_queue(struct usb_ep *_ep, struct usb_request *_req,
gfp_t gfp_flags);
static void transfer_complete(struct m66592_ep *ep,
struct m66592_request *req, int status);
/*-------------------------------------------------------------------------*/
static inline u16 get_usb_speed(struct m66592 *m66592)
{
return (m66592_read(m66592, M66592_DVSTCTR) & M66592_RHST);
}
static void enable_pipe_irq(struct m66592 *m66592, u16 pipenum,
unsigned long reg)
{
u16 tmp;
tmp = m66592_read(m66592, M66592_INTENB0);
m66592_bclr(m66592, M66592_BEMPE | M66592_NRDYE | M66592_BRDYE,
M66592_INTENB0);
m66592_bset(m66592, (1 << pipenum), reg);
m66592_write(m66592, tmp, M66592_INTENB0);
}
static void disable_pipe_irq(struct m66592 *m66592, u16 pipenum,
unsigned long reg)
{
u16 tmp;
tmp = m66592_read(m66592, M66592_INTENB0);
m66592_bclr(m66592, M66592_BEMPE | M66592_NRDYE | M66592_BRDYE,
M66592_INTENB0);
m66592_bclr(m66592, (1 << pipenum), reg);
m66592_write(m66592, tmp, M66592_INTENB0);
}
static void m66592_usb_connect(struct m66592 *m66592)
{
m66592_bset(m66592, M66592_CTRE, M66592_INTENB0);
m66592_bset(m66592, M66592_WDST | M66592_RDST | M66592_CMPL,
M66592_INTENB0);
m66592_bset(m66592, M66592_BEMPE | M66592_BRDYE, M66592_INTENB0);
m66592_bset(m66592, M66592_DPRPU, M66592_SYSCFG);
}
static void m66592_usb_disconnect(struct m66592 *m66592)
__releases(m66592->lock)
__acquires(m66592->lock)
{
m66592_bclr(m66592, M66592_CTRE, M66592_INTENB0);
m66592_bclr(m66592, M66592_WDST | M66592_RDST | M66592_CMPL,
M66592_INTENB0);
m66592_bclr(m66592, M66592_BEMPE | M66592_BRDYE, M66592_INTENB0);
m66592_bclr(m66592, M66592_DPRPU, M66592_SYSCFG);
m66592->gadget.speed = USB_SPEED_UNKNOWN;
spin_unlock(&m66592->lock);
m66592->driver->disconnect(&m66592->gadget);
spin_lock(&m66592->lock);
disable_controller(m66592);
INIT_LIST_HEAD(&m66592->ep[0].queue);
}
static inline u16 control_reg_get_pid(struct m66592 *m66592, u16 pipenum)
{
u16 pid = 0;
unsigned long offset;
if (pipenum == 0)
pid = m66592_read(m66592, M66592_DCPCTR) & M66592_PID;
else if (pipenum < M66592_MAX_NUM_PIPE) {
offset = get_pipectr_addr(pipenum);
pid = m66592_read(m66592, offset) & M66592_PID;
} else
pr_err("unexpect pipe num (%d)\n", pipenum);
return pid;
}
static inline void control_reg_set_pid(struct m66592 *m66592, u16 pipenum,
u16 pid)
{
unsigned long offset;
if (pipenum == 0)
m66592_mdfy(m66592, pid, M66592_PID, M66592_DCPCTR);
else if (pipenum < M66592_MAX_NUM_PIPE) {
offset = get_pipectr_addr(pipenum);
m66592_mdfy(m66592, pid, M66592_PID, offset);
} else
pr_err("unexpect pipe num (%d)\n", pipenum);
}
static inline void pipe_start(struct m66592 *m66592, u16 pipenum)
{
control_reg_set_pid(m66592, pipenum, M66592_PID_BUF);
}
static inline void pipe_stop(struct m66592 *m66592, u16 pipenum)
{
control_reg_set_pid(m66592, pipenum, M66592_PID_NAK);
}
static inline void pipe_stall(struct m66592 *m66592, u16 pipenum)
{
control_reg_set_pid(m66592, pipenum, M66592_PID_STALL);
}
static inline u16 control_reg_get(struct m66592 *m66592, u16 pipenum)
{
u16 ret = 0;
unsigned long offset;
if (pipenum == 0)
ret = m66592_read(m66592, M66592_DCPCTR);
else if (pipenum < M66592_MAX_NUM_PIPE) {
offset = get_pipectr_addr(pipenum);
ret = m66592_read(m66592, offset);
} else
pr_err("unexpect pipe num (%d)\n", pipenum);
return ret;
}
static inline void control_reg_sqclr(struct m66592 *m66592, u16 pipenum)
{
unsigned long offset;
pipe_stop(m66592, pipenum);
if (pipenum == 0)
m66592_bset(m66592, M66592_SQCLR, M66592_DCPCTR);
else if (pipenum < M66592_MAX_NUM_PIPE) {
offset = get_pipectr_addr(pipenum);
m66592_bset(m66592, M66592_SQCLR, offset);
} else
pr_err("unexpect pipe num(%d)\n", pipenum);
}
static inline int get_buffer_size(struct m66592 *m66592, u16 pipenum)
{
u16 tmp;
int size;
if (pipenum == 0) {
tmp = m66592_read(m66592, M66592_DCPCFG);
if ((tmp & M66592_CNTMD) != 0)
size = 256;
else {
tmp = m66592_read(m66592, M66592_DCPMAXP);
size = tmp & M66592_MAXP;
}
} else {
m66592_write(m66592, pipenum, M66592_PIPESEL);
tmp = m66592_read(m66592, M66592_PIPECFG);
if ((tmp & M66592_CNTMD) != 0) {
tmp = m66592_read(m66592, M66592_PIPEBUF);
size = ((tmp >> 10) + 1) * 64;
} else {
tmp = m66592_read(m66592, M66592_PIPEMAXP);
size = tmp & M66592_MXPS;
}
}
return size;
}
static inline void pipe_change(struct m66592 *m66592, u16 pipenum)
{
struct m66592_ep *ep = m66592->pipenum2ep[pipenum];
unsigned short mbw;
if (ep->use_dma)
return;
m66592_mdfy(m66592, pipenum, M66592_CURPIPE, ep->fifosel);
ndelay(450);
if (m66592->pdata->on_chip)
mbw = M66592_MBW_32;
else
mbw = M66592_MBW_16;
m66592_bset(m66592, mbw, ep->fifosel);
}
static int pipe_buffer_setting(struct m66592 *m66592,
struct m66592_pipe_info *info)
{
u16 bufnum = 0, buf_bsize = 0;
u16 pipecfg = 0;
if (info->pipe == 0)
return -EINVAL;
m66592_write(m66592, info->pipe, M66592_PIPESEL);
if (info->dir_in)
pipecfg |= M66592_DIR;
pipecfg |= info->type;
pipecfg |= info->epnum;
switch (info->type) {
case M66592_INT:
bufnum = 4 + (info->pipe - M66592_BASE_PIPENUM_INT);
buf_bsize = 0;
break;
case M66592_BULK:
/* isochronous pipes may be used as bulk pipes */
if (info->pipe >= M66592_BASE_PIPENUM_BULK)
bufnum = info->pipe - M66592_BASE_PIPENUM_BULK;
else
bufnum = info->pipe - M66592_BASE_PIPENUM_ISOC;
bufnum = M66592_BASE_BUFNUM + (bufnum * 16);
buf_bsize = 7;
pipecfg |= M66592_DBLB;
if (!info->dir_in)
pipecfg |= M66592_SHTNAK;
break;
case M66592_ISO:
bufnum = M66592_BASE_BUFNUM +
(info->pipe - M66592_BASE_PIPENUM_ISOC) * 16;
buf_bsize = 7;
break;
}
if (buf_bsize && ((bufnum + 16) >= M66592_MAX_BUFNUM)) {
pr_err("m66592 pipe memory is insufficient\n");
return -ENOMEM;
}
m66592_write(m66592, pipecfg, M66592_PIPECFG);
m66592_write(m66592, (buf_bsize << 10) | (bufnum), M66592_PIPEBUF);
m66592_write(m66592, info->maxpacket, M66592_PIPEMAXP);
if (info->interval)
info->interval--;
m66592_write(m66592, info->interval, M66592_PIPEPERI);
return 0;
}
static void pipe_buffer_release(struct m66592 *m66592,
struct m66592_pipe_info *info)
{
if (info->pipe == 0)
return;
if (is_bulk_pipe(info->pipe)) {
m66592->bulk--;
} else if (is_interrupt_pipe(info->pipe))
m66592->interrupt--;
else if (is_isoc_pipe(info->pipe)) {
m66592->isochronous--;
if (info->type == M66592_BULK)
m66592->bulk--;
} else
pr_err("ep_release: unexpect pipenum (%d)\n",
info->pipe);
}
static void pipe_initialize(struct m66592_ep *ep)
{
struct m66592 *m66592 = ep->m66592;
unsigned short mbw;
m66592_mdfy(m66592, 0, M66592_CURPIPE, ep->fifosel);
m66592_write(m66592, M66592_ACLRM, ep->pipectr);
m66592_write(m66592, 0, ep->pipectr);
m66592_write(m66592, M66592_SQCLR, ep->pipectr);
if (ep->use_dma) {
m66592_mdfy(m66592, ep->pipenum, M66592_CURPIPE, ep->fifosel);
ndelay(450);
if (m66592->pdata->on_chip)
mbw = M66592_MBW_32;
else
mbw = M66592_MBW_16;
m66592_bset(m66592, mbw, ep->fifosel);
}
}
static void m66592_ep_setting(struct m66592 *m66592, struct m66592_ep *ep,
const struct usb_endpoint_descriptor *desc,
u16 pipenum, int dma)
{
if ((pipenum != 0) && dma) {
if (m66592->num_dma == 0) {
m66592->num_dma++;
ep->use_dma = 1;
ep->fifoaddr = M66592_D0FIFO;
ep->fifosel = M66592_D0FIFOSEL;
ep->fifoctr = M66592_D0FIFOCTR;
ep->fifotrn = M66592_D0FIFOTRN;
} else if (!m66592->pdata->on_chip && m66592->num_dma == 1) {
m66592->num_dma++;
ep->use_dma = 1;
ep->fifoaddr = M66592_D1FIFO;
ep->fifosel = M66592_D1FIFOSEL;
ep->fifoctr = M66592_D1FIFOCTR;
ep->fifotrn = M66592_D1FIFOTRN;
} else {
ep->use_dma = 0;
ep->fifoaddr = M66592_CFIFO;
ep->fifosel = M66592_CFIFOSEL;
ep->fifoctr = M66592_CFIFOCTR;
ep->fifotrn = 0;
}
} else {
ep->use_dma = 0;
ep->fifoaddr = M66592_CFIFO;
ep->fifosel = M66592_CFIFOSEL;
ep->fifoctr = M66592_CFIFOCTR;
ep->fifotrn = 0;
}
ep->pipectr = get_pipectr_addr(pipenum);
ep->pipenum = pipenum;
ep->ep.maxpacket = usb_endpoint_maxp(desc);
m66592->pipenum2ep[pipenum] = ep;
m66592->epaddr2ep[desc->bEndpointAddress&USB_ENDPOINT_NUMBER_MASK] = ep;
INIT_LIST_HEAD(&ep->queue);
}
static void m66592_ep_release(struct m66592_ep *ep)
{
struct m66592 *m66592 = ep->m66592;
u16 pipenum = ep->pipenum;
if (pipenum == 0)
return;
if (ep->use_dma)
m66592->num_dma--;
ep->pipenum = 0;
ep->busy = 0;
ep->use_dma = 0;
}
static int alloc_pipe_config(struct m66592_ep *ep,
const struct usb_endpoint_descriptor *desc)
{
struct m66592 *m66592 = ep->m66592;
struct m66592_pipe_info info;
int dma = 0;
int *counter;
int ret;
ep->desc = desc;
BUG_ON(ep->pipenum);
switch (desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
case USB_ENDPOINT_XFER_BULK:
if (m66592->bulk >= M66592_MAX_NUM_BULK) {
if (m66592->isochronous >= M66592_MAX_NUM_ISOC) {
pr_err("bulk pipe is insufficient\n");
return -ENODEV;
} else {
info.pipe = M66592_BASE_PIPENUM_ISOC
+ m66592->isochronous;
counter = &m66592->isochronous;
}
} else {
info.pipe = M66592_BASE_PIPENUM_BULK + m66592->bulk;
counter = &m66592->bulk;
}
info.type = M66592_BULK;
dma = 1;
break;
case USB_ENDPOINT_XFER_INT:
if (m66592->interrupt >= M66592_MAX_NUM_INT) {
pr_err("interrupt pipe is insufficient\n");
return -ENODEV;
}
info.pipe = M66592_BASE_PIPENUM_INT + m66592->interrupt;
info.type = M66592_INT;
counter = &m66592->interrupt;
break;
case USB_ENDPOINT_XFER_ISOC:
if (m66592->isochronous >= M66592_MAX_NUM_ISOC) {
pr_err("isochronous pipe is insufficient\n");
return -ENODEV;
}
info.pipe = M66592_BASE_PIPENUM_ISOC + m66592->isochronous;
info.type = M66592_ISO;
counter = &m66592->isochronous;
break;
default:
pr_err("unexpect xfer type\n");
return -EINVAL;
}
ep->type = info.type;
info.epnum = desc->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
info.maxpacket = usb_endpoint_maxp(desc);
info.interval = desc->bInterval;
if (desc->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
info.dir_in = 1;
else
info.dir_in = 0;
ret = pipe_buffer_setting(m66592, &info);
if (ret < 0) {
pr_err("pipe_buffer_setting fail\n");
return ret;
}
(*counter)++;
if ((counter == &m66592->isochronous) && info.type == M66592_BULK)
m66592->bulk++;
m66592_ep_setting(m66592, ep, desc, info.pipe, dma);
pipe_initialize(ep);
return 0;
}
static int free_pipe_config(struct m66592_ep *ep)
{
struct m66592 *m66592 = ep->m66592;
struct m66592_pipe_info info;
info.pipe = ep->pipenum;
info.type = ep->type;
pipe_buffer_release(m66592, &info);
m66592_ep_release(ep);
return 0;
}
/*-------------------------------------------------------------------------*/
static void pipe_irq_enable(struct m66592 *m66592, u16 pipenum)
{
enable_irq_ready(m66592, pipenum);
enable_irq_nrdy(m66592, pipenum);
}
static void pipe_irq_disable(struct m66592 *m66592, u16 pipenum)
{
disable_irq_ready(m66592, pipenum);
disable_irq_nrdy(m66592, pipenum);
}
/* if complete is true, gadget driver complete function is not call */
static void control_end(struct m66592 *m66592, unsigned ccpl)
{
m66592->ep[0].internal_ccpl = ccpl;
pipe_start(m66592, 0);
m66592_bset(m66592, M66592_CCPL, M66592_DCPCTR);
}
static void start_ep0_write(struct m66592_ep *ep, struct m66592_request *req)
{
struct m66592 *m66592 = ep->m66592;
pipe_change(m66592, ep->pipenum);
m66592_mdfy(m66592, M66592_ISEL | M66592_PIPE0,
(M66592_ISEL | M66592_CURPIPE),
M66592_CFIFOSEL);
m66592_write(m66592, M66592_BCLR, ep->fifoctr);
if (req->req.length == 0) {
m66592_bset(m66592, M66592_BVAL, ep->fifoctr);
pipe_start(m66592, 0);
transfer_complete(ep, req, 0);
} else {
m66592_write(m66592, ~M66592_BEMP0, M66592_BEMPSTS);
irq_ep0_write(ep, req);
}
}
static void start_packet_write(struct m66592_ep *ep, struct m66592_request *req)
{
struct m66592 *m66592 = ep->m66592;
u16 tmp;
pipe_change(m66592, ep->pipenum);
disable_irq_empty(m66592, ep->pipenum);
pipe_start(m66592, ep->pipenum);
tmp = m66592_read(m66592, ep->fifoctr);
if (unlikely((tmp & M66592_FRDY) == 0))
pipe_irq_enable(m66592, ep->pipenum);
else
irq_packet_write(ep, req);
}
static void start_packet_read(struct m66592_ep *ep, struct m66592_request *req)
{
struct m66592 *m66592 = ep->m66592;
u16 pipenum = ep->pipenum;
if (ep->pipenum == 0) {
m66592_mdfy(m66592, M66592_PIPE0,
(M66592_ISEL | M66592_CURPIPE),
M66592_CFIFOSEL);
m66592_write(m66592, M66592_BCLR, ep->fifoctr);
pipe_start(m66592, pipenum);
pipe_irq_enable(m66592, pipenum);
} else {
if (ep->use_dma) {
m66592_bset(m66592, M66592_TRCLR, ep->fifosel);
pipe_change(m66592, pipenum);
m66592_bset(m66592, M66592_TRENB, ep->fifosel);
m66592_write(m66592,
(req->req.length + ep->ep.maxpacket - 1)
/ ep->ep.maxpacket,
ep->fifotrn);
}
pipe_start(m66592, pipenum); /* trigger once */
pipe_irq_enable(m66592, pipenum);
}
}
static void start_packet(struct m66592_ep *ep, struct m66592_request *req)
{
if (ep->desc->bEndpointAddress & USB_DIR_IN)
start_packet_write(ep, req);
else
start_packet_read(ep, req);
}
static void start_ep0(struct m66592_ep *ep, struct m66592_request *req)
{
u16 ctsq;
ctsq = m66592_read(ep->m66592, M66592_INTSTS0) & M66592_CTSQ;
switch (ctsq) {
case M66592_CS_RDDS:
start_ep0_write(ep, req);
break;
case M66592_CS_WRDS:
start_packet_read(ep, req);
break;
case M66592_CS_WRND:
control_end(ep->m66592, 0);
break;
default:
pr_err("start_ep0: unexpect ctsq(%x)\n", ctsq);
break;
}
}
static void init_controller(struct m66592 *m66592)
{
unsigned int endian;
if (m66592->pdata->on_chip) {
if (m66592->pdata->endian)
endian = 0; /* big endian */
else
endian = M66592_LITTLE; /* little endian */
m66592_bset(m66592, M66592_HSE, M66592_SYSCFG); /* High spd */
m66592_bclr(m66592, M66592_USBE, M66592_SYSCFG);
m66592_bclr(m66592, M66592_DPRPU, M66592_SYSCFG);
m66592_bset(m66592, M66592_USBE, M66592_SYSCFG);
/* This is a workaound for SH7722 2nd cut */
m66592_bset(m66592, 0x8000, M66592_DVSTCTR);
m66592_bset(m66592, 0x1000, M66592_TESTMODE);
m66592_bclr(m66592, 0x8000, M66592_DVSTCTR);
m66592_bset(m66592, M66592_INTL, M66592_INTENB1);
m66592_write(m66592, 0, M66592_CFBCFG);
m66592_write(m66592, 0, M66592_D0FBCFG);
m66592_bset(m66592, endian, M66592_CFBCFG);
m66592_bset(m66592, endian, M66592_D0FBCFG);
} else {
unsigned int clock, vif, irq_sense;
if (m66592->pdata->endian)
endian = M66592_BIGEND; /* big endian */
else
endian = 0; /* little endian */
if (m66592->pdata->vif)
vif = M66592_LDRV; /* 3.3v */
else
vif = 0; /* 1.5v */
switch (m66592->pdata->xtal) {
case M66592_PLATDATA_XTAL_12MHZ:
clock = M66592_XTAL12;
break;
case M66592_PLATDATA_XTAL_24MHZ:
clock = M66592_XTAL24;
break;
case M66592_PLATDATA_XTAL_48MHZ:
clock = M66592_XTAL48;
break;
default:
pr_warning("m66592-udc: xtal configuration error\n");
clock = 0;
}
switch (m66592->irq_trigger) {
case IRQF_TRIGGER_LOW:
irq_sense = M66592_INTL;
break;
case IRQF_TRIGGER_FALLING:
irq_sense = 0;
break;
default:
pr_warning("m66592-udc: irq trigger config error\n");
irq_sense = 0;
}
m66592_bset(m66592,
(vif & M66592_LDRV) | (endian & M66592_BIGEND),
M66592_PINCFG);
m66592_bset(m66592, M66592_HSE, M66592_SYSCFG); /* High spd */
m66592_mdfy(m66592, clock & M66592_XTAL, M66592_XTAL,
M66592_SYSCFG);
m66592_bclr(m66592, M66592_USBE, M66592_SYSCFG);
m66592_bclr(m66592, M66592_DPRPU, M66592_SYSCFG);
m66592_bset(m66592, M66592_USBE, M66592_SYSCFG);
m66592_bset(m66592, M66592_XCKE, M66592_SYSCFG);
msleep(3);
m66592_bset(m66592, M66592_RCKE | M66592_PLLC, M66592_SYSCFG);
msleep(1);
m66592_bset(m66592, M66592_SCKE, M66592_SYSCFG);
m66592_bset(m66592, irq_sense & M66592_INTL, M66592_INTENB1);
m66592_write(m66592, M66592_BURST | M66592_CPU_ADR_RD_WR,
M66592_DMA0CFG);
}
}
static void disable_controller(struct m66592 *m66592)
{
m66592_bclr(m66592, M66592_UTST, M66592_TESTMODE);
if (!m66592->pdata->on_chip) {
m66592_bclr(m66592, M66592_SCKE, M66592_SYSCFG);
udelay(1);
m66592_bclr(m66592, M66592_PLLC, M66592_SYSCFG);
udelay(1);
m66592_bclr(m66592, M66592_RCKE, M66592_SYSCFG);
udelay(1);
m66592_bclr(m66592, M66592_XCKE, M66592_SYSCFG);
}
}
static void m66592_start_xclock(struct m66592 *m66592)
{
u16 tmp;
if (!m66592->pdata->on_chip) {
tmp = m66592_read(m66592, M66592_SYSCFG);
if (!(tmp & M66592_XCKE))
m66592_bset(m66592, M66592_XCKE, M66592_SYSCFG);
}
}
/*-------------------------------------------------------------------------*/
static void transfer_complete(struct m66592_ep *ep,
struct m66592_request *req, int status)
__releases(m66592->lock)
__acquires(m66592->lock)
{
int restart = 0;
if (unlikely(ep->pipenum == 0)) {
if (ep->internal_ccpl) {
ep->internal_ccpl = 0;
return;
}
}
list_del_init(&req->queue);
if (ep->m66592->gadget.speed == USB_SPEED_UNKNOWN)
req->req.status = -ESHUTDOWN;
else
req->req.status = status;
if (!list_empty(&ep->queue))
restart = 1;
spin_unlock(&ep->m66592->lock);
req->req.complete(&ep->ep, &req->req);
spin_lock(&ep->m66592->lock);
if (restart) {
req = list_entry(ep->queue.next, struct m66592_request, queue);
if (ep->desc)
start_packet(ep, req);
}
}
static void irq_ep0_write(struct m66592_ep *ep, struct m66592_request *req)
{
int i;
u16 tmp;
unsigned bufsize;
size_t size;
void *buf;
u16 pipenum = ep->pipenum;
struct m66592 *m66592 = ep->m66592;
pipe_change(m66592, pipenum);
m66592_bset(m66592, M66592_ISEL, ep->fifosel);
i = 0;
do {
tmp = m66592_read(m66592, ep->fifoctr);
if (i++ > 100000) {
pr_err("pipe0 is busy. maybe cpu i/o bus "
"conflict. please power off this controller.");
return;
}
ndelay(1);
} while ((tmp & M66592_FRDY) == 0);
/* prepare parameters */
bufsize = get_buffer_size(m66592, pipenum);
buf = req->req.buf + req->req.actual;
size = min(bufsize, req->req.length - req->req.actual);
/* write fifo */
if (req->req.buf) {
if (size > 0)
m66592_write_fifo(m66592, ep, buf, size);
if ((size == 0) || ((size % ep->ep.maxpacket) != 0))
m66592_bset(m66592, M66592_BVAL, ep->fifoctr);
}
/* update parameters */
req->req.actual += size;
/* check transfer finish */
if ((!req->req.zero && (req->req.actual == req->req.length))
|| (size % ep->ep.maxpacket)
|| (size == 0)) {
disable_irq_ready(m66592, pipenum);
disable_irq_empty(m66592, pipenum);
} else {
disable_irq_ready(m66592, pipenum);
enable_irq_empty(m66592, pipenum);
}
pipe_start(m66592, pipenum);
}
static void irq_packet_write(struct m66592_ep *ep, struct m66592_request *req)
{
u16 tmp;
unsigned bufsize;
size_t size;
void *buf;
u16 pipenum = ep->pipenum;
struct m66592 *m66592 = ep->m66592;
pipe_change(m66592, pipenum);
tmp = m66592_read(m66592, ep->fifoctr);
if (unlikely((tmp & M66592_FRDY) == 0)) {
pipe_stop(m66592, pipenum);
pipe_irq_disable(m66592, pipenum);
pr_err("write fifo not ready. pipnum=%d\n", pipenum);
return;
}
/* prepare parameters */
bufsize = get_buffer_size(m66592, pipenum);
buf = req->req.buf + req->req.actual;
size = min(bufsize, req->req.length - req->req.actual);
/* write fifo */
if (req->req.buf) {
m66592_write_fifo(m66592, ep, buf, size);
if ((size == 0)
|| ((size % ep->ep.maxpacket) != 0)
|| ((bufsize != ep->ep.maxpacket)
&& (bufsize > size)))
m66592_bset(m66592, M66592_BVAL, ep->fifoctr);
}
/* update parameters */
req->req.actual += size;
/* check transfer finish */
if ((!req->req.zero && (req->req.actual == req->req.length))
|| (size % ep->ep.maxpacket)
|| (size == 0)) {
disable_irq_ready(m66592, pipenum);
enable_irq_empty(m66592, pipenum);
} else {
disable_irq_empty(m66592, pipenum);
pipe_irq_enable(m66592, pipenum);
}
}
static void irq_packet_read(struct m66592_ep *ep, struct m66592_request *req)
{
u16 tmp;
int rcv_len, bufsize, req_len;
int size;
void *buf;
u16 pipenum = ep->pipenum;
struct m66592 *m66592 = ep->m66592;
int finish = 0;
pipe_change(m66592, pipenum);
tmp = m66592_read(m66592, ep->fifoctr);
if (unlikely((tmp & M66592_FRDY) == 0)) {
req->req.status = -EPIPE;
pipe_stop(m66592, pipenum);
pipe_irq_disable(m66592, pipenum);
pr_err("read fifo not ready");
return;
}
/* prepare parameters */
rcv_len = tmp & M66592_DTLN;
bufsize = get_buffer_size(m66592, pipenum);
buf = req->req.buf + req->req.actual;
req_len = req->req.length - req->req.actual;
if (rcv_len < bufsize)
size = min(rcv_len, req_len);
else
size = min(bufsize, req_len);
/* update parameters */
req->req.actual += size;
/* check transfer finish */
if ((!req->req.zero && (req->req.actual == req->req.length))
|| (size % ep->ep.maxpacket)
|| (size == 0)) {
pipe_stop(m66592, pipenum);
pipe_irq_disable(m66592, pipenum);
finish = 1;
}
/* read fifo */
if (req->req.buf) {
if (size == 0)
m66592_write(m66592, M66592_BCLR, ep->fifoctr);
else
m66592_read_fifo(m66592, ep->fifoaddr, buf, size);
}
if ((ep->pipenum != 0) && finish)
transfer_complete(ep, req, 0);
}
static void irq_pipe_ready(struct m66592 *m66592, u16 status, u16 enb)
{
u16 check;
u16 pipenum;
struct m66592_ep *ep;
struct m66592_request *req;
if ((status & M66592_BRDY0) && (enb & M66592_BRDY0)) {
m66592_write(m66592, ~M66592_BRDY0, M66592_BRDYSTS);
m66592_mdfy(m66592, M66592_PIPE0, M66592_CURPIPE,
M66592_CFIFOSEL);
ep = &m66592->ep[0];
req = list_entry(ep->queue.next, struct m66592_request, queue);
irq_packet_read(ep, req);
} else {
for (pipenum = 1; pipenum < M66592_MAX_NUM_PIPE; pipenum++) {
check = 1 << pipenum;
if ((status & check) && (enb & check)) {
m66592_write(m66592, ~check, M66592_BRDYSTS);
ep = m66592->pipenum2ep[pipenum];
req = list_entry(ep->queue.next,
struct m66592_request, queue);
if (ep->desc->bEndpointAddress & USB_DIR_IN)
irq_packet_write(ep, req);
else
irq_packet_read(ep, req);
}
}
}
}
static void irq_pipe_empty(struct m66592 *m66592, u16 status, u16 enb)
{
u16 tmp;
u16 check;
u16 pipenum;
struct m66592_ep *ep;
struct m66592_request *req;
if ((status & M66592_BEMP0) && (enb & M66592_BEMP0)) {
m66592_write(m66592, ~M66592_BEMP0, M66592_BEMPSTS);
ep = &m66592->ep[0];
req = list_entry(ep->queue.next, struct m66592_request, queue);
irq_ep0_write(ep, req);
} else {
for (pipenum = 1; pipenum < M66592_MAX_NUM_PIPE; pipenum++) {
check = 1 << pipenum;
if ((status & check) && (enb & check)) {
m66592_write(m66592, ~check, M66592_BEMPSTS);
tmp = control_reg_get(m66592, pipenum);
if ((tmp & M66592_INBUFM) == 0) {
disable_irq_empty(m66592, pipenum);
pipe_irq_disable(m66592, pipenum);
pipe_stop(m66592, pipenum);
ep = m66592->pipenum2ep[pipenum];
req = list_entry(ep->queue.next,
struct m66592_request,
queue);
if (!list_empty(&ep->queue))
transfer_complete(ep, req, 0);
}
}
}
}
}
static void get_status(struct m66592 *m66592, struct usb_ctrlrequest *ctrl)
__releases(m66592->lock)
__acquires(m66592->lock)
{
struct m66592_ep *ep;
u16 pid;
u16 status = 0;
u16 w_index = le16_to_cpu(ctrl->wIndex);
switch (ctrl->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
status = 1 << USB_DEVICE_SELF_POWERED;
break;
case USB_RECIP_INTERFACE:
status = 0;
break;
case USB_RECIP_ENDPOINT:
ep = m66592->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK];
pid = control_reg_get_pid(m66592, ep->pipenum);
if (pid == M66592_PID_STALL)
status = 1 << USB_ENDPOINT_HALT;
else
status = 0;
break;
default:
pipe_stall(m66592, 0);
return; /* exit */
}
m66592->ep0_data = cpu_to_le16(status);
m66592->ep0_req->buf = &m66592->ep0_data;
m66592->ep0_req->length = 2;
/* AV: what happens if we get called again before that gets through? */
spin_unlock(&m66592->lock);
m66592_queue(m66592->gadget.ep0, m66592->ep0_req, GFP_KERNEL);
spin_lock(&m66592->lock);
}
static void clear_feature(struct m66592 *m66592, struct usb_ctrlrequest *ctrl)
{
switch (ctrl->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
control_end(m66592, 1);
break;
case USB_RECIP_INTERFACE:
control_end(m66592, 1);
break;
case USB_RECIP_ENDPOINT: {
struct m66592_ep *ep;
struct m66592_request *req;
u16 w_index = le16_to_cpu(ctrl->wIndex);
ep = m66592->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK];
pipe_stop(m66592, ep->pipenum);
control_reg_sqclr(m66592, ep->pipenum);
control_end(m66592, 1);
req = list_entry(ep->queue.next,
struct m66592_request, queue);
if (ep->busy) {
ep->busy = 0;
if (list_empty(&ep->queue))
break;
start_packet(ep, req);
} else if (!list_empty(&ep->queue))
pipe_start(m66592, ep->pipenum);
}
break;
default:
pipe_stall(m66592, 0);
break;
}
}
static void set_feature(struct m66592 *m66592, struct usb_ctrlrequest *ctrl)
{
u16 tmp;
int timeout = 3000;
switch (ctrl->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
switch (le16_to_cpu(ctrl->wValue)) {
case USB_DEVICE_TEST_MODE:
control_end(m66592, 1);
/* Wait for the completion of status stage */
do {
tmp = m66592_read(m66592, M66592_INTSTS0) &
M66592_CTSQ;
udelay(1);
} while (tmp != M66592_CS_IDST || timeout-- > 0);
if (tmp == M66592_CS_IDST)
m66592_bset(m66592,
le16_to_cpu(ctrl->wIndex >> 8),
M66592_TESTMODE);
break;
default:
pipe_stall(m66592, 0);
break;
}
break;
case USB_RECIP_INTERFACE:
control_end(m66592, 1);
break;
case USB_RECIP_ENDPOINT: {
struct m66592_ep *ep;
u16 w_index = le16_to_cpu(ctrl->wIndex);
ep = m66592->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK];
pipe_stall(m66592, ep->pipenum);
control_end(m66592, 1);
}
break;
default:
pipe_stall(m66592, 0);
break;
}
}
/* if return value is true, call class driver's setup() */
static int setup_packet(struct m66592 *m66592, struct usb_ctrlrequest *ctrl)
{
u16 *p = (u16 *)ctrl;
unsigned long offset = M66592_USBREQ;
int i, ret = 0;
/* read fifo */
m66592_write(m66592, ~M66592_VALID, M66592_INTSTS0);
for (i = 0; i < 4; i++)
p[i] = m66592_read(m66592, offset + i*2);
/* check request */
if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
switch (ctrl->bRequest) {
case USB_REQ_GET_STATUS:
get_status(m66592, ctrl);
break;
case USB_REQ_CLEAR_FEATURE:
clear_feature(m66592, ctrl);
break;
case USB_REQ_SET_FEATURE:
set_feature(m66592, ctrl);
break;
default:
ret = 1;
break;
}
} else
ret = 1;
return ret;
}
static void m66592_update_usb_speed(struct m66592 *m66592)
{
u16 speed = get_usb_speed(m66592);
switch (speed) {
case M66592_HSMODE:
m66592->gadget.speed = USB_SPEED_HIGH;
break;
case M66592_FSMODE:
m66592->gadget.speed = USB_SPEED_FULL;
break;
default:
m66592->gadget.speed = USB_SPEED_UNKNOWN;
pr_err("USB speed unknown\n");
}
}
static void irq_device_state(struct m66592 *m66592)
{
u16 dvsq;
dvsq = m66592_read(m66592, M66592_INTSTS0) & M66592_DVSQ;
m66592_write(m66592, ~M66592_DVST, M66592_INTSTS0);
if (dvsq == M66592_DS_DFLT) { /* bus reset */
m66592->driver->disconnect(&m66592->gadget);
m66592_update_usb_speed(m66592);
}
if (m66592->old_dvsq == M66592_DS_CNFG && dvsq != M66592_DS_CNFG)
m66592_update_usb_speed(m66592);
if ((dvsq == M66592_DS_CNFG || dvsq == M66592_DS_ADDS)
&& m66592->gadget.speed == USB_SPEED_UNKNOWN)
m66592_update_usb_speed(m66592);
m66592->old_dvsq = dvsq;
}
static void irq_control_stage(struct m66592 *m66592)
__releases(m66592->lock)
__acquires(m66592->lock)
{
struct usb_ctrlrequest ctrl;
u16 ctsq;
ctsq = m66592_read(m66592, M66592_INTSTS0) & M66592_CTSQ;
m66592_write(m66592, ~M66592_CTRT, M66592_INTSTS0);
switch (ctsq) {
case M66592_CS_IDST: {
struct m66592_ep *ep;
struct m66592_request *req;
ep = &m66592->ep[0];
req = list_entry(ep->queue.next, struct m66592_request, queue);
transfer_complete(ep, req, 0);
}
break;
case M66592_CS_RDDS:
case M66592_CS_WRDS:
case M66592_CS_WRND:
if (setup_packet(m66592, &ctrl)) {
spin_unlock(&m66592->lock);
if (m66592->driver->setup(&m66592->gadget, &ctrl) < 0)
pipe_stall(m66592, 0);
spin_lock(&m66592->lock);
}
break;
case M66592_CS_RDSS:
case M66592_CS_WRSS:
control_end(m66592, 0);
break;
default:
pr_err("ctrl_stage: unexpect ctsq(%x)\n", ctsq);
break;
}
}
static irqreturn_t m66592_irq(int irq, void *_m66592)
{
struct m66592 *m66592 = _m66592;
u16 intsts0;
u16 intenb0;
u16 brdysts, nrdysts, bempsts;
u16 brdyenb, nrdyenb, bempenb;
u16 savepipe;
u16 mask0;
spin_lock(&m66592->lock);
intsts0 = m66592_read(m66592, M66592_INTSTS0);
intenb0 = m66592_read(m66592, M66592_INTENB0);
if (m66592->pdata->on_chip && !intsts0 && !intenb0) {
/*
* When USB clock stops, it cannot read register. Even if a
* clock stops, the interrupt occurs. So this driver turn on
* a clock by this timing and do re-reading of register.
*/
m66592_start_xclock(m66592);
intsts0 = m66592_read(m66592, M66592_INTSTS0);
intenb0 = m66592_read(m66592, M66592_INTENB0);
}
savepipe = m66592_read(m66592, M66592_CFIFOSEL);
mask0 = intsts0 & intenb0;
if (mask0) {
brdysts = m66592_read(m66592, M66592_BRDYSTS);
nrdysts = m66592_read(m66592, M66592_NRDYSTS);
bempsts = m66592_read(m66592, M66592_BEMPSTS);
brdyenb = m66592_read(m66592, M66592_BRDYENB);
nrdyenb = m66592_read(m66592, M66592_NRDYENB);
bempenb = m66592_read(m66592, M66592_BEMPENB);
if (mask0 & M66592_VBINT) {
m66592_write(m66592, 0xffff & ~M66592_VBINT,
M66592_INTSTS0);
m66592_start_xclock(m66592);
/* start vbus sampling */
m66592->old_vbus = m66592_read(m66592, M66592_INTSTS0)
& M66592_VBSTS;
m66592->scount = M66592_MAX_SAMPLING;
mod_timer(&m66592->timer,
jiffies + msecs_to_jiffies(50));
}
if (intsts0 & M66592_DVSQ)
irq_device_state(m66592);
if ((intsts0 & M66592_BRDY) && (intenb0 & M66592_BRDYE)
&& (brdysts & brdyenb)) {
irq_pipe_ready(m66592, brdysts, brdyenb);
}
if ((intsts0 & M66592_BEMP) && (intenb0 & M66592_BEMPE)
&& (bempsts & bempenb)) {
irq_pipe_empty(m66592, bempsts, bempenb);
}
if (intsts0 & M66592_CTRT)
irq_control_stage(m66592);
}
m66592_write(m66592, savepipe, M66592_CFIFOSEL);
spin_unlock(&m66592->lock);
return IRQ_HANDLED;
}
static void m66592_timer(unsigned long _m66592)
{
struct m66592 *m66592 = (struct m66592 *)_m66592;
unsigned long flags;
u16 tmp;
spin_lock_irqsave(&m66592->lock, flags);
tmp = m66592_read(m66592, M66592_SYSCFG);
if (!(tmp & M66592_RCKE)) {
m66592_bset(m66592, M66592_RCKE | M66592_PLLC, M66592_SYSCFG);
udelay(10);
m66592_bset(m66592, M66592_SCKE, M66592_SYSCFG);
}
if (m66592->scount > 0) {
tmp = m66592_read(m66592, M66592_INTSTS0) & M66592_VBSTS;
if (tmp == m66592->old_vbus) {
m66592->scount--;
if (m66592->scount == 0) {
if (tmp == M66592_VBSTS)
m66592_usb_connect(m66592);
else
m66592_usb_disconnect(m66592);
} else {
mod_timer(&m66592->timer,
jiffies + msecs_to_jiffies(50));
}
} else {
m66592->scount = M66592_MAX_SAMPLING;
m66592->old_vbus = tmp;
mod_timer(&m66592->timer,
jiffies + msecs_to_jiffies(50));
}
}
spin_unlock_irqrestore(&m66592->lock, flags);
}
/*-------------------------------------------------------------------------*/
static int m66592_enable(struct usb_ep *_ep,
const struct usb_endpoint_descriptor *desc)
{
struct m66592_ep *ep;
ep = container_of(_ep, struct m66592_ep, ep);
return alloc_pipe_config(ep, desc);
}
static int m66592_disable(struct usb_ep *_ep)
{
struct m66592_ep *ep;
struct m66592_request *req;
unsigned long flags;
ep = container_of(_ep, struct m66592_ep, ep);
BUG_ON(!ep);
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct m66592_request, queue);
spin_lock_irqsave(&ep->m66592->lock, flags);
transfer_complete(ep, req, -ECONNRESET);
spin_unlock_irqrestore(&ep->m66592->lock, flags);
}
pipe_irq_disable(ep->m66592, ep->pipenum);
return free_pipe_config(ep);
}
static struct usb_request *m66592_alloc_request(struct usb_ep *_ep,
gfp_t gfp_flags)
{
struct m66592_request *req;
req = kzalloc(sizeof(struct m66592_request), gfp_flags);
if (!req)
return NULL;
INIT_LIST_HEAD(&req->queue);
return &req->req;
}
static void m66592_free_request(struct usb_ep *_ep, struct usb_request *_req)
{
struct m66592_request *req;
req = container_of(_req, struct m66592_request, req);
kfree(req);
}
static int m66592_queue(struct usb_ep *_ep, struct usb_request *_req,
gfp_t gfp_flags)
{
struct m66592_ep *ep;
struct m66592_request *req;
unsigned long flags;
int request = 0;
ep = container_of(_ep, struct m66592_ep, ep);
req = container_of(_req, struct m66592_request, req);
if (ep->m66592->gadget.speed == USB_SPEED_UNKNOWN)
return -ESHUTDOWN;
spin_lock_irqsave(&ep->m66592->lock, flags);
if (list_empty(&ep->queue))
request = 1;
list_add_tail(&req->queue, &ep->queue);
req->req.actual = 0;
req->req.status = -EINPROGRESS;
if (ep->desc == NULL) /* control */
start_ep0(ep, req);
else {
if (request && !ep->busy)
start_packet(ep, req);
}
spin_unlock_irqrestore(&ep->m66592->lock, flags);
return 0;
}
static int m66592_dequeue(struct usb_ep *_ep, struct usb_request *_req)
{
struct m66592_ep *ep;
struct m66592_request *req;
unsigned long flags;
ep = container_of(_ep, struct m66592_ep, ep);
req = container_of(_req, struct m66592_request, req);
spin_lock_irqsave(&ep->m66592->lock, flags);
if (!list_empty(&ep->queue))
transfer_complete(ep, req, -ECONNRESET);
spin_unlock_irqrestore(&ep->m66592->lock, flags);
return 0;
}
static int m66592_set_halt(struct usb_ep *_ep, int value)
{
struct m66592_ep *ep;
struct m66592_request *req;
unsigned long flags;
int ret = 0;
ep = container_of(_ep, struct m66592_ep, ep);
req = list_entry(ep->queue.next, struct m66592_request, queue);
spin_lock_irqsave(&ep->m66592->lock, flags);
if (!list_empty(&ep->queue)) {
ret = -EAGAIN;
goto out;
}
if (value) {
ep->busy = 1;
pipe_stall(ep->m66592, ep->pipenum);
} else {
ep->busy = 0;
pipe_stop(ep->m66592, ep->pipenum);
}
out:
spin_unlock_irqrestore(&ep->m66592->lock, flags);
return ret;
}
static void m66592_fifo_flush(struct usb_ep *_ep)
{
struct m66592_ep *ep;
unsigned long flags;
ep = container_of(_ep, struct m66592_ep, ep);
spin_lock_irqsave(&ep->m66592->lock, flags);
if (list_empty(&ep->queue) && !ep->busy) {
pipe_stop(ep->m66592, ep->pipenum);
m66592_bclr(ep->m66592, M66592_BCLR, ep->fifoctr);
}
spin_unlock_irqrestore(&ep->m66592->lock, flags);
}
static struct usb_ep_ops m66592_ep_ops = {
.enable = m66592_enable,
.disable = m66592_disable,
.alloc_request = m66592_alloc_request,
.free_request = m66592_free_request,
.queue = m66592_queue,
.dequeue = m66592_dequeue,
.set_halt = m66592_set_halt,
.fifo_flush = m66592_fifo_flush,
};
/*-------------------------------------------------------------------------*/
static struct m66592 *the_controller;
static int m66592_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *))
{
struct m66592 *m66592 = the_controller;
int retval;
if (!driver
|| driver->max_speed < USB_SPEED_HIGH
|| !bind
|| !driver->setup)
return -EINVAL;
if (!m66592)
return -ENODEV;
if (m66592->driver)
return -EBUSY;
/* hook up the driver */
driver->driver.bus = NULL;
m66592->driver = driver;
m66592->gadget.dev.driver = &driver->driver;
retval = device_add(&m66592->gadget.dev);
if (retval) {
pr_err("device_add error (%d)\n", retval);
goto error;
}
retval = bind(&m66592->gadget);
if (retval) {
pr_err("bind to driver error (%d)\n", retval);
device_del(&m66592->gadget.dev);
goto error;
}
m66592_bset(m66592, M66592_VBSE | M66592_URST, M66592_INTENB0);
if (m66592_read(m66592, M66592_INTSTS0) & M66592_VBSTS) {
m66592_start_xclock(m66592);
/* start vbus sampling */
m66592->old_vbus = m66592_read(m66592,
M66592_INTSTS0) & M66592_VBSTS;
m66592->scount = M66592_MAX_SAMPLING;
mod_timer(&m66592->timer, jiffies + msecs_to_jiffies(50));
}
return 0;
error:
m66592->driver = NULL;
m66592->gadget.dev.driver = NULL;
return retval;
}
static int m66592_stop(struct usb_gadget_driver *driver)
{
struct m66592 *m66592 = the_controller;
unsigned long flags;
if (driver != m66592->driver || !driver->unbind)
return -EINVAL;
spin_lock_irqsave(&m66592->lock, flags);
if (m66592->gadget.speed != USB_SPEED_UNKNOWN)
m66592_usb_disconnect(m66592);
spin_unlock_irqrestore(&m66592->lock, flags);
m66592_bclr(m66592, M66592_VBSE | M66592_URST, M66592_INTENB0);
driver->unbind(&m66592->gadget);
m66592->gadget.dev.driver = NULL;
init_controller(m66592);
disable_controller(m66592);
device_del(&m66592->gadget.dev);
m66592->driver = NULL;
return 0;
}
/*-------------------------------------------------------------------------*/
static int m66592_get_frame(struct usb_gadget *_gadget)
{
struct m66592 *m66592 = gadget_to_m66592(_gadget);
return m66592_read(m66592, M66592_FRMNUM) & 0x03FF;
}
static int m66592_pullup(struct usb_gadget *gadget, int is_on)
{
struct m66592 *m66592 = gadget_to_m66592(gadget);
unsigned long flags;
spin_lock_irqsave(&m66592->lock, flags);
if (is_on)
m66592_bset(m66592, M66592_DPRPU, M66592_SYSCFG);
else
m66592_bclr(m66592, M66592_DPRPU, M66592_SYSCFG);
spin_unlock_irqrestore(&m66592->lock, flags);
return 0;
}
static struct usb_gadget_ops m66592_gadget_ops = {
.get_frame = m66592_get_frame,
.start = m66592_start,
.stop = m66592_stop,
.pullup = m66592_pullup,
};
static int __exit m66592_remove(struct platform_device *pdev)
{
struct m66592 *m66592 = dev_get_drvdata(&pdev->dev);
usb_del_gadget_udc(&m66592->gadget);
del_timer_sync(&m66592->timer);
iounmap(m66592->reg);
free_irq(platform_get_irq(pdev, 0), m66592);
m66592_free_request(&m66592->ep[0].ep, m66592->ep0_req);
#ifdef CONFIG_HAVE_CLK
if (m66592->pdata->on_chip) {
clk_disable(m66592->clk);
clk_put(m66592->clk);
}
#endif
kfree(m66592);
return 0;
}
static void nop_completion(struct usb_ep *ep, struct usb_request *r)
{
}
static int __init m66592_probe(struct platform_device *pdev)
{
struct resource *res, *ires;
void __iomem *reg = NULL;
struct m66592 *m66592 = NULL;
#ifdef CONFIG_HAVE_CLK
char clk_name[8];
#endif
int ret = 0;
int i;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
pr_err("platform_get_resource error.\n");
goto clean_up;
}
ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!ires) {
ret = -ENODEV;
dev_err(&pdev->dev,
"platform_get_resource IORESOURCE_IRQ error.\n");
goto clean_up;
}
reg = ioremap(res->start, resource_size(res));
if (reg == NULL) {
ret = -ENOMEM;
pr_err("ioremap error.\n");
goto clean_up;
}
if (pdev->dev.platform_data == NULL) {
dev_err(&pdev->dev, "no platform data\n");
ret = -ENODEV;
goto clean_up;
}
/* initialize ucd */
m66592 = kzalloc(sizeof(struct m66592), GFP_KERNEL);
if (m66592 == NULL) {
ret = -ENOMEM;
pr_err("kzalloc error\n");
goto clean_up;
}
m66592->pdata = pdev->dev.platform_data;
m66592->irq_trigger = ires->flags & IRQF_TRIGGER_MASK;
spin_lock_init(&m66592->lock);
dev_set_drvdata(&pdev->dev, m66592);
m66592->gadget.ops = &m66592_gadget_ops;
device_initialize(&m66592->gadget.dev);
dev_set_name(&m66592->gadget.dev, "gadget");
m66592->gadget.max_speed = USB_SPEED_HIGH;
m66592->gadget.dev.parent = &pdev->dev;
m66592->gadget.dev.dma_mask = pdev->dev.dma_mask;
m66592->gadget.dev.release = pdev->dev.release;
m66592->gadget.name = udc_name;
init_timer(&m66592->timer);
m66592->timer.function = m66592_timer;
m66592->timer.data = (unsigned long)m66592;
m66592->reg = reg;
ret = request_irq(ires->start, m66592_irq, IRQF_SHARED,
udc_name, m66592);
if (ret < 0) {
pr_err("request_irq error (%d)\n", ret);
goto clean_up;
}
#ifdef CONFIG_HAVE_CLK
if (m66592->pdata->on_chip) {
snprintf(clk_name, sizeof(clk_name), "usbf%d", pdev->id);
m66592->clk = clk_get(&pdev->dev, clk_name);
if (IS_ERR(m66592->clk)) {
dev_err(&pdev->dev, "cannot get clock \"%s\"\n",
clk_name);
ret = PTR_ERR(m66592->clk);
goto clean_up2;
}
clk_enable(m66592->clk);
}
#endif
INIT_LIST_HEAD(&m66592->gadget.ep_list);
m66592->gadget.ep0 = &m66592->ep[0].ep;
INIT_LIST_HEAD(&m66592->gadget.ep0->ep_list);
for (i = 0; i < M66592_MAX_NUM_PIPE; i++) {
struct m66592_ep *ep = &m66592->ep[i];
if (i != 0) {
INIT_LIST_HEAD(&m66592->ep[i].ep.ep_list);
list_add_tail(&m66592->ep[i].ep.ep_list,
&m66592->gadget.ep_list);
}
ep->m66592 = m66592;
INIT_LIST_HEAD(&ep->queue);
ep->ep.name = m66592_ep_name[i];
ep->ep.ops = &m66592_ep_ops;
ep->ep.maxpacket = 512;
}
m66592->ep[0].ep.maxpacket = 64;
m66592->ep[0].pipenum = 0;
m66592->ep[0].fifoaddr = M66592_CFIFO;
m66592->ep[0].fifosel = M66592_CFIFOSEL;
m66592->ep[0].fifoctr = M66592_CFIFOCTR;
m66592->ep[0].fifotrn = 0;
m66592->ep[0].pipectr = get_pipectr_addr(0);
m66592->pipenum2ep[0] = &m66592->ep[0];
m66592->epaddr2ep[0] = &m66592->ep[0];
the_controller = m66592;
m66592->ep0_req = m66592_alloc_request(&m66592->ep[0].ep, GFP_KERNEL);
if (m66592->ep0_req == NULL)
goto clean_up3;
m66592->ep0_req->complete = nop_completion;
init_controller(m66592);
ret = usb_add_gadget_udc(&pdev->dev, &m66592->gadget);
if (ret)
goto err_add_udc;
dev_info(&pdev->dev, "version %s\n", DRIVER_VERSION);
return 0;
err_add_udc:
m66592_free_request(&m66592->ep[0].ep, m66592->ep0_req);
clean_up3:
#ifdef CONFIG_HAVE_CLK
if (m66592->pdata->on_chip) {
clk_disable(m66592->clk);
clk_put(m66592->clk);
}
clean_up2:
#endif
free_irq(ires->start, m66592);
clean_up:
if (m66592) {
if (m66592->ep0_req)
m66592_free_request(&m66592->ep[0].ep, m66592->ep0_req);
kfree(m66592);
}
if (reg)
iounmap(reg);
return ret;
}
/*-------------------------------------------------------------------------*/
static struct platform_driver m66592_driver = {
.remove = __exit_p(m66592_remove),
.driver = {
.name = (char *) udc_name,
.owner = THIS_MODULE,
},
};
static int __init m66592_udc_init(void)
{
return platform_driver_probe(&m66592_driver, m66592_probe);
}
module_init(m66592_udc_init);
static void __exit m66592_udc_cleanup(void)
{
platform_driver_unregister(&m66592_driver);
}
module_exit(m66592_udc_cleanup);
| gpl-2.0 |
NoelMacwan/SXDHuashan | drivers/gpu/drm/nouveau/nv20_fb.c | 5407 | 3880 | #include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_drm.h"
static struct drm_mm_node *
nv20_fb_alloc_tag(struct drm_device *dev, uint32_t size)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fb_engine *pfb = &dev_priv->engine.fb;
struct drm_mm_node *mem;
int ret;
ret = drm_mm_pre_get(&pfb->tag_heap);
if (ret)
return NULL;
spin_lock(&dev_priv->tile.lock);
mem = drm_mm_search_free(&pfb->tag_heap, size, 0, 0);
if (mem)
mem = drm_mm_get_block_atomic(mem, size, 0);
spin_unlock(&dev_priv->tile.lock);
return mem;
}
static void
nv20_fb_free_tag(struct drm_device *dev, struct drm_mm_node **pmem)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct drm_mm_node *mem = *pmem;
if (mem) {
spin_lock(&dev_priv->tile.lock);
drm_mm_put_block(mem);
spin_unlock(&dev_priv->tile.lock);
*pmem = NULL;
}
}
void
nv20_fb_init_tile_region(struct drm_device *dev, int i, uint32_t addr,
uint32_t size, uint32_t pitch, uint32_t flags)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_tile_reg *tile = &dev_priv->tile.reg[i];
int bpp = (flags & NOUVEAU_GEM_TILE_32BPP ? 32 : 16);
tile->addr = 0x00000001 | addr;
tile->limit = max(1u, addr + size) - 1;
tile->pitch = pitch;
/* Allocate some of the on-die tag memory, used to store Z
* compression meta-data (most likely just a bitmap determining
* if a given tile is compressed or not).
*/
if (flags & NOUVEAU_GEM_TILE_ZETA) {
tile->tag_mem = nv20_fb_alloc_tag(dev, size / 256);
if (tile->tag_mem) {
/* Enable Z compression */
tile->zcomp = tile->tag_mem->start;
if (dev_priv->chipset >= 0x25) {
if (bpp == 16)
tile->zcomp |= NV25_PFB_ZCOMP_MODE_16;
else
tile->zcomp |= NV25_PFB_ZCOMP_MODE_32;
} else {
tile->zcomp |= NV20_PFB_ZCOMP_EN;
if (bpp != 16)
tile->zcomp |= NV20_PFB_ZCOMP_MODE_32;
}
}
tile->addr |= 2;
}
}
void
nv20_fb_free_tile_region(struct drm_device *dev, int i)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_tile_reg *tile = &dev_priv->tile.reg[i];
tile->addr = tile->limit = tile->pitch = tile->zcomp = 0;
nv20_fb_free_tag(dev, &tile->tag_mem);
}
void
nv20_fb_set_tile_region(struct drm_device *dev, int i)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_tile_reg *tile = &dev_priv->tile.reg[i];
nv_wr32(dev, NV10_PFB_TLIMIT(i), tile->limit);
nv_wr32(dev, NV10_PFB_TSIZE(i), tile->pitch);
nv_wr32(dev, NV10_PFB_TILE(i), tile->addr);
nv_wr32(dev, NV20_PFB_ZCOMP(i), tile->zcomp);
}
int
nv20_fb_vram_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
u32 mem_size = nv_rd32(dev, 0x10020c);
u32 pbus1218 = nv_rd32(dev, 0x001218);
dev_priv->vram_size = mem_size & 0xff000000;
switch (pbus1218 & 0x00000300) {
case 0x00000000: dev_priv->vram_type = NV_MEM_TYPE_SDRAM; break;
case 0x00000100: dev_priv->vram_type = NV_MEM_TYPE_DDR1; break;
case 0x00000200: dev_priv->vram_type = NV_MEM_TYPE_GDDR3; break;
case 0x00000300: dev_priv->vram_type = NV_MEM_TYPE_GDDR2; break;
}
return 0;
}
int
nv20_fb_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fb_engine *pfb = &dev_priv->engine.fb;
int i;
if (dev_priv->chipset >= 0x25)
drm_mm_init(&pfb->tag_heap, 0, 64 * 1024);
else
drm_mm_init(&pfb->tag_heap, 0, 32 * 1024);
/* Turn all the tiling regions off. */
pfb->num_tiles = NV10_PFB_TILE__SIZE;
for (i = 0; i < pfb->num_tiles; i++)
pfb->set_tile_region(dev, i);
return 0;
}
void
nv20_fb_takedown(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fb_engine *pfb = &dev_priv->engine.fb;
int i;
for (i = 0; i < pfb->num_tiles; i++)
pfb->free_tile_region(dev, i);
drm_mm_takedown(&pfb->tag_heap);
}
| gpl-2.0 |
desteam/android_kernel_huawei_msm7x30 | arch/arm/mach-s5p64x0/clock.c | 7711 | 5439 | /* linux/arch/arm/mach-s5p64x0/clock.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* S5P64X0 - Clock support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <plat/cpu-freq.h>
#include <plat/clock.h>
#include <plat/cpu.h>
#include <plat/pll.h>
#include <plat/s5p-clock.h>
#include <plat/clock-clksrc.h>
#include "common.h"
struct clksrc_clk clk_mout_apll = {
.clk = {
.name = "mout_apll",
.id = -1,
},
.sources = &clk_src_apll,
.reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 0, .size = 1 },
};
struct clksrc_clk clk_mout_mpll = {
.clk = {
.name = "mout_mpll",
.id = -1,
},
.sources = &clk_src_mpll,
.reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 1, .size = 1 },
};
struct clksrc_clk clk_mout_epll = {
.clk = {
.name = "mout_epll",
.id = -1,
},
.sources = &clk_src_epll,
.reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 2, .size = 1 },
};
enum perf_level {
L0 = 532*1000,
L1 = 266*1000,
L2 = 133*1000,
};
static const u32 clock_table[][3] = {
/*{ARM_CLK, DIVarm, DIVhclk}*/
{L0 * 1000, (0 << ARM_DIV_RATIO_SHIFT), (3 << S5P64X0_CLKDIV0_HCLK_SHIFT)},
{L1 * 1000, (1 << ARM_DIV_RATIO_SHIFT), (1 << S5P64X0_CLKDIV0_HCLK_SHIFT)},
{L2 * 1000, (3 << ARM_DIV_RATIO_SHIFT), (0 << S5P64X0_CLKDIV0_HCLK_SHIFT)},
};
static unsigned long s5p64x0_armclk_get_rate(struct clk *clk)
{
unsigned long rate = clk_get_rate(clk->parent);
u32 clkdiv;
/* divisor mask starts at bit0, so no need to shift */
clkdiv = __raw_readl(ARM_CLK_DIV) & ARM_DIV_MASK;
return rate / (clkdiv + 1);
}
static unsigned long s5p64x0_armclk_round_rate(struct clk *clk,
unsigned long rate)
{
u32 iter;
for (iter = 1 ; iter < ARRAY_SIZE(clock_table) ; iter++) {
if (rate > clock_table[iter][0])
return clock_table[iter-1][0];
}
return clock_table[ARRAY_SIZE(clock_table) - 1][0];
}
static int s5p64x0_armclk_set_rate(struct clk *clk, unsigned long rate)
{
u32 round_tmp;
u32 iter;
u32 clk_div0_tmp;
u32 cur_rate = clk->ops->get_rate(clk);
unsigned long flags;
round_tmp = clk->ops->round_rate(clk, rate);
if (round_tmp == cur_rate)
return 0;
for (iter = 0 ; iter < ARRAY_SIZE(clock_table) ; iter++) {
if (round_tmp == clock_table[iter][0])
break;
}
if (iter >= ARRAY_SIZE(clock_table))
iter = ARRAY_SIZE(clock_table) - 1;
local_irq_save(flags);
if (cur_rate > round_tmp) {
/* Frequency Down */
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) & ~(ARM_DIV_MASK);
clk_div0_tmp |= clock_table[iter][1];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) &
~(S5P64X0_CLKDIV0_HCLK_MASK);
clk_div0_tmp |= clock_table[iter][2];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
} else {
/* Frequency Up */
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) &
~(S5P64X0_CLKDIV0_HCLK_MASK);
clk_div0_tmp |= clock_table[iter][2];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) & ~(ARM_DIV_MASK);
clk_div0_tmp |= clock_table[iter][1];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
}
local_irq_restore(flags);
clk->rate = clock_table[iter][0];
return 0;
}
static struct clk_ops s5p64x0_clkarm_ops = {
.get_rate = s5p64x0_armclk_get_rate,
.set_rate = s5p64x0_armclk_set_rate,
.round_rate = s5p64x0_armclk_round_rate,
};
struct clksrc_clk clk_armclk = {
.clk = {
.name = "armclk",
.id = 1,
.parent = &clk_mout_apll.clk,
.ops = &s5p64x0_clkarm_ops,
},
.reg_div = { .reg = S5P64X0_CLK_DIV0, .shift = 0, .size = 4 },
};
struct clksrc_clk clk_dout_mpll = {
.clk = {
.name = "dout_mpll",
.id = -1,
.parent = &clk_mout_mpll.clk,
},
.reg_div = { .reg = S5P64X0_CLK_DIV0, .shift = 4, .size = 1 },
};
static struct clk *clkset_hclk_low_list[] = {
&clk_mout_apll.clk,
&clk_mout_mpll.clk,
};
struct clksrc_sources clkset_hclk_low = {
.sources = clkset_hclk_low_list,
.nr_sources = ARRAY_SIZE(clkset_hclk_low_list),
};
int s5p64x0_pclk_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_PCLK, clk, enable);
}
int s5p64x0_hclk0_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_HCLK0, clk, enable);
}
int s5p64x0_hclk1_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_HCLK1, clk, enable);
}
int s5p64x0_sclk_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_SCLK0, clk, enable);
}
int s5p64x0_sclk1_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_SCLK1, clk, enable);
}
int s5p64x0_mem_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_MEM0, clk, enable);
}
int s5p64x0_clk48m_ctrl(struct clk *clk, int enable)
{
unsigned long flags;
u32 val;
/* can't rely on clock lock, this register has other usages */
local_irq_save(flags);
val = __raw_readl(S5P64X0_OTHERS);
if (enable)
val |= S5P64X0_OTHERS_USB_SIG_MASK;
else
val &= ~S5P64X0_OTHERS_USB_SIG_MASK;
__raw_writel(val, S5P64X0_OTHERS);
local_irq_restore(flags);
return 0;
}
| gpl-2.0 |
drikinukoda/android_kernel_lge_e8lte | drivers/staging/winbond/reg.c | 8223 | 92476 | #include "wbhal.h"
#include "wb35reg_f.h"
#include "core.h"
/*
* ====================================================
* Original Phy.h
* ====================================================
*/
/*
* ====================================================
* For MAXIM2825/6/7 Ver. 331 or more
*
* 0x00 0x000a2
* 0x01 0x21cc0
* 0x02 0x13802
* 0x02 0x1383a
*
* channe1 01 ; 0x03 0x30142 ; 0x04 0x0b333;
* channe1 02 ; 0x03 0x32141 ; 0x04 0x08444;
* channe1 03 ; 0x03 0x32143 ; 0x04 0x0aeee;
* channe1 04 ; 0x03 0x32142 ; 0x04 0x0b333;
* channe1 05 ; 0x03 0x31141 ; 0x04 0x08444;
* channe1 06 ; 0x03 0x31143 ; 0x04 0x0aeee;
* channe1 07 ; 0x03 0x31142 ; 0x04 0x0b333;
* channe1 08 ; 0x03 0x33141 ; 0x04 0x08444;
* channe1 09 ; 0x03 0x33143 ; 0x04 0x0aeee;
* channe1 10 ; 0x03 0x33142 ; 0x04 0x0b333;
* channe1 11 ; 0x03 0x30941 ; 0x04 0x08444;
* channe1 12 ; 0x03 0x30943 ; 0x04 0x0aeee;
* channe1 13 ; 0x03 0x30942 ; 0x04 0x0b333;
*
* 0x05 0x28986
* 0x06 0x18008
* 0x07 0x38400
* 0x08 0x05100; 100 Hz DC
* 0x08 0x05900; 30 KHz DC
* 0x09 0x24f08
* 0x0a 0x17e00, 0x17ea0
* 0x0b 0x37d80
* 0x0c 0x0c900 -- 0x0ca00 (lager power 9db than 0x0c000), 0x0c000
*/
/* MAX2825 (pure b/g) */
u32 max2825_rf_data[] = {
(0x00<<18) | 0x000a2,
(0x01<<18) | 0x21cc0,
(0x02<<18) | 0x13806,
(0x03<<18) | 0x30142,
(0x04<<18) | 0x0b333,
(0x05<<18) | 0x289A6,
(0x06<<18) | 0x18008,
(0x07<<18) | 0x38000,
(0x08<<18) | 0x05100,
(0x09<<18) | 0x24f08,
(0x0A<<18) | 0x14000,
(0x0B<<18) | 0x37d80,
(0x0C<<18) | 0x0c100 /* 11a: 0x0c300, 11g: 0x0c100 */
};
u32 max2825_channel_data_24[][3] = {
{(0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 01 */
{(0x03 << 18) | 0x32141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 02 */
{(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 03 */
{(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 04 */
{(0x03 << 18) | 0x31141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 05 */
{(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 06 */
{(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 07 */
{(0x03 << 18) | 0x33141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 08 */
{(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 09 */
{(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 10 */
{(0x03 << 18) | 0x30941, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channel 11 */
{(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channel 12 */
{(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 13 */
{(0x03 << 18) | 0x32941, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6} /* channel 14 (2484MHz) */
};
u32 max2825_power_data_24[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100};
/* ========================================== */
/* MAX2827 (a/b/g) */
u32 max2827_rf_data[] = {
(0x00 << 18) | 0x000a2,
(0x01 << 18) | 0x21cc0,
(0x02 << 18) | 0x13806,
(0x03 << 18) | 0x30142,
(0x04 << 18) | 0x0b333,
(0x05 << 18) | 0x289A6,
(0x06 << 18) | 0x18008,
(0x07 << 18) | 0x38000,
(0x08 << 18) | 0x05100,
(0x09 << 18) | 0x24f08,
(0x0A << 18) | 0x14000,
(0x0B << 18) | 0x37d80,
(0x0C << 18) | 0x0c100 /* 11a: 0x0c300, 11g: 0x0c100 */
};
u32 max2827_channel_data_24[][3] = {
{(0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 01 */
{(0x03 << 18) | 0x32141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 02 */
{(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 03 */
{(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 04 */
{(0x03 << 18) | 0x31141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 05 */
{(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 06 */
{(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 07 */
{(0x03 << 18) | 0x33141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 08 */
{(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 09 */
{(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 10 */
{(0x03 << 18) | 0x30941, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 11 */
{(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 12 */
{(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 13 */
{(0x03 << 18) | 0x32941, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6} /* channel 14 (2484MHz) */
};
u32 max2827_channel_data_50[][3] = {
{(0x03 << 18) | 0x33cc3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x2A9A6}, /* channel 36 */
{(0x03 << 18) | 0x302c0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2A9A6}, /* channel 40 */
{(0x03 << 18) | 0x302c2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2A9A6}, /* channel 44 */
{(0x03 << 18) | 0x322c1, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x2A9A6}, /* channel 48 */
{(0x03 << 18) | 0x312c1, (0x04 << 18) | 0x0a666, (0x05 << 18) | 0x2A9A6}, /* channel 52 */
{(0x03 << 18) | 0x332c3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x2A9A6}, /* channel 56 */
{(0x03 << 18) | 0x30ac0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2A9A6}, /* channel 60 */
{(0x03 << 18) | 0x30ac2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2A9A6} /* channel 64 */
};
u32 max2827_power_data_24[] = {(0x0C << 18) | 0x0C000, (0x0C << 18) | 0x0D600, (0x0C << 18) | 0x0C100};
u32 max2827_power_data_50[] = {(0x0C << 18) | 0x0C400, (0x0C << 18) | 0x0D500, (0x0C << 18) | 0x0C300};
/* ======================================================= */
/* MAX2828 (a/b/g) */
u32 max2828_rf_data[] = {
(0x00 << 18) | 0x000a2,
(0x01 << 18) | 0x21cc0,
(0x02 << 18) | 0x13806,
(0x03 << 18) | 0x30142,
(0x04 << 18) | 0x0b333,
(0x05 << 18) | 0x289A6,
(0x06 << 18) | 0x18008,
(0x07 << 18) | 0x38000,
(0x08 << 18) | 0x05100,
(0x09 << 18) | 0x24f08,
(0x0A << 18) | 0x14000,
(0x0B << 18) | 0x37d80,
(0x0C << 18) | 0x0c100 /* 11a: 0x0c300, 11g: 0x0c100 */
};
u32 max2828_channel_data_24[][3] = {
{(0x03 << 18) | 0x30142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 01 */
{(0x03 << 18) | 0x32141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 02 */
{(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 03 */
{(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 04 */
{(0x03 << 18) | 0x31141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 05 */
{(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 06 */
{(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 07 */
{(0x03 << 18) | 0x33141, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 08 */
{(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 09 */
{(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 10 */
{(0x03 << 18) | 0x30941, (0x04 << 18) | 0x08444, (0x05 << 18) | 0x289A6}, /* channe1 11 */
{(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0aeee, (0x05 << 18) | 0x289A6}, /* channe1 12 */
{(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channe1 13 */
{(0x03 << 18) | 0x32941, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6} /* channel 14 (2484MHz) */
};
u32 max2828_channel_data_50[][3] = {
{(0x03 << 18) | 0x33cc3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x289A6}, /* channel 36 */
{(0x03 << 18) | 0x302c0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x289A6}, /* channel 40 */
{(0x03 << 18) | 0x302c2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6}, /* channel 44 */
{(0x03 << 18) | 0x322c1, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x289A6}, /* channel 48 */
{(0x03 << 18) | 0x312c1, (0x04 << 18) | 0x0a666, (0x05 << 18) | 0x289A6}, /* channel 52 */
{(0x03 << 18) | 0x332c3, (0x04 << 18) | 0x08ccc, (0x05 << 18) | 0x289A6}, /* channel 56 */
{(0x03 << 18) | 0x30ac0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x289A6}, /* channel 60 */
{(0x03 << 18) | 0x30ac2, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x289A6} /* channel 64 */
};
u32 max2828_power_data_24[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100};
u32 max2828_power_data_50[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100};
/* ========================================================== */
/* MAX2829 (a/b/g) */
u32 max2829_rf_data[] = {
(0x00 << 18) | 0x000a2,
(0x01 << 18) | 0x23520,
(0x02 << 18) | 0x13802,
(0x03 << 18) | 0x30142,
(0x04 << 18) | 0x0b333,
(0x05 << 18) | 0x28906,
(0x06 << 18) | 0x18008,
(0x07 << 18) | 0x3B500,
(0x08 << 18) | 0x05100,
(0x09 << 18) | 0x24f08,
(0x0A << 18) | 0x14000,
(0x0B << 18) | 0x37d80,
(0x0C << 18) | 0x0F300 /* TXVGA=51, (MAX-6 dB) */
};
u32 max2829_channel_data_24[][3] = {
{(3 << 18) | 0x30142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 01 (2412MHz) */
{(3 << 18) | 0x32141, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 02 (2417MHz) */
{(3 << 18) | 0x32143, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 03 (2422MHz) */
{(3 << 18) | 0x32142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 04 (2427MHz) */
{(3 << 18) | 0x31141, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 05 (2432MHz) */
{(3 << 18) | 0x31143, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 06 (2437MHz) */
{(3 << 18) | 0x31142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 07 (2442MHz) */
{(3 << 18) | 0x33141, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 08 (2447MHz) */
{(3 << 18) | 0x33143, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 09 (2452MHz) */
{(3 << 18) | 0x33142, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 10 (2457MHz) */
{(3 << 18) | 0x30941, (4 << 18) | 0x08444, (5 << 18) | 0x289C6}, /* 11 (2462MHz) */
{(3 << 18) | 0x30943, (4 << 18) | 0x0aeee, (5 << 18) | 0x289C6}, /* 12 (2467MHz) */
{(3 << 18) | 0x30942, (4 << 18) | 0x0b333, (5 << 18) | 0x289C6}, /* 13 (2472MHz) */
{(3 << 18) | 0x32941, (4 << 18) | 0x09999, (5 << 18) | 0x289C6}, /* 14 (2484MHz) */
};
u32 max2829_channel_data_50[][4] = {
{36, (3 << 18) | 0x33cc3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 36 (5.180GHz) */
{40, (3 << 18) | 0x302c0, (4 << 18) | 0x08000, (5 << 18) | 0x2A946}, /* 40 (5.200GHz) */
{44, (3 << 18) | 0x302c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 44 (5.220GHz) */
{48, (3 << 18) | 0x322c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 48 (5.240GHz) */
{52, (3 << 18) | 0x312c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 52 (5.260GHz) */
{56, (3 << 18) | 0x332c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 56 (5.280GHz) */
{60, (3 << 18) | 0x30ac0, (4 << 18) | 0x08000, (5 << 18) | 0x2A946}, /* 60 (5.300GHz) */
{64, (3 << 18) | 0x30ac2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 64 (5.320GHz) */
{100, (3 << 18) | 0x30ec0, (4 << 18) | 0x08000, (5 << 18) | 0x2A9C6}, /* 100 (5.500GHz) */
{104, (3 << 18) | 0x30ec2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A9C6}, /* 104 (5.520GHz) */
{108, (3 << 18) | 0x32ec1, (4 << 18) | 0x09999, (5 << 18) | 0x2A9C6}, /* 108 (5.540GHz) */
{112, (3 << 18) | 0x31ec1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A9C6}, /* 112 (5.560GHz) */
{116, (3 << 18) | 0x33ec3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A9C6}, /* 116 (5.580GHz) */
{120, (3 << 18) | 0x301c0, (4 << 18) | 0x08000, (5 << 18) | 0x2A9C6}, /* 120 (5.600GHz) */
{124, (3 << 18) | 0x301c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A9C6}, /* 124 (5.620GHz) */
{128, (3 << 18) | 0x321c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A9C6}, /* 128 (5.640GHz) */
{132, (3 << 18) | 0x311c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A9C6}, /* 132 (5.660GHz) */
{136, (3 << 18) | 0x331c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A9C6}, /* 136 (5.680GHz) */
{140, (3 << 18) | 0x309c0, (4 << 18) | 0x08000, (5 << 18) | 0x2A9C6}, /* 140 (5.700GHz) */
{149, (3 << 18) | 0x329c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A9C6}, /* 149 (5.745GHz) */
{153, (3 << 18) | 0x319c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A9C6}, /* 153 (5.765GHz) */
{157, (3 << 18) | 0x339c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A9C6}, /* 157 (5.785GHz) */
{161, (3 << 18) | 0x305c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A9C6}, /* 161 (5.805GHz) */
/* Japan */
{ 184, (3 << 18) | 0x308c2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 184 (4.920GHz) */
{ 188, (3 << 18) | 0x328c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 188 (4.940GHz) */
{ 192, (3 << 18) | 0x318c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 192 (4.960GHz) */
{ 196, (3 << 18) | 0x338c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 196 (4.980GHz) */
{ 8, (3 << 18) | 0x324c1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 8 (5.040GHz) */
{ 12, (3 << 18) | 0x314c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 12 (5.060GHz) */
{ 16, (3 << 18) | 0x334c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 16 (5.080GHz) */
{ 34, (3 << 18) | 0x31cc2, (4 << 18) | 0x0b333, (5 << 18) | 0x2A946}, /* 34 (5.170GHz) */
{ 38, (3 << 18) | 0x33cc1, (4 << 18) | 0x09999, (5 << 18) | 0x2A946}, /* 38 (5.190GHz) */
{ 42, (3 << 18) | 0x302c1, (4 << 18) | 0x0a666, (5 << 18) | 0x2A946}, /* 42 (5.210GHz) */
{ 46, (3 << 18) | 0x322c3, (4 << 18) | 0x08ccc, (5 << 18) | 0x2A946}, /* 46 (5.230GHz) */
};
/*
* ====================================================================
* For MAXIM2825/6/7 Ver. 317 or less
*
* 0x00 0x00080
* 0x01 0x214c0
* 0x02 0x13802
*
* 2.4GHz Channels
* channe1 01 (2.412GHz); 0x03 0x30143 ;0x04 0x0accc
* channe1 02 (2.417GHz); 0x03 0x32140 ;0x04 0x09111
* channe1 03 (2.422GHz); 0x03 0x32142 ;0x04 0x0bbbb
* channe1 04 (2.427GHz); 0x03 0x32143 ;0x04 0x0accc
* channe1 05 (2.432GHz); 0x03 0x31140 ;0x04 0x09111
* channe1 06 (2.437GHz); 0x03 0x31142 ;0x04 0x0bbbb
* channe1 07 (2.442GHz); 0x03 0x31143 ;0x04 0x0accc
* channe1 08 (2.447GHz); 0x03 0x33140 ;0x04 0x09111
* channe1 09 (2.452GHz); 0x03 0x33142 ;0x04 0x0bbbb
* channe1 10 (2.457GHz); 0x03 0x33143 ;0x04 0x0accc
* channe1 11 (2.462GHz); 0x03 0x30940 ;0x04 0x09111
* channe1 12 (2.467GHz); 0x03 0x30942 ;0x04 0x0bbbb
* channe1 13 (2.472GHz); 0x03 0x30943 ;0x04 0x0accc
*
* 5.0Ghz Channels
* channel 36 (5.180GHz); 0x03 0x33cc0 ;0x04 0x0b333
* channel 40 (5.200GHz); 0x03 0x302c0 ;0x04 0x08000
* channel 44 (5.220GHz); 0x03 0x302c2 ;0x04 0x0b333
* channel 48 (5.240GHz); 0x03 0x322c1 ;0x04 0x09999
* channel 52 (5.260GHz); 0x03 0x312c1 ;0x04 0x0a666
* channel 56 (5.280GHz); 0x03 0x332c3 ;0x04 0x08ccc
* channel 60 (5.300GHz); 0x03 0x30ac0 ;0x04 0x08000
* channel 64 (5.320GHz); 0x03 0x30ac2 ;0x04 0x08333
*
* 2.4GHz band ; 0x05 0x28986;
* 5.0GHz band ; 0x05 0x2a986
* 0x06 0x18008
* 0x07 0x38400
* 0x08 0x05108
* 0x09 0x27ff8
* 0x0a 0x14000
* 0x0b 0x37f99
* 0x0c 0x0c000
* ====================================================================
*/
u32 maxim_317_rf_data[] = {
(0x00 << 18) | 0x000a2,
(0x01 << 18) | 0x214c0,
(0x02 << 18) | 0x13802,
(0x03 << 18) | 0x30143,
(0x04 << 18) | 0x0accc,
(0x05 << 18) | 0x28986,
(0x06 << 18) | 0x18008,
(0x07 << 18) | 0x38400,
(0x08 << 18) | 0x05108,
(0x09 << 18) | 0x27ff8,
(0x0A << 18) | 0x14000,
(0x0B << 18) | 0x37f99,
(0x0C << 18) | 0x0c000
};
u32 maxim_317_channel_data_24[][3] = {
{(0x03 << 18) | 0x30143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 01 */
{(0x03 << 18) | 0x32140, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 02 */
{(0x03 << 18) | 0x32142, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 03 */
{(0x03 << 18) | 0x32143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 04 */
{(0x03 << 18) | 0x31140, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 05 */
{(0x03 << 18) | 0x31142, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 06 */
{(0x03 << 18) | 0x31143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 07 */
{(0x03 << 18) | 0x33140, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 08 */
{(0x03 << 18) | 0x33142, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 09 */
{(0x03 << 18) | 0x33143, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986}, /* channe1 10 */
{(0x03 << 18) | 0x30940, (0x04 << 18) | 0x09111, (0x05 << 18) | 0x28986}, /* channe1 11 */
{(0x03 << 18) | 0x30942, (0x04 << 18) | 0x0bbbb, (0x05 << 18) | 0x28986}, /* channe1 12 */
{(0x03 << 18) | 0x30943, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x28986} /* channe1 13 */
};
u32 maxim_317_channel_data_50[][3] = {
{(0x03 << 18) | 0x33cc0, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2a986}, /* channel 36 */
{(0x03 << 18) | 0x302c0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2a986}, /* channel 40 */
{(0x03 << 18) | 0x302c3, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x2a986}, /* channel 44 */
{(0x03 << 18) | 0x322c1, (0x04 << 18) | 0x09666, (0x05 << 18) | 0x2a986}, /* channel 48 */
{(0x03 << 18) | 0x312c2, (0x04 << 18) | 0x09999, (0x05 << 18) | 0x2a986}, /* channel 52 */
{(0x03 << 18) | 0x332c0, (0x04 << 18) | 0x0b333, (0x05 << 18) | 0x2a99e}, /* channel 56 */
{(0x03 << 18) | 0x30ac0, (0x04 << 18) | 0x08000, (0x05 << 18) | 0x2a99e}, /* channel 60 */
{(0x03 << 18) | 0x30ac3, (0x04 << 18) | 0x0accc, (0x05 << 18) | 0x2a99e} /* channel 64 */
};
u32 maxim_317_power_data_24[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100};
u32 maxim_317_power_data_50[] = {(0x0C << 18) | 0x0c000, (0x0C << 18) | 0x0c100};
/*
* ===================================================================
* AL2230 MP (Mass Production Version)
* RF Registers Setting for Airoha AL2230 silicon after June 1st, 2004
* 20-bit length and LSB first
*
* Ch01 (2412MHz) ;0x00 0x09EFC ;0x01 0x8CCCC;
* Ch02 (2417MHz) ;0x00 0x09EFC ;0x01 0x8CCCD;
* Ch03 (2422MHz) ;0x00 0x09E7C ;0x01 0x8CCCC;
* Ch04 (2427MHz) ;0x00 0x09E7C ;0x01 0x8CCCD;
* Ch05 (2432MHz) ;0x00 0x05EFC ;0x01 0x8CCCC;
* Ch06 (2437MHz) ;0x00 0x05EFC ;0x01 0x8CCCD;
* Ch07 (2442MHz) ;0x00 0x05E7C ;0x01 0x8CCCC;
* Ch08 (2447MHz) ;0x00 0x05E7C ;0x01 0x8CCCD;
* Ch09 (2452MHz) ;0x00 0x0DEFC ;0x01 0x8CCCC;
* Ch10 (2457MHz) ;0x00 0x0DEFC ;0x01 0x8CCCD;
* Ch11 (2462MHz) ;0x00 0x0DE7C ;0x01 0x8CCCC;
* Ch12 (2467MHz) ;0x00 0x0DE7C ;0x01 0x8CCCD;
* Ch13 (2472MHz) ;0x00 0x03EFC ;0x01 0x8CCCC;
* Ch14 (2484Mhz) ;0x00 0x03E7C ;0x01 0x86666;
*
* 0x02 0x401D8; RXDCOC BW 100Hz for RXHP low
* 0x02 0x481DC; RXDCOC BW 30Khz for RXHP low
*
* 0x03 0xCFFF0
* 0x04 0x23800
* 0x05 0xA3B72
* 0x06 0x6DA01
* 0x07 0xE1688
* 0x08 0x11600
* 0x09 0x99E02
* 0x0A 0x5DDB0
* 0x0B 0xD9900
* 0x0C 0x3FFBD
* 0x0D 0xB0000
* 0x0F 0xF00A0
*
* RF Calibration for Airoha AL2230
*
* 0x0f 0xf00a0 ; Initial Setting
* 0x0f 0xf00b0 ; Activate TX DCC
* 0x0f 0xf02a0 ; Activate Phase Calibration
* 0x0f 0xf00e0 ; Activate Filter RC Calibration
* 0x0f 0xf00a0 ; Restore Initial Setting
* ==================================================================
*/
u32 al2230_rf_data[] = {
(0x00 << 20) | 0x09EFC,
(0x01 << 20) | 0x8CCCC,
(0x02 << 20) | 0x40058,
(0x03 << 20) | 0xCFFF0,
(0x04 << 20) | 0x24100,
(0x05 << 20) | 0xA3B2F,
(0x06 << 20) | 0x6DA01,
(0x07 << 20) | 0xE3628,
(0x08 << 20) | 0x11600,
(0x09 << 20) | 0x9DC02,
(0x0A << 20) | 0x5ddb0,
(0x0B << 20) | 0xD9900,
(0x0C << 20) | 0x3FFBD,
(0x0D << 20) | 0xB0000,
(0x0F << 20) | 0xF01A0
};
u32 al2230s_rf_data[] = {
(0x00 << 20) | 0x09EFC,
(0x01 << 20) | 0x8CCCC,
(0x02 << 20) | 0x40058,
(0x03 << 20) | 0xCFFF0,
(0x04 << 20) | 0x24100,
(0x05 << 20) | 0xA3B2F,
(0x06 << 20) | 0x6DA01,
(0x07 << 20) | 0xE3628,
(0x08 << 20) | 0x11600,
(0x09 << 20) | 0x9DC02,
(0x0A << 20) | 0x5DDB0,
(0x0B << 20) | 0xD9900,
(0x0C << 20) | 0x3FFBD,
(0x0D << 20) | 0xB0000,
(0x0F << 20) | 0xF01A0
};
u32 al2230_channel_data_24[][2] = {
{(0x00 << 20) | 0x09EFC, (0x01 << 20) | 0x8CCCC}, /* channe1 01 */
{(0x00 << 20) | 0x09EFC, (0x01 << 20) | 0x8CCCD}, /* channe1 02 */
{(0x00 << 20) | 0x09E7C, (0x01 << 20) | 0x8CCCC}, /* channe1 03 */
{(0x00 << 20) | 0x09E7C, (0x01 << 20) | 0x8CCCD}, /* channe1 04 */
{(0x00 << 20) | 0x05EFC, (0x01 << 20) | 0x8CCCC}, /* channe1 05 */
{(0x00 << 20) | 0x05EFC, (0x01 << 20) | 0x8CCCD}, /* channe1 06 */
{(0x00 << 20) | 0x05E7C, (0x01 << 20) | 0x8CCCC}, /* channe1 07 */
{(0x00 << 20) | 0x05E7C, (0x01 << 20) | 0x8CCCD}, /* channe1 08 */
{(0x00 << 20) | 0x0DEFC, (0x01 << 20) | 0x8CCCC}, /* channe1 09 */
{(0x00 << 20) | 0x0DEFC, (0x01 << 20) | 0x8CCCD}, /* channe1 10 */
{(0x00 << 20) | 0x0DE7C, (0x01 << 20) | 0x8CCCC}, /* channe1 11 */
{(0x00 << 20) | 0x0DE7C, (0x01 << 20) | 0x8CCCD}, /* channe1 12 */
{(0x00 << 20) | 0x03EFC, (0x01 << 20) | 0x8CCCC}, /* channe1 13 */
{(0x00 << 20) | 0x03E7C, (0x01 << 20) | 0x86666} /* channe1 14 */
};
/* Current setting. u32 airoha_power_data_24[] = {(0x09 << 20) | 0x90202, (0x09 << 20) | 0x96602, (0x09 << 20) | 0x97602}; */
#define AIROHA_TXVGA_LOW_INDEX 31 /* Index for 0x90202 */
#define AIROHA_TXVGA_MIDDLE_INDEX 12 /* Index for 0x96602 */
#define AIROHA_TXVGA_HIGH_INDEX 8 /* Index for 0x97602 1.0.24.0 1.0.28.0 */
u32 al2230_txvga_data[][2] = {
/* value , index */
{0x090202, 0},
{0x094202, 2},
{0x092202, 4},
{0x096202, 6},
{0x091202, 8},
{0x095202, 10},
{0x093202, 12},
{0x097202, 14},
{0x090A02, 16},
{0x094A02, 18},
{0x092A02, 20},
{0x096A02, 22},
{0x091A02, 24},
{0x095A02, 26},
{0x093A02, 28},
{0x097A02, 30},
{0x090602, 32},
{0x094602, 34},
{0x092602, 36},
{0x096602, 38},
{0x091602, 40},
{0x095602, 42},
{0x093602, 44},
{0x097602, 46},
{0x090E02, 48},
{0x098E02, 49},
{0x094E02, 50},
{0x09CE02, 51},
{0x092E02, 52},
{0x09AE02, 53},
{0x096E02, 54},
{0x09EE02, 55},
{0x091E02, 56},
{0x099E02, 57},
{0x095E02, 58},
{0x09DE02, 59},
{0x093E02, 60},
{0x09BE02, 61},
{0x097E02, 62},
{0x09FE02, 63}
};
/*
* ==========================================
* For Airoha AL7230, 2.4Ghz band
* 24bit, MSB first
*/
/* channel independent registers: */
u32 al7230_rf_data_24[] = {
(0x00 << 24) | 0x003790,
(0x01 << 24) | 0x133331,
(0x02 << 24) | 0x841FF2,
(0x03 << 24) | 0x3FDFA3,
(0x04 << 24) | 0x7FD784,
(0x05 << 24) | 0x802B55,
(0x06 << 24) | 0x56AF36,
(0x07 << 24) | 0xCE0207,
(0x08 << 24) | 0x6EBC08,
(0x09 << 24) | 0x221BB9,
(0x0A << 24) | 0xE0000A,
(0x0B << 24) | 0x08071B,
(0x0C << 24) | 0x000A3C,
(0x0D << 24) | 0xFFFFFD,
(0x0E << 24) | 0x00000E,
(0x0F << 24) | 0x1ABA8F
};
u32 al7230_channel_data_24[][2] = {
{(0x00 << 24) | 0x003790, (0x01 << 24) | 0x133331}, /* channe1 01 */
{(0x00 << 24) | 0x003790, (0x01 << 24) | 0x1B3331}, /* channe1 02 */
{(0x00 << 24) | 0x003790, (0x01 << 24) | 0x033331}, /* channe1 03 */
{(0x00 << 24) | 0x003790, (0x01 << 24) | 0x0B3331}, /* channe1 04 */
{(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x133331}, /* channe1 05 */
{(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x1B3331}, /* channe1 06 */
{(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x033331}, /* channe1 07 */
{(0x00 << 24) | 0x0037A0, (0x01 << 24) | 0x0B3331}, /* channe1 08 */
{(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x133331}, /* channe1 09 */
{(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x1B3331}, /* channe1 10 */
{(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x033331}, /* channe1 11 */
{(0x00 << 24) | 0x0037B0, (0x01 << 24) | 0x0B3331}, /* channe1 12 */
{(0x00 << 24) | 0x0037C0, (0x01 << 24) | 0x133331}, /* channe1 13 */
{(0x00 << 24) | 0x0037C0, (0x01 << 24) | 0x066661} /* channel 14 */
};
/* channel independent registers: */
u32 al7230_rf_data_50[] = {
(0x00 << 24) | 0x0FF520,
(0x01 << 24) | 0x000001,
(0x02 << 24) | 0x451FE2,
(0x03 << 24) | 0x5FDFA3,
(0x04 << 24) | 0x6FD784,
(0x05 << 24) | 0x853F55,
(0x06 << 24) | 0x56AF36,
(0x07 << 24) | 0xCE0207,
(0x08 << 24) | 0x6EBC08,
(0x09 << 24) | 0x221BB9,
(0x0A << 24) | 0xE0600A,
(0x0B << 24) | 0x08044B,
(0x0C << 24) | 0x00143C,
(0x0D << 24) | 0xFFFFFD,
(0x0E << 24) | 0x00000E,
(0x0F << 24) | 0x12BACF /* 5Ghz default state */
};
u32 al7230_channel_data_5[][4] = {
/* channel dependent registers: 0x00, 0x01 and 0x04 */
/* 11J =========== */
{184, (0x00 << 24) | 0x0FF520, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 184 */
{188, (0x00 << 24) | 0x0FF520, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 188 */
{192, (0x00 << 24) | 0x0FF530, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 192 */
{196, (0x00 << 24) | 0x0FF530, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 196 */
{8, (0x00 << 24) | 0x0FF540, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 008 */
{12, (0x00 << 24) | 0x0FF540, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 012 */
{16, (0x00 << 24) | 0x0FF550, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 016 */
{34, (0x00 << 24) | 0x0FF560, (0x01 << 24) | 0x055551, (0x04 << 24) | 0x77F784}, /* channel 034 */
{38, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x100001, (0x04 << 24) | 0x77F784}, /* channel 038 */
{42, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x1AAAA1, (0x04 << 24) | 0x77F784}, /* channel 042 */
{46, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x055551, (0x04 << 24) | 0x77F784}, /* channel 046 */
/* 11 A/H ========= */
{36, (0x00 << 24) | 0x0FF560, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 036 */
{40, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 040 */
{44, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 044 */
{48, (0x00 << 24) | 0x0FF570, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 048 */
{52, (0x00 << 24) | 0x0FF580, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 052 */
{56, (0x00 << 24) | 0x0FF580, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 056 */
{60, (0x00 << 24) | 0x0FF580, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 060 */
{64, (0x00 << 24) | 0x0FF590, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 064 */
{100, (0x00 << 24) | 0x0FF5C0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 100 */
{104, (0x00 << 24) | 0x0FF5C0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 104 */
{108, (0x00 << 24) | 0x0FF5C0, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 108 */
{112, (0x00 << 24) | 0x0FF5D0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 112 */
{116, (0x00 << 24) | 0x0FF5D0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 116 */
{120, (0x00 << 24) | 0x0FF5D0, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 120 */
{124, (0x00 << 24) | 0x0FF5E0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 124 */
{128, (0x00 << 24) | 0x0FF5E0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 128 */
{132, (0x00 << 24) | 0x0FF5E0, (0x01 << 24) | 0x0AAAA1, (0x04 << 24) | 0x77F784}, /* channel 132 */
{136, (0x00 << 24) | 0x0FF5F0, (0x01 << 24) | 0x155551, (0x04 << 24) | 0x77F784}, /* channel 136 */
{140, (0x00 << 24) | 0x0FF5F0, (0x01 << 24) | 0x000001, (0x04 << 24) | 0x67F784}, /* channel 140 */
{149, (0x00 << 24) | 0x0FF600, (0x01 << 24) | 0x180001, (0x04 << 24) | 0x77F784}, /* channel 149 */
{153, (0x00 << 24) | 0x0FF600, (0x01 << 24) | 0x02AAA1, (0x04 << 24) | 0x77F784}, /* channel 153 */
{157, (0x00 << 24) | 0x0FF600, (0x01 << 24) | 0x0D5551, (0x04 << 24) | 0x77F784}, /* channel 157 */
{161, (0x00 << 24) | 0x0FF610, (0x01 << 24) | 0x180001, (0x04 << 24) | 0x77F784}, /* channel 161 */
{165, (0x00 << 24) | 0x0FF610, (0x01 << 24) | 0x02AAA1, (0x04 << 24) | 0x77F784} /* channel 165 */
};
/*
* RF Calibration <=== Register 0x0F
* 0x0F 0x1ABA8F; start from 2.4Ghz default state
* 0x0F 0x9ABA8F; TXDC compensation
* 0x0F 0x3ABA8F; RXFIL adjustment
* 0x0F 0x1ABA8F; restore 2.4Ghz default state
*/
/* TXVGA Mapping Table <=== Register 0x0B */
u32 al7230_txvga_data[][2] = {
{0x08040B, 0}, /* TXVGA = 0; */
{0x08041B, 1}, /* TXVGA = 1; */
{0x08042B, 2}, /* TXVGA = 2; */
{0x08043B, 3}, /* TXVGA = 3; */
{0x08044B, 4}, /* TXVGA = 4; */
{0x08045B, 5}, /* TXVGA = 5; */
{0x08046B, 6}, /* TXVGA = 6; */
{0x08047B, 7}, /* TXVGA = 7; */
{0x08048B, 8}, /* TXVGA = 8; */
{0x08049B, 9}, /* TXVGA = 9; */
{0x0804AB, 10}, /* TXVGA = 10; */
{0x0804BB, 11}, /* TXVGA = 11; */
{0x0804CB, 12}, /* TXVGA = 12; */
{0x0804DB, 13}, /* TXVGA = 13; */
{0x0804EB, 14}, /* TXVGA = 14; */
{0x0804FB, 15}, /* TXVGA = 15; */
{0x08050B, 16}, /* TXVGA = 16; */
{0x08051B, 17}, /* TXVGA = 17; */
{0x08052B, 18}, /* TXVGA = 18; */
{0x08053B, 19}, /* TXVGA = 19; */
{0x08054B, 20}, /* TXVGA = 20; */
{0x08055B, 21}, /* TXVGA = 21; */
{0x08056B, 22}, /* TXVGA = 22; */
{0x08057B, 23}, /* TXVGA = 23; */
{0x08058B, 24}, /* TXVGA = 24; */
{0x08059B, 25}, /* TXVGA = 25; */
{0x0805AB, 26}, /* TXVGA = 26; */
{0x0805BB, 27}, /* TXVGA = 27; */
{0x0805CB, 28}, /* TXVGA = 28; */
{0x0805DB, 29}, /* TXVGA = 29; */
{0x0805EB, 30}, /* TXVGA = 30; */
{0x0805FB, 31}, /* TXVGA = 31; */
{0x08060B, 32}, /* TXVGA = 32; */
{0x08061B, 33}, /* TXVGA = 33; */
{0x08062B, 34}, /* TXVGA = 34; */
{0x08063B, 35}, /* TXVGA = 35; */
{0x08064B, 36}, /* TXVGA = 36; */
{0x08065B, 37}, /* TXVGA = 37; */
{0x08066B, 38}, /* TXVGA = 38; */
{0x08067B, 39}, /* TXVGA = 39; */
{0x08068B, 40}, /* TXVGA = 40; */
{0x08069B, 41}, /* TXVGA = 41; */
{0x0806AB, 42}, /* TXVGA = 42; */
{0x0806BB, 43}, /* TXVGA = 43; */
{0x0806CB, 44}, /* TXVGA = 44; */
{0x0806DB, 45}, /* TXVGA = 45; */
{0x0806EB, 46}, /* TXVGA = 46; */
{0x0806FB, 47}, /* TXVGA = 47; */
{0x08070B, 48}, /* TXVGA = 48; */
{0x08071B, 49}, /* TXVGA = 49; */
{0x08072B, 50}, /* TXVGA = 50; */
{0x08073B, 51}, /* TXVGA = 51; */
{0x08074B, 52}, /* TXVGA = 52; */
{0x08075B, 53}, /* TXVGA = 53; */
{0x08076B, 54}, /* TXVGA = 54; */
{0x08077B, 55}, /* TXVGA = 55; */
{0x08078B, 56}, /* TXVGA = 56; */
{0x08079B, 57}, /* TXVGA = 57; */
{0x0807AB, 58}, /* TXVGA = 58; */
{0x0807BB, 59}, /* TXVGA = 59; */
{0x0807CB, 60}, /* TXVGA = 60; */
{0x0807DB, 61}, /* TXVGA = 61; */
{0x0807EB, 62}, /* TXVGA = 62; */
{0x0807FB, 63}, /* TXVGA = 63; */
};
/* ============================================= */
/*
* W89RF242 RFIC SPI programming initial data
* Winbond WLAN 11g RFIC BB-SPI register -- version FA5976A rev 1.3b
*/
u32 w89rf242_rf_data[] = {
(0x00 << 24) | 0xF86100, /* 3E184; MODA (0x00) -- Normal mode ; calibration off */
(0x01 << 24) | 0xEFFFC2, /* 3BFFF; MODB (0x01) -- turn off RSSI, and other circuits are turned on */
(0x02 << 24) | 0x102504, /* 04094; FSET (0x02) -- default 20MHz crystal ; Icmp=1.5mA */
(0x03 << 24) | 0x026286, /* 0098A; FCHN (0x03) -- default CH7, 2442MHz */
(0x04 << 24) | 0x000208, /* 02008; FCAL (0x04) -- XTAL Freq Trim=001000 (socket board#1); FA5976AYG_v1.3C */
(0x05 << 24) | 0x24C60A, /* 09316; GANA (0x05) -- TX VGA default (TXVGA=0x18(12)) & TXGPK=110 ; FA5976A_1.3D */
(0x06 << 24) | 0x3432CC, /* 0D0CB; GANB (0x06) -- RXDC(DC offset) on; LNA=11; RXVGA=001011(11) ; RXFLSW=11(010001); RXGPK=00; RXGCF=00; -50dBm input */
(0x07 << 24) | 0x0C68CE, /* 031A3; FILT (0x07) -- TX/RX filter with auto-tuning; TFLBW=011; RFLBW=100 */
(0x08 << 24) | 0x100010, /* 04000; TCAL (0x08) -- for LO */
(0x09 << 24) | 0x004012, /* 1B900; RCALA (0x09) -- FASTS=11; HPDE=01 (100nsec); SEHP=1 (select B0 pin=RXHP); RXHP=1 (Turn on RXHP function)(FA5976A_1.3C) */
(0x0A << 24) | 0x704014, /* 1C100; RCALB (0x0A) */
(0x0B << 24) | 0x18BDD6, /* 062F7; IQCAL (0x0B) -- Turn on LO phase tuner=0111 & RX-LO phase = 0111; FA5976A_1.3B */
(0x0C << 24) | 0x575558, /* 15D55 ; IBSA (0x0C) -- IFPre =11 ; TC5376A_v1.3A for corner */
(0x0D << 24) | 0x55545A, /* 15555 ; IBSB (0x0D) */
(0x0E << 24) | 0x5557DC, /* 1555F ; IBSC (0x0E) -- IRLNA & IRLNB (PTAT & Const current)=01/01; FA5976B_1.3F */
(0x10 << 24) | 0x000C20, /* 00030 ; TMODA (0x10) -- LNA_gain_step=0011 ; LNA=15/16dB */
(0x11 << 24) | 0x0C0022, /* 03000 ; TMODB (0x11) -- Turn ON RX-Q path Test Switch; To improve IQ path group delay (FA5976A_1.3C) */
(0x12 << 24) | 0x000024 /* TMODC (0x12) -- Turn OFF Tempearure sensor */
};
u32 w89rf242_channel_data_24[][2] = {
{(0x03 << 24) | 0x025B06, (0x04 << 24) | 0x080408}, /* channe1 01 */
{(0x03 << 24) | 0x025C46, (0x04 << 24) | 0x080408}, /* channe1 02 */
{(0x03 << 24) | 0x025D86, (0x04 << 24) | 0x080408}, /* channe1 03 */
{(0x03 << 24) | 0x025EC6, (0x04 << 24) | 0x080408}, /* channe1 04 */
{(0x03 << 24) | 0x026006, (0x04 << 24) | 0x080408}, /* channe1 05 */
{(0x03 << 24) | 0x026146, (0x04 << 24) | 0x080408}, /* channe1 06 */
{(0x03 << 24) | 0x026286, (0x04 << 24) | 0x080408}, /* channe1 07 */
{(0x03 << 24) | 0x0263C6, (0x04 << 24) | 0x080408}, /* channe1 08 */
{(0x03 << 24) | 0x026506, (0x04 << 24) | 0x080408}, /* channe1 09 */
{(0x03 << 24) | 0x026646, (0x04 << 24) | 0x080408}, /* channe1 10 */
{(0x03 << 24) | 0x026786, (0x04 << 24) | 0x080408}, /* channe1 11 */
{(0x03 << 24) | 0x0268C6, (0x04 << 24) | 0x080408}, /* channe1 12 */
{(0x03 << 24) | 0x026A06, (0x04 << 24) | 0x080408}, /* channe1 13 */
{(0x03 << 24) | 0x026D06, (0x04 << 24) | 0x080408} /* channe1 14 */
};
u32 w89rf242_power_data_24[] = {(0x05 << 24) | 0x24C48A, (0x05 << 24) | 0x24C48A, (0x05 << 24) | 0x24C48A};
u32 w89rf242_txvga_old_mapping[][2] = {
{0, 0} , /* New <-> Old */
{1, 1} ,
{2, 2} ,
{3, 3} ,
{4, 4} ,
{6, 5} ,
{8, 6},
{10, 7},
{12, 8},
{14, 9},
{16, 10},
{18, 11},
{20, 12},
{22, 13},
{24, 14},
{26, 15},
{28, 16},
{30, 17},
{32, 18},
{34, 19},
};
u32 w89rf242_txvga_data[][5] = {
/* low gain mode */
{(0x05 << 24) | 0x24C00A, 0, 0x00292315, 0x0800FEFF, 0x52523131}, /* min gain */
{(0x05 << 24) | 0x24C80A, 1, 0x00292315, 0x0800FEFF, 0x52523131},
{(0x05 << 24) | 0x24C04A, 2, 0x00292315, 0x0800FEFF, 0x52523131}, /* (default) +14dBm (ANT) */
{(0x05 << 24) | 0x24C84A, 3, 0x00292315, 0x0800FEFF, 0x52523131},
/* TXVGA=0x10 */
{(0x05 << 24) | 0x24C40A, 4, 0x00292315, 0x0800FEFF, 0x60603838},
{(0x05 << 24) | 0x24C40A, 5, 0x00262114, 0x0700FEFF, 0x65653B3B},
/* TXVGA=0x11 */
{ (0x05 << 24) | 0x24C44A, 6, 0x00241F13, 0x0700FFFF, 0x58583333},
{ (0x05 << 24) | 0x24C44A, 7, 0x00292315, 0x0800FEFF, 0x5E5E3737},
/* TXVGA=0x12 */
{(0x05 << 24) | 0x24C48A, 8, 0x00262114, 0x0700FEFF, 0x53533030},
{(0x05 << 24) | 0x24C48A, 9, 0x00241F13, 0x0700FFFF, 0x59593434},
/* TXVGA=0x13 */
{(0x05 << 24) | 0x24C4CA, 10, 0x00292315, 0x0800FEFF, 0x52523030},
{(0x05 << 24) | 0x24C4CA, 11, 0x00262114, 0x0700FEFF, 0x56563232},
/* TXVGA=0x14 */
{(0x05 << 24) | 0x24C50A, 12, 0x00292315, 0x0800FEFF, 0x54543131},
{(0x05 << 24) | 0x24C50A, 13, 0x00262114, 0x0700FEFF, 0x58583434},
/* TXVGA=0x15 */
{(0x05 << 24) | 0x24C54A, 14, 0x00292315, 0x0800FEFF, 0x54543131},
{(0x05 << 24) | 0x24C54A, 15, 0x00262114, 0x0700FEFF, 0x59593434},
/* TXVGA=0x16 */
{(0x05 << 24) | 0x24C58A, 16, 0x00292315, 0x0800FEFF, 0x55553131},
{(0x05 << 24) | 0x24C58A, 17, 0x00292315, 0x0800FEFF, 0x5B5B3535},
/* TXVGA=0x17 */
{(0x05 << 24) | 0x24C5CA, 18, 0x00262114, 0x0700FEFF, 0x51512F2F},
{(0x05 << 24) | 0x24C5CA, 19, 0x00241F13, 0x0700FFFF, 0x55553131},
/* TXVGA=0x18 */
{(0x05 << 24) | 0x24C60A, 20, 0x00292315, 0x0800FEFF, 0x4F4F2E2E},
{(0x05 << 24) | 0x24C60A, 21, 0x00262114, 0x0700FEFF, 0x53533030},
/* TXVGA=0x19 */
{(0x05 << 24) | 0x24C64A, 22, 0x00292315, 0x0800FEFF, 0x4E4E2D2D},
{(0x05 << 24) | 0x24C64A, 23, 0x00262114, 0x0700FEFF, 0x53533030},
/* TXVGA=0x1A */
{(0x05 << 24) | 0x24C68A, 24, 0x00292315, 0x0800FEFF, 0x50502E2E},
{(0x05 << 24) | 0x24C68A, 25, 0x00262114, 0x0700FEFF, 0x55553131},
/* TXVGA=0x1B */
{(0x05 << 24) | 0x24C6CA, 26, 0x00262114, 0x0700FEFF, 0x53533030},
{(0x05 << 24) | 0x24C6CA, 27, 0x00292315, 0x0800FEFF, 0x5A5A3434},
/* TXVGA=0x1C */
{(0x05 << 24) | 0x24C70A, 28, 0x00292315, 0x0800FEFF, 0x55553131},
{(0x05 << 24) | 0x24C70A, 29, 0x00292315, 0x0800FEFF, 0x5D5D3636},
/* TXVGA=0x1D */
{(0x05 << 24) | 0x24C74A, 30, 0x00292315, 0x0800FEFF, 0x5F5F3737},
{(0x05 << 24) | 0x24C74A, 31, 0x00262114, 0x0700FEFF, 0x65653B3B},
/* TXVGA=0x1E */
{(0x05 << 24) | 0x24C78A, 32, 0x00292315, 0x0800FEFF, 0x66663B3B},
{(0x05 << 24) | 0x24C78A, 33, 0x00262114, 0x0700FEFF, 0x70704141},
/* TXVGA=0x1F */
{(0x05 << 24) | 0x24C7CA, 34, 0x00292315, 0x0800FEFF, 0x72724242}
};
/* ================================================================================================== */
/*
* =============================================================================================================
* Uxx_ReadEthernetAddress --
*
* Routine Description:
* Reads in the Ethernet address from the IC.
*
* Arguments:
* pHwData - The pHwData structure
*
* Return Value:
*
* The address is stored in EthernetIDAddr.
* =============================================================================================================
*/
void Uxx_ReadEthernetAddress(struct hw_data *pHwData)
{
u32 ltmp;
/*
* Reading Ethernet address from EEPROM and set into hardware due to MAC address maybe change.
* Only unplug and plug again can make hardware read EEPROM again.
*/
Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08000000); /* Start EEPROM access + Read + address(0x0d) */
Wb35Reg_ReadSync(pHwData, 0x03b4, <mp);
*(u16 *)pHwData->PermanentMacAddress = cpu_to_le16((u16) ltmp);
Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08010000); /* Start EEPROM access + Read + address(0x0d) */
Wb35Reg_ReadSync(pHwData, 0x03b4, <mp);
*(u16 *)(pHwData->PermanentMacAddress + 2) = cpu_to_le16((u16) ltmp);
Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08020000); /* Start EEPROM access + Read + address(0x0d) */
Wb35Reg_ReadSync(pHwData, 0x03b4, <mp);
*(u16 *)(pHwData->PermanentMacAddress + 4) = cpu_to_le16((u16) ltmp);
*(u16 *)(pHwData->PermanentMacAddress + 6) = 0;
Wb35Reg_WriteSync(pHwData, 0x03e8, cpu_to_le32(*(u32 *)pHwData->PermanentMacAddress));
Wb35Reg_WriteSync(pHwData, 0x03ec, cpu_to_le32(*(u32 *)(pHwData->PermanentMacAddress + 4)));
}
/*
* ===============================================================================================================
* CardGetMulticastBit --
* Description:
* For a given multicast address, returns the byte and bit in the card multicast registers that it hashes to.
* Calls CardComputeCrc() to determine the CRC value.
* Arguments:
* Address - the address
* Byte - the byte that it hashes to
* Value - will have a 1 in the relevant bit
* Return Value:
* None.
* ==============================================================================================================
*/
void CardGetMulticastBit(u8 Address[ETH_ALEN], u8 *Byte, u8 *Value)
{
u32 Crc;
u32 BitNumber;
/* First compute the CRC. */
Crc = CardComputeCrc(Address, ETH_ALEN);
/* The computed CRC is bit0~31 from left to right */
/* At first we should do right shift 25bits, and read 7bits by using '&', 2^7=128 */
BitNumber = (u32) ((Crc >> 26) & 0x3f);
*Byte = (u8) (BitNumber >> 3); /* 900514 original (BitNumber / 8) */
*Value = (u8) ((u8) 1 << (BitNumber % 8));
}
void Uxx_power_on_procedure(struct hw_data *pHwData)
{
u32 ltmp, loop;
if (pHwData->phy_type <= RF_MAXIM_V1)
Wb35Reg_WriteSync(pHwData, 0x03d4, 0xffffff38);
else {
Wb35Reg_WriteSync(pHwData, 0x03f4, 0xFF5807FF);
Wb35Reg_WriteSync(pHwData, 0x03d4, 0x80); /* regulator on only */
msleep(10);
Wb35Reg_WriteSync(pHwData, 0x03d4, 0xb8); /* REG_ON RF_RSTN on, and */
msleep(10);
ltmp = 0x4968;
if ((pHwData->phy_type == RF_WB_242) ||
(RF_WB_242_1 == pHwData->phy_type))
ltmp = 0x4468;
Wb35Reg_WriteSync(pHwData, 0x03d0, ltmp);
Wb35Reg_WriteSync(pHwData, 0x03d4, 0xa0); /* PLL_PD REF_PD set to 0 */
msleep(20);
Wb35Reg_ReadSync(pHwData, 0x03d0, <mp);
loop = 500; /* Wait for 5 second */
while (!(ltmp & 0x20) && loop--) {
msleep(10);
if (!Wb35Reg_ReadSync(pHwData, 0x03d0, <mp))
break;
}
Wb35Reg_WriteSync(pHwData, 0x03d4, 0xe0); /* MLK_EN */
}
Wb35Reg_WriteSync(pHwData, 0x03b0, 1); /* Reset hardware first */
msleep(10);
/* Set burst write delay */
Wb35Reg_WriteSync(pHwData, 0x03f8, 0x7ff);
}
void Set_ChanIndep_RfData_al7230_24(struct hw_data *pHwData, u32 *pltmp , char number)
{
u8 i;
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = al7230_rf_data_24[i];
pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_rf_data_24[i] & 0xffffff);
}
}
void Set_ChanIndep_RfData_al7230_50(struct hw_data *pHwData, u32 *pltmp, char number)
{
u8 i;
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = al7230_rf_data_50[i];
pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_rf_data_50[i] & 0xffffff);
}
}
/*
* =============================================================================================================
* RFSynthesizer_initial --
* =============================================================================================================
*/
void RFSynthesizer_initial(struct hw_data *pHwData)
{
u32 altmp[32];
u32 *pltmp = altmp;
u32 ltmp;
u8 number = 0x00; /* The number of register vale */
u8 i;
/*
* bit[31] SPI Enable.
* 1=perform synthesizer program operation. This bit will
* cleared automatically after the operation is completed.
* bit[30] SPI R/W Control
* 0=write, 1=read
* bit[29:24] SPI Data Format Length
* bit[17:4 ] RF Data bits.
* bit[3 :0 ] RF address.
*/
switch (pHwData->phy_type) {
case RF_MAXIM_2825:
case RF_MAXIM_V1: /* 11g Winbond 2nd BB(with Phy board (v1) + Maxim 331) */
number = ARRAY_SIZE(max2825_rf_data);
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = max2825_rf_data[i]; /* Backup Rf parameter */
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2825_rf_data[i], 18);
}
break;
case RF_MAXIM_2827:
number = ARRAY_SIZE(max2827_rf_data);
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = max2827_rf_data[i];
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_rf_data[i], 18);
}
break;
case RF_MAXIM_2828:
number = ARRAY_SIZE(max2828_rf_data);
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = max2828_rf_data[i];
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_rf_data[i], 18);
}
break;
case RF_MAXIM_2829:
number = ARRAY_SIZE(max2829_rf_data);
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = max2829_rf_data[i];
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2829_rf_data[i], 18);
}
break;
case RF_AIROHA_2230:
number = ARRAY_SIZE(al2230_rf_data);
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = al2230_rf_data[i];
pltmp[i] = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_rf_data[i], 20);
}
break;
case RF_AIROHA_2230S:
number = ARRAY_SIZE(al2230s_rf_data);
for (i = 0; i < number; i++) {
pHwData->phy_para[i] = al2230s_rf_data[i];
pltmp[i] = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230s_rf_data[i], 20);
}
break;
case RF_AIROHA_7230:
/* Start to fill RF parameters, PLL_ON should be pulled low. */
Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000000);
pr_debug("* PLL_ON low\n");
number = ARRAY_SIZE(al7230_rf_data_24);
Set_ChanIndep_RfData_al7230_24(pHwData, pltmp, number);
break;
case RF_WB_242:
case RF_WB_242_1:
number = ARRAY_SIZE(w89rf242_rf_data);
for (i = 0; i < number; i++) {
ltmp = w89rf242_rf_data[i];
if (i == 4) { /* Update the VCO trim from EEPROM */
ltmp &= ~0xff0; /* Mask bit4 ~bit11 */
ltmp |= pHwData->VCO_trim << 4;
}
pHwData->phy_para[i] = ltmp;
pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse(ltmp, 24);
}
break;
}
pHwData->phy_number = number;
/* The 16 is the maximum capability of hardware. Here use 12 */
if (number > 12) {
for (i = 0; i < 12; i++) /* For Al2230 */
Wb35Reg_WriteSync(pHwData, 0x0864, pltmp[i]);
pltmp += 12;
number -= 12;
}
/* Write to register. number must less and equal than 16 */
for (i = 0; i < number; i++)
Wb35Reg_WriteSync(pHwData, 0x864, pltmp[i]);
/* Calibration only 1 time */
if (pHwData->CalOneTime)
return;
pHwData->CalOneTime = 1;
switch (pHwData->phy_type) {
case RF_AIROHA_2230:
ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x07 << 20) | 0xE168E, 20);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(10);
ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_rf_data[7], 20);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(10);
case RF_AIROHA_2230S:
Wb35Reg_WriteSync(pHwData, 0x03d4, 0x80); /* regulator on only */
msleep(10);
Wb35Reg_WriteSync(pHwData, 0x03d4, 0xa0); /* PLL_PD REF_PD set to 0 */
msleep(10);
Wb35Reg_WriteSync(pHwData, 0x03d4, 0xe0); /* MLK_EN */
Wb35Reg_WriteSync(pHwData, 0x03b0, 1); /* Reset hardware first */
msleep(10);
/* ========================================================= */
/* The follow code doesn't use the burst-write mode */
ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F<<20) | 0xF01A0, 20);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
ltmp = pHwData->reg.BB5C & 0xfffff000;
Wb35Reg_WriteSync(pHwData, 0x105c, ltmp);
pHwData->reg.BB50 |= 0x13; /* (MASK_IQCAL_MODE|MASK_CALIB_START) */
Wb35Reg_WriteSync(pHwData, 0x1050, pHwData->reg.BB50);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F << 20) | 0xF01B0, 20);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F << 20) | 0xF01E0, 20);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse((0x0F << 20) | 0xF01A0, 20);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp) ;
Wb35Reg_WriteSync(pHwData, 0x105c, pHwData->reg.BB5C);
pHwData->reg.BB50 &= ~0x13; /* (MASK_IQCAL_MODE|MASK_CALIB_START); */
Wb35Reg_WriteSync(pHwData, 0x1050, pHwData->reg.BB50);
break;
case RF_AIROHA_7230:
/* RF parameters have filled completely, PLL_ON should be pulled high */
Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000080);
pr_debug("* PLL_ON high\n");
/* 2.4GHz */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x9ABA8F;
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x3ABA8F;
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x1ABA8F;
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
/* 5GHz */
Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000000);
pr_debug("* PLL_ON low\n");
number = ARRAY_SIZE(al7230_rf_data_50);
Set_ChanIndep_RfData_al7230_50(pHwData, pltmp, number);
/* Write to register. number must less and equal than 16 */
for (i = 0; i < number; i++)
Wb35Reg_WriteSync(pHwData, 0x0864, pltmp[i]);
msleep(5);
Wb35Reg_WriteSync(pHwData, 0x03dc, 0x00000080);
pr_debug("* PLL_ON high\n");
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x9ABA8F;
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x3ABA8F;
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x12BACF;
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
break;
case RF_WB_242:
case RF_WB_242_1:
/* for FA5976A */
ltmp = pHwData->reg.BB5C & 0xfffff000;
Wb35Reg_WriteSync(pHwData, 0x105c, ltmp);
Wb35Reg_WriteSync(pHwData, 0x1058, 0);
pHwData->reg.BB50 |= 0x3; /* (MASK_IQCAL_MODE|MASK_CALIB_START); */
Wb35Reg_WriteSync(pHwData, 0x1050, pHwData->reg.BB50);
/* ----- Calibration (1). VCO frequency calibration */
/* Calibration (1a.0). Synthesizer reset */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x0F<<24) | 0x00101E, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
/* Calibration (1a). VCO frequency calibration mode ; waiting 2msec VCO calibration time */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFE69c0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(2);
/* ----- Calibration (2). TX baseband Gm-C filter auto-tuning */
/* Calibration (2a). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xF8EBC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (2b.0). TX filter auto-tuning BW: TFLBW=101 (TC5376A default) */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x07<<24) | 0x0C68CE, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (2b). send TX reset signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x0F<<24) | 0x00201E, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (2c). turn-on TX Gm-C filter auto-tuning */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFCEBC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
udelay(150); /* Sleep 150 us */
/* turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xF8EBC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* ----- Calibration (3). RX baseband Gm-C filter auto-tuning */
/* Calibration (3a). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (3b.0). RX filter auto-tuning BW: RFLBW=100 (TC5376A+corner default;) */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x07<<24) | 0x0C68CE, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (3b). send RX reset signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x0F<<24) | 0x00401E, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (3c). turn-on RX Gm-C filter auto-tuning */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFEEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
udelay(150); /* Sleep 150 us */
/* Calibration (3e). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* ----- Calibration (4). TX LO leakage calibration */
/* Calibration (4a). TX LO leakage calibration */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFD6BC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
udelay(150); /* Sleep 150 us */
/* ----- Calibration (5). RX DC offset calibration */
/* Calibration (5a). turn off ENCAL signal and set to RX SW DC calibration mode */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (5b). turn off AGC servo-loop & RSSI */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x01<<24) | 0xEBFFC2, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* for LNA=11 -------- */
/* Calibration (5c-h). RX DC offset current bias ON; & LNA=11; RXVGA=111111 */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x343FCC, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(2);
/* Calibration (5f). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* for LNA=10 -------- */
/* Calibration (5c-m). RX DC offset current bias ON; & LNA=10; RXVGA=111111 */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x342FCC, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(2);
/* Calibration (5f). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* for LNA=01 -------- */
/* Calibration (5c-m). RX DC offset current bias ON; & LNA=01; RXVGA=111111 */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x341FCC, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(2);
/* Calibration (5f). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* for LNA=00 -------- */
/* Calibration (5c-l). RX DC offset current bias ON; & LNA=00; RXVGA=111111 */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x06<<24) | 0x340FCC, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (5d). turn on RX DC offset cal function; and waiting 2 msec cal time */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFF6DC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(2);
/* Calibration (5f). turn off ENCAL signal */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xFAEDC0, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* Calibration (5g). turn on AGC servo-loop */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x01<<24) | 0xEFFFC2, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
/* ----- Calibration (7). Switch RF chip to normal mode */
/* 0x00 0xF86100 ; 3E184 ; Switch RF chip to normal mode */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse((0x00<<24) | 0xF86100, 24);
Wb35Reg_WriteSync(pHwData, 0x0864, ltmp);
msleep(5);
break;
}
}
void BBProcessor_AL7230_2400(struct hw_data *pHwData)
{
struct wb35_reg *reg = &pHwData->reg;
u32 pltmp[12];
pltmp[0] = 0x16A8337A; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9AFF9AA6; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xFFF72031; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xFFF72031;
pltmp[4] = 0x0FacDCC5; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00CAA333; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0xF2211111; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x06443440; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0xA8002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0x40000528;
pltmp[11] = 0x232D7F30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232D7F30;
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002c54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002c54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = 0x00332C1B; /* 0x1048 11b TX RC filter */
pltmp[7] = 0x0A00FEFF; /* 0x104c 11b TX RC filter */
pltmp[8] = 0x2B106208; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x2B106208;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x52524242; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x52524242;
pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
}
void BBProcessor_AL7230_5000(struct hw_data *pHwData)
{
struct wb35_reg *reg = &pHwData->reg;
u32 pltmp[12];
pltmp[0] = 0x16AA6678; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9AFFA0B2; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xEFFF233E; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xEFFF233E;
pltmp[4] = 0x0FacDCC5; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00CAA333; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0xF2432111; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x05C43440; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0x40000528;
pltmp[11] = 0x232FDF30;/* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232FDF30;
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x80002C7C; /* 0x1030 B_ACQ_Ctrl */
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = 0x00332C1B; /* 0x1048 11b TX RC filter */
pltmp[7] = 0x0A00FEFF; /* 0x104c 11b TX RC filter */
pltmp[8] = 0x2B107208; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x2B107208;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x52524242; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x52524242;
pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
}
/*
* ===========================================================================
* BBProcessorPowerupInit --
*
* Description:
* Initialize the Baseband processor.
*
* Arguments:
* pHwData - Handle of the USB Device.
*
* Return values:
* None.
*============================================================================
*/
void BBProcessor_initial(struct hw_data *pHwData)
{
struct wb35_reg *reg = &pHwData->reg;
u32 i, pltmp[12];
switch (pHwData->phy_type) {
case RF_MAXIM_V1: /* Initializng the Winbond 2nd BB(with Phy board (v1) + Maxim 331) */
pltmp[0] = 0x16F47E77; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9AFFAEA4; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xEFFF1A34; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xEFFF1A34;
pltmp[4] = 0x0FABE0B7; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00CAA332; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0xF6632111; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x04CC3640; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = (pHwData->phy_type == 3) ? 0x40000a28 : 0x40000228; /* 0x1028 MAXIM_331(b31=0) + WBRF_V1(b11=1) : MAXIM_331(b31=0) + WBRF_V2(b11=0) */
pltmp[11] = 0x232FDF30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232FDF30; /* Modify for 33's 1.0.95.xxx version, antenna 1 */
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002C54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B6C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = 0x00453B24; /* 0x1048 11b TX RC filter */
pltmp[7] = 0x0E00FEFF; /* 0x104c 11b TX RC filter */
pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x27106208;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x64646464; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x64646464;
pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
case RF_MAXIM_2825:
case RF_MAXIM_2827:
case RF_MAXIM_2828:
pltmp[0] = 0x16b47e77; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9affaea4; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xefff1a34; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xefff1a34;
pltmp[4] = 0x0fabe0b7; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0xf6632111; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x04CC3640; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0x40000528;
pltmp[11] = 0x232fdf30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232fdf30; /* antenna 1 */
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002C54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B6C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = 0x00453B24; /* 0x1048 11b TX RC filter */
pltmp[7] = 0x0D00FDFF; /* 0x104c 11b TX RC filter */
pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x27106208;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x64646464; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x64646464;
pltmp[11] = 0xAA28C000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
case RF_MAXIM_2829:
pltmp[0] = 0x16b47e77; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9affaea4; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xf4ff1632; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xf4ff1632;
pltmp[4] = 0x0fabe0b7; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0xf8632112; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x04CC3640; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0x40000528;
pltmp[11] = 0x232fdf30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232fdf30; /* antenna 1 */
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002C54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5b2c8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = 0x002c2617; /* 0x1048 11b TX RC filter */
pltmp[7] = 0x0800feff; /* 0x104c 11b TX RC filter */
pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x27106208;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x64644a4a; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x64646464;
pltmp[11] = 0xAA28C000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
case RF_AIROHA_2230:
pltmp[0] = 0X16764A77; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9affafb2; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xFFFd203c; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xFFFd203c;
pltmp[4] = 0X0FBFDCc5; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0XF6632111; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x04C43640; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0X40000528;
pltmp[11] = 0x232dfF30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232dfF30; /* antenna 1 */
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002C54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = BB48_DEFAULT_AL2230_11G; /* 0x1048 11b TX RC filter */
reg->BB48 = BB48_DEFAULT_AL2230_11G; /* 20051221 ch14 */
pltmp[7] = BB4C_DEFAULT_AL2230_11G; /* 0x104c 11b TX RC filter */
reg->BB4C = BB4C_DEFAULT_AL2230_11G;
pltmp[8] = 0x27106200; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x27106200;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x52524242; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x52524242;
pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
case RF_AIROHA_2230S:
pltmp[0] = 0X16764A77; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9affafb2; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55d00a04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xFFFd203c; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xFFFd203c;
pltmp[4] = 0X0FBFDCc5; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x00caa332; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0XF6632111; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x04C43640; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0x00002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0X40000528;
pltmp[11] = 0x232dfF30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x232dfF30; /* antenna 1 */
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002C54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = 0x00000000; /* 0x103c 11a TX LS filter */
reg->BB3C = 0x00000000;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = BB48_DEFAULT_AL2230_11G; /* 0x1048 11b TX RC filter */
reg->BB48 = BB48_DEFAULT_AL2230_11G; /* ch14 */
pltmp[7] = BB4C_DEFAULT_AL2230_11G; /* 0x104c 11b TX RC filter */
reg->BB4C = BB4C_DEFAULT_AL2230_11G;
pltmp[8] = 0x27106200; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x27106200;
pltmp[9] = 0; /* 0x1054 */
reg->BB54 = 0x00000000;
pltmp[10] = 0x52523232; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x52523232;
pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
case RF_AIROHA_7230:
BBProcessor_AL7230_2400(pHwData);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
case RF_WB_242:
case RF_WB_242_1:
pltmp[0] = 0x16A8525D; /* 0x1000 AGC_Ctrl1 */
pltmp[1] = 0x9AFF9ABA; /* 0x1004 AGC_Ctrl2 */
pltmp[2] = 0x55D00A04; /* 0x1008 AGC_Ctrl3 */
pltmp[3] = 0xEEE91C32; /* 0x100c AGC_Ctrl4 */
reg->BB0C = 0xEEE91C32;
pltmp[4] = 0x0FACDCC5; /* 0x1010 AGC_Ctrl5 */
pltmp[5] = 0x000AA344; /* 0x1014 AGC_Ctrl6 */
pltmp[6] = 0x22222221; /* 0x1018 AGC_Ctrl7 */
pltmp[7] = 0x0FA3F0ED; /* 0x101c AGC_Ctrl8 */
pltmp[8] = 0x04CC3440; /* 0x1020 AGC_Ctrl9 */
pltmp[9] = 0xA9002A79; /* 0x1024 AGC_Ctrl10 */
pltmp[10] = 0x40000528; /* 0x1028 */
pltmp[11] = 0x23457F30; /* 0x102c A_ACQ_Ctrl */
reg->BB2C = 0x23457F30;
Wb35Reg_BurstWrite(pHwData, 0x1000, pltmp, 12, AUTO_INCREMENT);
pltmp[0] = 0x00002C54; /* 0x1030 B_ACQ_Ctrl */
reg->BB30 = 0x00002C54;
pltmp[1] = 0x00C0D6C5; /* 0x1034 A_TXRX_Ctrl */
pltmp[2] = 0x5B2C8769; /* 0x1038 B_TXRX_Ctrl */
pltmp[3] = pHwData->BB3c_cal; /* 0x103c 11a TX LS filter */
reg->BB3C = pHwData->BB3c_cal;
pltmp[4] = 0x00003F29; /* 0x1040 11a TX LS filter */
pltmp[5] = 0x0EFEFBFE; /* 0x1044 11a TX LS filter */
pltmp[6] = BB48_DEFAULT_WB242_11G; /* 0x1048 11b TX RC filter */
reg->BB48 = BB48_DEFAULT_WB242_11G;
pltmp[7] = BB4C_DEFAULT_WB242_11G; /* 0x104c 11b TX RC filter */
reg->BB4C = BB4C_DEFAULT_WB242_11G;
pltmp[8] = 0x27106208; /* 0x1050 MODE_Ctrl */
reg->BB50 = 0x27106208;
pltmp[9] = pHwData->BB54_cal; /* 0x1054 */
reg->BB54 = pHwData->BB54_cal;
pltmp[10] = 0x52523131; /* 0x1058 IQ_Alpha */
reg->BB58 = 0x52523131;
pltmp[11] = 0xAA0AC000; /* 0x105c DC_Cancel */
Wb35Reg_BurstWrite(pHwData, 0x1030, pltmp, 12, AUTO_INCREMENT);
Wb35Reg_Write(pHwData, 0x1070, 0x00000045);
break;
}
/* Fill the LNA table */
reg->LNAValue[0] = (u8) (reg->BB0C & 0xff);
reg->LNAValue[1] = 0;
reg->LNAValue[2] = (u8) ((reg->BB0C & 0xff00) >> 8);
reg->LNAValue[3] = 0;
/* Fill SQ3 table */
for (i = 0; i < MAX_SQ3_FILTER_SIZE; i++)
reg->SQ3_filter[i] = 0x2f; /* half of Bit 0 ~ 6 */
}
void set_tx_power_per_channel_max2829(struct hw_data *pHwData, struct chan_info Channel)
{
RFSynthesizer_SetPowerIndex(pHwData, 100);
}
void set_tx_power_per_channel_al2230(struct hw_data *pHwData, struct chan_info Channel)
{
u8 index = 100;
if (pHwData->TxVgaFor24[Channel.ChanNo - 1] != 0xff)
index = pHwData->TxVgaFor24[Channel.ChanNo - 1];
RFSynthesizer_SetPowerIndex(pHwData, index);
}
void set_tx_power_per_channel_al7230(struct hw_data *pHwData, struct chan_info Channel)
{
u8 i, index = 100;
switch (Channel.band) {
case BAND_TYPE_DSSS:
case BAND_TYPE_OFDM_24:
if (pHwData->TxVgaFor24[Channel.ChanNo - 1] != 0xff)
index = pHwData->TxVgaFor24[Channel.ChanNo - 1];
break;
case BAND_TYPE_OFDM_5:
for (i = 0; i < 35; i++) {
if (Channel.ChanNo == pHwData->TxVgaFor50[i].ChanNo) {
if (pHwData->TxVgaFor50[i].TxVgaValue != 0xff)
index = pHwData->TxVgaFor50[i].TxVgaValue;
break;
}
}
break;
}
RFSynthesizer_SetPowerIndex(pHwData, index);
}
void set_tx_power_per_channel_wb242(struct hw_data *pHwData, struct chan_info Channel)
{
u8 index = 100;
switch (Channel.band) {
case BAND_TYPE_DSSS:
case BAND_TYPE_OFDM_24:
if (pHwData->TxVgaFor24[Channel.ChanNo - 1] != 0xff)
index = pHwData->TxVgaFor24[Channel.ChanNo - 1];
break;
case BAND_TYPE_OFDM_5:
break;
}
RFSynthesizer_SetPowerIndex(pHwData, index);
}
/*
* ==========================================================================
* RFSynthesizer_SwitchingChannel --
*
* Description:
* Swithch the RF channel.
*
* Arguments:
* pHwData - Handle of the USB Device.
* Channel - The channel no.
*
* Return values:
* None.
* ===========================================================================
*/
void RFSynthesizer_SwitchingChannel(struct hw_data *pHwData, struct chan_info Channel)
{
struct wb35_reg *reg = &pHwData->reg;
u32 pltmp[16]; /* The 16 is the maximum capability of hardware */
u32 count, ltmp;
u8 i, j, number;
u8 ChnlTmp;
switch (pHwData->phy_type) {
case RF_MAXIM_2825:
case RF_MAXIM_V1: /* 11g Winbond 2nd BB(with Phy board (v1) + Maxim 331) */
if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 13 */
for (i = 0; i < 3; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2825_channel_data_24[Channel.ChanNo-1][i], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
}
RFSynthesizer_SetPowerIndex(pHwData, 100);
break;
case RF_MAXIM_2827:
if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 13 */
for (i = 0; i < 3; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_channel_data_24[Channel.ChanNo-1][i], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
} else if (Channel.band == BAND_TYPE_OFDM_5) { /* channel 36 ~ 64 */
ChnlTmp = (Channel.ChanNo - 36) / 4;
for (i = 0; i < 3; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_channel_data_50[ChnlTmp][i], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
}
RFSynthesizer_SetPowerIndex(pHwData, 100);
break;
case RF_MAXIM_2828:
if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 13 */
for (i = 0; i < 3; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_channel_data_24[Channel.ChanNo-1][i], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
} else if (Channel.band == BAND_TYPE_OFDM_5) { /* channel 36 ~ 64 */
ChnlTmp = (Channel.ChanNo - 36) / 4;
for (i = 0; i < 3; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_channel_data_50[ChnlTmp][i], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
}
RFSynthesizer_SetPowerIndex(pHwData, 100);
break;
case RF_MAXIM_2829:
if (Channel.band <= BAND_TYPE_OFDM_24) {
for (i = 0; i < 3; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2829_channel_data_24[Channel.ChanNo-1][i], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
} else if (Channel.band == BAND_TYPE_OFDM_5) {
count = ARRAY_SIZE(max2829_channel_data_50);
for (i = 0; i < count; i++) {
if (max2829_channel_data_50[i][0] == Channel.ChanNo) {
for (j = 0; j < 3; j++)
pltmp[j] = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2829_channel_data_50[i][j+1], 18);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
if ((max2829_channel_data_50[i][3] & 0x3FFFF) == 0x2A946) {
ltmp = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse((5 << 18) | 0x2A906, 18);
Wb35Reg_Write(pHwData, 0x0864, ltmp);
} else { /* 0x2A9C6 */
ltmp = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse((5 << 18) | 0x2A986, 18);
Wb35Reg_Write(pHwData, 0x0864, ltmp);
}
}
}
}
set_tx_power_per_channel_max2829(pHwData, Channel);
break;
case RF_AIROHA_2230:
case RF_AIROHA_2230S:
if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 14 */
for (i = 0; i < 2; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_channel_data_24[Channel.ChanNo-1][i], 20);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 2, NO_INCREMENT);
}
set_tx_power_per_channel_al2230(pHwData, Channel);
break;
case RF_AIROHA_7230:
/* Channel independent registers */
if (Channel.band != pHwData->band) {
if (Channel.band <= BAND_TYPE_OFDM_24) {
/* Update BB register */
BBProcessor_AL7230_2400(pHwData);
number = ARRAY_SIZE(al7230_rf_data_24);
Set_ChanIndep_RfData_al7230_24(pHwData, pltmp, number);
} else {
/* Update BB register */
BBProcessor_AL7230_5000(pHwData);
number = ARRAY_SIZE(al7230_rf_data_50);
Set_ChanIndep_RfData_al7230_50(pHwData, pltmp, number);
}
/* Write to register. number must less and equal than 16 */
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, number, NO_INCREMENT);
pr_debug("Band changed\n");
}
if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 14 */
for (i = 0; i < 2; i++)
pltmp[i] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_channel_data_24[Channel.ChanNo-1][i]&0xffffff);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 2, NO_INCREMENT);
} else if (Channel.band == BAND_TYPE_OFDM_5) {
/* Update Reg12 */
if ((Channel.ChanNo > 64) && (Channel.ChanNo <= 165)) {
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x00143c;
Wb35Reg_Write(pHwData, 0x0864, ltmp);
} else { /* reg12 = 0x00147c at Channel 4920 ~ 5320 */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | 0x00147c;
Wb35Reg_Write(pHwData, 0x0864, ltmp);
}
count = ARRAY_SIZE(al7230_channel_data_5);
for (i = 0; i < count; i++) {
if (al7230_channel_data_5[i][0] == Channel.ChanNo) {
for (j = 0; j < 3; j++)
pltmp[j] = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_channel_data_5[i][j+1] & 0xffffff);
Wb35Reg_BurstWrite(pHwData, 0x0864, pltmp, 3, NO_INCREMENT);
}
}
}
set_tx_power_per_channel_al7230(pHwData, Channel);
break;
case RF_WB_242:
case RF_WB_242_1:
if (Channel.band <= BAND_TYPE_OFDM_24) { /* channel 1 ~ 14 */
ltmp = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse(w89rf242_channel_data_24[Channel.ChanNo-1][0], 24);
Wb35Reg_Write(pHwData, 0x864, ltmp);
}
set_tx_power_per_channel_wb242(pHwData, Channel);
break;
}
if (Channel.band <= BAND_TYPE_OFDM_24) {
/* BB: select 2.4 GHz, bit[12-11]=00 */
reg->BB50 &= ~(BIT(11) | BIT(12));
Wb35Reg_Write(pHwData, 0x1050, reg->BB50); /* MODE_Ctrl */
/* MAC: select 2.4 GHz, bit[5]=0 */
reg->M78_ERPInformation &= ~BIT(5);
Wb35Reg_Write(pHwData, 0x0878, reg->M78_ERPInformation);
/* enable 11b Baseband */
reg->BB30 &= ~BIT(31);
Wb35Reg_Write(pHwData, 0x1030, reg->BB30);
} else if (Channel.band == BAND_TYPE_OFDM_5) {
/* BB: select 5 GHz */
reg->BB50 &= ~(BIT(11) | BIT(12));
if (Channel.ChanNo <= 64)
reg->BB50 |= BIT(12); /* 10-5.25GHz */
else if ((Channel.ChanNo >= 100) && (Channel.ChanNo <= 124))
reg->BB50 |= BIT(11); /* 01-5.48GHz */
else if ((Channel.ChanNo >= 128) && (Channel.ChanNo <= 161))
reg->BB50 |= (BIT(12) | BIT(11)); /* 11-5.775GHz */
else /* Chan 184 ~ 196 will use bit[12-11] = 10 in version sh-src-1.2.25 */
reg->BB50 |= BIT(12);
Wb35Reg_Write(pHwData, 0x1050, reg->BB50); /* MODE_Ctrl */
/* (1) M78 should alway use 2.4G setting when using RF_AIROHA_7230 */
/* (2) BB30 has been updated previously. */
if (pHwData->phy_type != RF_AIROHA_7230) {
/* MAC: select 5 GHz, bit[5]=1 */
reg->M78_ERPInformation |= BIT(5);
Wb35Reg_Write(pHwData, 0x0878, reg->M78_ERPInformation);
/* disable 11b Baseband */
reg->BB30 |= BIT(31);
Wb35Reg_Write(pHwData, 0x1030, reg->BB30);
}
}
}
/*
* Set the tx power directly from DUT GUI, not from the EEPROM.
* Return the current setting
*/
u8 RFSynthesizer_SetPowerIndex(struct hw_data *pHwData, u8 PowerIndex)
{
u32 Band = pHwData->band;
u8 index = 0;
if (pHwData->power_index == PowerIndex)
return PowerIndex;
if (RF_MAXIM_2825 == pHwData->phy_type) {
/* Channel 1 - 13 */
index = RFSynthesizer_SetMaxim2825Power(pHwData, PowerIndex);
} else if (RF_MAXIM_2827 == pHwData->phy_type) {
if (Band <= BAND_TYPE_OFDM_24) /* Channel 1 - 13 */
index = RFSynthesizer_SetMaxim2827_24Power(pHwData, PowerIndex);
else /* Channel 36 - 64 */
index = RFSynthesizer_SetMaxim2827_50Power(pHwData, PowerIndex);
} else if (RF_MAXIM_2828 == pHwData->phy_type) {
if (Band <= BAND_TYPE_OFDM_24) /* Channel 1 - 13 */
index = RFSynthesizer_SetMaxim2828_24Power(pHwData, PowerIndex);
else /* Channel 36 - 64 */
index = RFSynthesizer_SetMaxim2828_50Power(pHwData, PowerIndex);
} else if (RF_AIROHA_2230 == pHwData->phy_type) {
/* Power index: 0 ~ 63 --- Channel 1 - 14 */
index = RFSynthesizer_SetAiroha2230Power(pHwData, PowerIndex);
index = (u8) al2230_txvga_data[index][1];
} else if (RF_AIROHA_2230S == pHwData->phy_type) {
/* Power index: 0 ~ 63 --- Channel 1 - 14 */
index = RFSynthesizer_SetAiroha2230Power(pHwData, PowerIndex);
index = (u8) al2230_txvga_data[index][1];
} else if (RF_AIROHA_7230 == pHwData->phy_type) {
/* Power index: 0 ~ 63 */
index = RFSynthesizer_SetAiroha7230Power(pHwData, PowerIndex);
index = (u8)al7230_txvga_data[index][1];
} else if ((RF_WB_242 == pHwData->phy_type) ||
(RF_WB_242_1 == pHwData->phy_type)) {
/* Power index: 0 ~ 19 for original. New range is 0 ~ 33 */
index = RFSynthesizer_SetWinbond242Power(pHwData, PowerIndex);
index = (u8)w89rf242_txvga_data[index][1];
}
pHwData->power_index = index; /* Backup current */
return index;
}
/* -- Sub function */
u8 RFSynthesizer_SetMaxim2828_24Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
if (index > 1)
index = 1;
PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_power_data_24[index], 18);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return index;
}
u8 RFSynthesizer_SetMaxim2828_50Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
if (index > 1)
index = 1;
PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2828_power_data_50[index], 18);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return index;
}
u8 RFSynthesizer_SetMaxim2827_24Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
if (index > 1)
index = 1;
PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_power_data_24[index], 18);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return index;
}
u8 RFSynthesizer_SetMaxim2827_50Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
if (index > 1)
index = 1;
PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2827_power_data_50[index], 18);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return index;
}
u8 RFSynthesizer_SetMaxim2825Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
if (index > 1)
index = 1;
PowerData = (1 << 31) | (0 << 30) | (18 << 24) | BitReverse(max2825_power_data_24[index], 18);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return index;
}
u8 RFSynthesizer_SetAiroha2230Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
u8 i, count;
count = ARRAY_SIZE(al2230_txvga_data);
for (i = 0; i < count; i++) {
if (al2230_txvga_data[i][1] >= index)
break;
}
if (i == count)
i--;
PowerData = (1 << 31) | (0 << 30) | (20 << 24) | BitReverse(al2230_txvga_data[i][0], 20);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return i;
}
u8 RFSynthesizer_SetAiroha7230Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
u8 i, count;
count = ARRAY_SIZE(al7230_txvga_data);
for (i = 0; i < count; i++) {
if (al7230_txvga_data[i][1] >= index)
break;
}
if (i == count)
i--;
PowerData = (1 << 31) | (0 << 30) | (24 << 24) | (al7230_txvga_data[i][0] & 0xffffff);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
return i;
}
u8 RFSynthesizer_SetWinbond242Power(struct hw_data *pHwData, u8 index)
{
u32 PowerData;
u8 i, count;
count = ARRAY_SIZE(w89rf242_txvga_data);
for (i = 0; i < count; i++) {
if (w89rf242_txvga_data[i][1] >= index)
break;
}
if (i == count)
i--;
/* Set TxVga into RF */
PowerData = (1 << 31) | (0 << 30) | (24 << 24) | BitReverse(w89rf242_txvga_data[i][0], 24);
Wb35Reg_Write(pHwData, 0x0864, PowerData);
/* Update BB48 BB4C BB58 for high precision txvga */
Wb35Reg_Write(pHwData, 0x1048, w89rf242_txvga_data[i][2]);
Wb35Reg_Write(pHwData, 0x104c, w89rf242_txvga_data[i][3]);
Wb35Reg_Write(pHwData, 0x1058, w89rf242_txvga_data[i][4]);
return i;
}
/*
* ===========================================================================
* Dxx_initial --
* Mxx_initial --
*
* Routine Description:
* Initial the hardware setting and module variable
* ===========================================================================
*/
void Dxx_initial(struct hw_data *pHwData)
{
struct wb35_reg *reg = &pHwData->reg;
/*
* Old IC: Single mode only.
* New IC: operation decide by Software set bit[4]. 1:multiple 0: single
*/
reg->D00_DmaControl = 0xc0000004; /* Txon, Rxon, multiple Rx for new 4k DMA */
/* Txon, Rxon, single Rx for old 8k ASIC */
if (!HAL_USB_MODE_BURST(pHwData))
reg->D00_DmaControl = 0xc0000000; /* Txon, Rxon, single Rx for new 4k DMA */
Wb35Reg_WriteSync(pHwData, 0x0400, reg->D00_DmaControl);
}
void Mxx_initial(struct hw_data *pHwData)
{
struct wb35_reg *reg = &pHwData->reg;
u32 tmp;
u32 pltmp[11];
u16 i;
/*
* ======================================================
* Initial Mxx register
* ======================================================
*/
/* M00 bit set */
reg->M00_MacControl = 0x80000000; /* Solve beacon sequence number stop by hardware */
/* M24 disable enter power save, BB RxOn and enable NAV attack */
reg->M24_MacControl = 0x08040042;
pltmp[0] = reg->M24_MacControl;
pltmp[1] = 0; /* Skip M28, because no initialize value is required. */
/* M2C CWmin and CWmax setting */
pHwData->cwmin = DEFAULT_CWMIN;
pHwData->cwmax = DEFAULT_CWMAX;
reg->M2C_MacControl = DEFAULT_CWMIN << 10;
reg->M2C_MacControl |= DEFAULT_CWMAX;
pltmp[2] = reg->M2C_MacControl;
/* M30 BSSID */
pltmp[3] = *(u32 *)pHwData->bssid;
/* M34 */
pHwData->AID = DEFAULT_AID;
tmp = *(u16 *) (pHwData->bssid + 4);
tmp |= DEFAULT_AID << 16;
pltmp[4] = tmp;
/* M38 */
reg->M38_MacControl = (DEFAULT_RATE_RETRY_LIMIT << 8) | (DEFAULT_LONG_RETRY_LIMIT << 4) | DEFAULT_SHORT_RETRY_LIMIT;
pltmp[5] = reg->M38_MacControl;
/* M3C */
tmp = (DEFAULT_PIFST << 26) | (DEFAULT_EIFST << 16) | (DEFAULT_DIFST << 8) | (DEFAULT_SIFST << 4) | DEFAULT_OSIFST ;
reg->M3C_MacControl = tmp;
pltmp[6] = tmp;
/* M40 */
pHwData->slot_time_select = DEFAULT_SLOT_TIME;
tmp = (DEFAULT_ATIMWD << 16) | DEFAULT_SLOT_TIME;
reg->M40_MacControl = tmp;
pltmp[7] = tmp;
/* M44 */
tmp = DEFAULT_MAX_TX_MSDU_LIFE_TIME << 10; /* *1024 */
reg->M44_MacControl = tmp;
pltmp[8] = tmp;
/* M48 */
pHwData->BeaconPeriod = DEFAULT_BEACON_INTERVAL;
pHwData->ProbeDelay = DEFAULT_PROBE_DELAY_TIME;
tmp = (DEFAULT_BEACON_INTERVAL << 16) | DEFAULT_PROBE_DELAY_TIME;
reg->M48_MacControl = tmp;
pltmp[9] = tmp;
/* M4C */
reg->M4C_MacStatus = (DEFAULT_PROTOCOL_VERSION << 30) | (DEFAULT_MAC_POWER_STATE << 28) | (DEFAULT_DTIM_ALERT_TIME << 24);
pltmp[10] = reg->M4C_MacStatus;
for (i = 0; i < 11; i++)
Wb35Reg_WriteSync(pHwData, 0x0824 + i * 4, pltmp[i]);
/* M60 */
Wb35Reg_WriteSync(pHwData, 0x0860, 0x12481248);
reg->M60_MacControl = 0x12481248;
/* M68 */
Wb35Reg_WriteSync(pHwData, 0x0868, 0x00050900);
reg->M68_MacControl = 0x00050900;
/* M98 */
Wb35Reg_WriteSync(pHwData, 0x0898, 0xffff8888);
reg->M98_MacControl = 0xffff8888;
}
void Uxx_power_off_procedure(struct hw_data *pHwData)
{
/* SW, PMU reset and turn off clock */
Wb35Reg_WriteSync(pHwData, 0x03b0, 3);
Wb35Reg_WriteSync(pHwData, 0x03f0, 0xf9);
}
/*Decide the TxVga of every channel */
void GetTxVgaFromEEPROM(struct hw_data *pHwData)
{
u32 i, j, ltmp;
u16 Value[MAX_TXVGA_EEPROM];
u8 *pctmp;
u8 ctmp = 0;
/* Get the entire TxVga setting in EEPROM */
for (i = 0; i < MAX_TXVGA_EEPROM; i++) {
Wb35Reg_WriteSync(pHwData, 0x03b4, 0x08100000 + 0x00010000 * i);
Wb35Reg_ReadSync(pHwData, 0x03b4, <mp);
Value[i] = (u16) (ltmp & 0xffff); /* Get 16 bit available */
Value[i] = cpu_to_le16(Value[i]); /* [7:0]2412 [7:0]2417 .... */
}
/* Adjust the filed which fills with reserved value. */
pctmp = (u8 *) Value;
for (i = 0; i < (MAX_TXVGA_EEPROM * 2); i++) {
if (pctmp[i] != 0xff)
ctmp = pctmp[i];
else
pctmp[i] = ctmp;
}
/* Adjust WB_242 to WB_242_1 TxVga scale */
if (pHwData->phy_type == RF_WB_242) {
for (i = 0; i < 4; i++) { /* Only 2412 2437 2462 2484 case must be modified */
for (j = 0; j < ARRAY_SIZE(w89rf242_txvga_old_mapping); j++) {
if (pctmp[i] < (u8) w89rf242_txvga_old_mapping[j][1]) {
pctmp[i] = (u8) w89rf242_txvga_old_mapping[j][0];
break;
}
}
if (j == ARRAY_SIZE(w89rf242_txvga_old_mapping))
pctmp[i] = (u8)w89rf242_txvga_old_mapping[j-1][0];
}
}
memcpy(pHwData->TxVgaSettingInEEPROM, pctmp, MAX_TXVGA_EEPROM * 2); /* MAX_TXVGA_EEPROM is u16 count */
EEPROMTxVgaAdjust(pHwData);
}
/*
* This function will affect the TxVga parameter in HAL. If hal_set_current_channel
* or RFSynthesizer_SetPowerIndex be called, new TxVga will take effect.
* TxVgaSettingInEEPROM of sHwData is an u8 array point to EEPROM contain for IS89C35
* This function will use default TxVgaSettingInEEPROM data to calculate new TxVga.
*/
void EEPROMTxVgaAdjust(struct hw_data *pHwData)
{
u8 *pTxVga = pHwData->TxVgaSettingInEEPROM;
s16 i, stmp;
/* -- 2.4G -- */
/* channel 1 ~ 5 */
stmp = pTxVga[1] - pTxVga[0];
for (i = 0; i < 5; i++)
pHwData->TxVgaFor24[i] = pTxVga[0] + stmp * i / 4;
/* channel 6 ~ 10 */
stmp = pTxVga[2] - pTxVga[1];
for (i = 5; i < 10; i++)
pHwData->TxVgaFor24[i] = pTxVga[1] + stmp * (i - 5) / 4;
/* channel 11 ~ 13 */
stmp = pTxVga[3] - pTxVga[2];
for (i = 10; i < 13; i++)
pHwData->TxVgaFor24[i] = pTxVga[2] + stmp * (i - 10) / 2;
/* channel 14 */
pHwData->TxVgaFor24[13] = pTxVga[3];
/* -- 5G -- */
if (pHwData->phy_type == RF_AIROHA_7230) {
/* channel 184 */
pHwData->TxVgaFor50[0].ChanNo = 184;
pHwData->TxVgaFor50[0].TxVgaValue = pTxVga[4];
/* channel 196 */
pHwData->TxVgaFor50[3].ChanNo = 196;
pHwData->TxVgaFor50[3].TxVgaValue = pTxVga[5];
/* interpolate */
pHwData->TxVgaFor50[1].ChanNo = 188;
pHwData->TxVgaFor50[2].ChanNo = 192;
stmp = pTxVga[5] - pTxVga[4];
pHwData->TxVgaFor50[2].TxVgaValue = pTxVga[5] - stmp / 3;
pHwData->TxVgaFor50[1].TxVgaValue = pTxVga[5] - stmp * 2 / 3;
/* channel 16 */
pHwData->TxVgaFor50[6].ChanNo = 16;
pHwData->TxVgaFor50[6].TxVgaValue = pTxVga[6];
pHwData->TxVgaFor50[4].ChanNo = 8;
pHwData->TxVgaFor50[4].TxVgaValue = pTxVga[6];
pHwData->TxVgaFor50[5].ChanNo = 12;
pHwData->TxVgaFor50[5].TxVgaValue = pTxVga[6];
/* channel 36 */
pHwData->TxVgaFor50[8].ChanNo = 36;
pHwData->TxVgaFor50[8].TxVgaValue = pTxVga[7];
pHwData->TxVgaFor50[7].ChanNo = 34;
pHwData->TxVgaFor50[7].TxVgaValue = pTxVga[7];
pHwData->TxVgaFor50[9].ChanNo = 38;
pHwData->TxVgaFor50[9].TxVgaValue = pTxVga[7];
/* channel 40 */
pHwData->TxVgaFor50[10].ChanNo = 40;
pHwData->TxVgaFor50[10].TxVgaValue = pTxVga[8];
/* channel 48 */
pHwData->TxVgaFor50[14].ChanNo = 48;
pHwData->TxVgaFor50[14].TxVgaValue = pTxVga[9];
/* interpolate */
pHwData->TxVgaFor50[11].ChanNo = 42;
pHwData->TxVgaFor50[12].ChanNo = 44;
pHwData->TxVgaFor50[13].ChanNo = 46;
stmp = pTxVga[9] - pTxVga[8];
pHwData->TxVgaFor50[13].TxVgaValue = pTxVga[9] - stmp / 4;
pHwData->TxVgaFor50[12].TxVgaValue = pTxVga[9] - stmp * 2 / 4;
pHwData->TxVgaFor50[11].TxVgaValue = pTxVga[9] - stmp * 3 / 4;
/* channel 52 */
pHwData->TxVgaFor50[15].ChanNo = 52;
pHwData->TxVgaFor50[15].TxVgaValue = pTxVga[10];
/* channel 64 */
pHwData->TxVgaFor50[18].ChanNo = 64;
pHwData->TxVgaFor50[18].TxVgaValue = pTxVga[11];
/* interpolate */
pHwData->TxVgaFor50[16].ChanNo = 56;
pHwData->TxVgaFor50[17].ChanNo = 60;
stmp = pTxVga[11] - pTxVga[10];
pHwData->TxVgaFor50[17].TxVgaValue = pTxVga[11] - stmp / 3;
pHwData->TxVgaFor50[16].TxVgaValue = pTxVga[11] - stmp * 2 / 3;
/* channel 100 */
pHwData->TxVgaFor50[19].ChanNo = 100;
pHwData->TxVgaFor50[19].TxVgaValue = pTxVga[12];
/* channel 112 */
pHwData->TxVgaFor50[22].ChanNo = 112;
pHwData->TxVgaFor50[22].TxVgaValue = pTxVga[13];
/* interpolate */
pHwData->TxVgaFor50[20].ChanNo = 104;
pHwData->TxVgaFor50[21].ChanNo = 108;
stmp = pTxVga[13] - pTxVga[12];
pHwData->TxVgaFor50[21].TxVgaValue = pTxVga[13] - stmp / 3;
pHwData->TxVgaFor50[20].TxVgaValue = pTxVga[13] - stmp * 2 / 3;
/* channel 128 */
pHwData->TxVgaFor50[26].ChanNo = 128;
pHwData->TxVgaFor50[26].TxVgaValue = pTxVga[14];
/* interpolate */
pHwData->TxVgaFor50[23].ChanNo = 116;
pHwData->TxVgaFor50[24].ChanNo = 120;
pHwData->TxVgaFor50[25].ChanNo = 124;
stmp = pTxVga[14] - pTxVga[13];
pHwData->TxVgaFor50[25].TxVgaValue = pTxVga[14] - stmp / 4;
pHwData->TxVgaFor50[24].TxVgaValue = pTxVga[14] - stmp * 2 / 4;
pHwData->TxVgaFor50[23].TxVgaValue = pTxVga[14] - stmp * 3 / 4;
/* channel 140 */
pHwData->TxVgaFor50[29].ChanNo = 140;
pHwData->TxVgaFor50[29].TxVgaValue = pTxVga[15];
/* interpolate */
pHwData->TxVgaFor50[27].ChanNo = 132;
pHwData->TxVgaFor50[28].ChanNo = 136;
stmp = pTxVga[15] - pTxVga[14];
pHwData->TxVgaFor50[28].TxVgaValue = pTxVga[15] - stmp / 3;
pHwData->TxVgaFor50[27].TxVgaValue = pTxVga[15] - stmp * 2 / 3;
/* channel 149 */
pHwData->TxVgaFor50[30].ChanNo = 149;
pHwData->TxVgaFor50[30].TxVgaValue = pTxVga[16];
/* channel 165 */
pHwData->TxVgaFor50[34].ChanNo = 165;
pHwData->TxVgaFor50[34].TxVgaValue = pTxVga[17];
/* interpolate */
pHwData->TxVgaFor50[31].ChanNo = 153;
pHwData->TxVgaFor50[32].ChanNo = 157;
pHwData->TxVgaFor50[33].ChanNo = 161;
stmp = pTxVga[17] - pTxVga[16];
pHwData->TxVgaFor50[33].TxVgaValue = pTxVga[17] - stmp / 4;
pHwData->TxVgaFor50[32].TxVgaValue = pTxVga[17] - stmp * 2 / 4;
pHwData->TxVgaFor50[31].TxVgaValue = pTxVga[17] - stmp * 3 / 4;
}
}
void BBProcessor_RateChanging(struct hw_data *pHwData, u8 rate)
{
struct wb35_reg *reg = &pHwData->reg;
unsigned char Is11bRate;
Is11bRate = (rate % 6) ? 1 : 0;
switch (pHwData->phy_type) {
case RF_AIROHA_2230:
case RF_AIROHA_2230S:
if (Is11bRate) {
if ((reg->BB48 != BB48_DEFAULT_AL2230_11B) &&
(reg->BB4C != BB4C_DEFAULT_AL2230_11B)) {
Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_AL2230_11B);
Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_AL2230_11B);
}
} else {
if ((reg->BB48 != BB48_DEFAULT_AL2230_11G) &&
(reg->BB4C != BB4C_DEFAULT_AL2230_11G)) {
Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_AL2230_11G);
Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_AL2230_11G);
}
}
break;
case RF_WB_242:
if (Is11bRate) {
if ((reg->BB48 != BB48_DEFAULT_WB242_11B) &&
(reg->BB4C != BB4C_DEFAULT_WB242_11B)) {
reg->BB48 = BB48_DEFAULT_WB242_11B;
reg->BB4C = BB4C_DEFAULT_WB242_11B;
Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_WB242_11B);
Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_WB242_11B);
}
} else {
if ((reg->BB48 != BB48_DEFAULT_WB242_11G) &&
(reg->BB4C != BB4C_DEFAULT_WB242_11G)) {
reg->BB48 = BB48_DEFAULT_WB242_11G;
reg->BB4C = BB4C_DEFAULT_WB242_11G;
Wb35Reg_Write(pHwData, 0x1048, BB48_DEFAULT_WB242_11G);
Wb35Reg_Write(pHwData, 0x104c, BB4C_DEFAULT_WB242_11G);
}
}
break;
}
}
| gpl-2.0 |
acroreiser/LowLatencyKernel | arch/mips/pci/fixup-lemote2f.c | 8479 | 4879 | /*
* Copyright (C) 2008 Lemote Technology
* Copyright (C) 2004 ICT CAS
* Author: Li xiaoyu, lixy@ict.ac.cn
*
* Copyright (C) 2007 Lemote, Inc.
* Author: Fuxin Zhang, zhangfx@lemote.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/init.h>
#include <linux/pci.h>
#include <loongson.h>
#include <cs5536/cs5536.h>
#include <cs5536/cs5536_pci.h>
/* PCI interrupt pins
*
* These should not be changed, or you should consider loongson2f interrupt
* register and your pci card dispatch
*/
#define PCIA 4
#define PCIB 5
#define PCIC 6
#define PCID 7
/* all the pci device has the PCIA pin, check the datasheet. */
static char irq_tab[][5] __initdata = {
/* INTA INTB INTC INTD */
{0, 0, 0, 0, 0}, /* 11: Unused */
{0, 0, 0, 0, 0}, /* 12: Unused */
{0, 0, 0, 0, 0}, /* 13: Unused */
{0, 0, 0, 0, 0}, /* 14: Unused */
{0, 0, 0, 0, 0}, /* 15: Unused */
{0, 0, 0, 0, 0}, /* 16: Unused */
{0, PCIA, 0, 0, 0}, /* 17: RTL8110-0 */
{0, PCIB, 0, 0, 0}, /* 18: RTL8110-1 */
{0, PCIC, 0, 0, 0}, /* 19: SiI3114 */
{0, PCID, 0, 0, 0}, /* 20: 3-ports nec usb */
{0, PCIA, PCIB, PCIC, PCID}, /* 21: PCI-SLOT */
{0, 0, 0, 0, 0}, /* 22: Unused */
{0, 0, 0, 0, 0}, /* 23: Unused */
{0, 0, 0, 0, 0}, /* 24: Unused */
{0, 0, 0, 0, 0}, /* 25: Unused */
{0, 0, 0, 0, 0}, /* 26: Unused */
{0, 0, 0, 0, 0}, /* 27: Unused */
};
int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
int virq;
if ((PCI_SLOT(dev->devfn) != PCI_IDSEL_CS5536)
&& (PCI_SLOT(dev->devfn) < 32)) {
virq = irq_tab[slot][pin];
printk(KERN_INFO "slot: %d, pin: %d, irq: %d\n", slot, pin,
virq + LOONGSON_IRQ_BASE);
if (virq != 0)
return LOONGSON_IRQ_BASE + virq;
else
return 0;
} else if (PCI_SLOT(dev->devfn) == PCI_IDSEL_CS5536) { /* cs5536 */
switch (PCI_FUNC(dev->devfn)) {
case 2:
pci_write_config_byte(dev, PCI_INTERRUPT_LINE,
CS5536_IDE_INTR);
return CS5536_IDE_INTR; /* for IDE */
case 3:
pci_write_config_byte(dev, PCI_INTERRUPT_LINE,
CS5536_ACC_INTR);
return CS5536_ACC_INTR; /* for AUDIO */
case 4: /* for OHCI */
case 5: /* for EHCI */
case 6: /* for UDC */
case 7: /* for OTG */
pci_write_config_byte(dev, PCI_INTERRUPT_LINE,
CS5536_USB_INTR);
return CS5536_USB_INTR;
}
return dev->irq;
} else {
printk(KERN_INFO " strange pci slot number.\n");
return 0;
}
}
/* Do platform specific device initialization at pci_enable_device() time */
int pcibios_plat_dev_init(struct pci_dev *dev)
{
return 0;
}
/* CS5536 SPEC. fixup */
static void __init loongson_cs5536_isa_fixup(struct pci_dev *pdev)
{
/* the uart1 and uart2 interrupt in PIC is enabled as default */
pci_write_config_dword(pdev, PCI_UART1_INT_REG, 1);
pci_write_config_dword(pdev, PCI_UART2_INT_REG, 1);
}
static void __init loongson_cs5536_ide_fixup(struct pci_dev *pdev)
{
/* setting the mutex pin as IDE function */
pci_write_config_dword(pdev, PCI_IDE_CFG_REG,
CS5536_IDE_FLASH_SIGNATURE);
}
static void __init loongson_cs5536_acc_fixup(struct pci_dev *pdev)
{
/* enable the AUDIO interrupt in PIC */
pci_write_config_dword(pdev, PCI_ACC_INT_REG, 1);
pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0xc0);
}
static void __init loongson_cs5536_ohci_fixup(struct pci_dev *pdev)
{
/* enable the OHCI interrupt in PIC */
/* THE OHCI, EHCI, UDC, OTG are shared with interrupt in PIC */
pci_write_config_dword(pdev, PCI_OHCI_INT_REG, 1);
}
static void __init loongson_cs5536_ehci_fixup(struct pci_dev *pdev)
{
u32 hi, lo;
/* Serial short detect enable */
_rdmsr(USB_MSR_REG(USB_CONFIG), &hi, &lo);
_wrmsr(USB_MSR_REG(USB_CONFIG), (1 << 1) | (1 << 3), lo);
/* setting the USB2.0 micro frame length */
pci_write_config_dword(pdev, PCI_EHCI_FLADJ_REG, 0x2000);
}
static void __init loongson_nec_fixup(struct pci_dev *pdev)
{
unsigned int val;
pci_read_config_dword(pdev, 0xe0, &val);
/* Only 2 port be used */
pci_write_config_dword(pdev, 0xe0, (val & ~3) | 0x2);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_ISA,
loongson_cs5536_isa_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_OHC,
loongson_cs5536_ohci_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_EHC,
loongson_cs5536_ehci_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_AUDIO,
loongson_cs5536_acc_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_IDE,
loongson_cs5536_ide_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_USB,
loongson_nec_fixup);
| gpl-2.0 |
n3ocort3x/msm_htc_helper | arch/mips/cavium-octeon/executive/cvmx-sysinfo.c | 8735 | 3569 | /***********************license start***************
* Author: Cavium Networks
*
* Contact: support@caviumnetworks.com
* This file is part of the OCTEON SDK
*
* Copyright (c) 2003-2008 Cavium Networks
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 2, as
* published by the Free Software Foundation.
*
* This file is distributed in the hope that it will be useful, but
* AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
* NONINFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* or visit http://www.gnu.org/licenses/.
*
* This file may also be available under a different license from Cavium.
* Contact Cavium Networks for more information
***********************license end**************************************/
/*
* This module provides system/board/application information obtained
* by the bootloader.
*/
#include <linux/module.h>
#include <asm/octeon/cvmx.h>
#include <asm/octeon/cvmx-spinlock.h>
#include <asm/octeon/cvmx-sysinfo.h>
/**
* This structure defines the private state maintained by sysinfo module.
*
*/
static struct {
struct cvmx_sysinfo sysinfo; /* system information */
cvmx_spinlock_t lock; /* mutex spinlock */
} state = {
.lock = CVMX_SPINLOCK_UNLOCKED_INITIALIZER
};
/*
* Global variables that define the min/max of the memory region set
* up for 32 bit userspace access.
*/
uint64_t linux_mem32_min;
uint64_t linux_mem32_max;
uint64_t linux_mem32_wired;
uint64_t linux_mem32_offset;
/**
* This function returns the application information as obtained
* by the bootloader. This provides the core mask of the cores
* running the same application image, as well as the physical
* memory regions available to the core.
*
* Returns Pointer to the boot information structure
*
*/
struct cvmx_sysinfo *cvmx_sysinfo_get(void)
{
return &(state.sysinfo);
}
EXPORT_SYMBOL(cvmx_sysinfo_get);
/**
* This function is used in non-simple executive environments (such as
* Linux kernel, u-boot, etc.) to configure the minimal fields that
* are required to use simple executive files directly.
*
* Locking (if required) must be handled outside of this
* function
*
* @phy_mem_desc_ptr:
* Pointer to global physical memory descriptor
* (bootmem descriptor) @board_type: Octeon board
* type enumeration
*
* @board_rev_major:
* Board major revision
* @board_rev_minor:
* Board minor revision
* @cpu_clock_hz:
* CPU clock freqency in hertz
*
* Returns 0: Failure
* 1: success
*/
int cvmx_sysinfo_minimal_initialize(void *phy_mem_desc_ptr,
uint16_t board_type,
uint8_t board_rev_major,
uint8_t board_rev_minor,
uint32_t cpu_clock_hz)
{
/* The sysinfo structure was already initialized */
if (state.sysinfo.board_type)
return 0;
memset(&(state.sysinfo), 0x0, sizeof(state.sysinfo));
state.sysinfo.phy_mem_desc_ptr = phy_mem_desc_ptr;
state.sysinfo.board_type = board_type;
state.sysinfo.board_rev_major = board_rev_major;
state.sysinfo.board_rev_minor = board_rev_minor;
state.sysinfo.cpu_clock_hz = cpu_clock_hz;
return 1;
}
| gpl-2.0 |
iAMr00t/android_kernel_carbon_msm8928 | arch/mips/txx9/rbtx4938/setup.c | 8735 | 10511 | /*
* Setup pointers to hardware-dependent routines.
* Copyright (C) 2000-2001 Toshiba Corporation
*
* 2003-2005 (c) MontaVista Software, Inc. This file is licensed under the
* terms of the GNU General Public License version 2. This program is
* licensed "as is" without any warranty of any kind, whether express
* or implied.
*
* Support for TX4938 in 2.6 - Manish Lachwani (mlachwani@mvista.com)
*/
#include <linux/init.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/mtd/physmap.h>
#include <asm/reboot.h>
#include <asm/io.h>
#include <asm/txx9/generic.h>
#include <asm/txx9/pci.h>
#include <asm/txx9/rbtx4938.h>
#include <linux/spi/spi.h>
#include <asm/txx9/spi.h>
#include <asm/txx9pio.h>
static void rbtx4938_machine_restart(char *command)
{
local_irq_disable();
writeb(1, rbtx4938_softresetlock_addr);
writeb(1, rbtx4938_sfvol_addr);
writeb(1, rbtx4938_softreset_addr);
/* fallback */
(*_machine_halt)();
}
static void __init rbtx4938_pci_setup(void)
{
#ifdef CONFIG_PCI
int extarb = !(__raw_readq(&tx4938_ccfgptr->ccfg) & TX4938_CCFG_PCIARB);
struct pci_controller *c = &txx9_primary_pcic;
register_pci_controller(c);
if (__raw_readq(&tx4938_ccfgptr->ccfg) & TX4938_CCFG_PCI66)
txx9_pci_option =
(txx9_pci_option & ~TXX9_PCI_OPT_CLK_MASK) |
TXX9_PCI_OPT_CLK_66; /* already configured */
/* Reset PCI Bus */
writeb(0, rbtx4938_pcireset_addr);
/* Reset PCIC */
txx9_set64(&tx4938_ccfgptr->clkctr, TX4938_CLKCTR_PCIRST);
if ((txx9_pci_option & TXX9_PCI_OPT_CLK_MASK) ==
TXX9_PCI_OPT_CLK_66)
tx4938_pciclk66_setup();
mdelay(10);
/* clear PCIC reset */
txx9_clear64(&tx4938_ccfgptr->clkctr, TX4938_CLKCTR_PCIRST);
writeb(1, rbtx4938_pcireset_addr);
iob();
tx4938_report_pciclk();
tx4927_pcic_setup(tx4938_pcicptr, c, extarb);
if ((txx9_pci_option & TXX9_PCI_OPT_CLK_MASK) ==
TXX9_PCI_OPT_CLK_AUTO &&
txx9_pci66_check(c, 0, 0)) {
/* Reset PCI Bus */
writeb(0, rbtx4938_pcireset_addr);
/* Reset PCIC */
txx9_set64(&tx4938_ccfgptr->clkctr, TX4938_CLKCTR_PCIRST);
tx4938_pciclk66_setup();
mdelay(10);
/* clear PCIC reset */
txx9_clear64(&tx4938_ccfgptr->clkctr, TX4938_CLKCTR_PCIRST);
writeb(1, rbtx4938_pcireset_addr);
iob();
/* Reinitialize PCIC */
tx4938_report_pciclk();
tx4927_pcic_setup(tx4938_pcicptr, c, extarb);
}
if (__raw_readq(&tx4938_ccfgptr->pcfg) &
(TX4938_PCFG_ETH0_SEL|TX4938_PCFG_ETH1_SEL)) {
/* Reset PCIC1 */
txx9_set64(&tx4938_ccfgptr->clkctr, TX4938_CLKCTR_PCIC1RST);
/* PCI1DMD==0 => PCI1CLK==GBUSCLK/2 => PCI66 */
if (!(__raw_readq(&tx4938_ccfgptr->ccfg)
& TX4938_CCFG_PCI1DMD))
tx4938_ccfg_set(TX4938_CCFG_PCI1_66);
mdelay(10);
/* clear PCIC1 reset */
txx9_clear64(&tx4938_ccfgptr->clkctr, TX4938_CLKCTR_PCIC1RST);
tx4938_report_pci1clk();
/* mem:64K(max), io:64K(max) (enough for ETH0,ETH1) */
c = txx9_alloc_pci_controller(NULL, 0, 0x10000, 0, 0x10000);
register_pci_controller(c);
tx4927_pcic_setup(tx4938_pcic1ptr, c, 0);
}
tx4938_setup_pcierr_irq();
#endif /* CONFIG_PCI */
}
/* SPI support */
/* chip select for SPI devices */
#define SEEPROM1_CS 7 /* PIO7 */
#define SEEPROM2_CS 0 /* IOC */
#define SEEPROM3_CS 1 /* IOC */
#define SRTC_CS 2 /* IOC */
#define SPI_BUSNO 0
static int __init rbtx4938_ethaddr_init(void)
{
#ifdef CONFIG_PCI
unsigned char dat[17];
unsigned char sum;
int i;
/* 0-3: "MAC\0", 4-9:eth0, 10-15:eth1, 16:sum */
if (spi_eeprom_read(SPI_BUSNO, SEEPROM1_CS, 0, dat, sizeof(dat))) {
printk(KERN_ERR "seeprom: read error.\n");
return -ENODEV;
} else {
if (strcmp(dat, "MAC") != 0)
printk(KERN_WARNING "seeprom: bad signature.\n");
for (i = 0, sum = 0; i < sizeof(dat); i++)
sum += dat[i];
if (sum)
printk(KERN_WARNING "seeprom: bad checksum.\n");
}
tx4938_ethaddr_init(&dat[4], &dat[4 + 6]);
#endif /* CONFIG_PCI */
return 0;
}
static void __init rbtx4938_spi_setup(void)
{
/* set SPI_SEL */
txx9_set64(&tx4938_ccfgptr->pcfg, TX4938_PCFG_SPI_SEL);
}
static struct resource rbtx4938_fpga_resource;
static void __init rbtx4938_time_init(void)
{
tx4938_time_init(0);
}
static void __init rbtx4938_mem_setup(void)
{
unsigned long long pcfg;
if (txx9_master_clock == 0)
txx9_master_clock = 25000000; /* 25MHz */
tx4938_setup();
#ifdef CONFIG_PCI
txx9_alloc_pci_controller(&txx9_primary_pcic, 0, 0, 0, 0);
txx9_board_pcibios_setup = tx4927_pcibios_setup;
#else
set_io_port_base(RBTX4938_ETHER_BASE);
#endif
tx4938_sio_init(7372800, 0);
#ifdef CONFIG_TOSHIBA_RBTX4938_MPLEX_PIO58_61
pr_info("PIOSEL: disabling both ATA and NAND selection\n");
txx9_clear64(&tx4938_ccfgptr->pcfg,
TX4938_PCFG_NDF_SEL | TX4938_PCFG_ATA_SEL);
#endif
#ifdef CONFIG_TOSHIBA_RBTX4938_MPLEX_NAND
pr_info("PIOSEL: enabling NAND selection\n");
txx9_set64(&tx4938_ccfgptr->pcfg, TX4938_PCFG_NDF_SEL);
txx9_clear64(&tx4938_ccfgptr->pcfg, TX4938_PCFG_ATA_SEL);
#endif
#ifdef CONFIG_TOSHIBA_RBTX4938_MPLEX_ATA
pr_info("PIOSEL: enabling ATA selection\n");
txx9_set64(&tx4938_ccfgptr->pcfg, TX4938_PCFG_ATA_SEL);
txx9_clear64(&tx4938_ccfgptr->pcfg, TX4938_PCFG_NDF_SEL);
#endif
#ifdef CONFIG_TOSHIBA_RBTX4938_MPLEX_KEEP
pcfg = ____raw_readq(&tx4938_ccfgptr->pcfg);
pr_info("PIOSEL: NAND %s, ATA %s\n",
(pcfg & TX4938_PCFG_NDF_SEL) ? "enabled" : "disabled",
(pcfg & TX4938_PCFG_ATA_SEL) ? "enabled" : "disabled");
#endif
rbtx4938_spi_setup();
pcfg = ____raw_readq(&tx4938_ccfgptr->pcfg); /* updated */
/* fixup piosel */
if ((pcfg & (TX4938_PCFG_ATA_SEL | TX4938_PCFG_NDF_SEL)) ==
TX4938_PCFG_ATA_SEL)
writeb((readb(rbtx4938_piosel_addr) & 0x03) | 0x04,
rbtx4938_piosel_addr);
else if ((pcfg & (TX4938_PCFG_ATA_SEL | TX4938_PCFG_NDF_SEL)) ==
TX4938_PCFG_NDF_SEL)
writeb((readb(rbtx4938_piosel_addr) & 0x03) | 0x08,
rbtx4938_piosel_addr);
else
writeb(readb(rbtx4938_piosel_addr) & ~(0x08 | 0x04),
rbtx4938_piosel_addr);
rbtx4938_fpga_resource.name = "FPGA Registers";
rbtx4938_fpga_resource.start = CPHYSADDR(RBTX4938_FPGA_REG_ADDR);
rbtx4938_fpga_resource.end = CPHYSADDR(RBTX4938_FPGA_REG_ADDR) + 0xffff;
rbtx4938_fpga_resource.flags = IORESOURCE_MEM | IORESOURCE_BUSY;
if (request_resource(&txx9_ce_res[2], &rbtx4938_fpga_resource))
printk(KERN_ERR "request resource for fpga failed\n");
_machine_restart = rbtx4938_machine_restart;
writeb(0xff, rbtx4938_led_addr);
printk(KERN_INFO "RBTX4938 --- FPGA(Rev %02x) DIPSW:%02x,%02x\n",
readb(rbtx4938_fpga_rev_addr),
readb(rbtx4938_dipsw_addr), readb(rbtx4938_bdipsw_addr));
}
static void __init rbtx4938_ne_init(void)
{
struct resource res[] = {
{
.start = RBTX4938_RTL_8019_BASE,
.end = RBTX4938_RTL_8019_BASE + 0x20 - 1,
.flags = IORESOURCE_IO,
}, {
.start = RBTX4938_RTL_8019_IRQ,
.flags = IORESOURCE_IRQ,
}
};
platform_device_register_simple("ne", -1, res, ARRAY_SIZE(res));
}
static DEFINE_SPINLOCK(rbtx4938_spi_gpio_lock);
static void rbtx4938_spi_gpio_set(struct gpio_chip *chip, unsigned int offset,
int value)
{
u8 val;
unsigned long flags;
spin_lock_irqsave(&rbtx4938_spi_gpio_lock, flags);
val = readb(rbtx4938_spics_addr);
if (value)
val |= 1 << offset;
else
val &= ~(1 << offset);
writeb(val, rbtx4938_spics_addr);
mmiowb();
spin_unlock_irqrestore(&rbtx4938_spi_gpio_lock, flags);
}
static int rbtx4938_spi_gpio_dir_out(struct gpio_chip *chip,
unsigned int offset, int value)
{
rbtx4938_spi_gpio_set(chip, offset, value);
return 0;
}
static struct gpio_chip rbtx4938_spi_gpio_chip = {
.set = rbtx4938_spi_gpio_set,
.direction_output = rbtx4938_spi_gpio_dir_out,
.label = "RBTX4938-SPICS",
.base = 16,
.ngpio = 3,
};
static int __init rbtx4938_spi_init(void)
{
struct spi_board_info srtc_info = {
.modalias = "rtc-rs5c348",
.max_speed_hz = 1000000, /* 1.0Mbps @ Vdd 2.0V */
.bus_num = 0,
.chip_select = 16 + SRTC_CS,
/* Mode 1 (High-Active, Shift-Then-Sample), High Avtive CS */
.mode = SPI_MODE_1 | SPI_CS_HIGH,
};
spi_register_board_info(&srtc_info, 1);
spi_eeprom_register(SPI_BUSNO, SEEPROM1_CS, 128);
spi_eeprom_register(SPI_BUSNO, 16 + SEEPROM2_CS, 128);
spi_eeprom_register(SPI_BUSNO, 16 + SEEPROM3_CS, 128);
gpio_request(16 + SRTC_CS, "rtc-rs5c348");
gpio_direction_output(16 + SRTC_CS, 0);
gpio_request(SEEPROM1_CS, "seeprom1");
gpio_direction_output(SEEPROM1_CS, 1);
gpio_request(16 + SEEPROM2_CS, "seeprom2");
gpio_direction_output(16 + SEEPROM2_CS, 1);
gpio_request(16 + SEEPROM3_CS, "seeprom3");
gpio_direction_output(16 + SEEPROM3_CS, 1);
tx4938_spi_init(SPI_BUSNO);
return 0;
}
static void __init rbtx4938_mtd_init(void)
{
struct physmap_flash_data pdata = {
.width = 4,
};
switch (readb(rbtx4938_bdipsw_addr) & 7) {
case 0:
/* Boot */
txx9_physmap_flash_init(0, 0x1fc00000, 0x400000, &pdata);
/* System */
txx9_physmap_flash_init(1, 0x1e000000, 0x1000000, &pdata);
break;
case 1:
/* System */
txx9_physmap_flash_init(0, 0x1f000000, 0x1000000, &pdata);
/* Boot */
txx9_physmap_flash_init(1, 0x1ec00000, 0x400000, &pdata);
break;
case 2:
/* Ext */
txx9_physmap_flash_init(0, 0x1f000000, 0x1000000, &pdata);
/* System */
txx9_physmap_flash_init(1, 0x1e000000, 0x1000000, &pdata);
/* Boot */
txx9_physmap_flash_init(2, 0x1dc00000, 0x400000, &pdata);
break;
case 3:
/* Boot */
txx9_physmap_flash_init(1, 0x1bc00000, 0x400000, &pdata);
/* System */
txx9_physmap_flash_init(2, 0x1a000000, 0x1000000, &pdata);
break;
}
}
static void __init rbtx4938_arch_init(void)
{
gpiochip_add(&rbtx4938_spi_gpio_chip);
rbtx4938_pci_setup();
rbtx4938_spi_init();
}
static void __init rbtx4938_device_init(void)
{
rbtx4938_ethaddr_init();
rbtx4938_ne_init();
tx4938_wdt_init();
rbtx4938_mtd_init();
/* TC58DVM82A1FT: tDH=10ns, tWP=tRP=tREADID=35ns */
tx4938_ndfmc_init(10, 35);
tx4938_ata_init(RBTX4938_IRQ_IOC_ATA, 0, 1);
tx4938_dmac_init(0, 2);
tx4938_aclc_init();
platform_device_register_simple("txx9aclc-generic", -1, NULL, 0);
tx4938_sramc_init();
txx9_iocled_init(RBTX4938_LED_ADDR - IO_BASE, -1, 8, 1, "green", NULL);
}
struct txx9_board_vec rbtx4938_vec __initdata = {
.system = "Toshiba RBTX4938",
.prom_init = rbtx4938_prom_init,
.mem_setup = rbtx4938_mem_setup,
.irq_setup = rbtx4938_irq_setup,
.time_init = rbtx4938_time_init,
.device_init = rbtx4938_device_init,
.arch_init = rbtx4938_arch_init,
#ifdef CONFIG_PCI
.pci_map_irq = rbtx4938_pci_map_irq,
#endif
};
| gpl-2.0 |
mrjaydee82/SinLessKernelNew | drivers/scsi/libsas/sas_host_smp.c | 9503 | 9710 | /*
* Serial Attached SCSI (SAS) Expander discovery and configuration
*
* Copyright (C) 2007 James E.J. Bottomley
* <James.Bottomley@HansenPartnership.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 only.
*/
#include <linux/scatterlist.h>
#include <linux/blkdev.h>
#include <linux/slab.h>
#include <linux/export.h>
#include "sas_internal.h"
#include <scsi/scsi_transport.h>
#include <scsi/scsi_transport_sas.h>
#include "../scsi_sas_internal.h"
static void sas_host_smp_discover(struct sas_ha_struct *sas_ha, u8 *resp_data,
u8 phy_id)
{
struct sas_phy *phy;
struct sas_rphy *rphy;
if (phy_id >= sas_ha->num_phys) {
resp_data[2] = SMP_RESP_NO_PHY;
return;
}
resp_data[2] = SMP_RESP_FUNC_ACC;
phy = sas_ha->sas_phy[phy_id]->phy;
resp_data[9] = phy_id;
resp_data[13] = phy->negotiated_linkrate;
memcpy(resp_data + 16, sas_ha->sas_addr, SAS_ADDR_SIZE);
memcpy(resp_data + 24, sas_ha->sas_phy[phy_id]->attached_sas_addr,
SAS_ADDR_SIZE);
resp_data[40] = (phy->minimum_linkrate << 4) |
phy->minimum_linkrate_hw;
resp_data[41] = (phy->maximum_linkrate << 4) |
phy->maximum_linkrate_hw;
if (!sas_ha->sas_phy[phy_id]->port ||
!sas_ha->sas_phy[phy_id]->port->port_dev)
return;
rphy = sas_ha->sas_phy[phy_id]->port->port_dev->rphy;
resp_data[12] = rphy->identify.device_type << 4;
resp_data[14] = rphy->identify.initiator_port_protocols;
resp_data[15] = rphy->identify.target_port_protocols;
}
/**
* to_sas_gpio_gp_bit - given the gpio frame data find the byte/bit position of 'od'
* @od: od bit to find
* @data: incoming bitstream (from frame)
* @index: requested data register index (from frame)
* @count: total number of registers in the bitstream (from frame)
* @bit: bit position of 'od' in the returned byte
*
* returns NULL if 'od' is not in 'data'
*
* From SFF-8485 v0.7:
* "In GPIO_TX[1], bit 0 of byte 3 contains the first bit (i.e., OD0.0)
* and bit 7 of byte 0 contains the 32nd bit (i.e., OD10.1).
*
* In GPIO_TX[2], bit 0 of byte 3 contains the 33rd bit (i.e., OD10.2)
* and bit 7 of byte 0 contains the 64th bit (i.e., OD21.0)."
*
* The general-purpose (raw-bitstream) RX registers have the same layout
* although 'od' is renamed 'id' for 'input data'.
*
* SFF-8489 defines the behavior of the LEDs in response to the 'od' values.
*/
static u8 *to_sas_gpio_gp_bit(unsigned int od, u8 *data, u8 index, u8 count, u8 *bit)
{
unsigned int reg;
u8 byte;
/* gp registers start at index 1 */
if (index == 0)
return NULL;
index--; /* make index 0-based */
if (od < index * 32)
return NULL;
od -= index * 32;
reg = od >> 5;
if (reg >= count)
return NULL;
od &= (1 << 5) - 1;
byte = 3 - (od >> 3);
*bit = od & ((1 << 3) - 1);
return &data[reg * 4 + byte];
}
int try_test_sas_gpio_gp_bit(unsigned int od, u8 *data, u8 index, u8 count)
{
u8 *byte;
u8 bit;
byte = to_sas_gpio_gp_bit(od, data, index, count, &bit);
if (!byte)
return -1;
return (*byte >> bit) & 1;
}
EXPORT_SYMBOL(try_test_sas_gpio_gp_bit);
static int sas_host_smp_write_gpio(struct sas_ha_struct *sas_ha, u8 *resp_data,
u8 reg_type, u8 reg_index, u8 reg_count,
u8 *req_data)
{
struct sas_internal *i = to_sas_internal(sas_ha->core.shost->transportt);
int written;
if (i->dft->lldd_write_gpio == NULL) {
resp_data[2] = SMP_RESP_FUNC_UNK;
return 0;
}
written = i->dft->lldd_write_gpio(sas_ha, reg_type, reg_index,
reg_count, req_data);
if (written < 0) {
resp_data[2] = SMP_RESP_FUNC_FAILED;
written = 0;
} else
resp_data[2] = SMP_RESP_FUNC_ACC;
return written;
}
static void sas_report_phy_sata(struct sas_ha_struct *sas_ha, u8 *resp_data,
u8 phy_id)
{
struct sas_rphy *rphy;
struct dev_to_host_fis *fis;
int i;
if (phy_id >= sas_ha->num_phys) {
resp_data[2] = SMP_RESP_NO_PHY;
return;
}
resp_data[2] = SMP_RESP_PHY_NO_SATA;
if (!sas_ha->sas_phy[phy_id]->port)
return;
rphy = sas_ha->sas_phy[phy_id]->port->port_dev->rphy;
fis = (struct dev_to_host_fis *)
sas_ha->sas_phy[phy_id]->port->port_dev->frame_rcvd;
if (rphy->identify.target_port_protocols != SAS_PROTOCOL_SATA)
return;
resp_data[2] = SMP_RESP_FUNC_ACC;
resp_data[9] = phy_id;
memcpy(resp_data + 16, sas_ha->sas_phy[phy_id]->attached_sas_addr,
SAS_ADDR_SIZE);
/* check to see if we have a valid d2h fis */
if (fis->fis_type != 0x34)
return;
/* the d2h fis is required by the standard to be in LE format */
for (i = 0; i < 20; i += 4) {
u8 *dst = resp_data + 24 + i, *src =
&sas_ha->sas_phy[phy_id]->port->port_dev->frame_rcvd[i];
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
}
}
static void sas_phy_control(struct sas_ha_struct *sas_ha, u8 phy_id,
u8 phy_op, enum sas_linkrate min,
enum sas_linkrate max, u8 *resp_data)
{
struct sas_internal *i =
to_sas_internal(sas_ha->core.shost->transportt);
struct sas_phy_linkrates rates;
struct asd_sas_phy *asd_phy;
if (phy_id >= sas_ha->num_phys) {
resp_data[2] = SMP_RESP_NO_PHY;
return;
}
asd_phy = sas_ha->sas_phy[phy_id];
switch (phy_op) {
case PHY_FUNC_NOP:
case PHY_FUNC_LINK_RESET:
case PHY_FUNC_HARD_RESET:
case PHY_FUNC_DISABLE:
case PHY_FUNC_CLEAR_ERROR_LOG:
case PHY_FUNC_CLEAR_AFFIL:
case PHY_FUNC_TX_SATA_PS_SIGNAL:
break;
default:
resp_data[2] = SMP_RESP_PHY_UNK_OP;
return;
}
rates.minimum_linkrate = min;
rates.maximum_linkrate = max;
/* filter reset requests through libata eh */
if (phy_op == PHY_FUNC_LINK_RESET && sas_try_ata_reset(asd_phy) == 0) {
resp_data[2] = SMP_RESP_FUNC_ACC;
return;
}
if (i->dft->lldd_control_phy(asd_phy, phy_op, &rates))
resp_data[2] = SMP_RESP_FUNC_FAILED;
else
resp_data[2] = SMP_RESP_FUNC_ACC;
}
int sas_smp_host_handler(struct Scsi_Host *shost, struct request *req,
struct request *rsp)
{
u8 *req_data = NULL, *resp_data = NULL, *buf;
struct sas_ha_struct *sas_ha = SHOST_TO_SAS_HA(shost);
int error = -EINVAL;
/* eight is the minimum size for request and response frames */
if (blk_rq_bytes(req) < 8 || blk_rq_bytes(rsp) < 8)
goto out;
if (bio_offset(req->bio) + blk_rq_bytes(req) > PAGE_SIZE ||
bio_offset(rsp->bio) + blk_rq_bytes(rsp) > PAGE_SIZE) {
shost_printk(KERN_ERR, shost,
"SMP request/response frame crosses page boundary");
goto out;
}
req_data = kzalloc(blk_rq_bytes(req), GFP_KERNEL);
/* make sure frame can always be built ... we copy
* back only the requested length */
resp_data = kzalloc(max(blk_rq_bytes(rsp), 128U), GFP_KERNEL);
if (!req_data || !resp_data) {
error = -ENOMEM;
goto out;
}
local_irq_disable();
buf = kmap_atomic(bio_page(req->bio));
memcpy(req_data, buf, blk_rq_bytes(req));
kunmap_atomic(buf - bio_offset(req->bio));
local_irq_enable();
if (req_data[0] != SMP_REQUEST)
goto out;
/* always succeeds ... even if we can't process the request
* the result is in the response frame */
error = 0;
/* set up default don't know response */
resp_data[0] = SMP_RESPONSE;
resp_data[1] = req_data[1];
resp_data[2] = SMP_RESP_FUNC_UNK;
switch (req_data[1]) {
case SMP_REPORT_GENERAL:
req->resid_len -= 8;
rsp->resid_len -= 32;
resp_data[2] = SMP_RESP_FUNC_ACC;
resp_data[9] = sas_ha->num_phys;
break;
case SMP_REPORT_MANUF_INFO:
req->resid_len -= 8;
rsp->resid_len -= 64;
resp_data[2] = SMP_RESP_FUNC_ACC;
memcpy(resp_data + 12, shost->hostt->name,
SAS_EXPANDER_VENDOR_ID_LEN);
memcpy(resp_data + 20, "libsas virt phy",
SAS_EXPANDER_PRODUCT_ID_LEN);
break;
case SMP_READ_GPIO_REG:
/* FIXME: need GPIO support in the transport class */
break;
case SMP_DISCOVER:
req->resid_len -= 16;
if ((int)req->resid_len < 0) {
req->resid_len = 0;
error = -EINVAL;
goto out;
}
rsp->resid_len -= 56;
sas_host_smp_discover(sas_ha, resp_data, req_data[9]);
break;
case SMP_REPORT_PHY_ERR_LOG:
/* FIXME: could implement this with additional
* libsas callbacks providing the HW supports it */
break;
case SMP_REPORT_PHY_SATA:
req->resid_len -= 16;
if ((int)req->resid_len < 0) {
req->resid_len = 0;
error = -EINVAL;
goto out;
}
rsp->resid_len -= 60;
sas_report_phy_sata(sas_ha, resp_data, req_data[9]);
break;
case SMP_REPORT_ROUTE_INFO:
/* Can't implement; hosts have no routes */
break;
case SMP_WRITE_GPIO_REG: {
/* SFF-8485 v0.7 */
const int base_frame_size = 11;
int to_write = req_data[4];
if (blk_rq_bytes(req) < base_frame_size + to_write * 4 ||
req->resid_len < base_frame_size + to_write * 4) {
resp_data[2] = SMP_RESP_INV_FRM_LEN;
break;
}
to_write = sas_host_smp_write_gpio(sas_ha, resp_data, req_data[2],
req_data[3], to_write, &req_data[8]);
req->resid_len -= base_frame_size + to_write * 4;
rsp->resid_len -= 8;
break;
}
case SMP_CONF_ROUTE_INFO:
/* Can't implement; hosts have no routes */
break;
case SMP_PHY_CONTROL:
req->resid_len -= 44;
if ((int)req->resid_len < 0) {
req->resid_len = 0;
error = -EINVAL;
goto out;
}
rsp->resid_len -= 8;
sas_phy_control(sas_ha, req_data[9], req_data[10],
req_data[32] >> 4, req_data[33] >> 4,
resp_data);
break;
case SMP_PHY_TEST_FUNCTION:
/* FIXME: should this be implemented? */
break;
default:
/* probably a 2.0 function */
break;
}
local_irq_disable();
buf = kmap_atomic(bio_page(rsp->bio));
memcpy(buf, resp_data, blk_rq_bytes(rsp));
flush_kernel_dcache_page(bio_page(rsp->bio));
kunmap_atomic(buf - bio_offset(rsp->bio));
local_irq_enable();
out:
kfree(req_data);
kfree(resp_data);
return error;
}
| gpl-2.0 |
JaeYoulLee/Linux-Kernel | drivers/staging/rtl8712/rtl8712_io.c | 11295 | 4928 | /******************************************************************************
* rtl8712_io.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>.
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL8712_IO_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "rtl871x_io.h"
#include "osdep_intf.h"
#include "usb_ops.h"
u8 r8712_read8(struct _adapter *adapter, u32 addr)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
u8 (*_read8)(struct intf_hdl *pintfhdl, u32 addr);
u8 r_val;
_read8 = pintfhdl->io_ops._read8;
r_val = _read8(pintfhdl, addr);
return r_val;
}
u16 r8712_read16(struct _adapter *adapter, u32 addr)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
u16 (*_read16)(struct intf_hdl *pintfhdl, u32 addr);
u16 r_val;
_read16 = pintfhdl->io_ops._read16;
r_val = _read16(pintfhdl, addr);
return r_val;
}
u32 r8712_read32(struct _adapter *adapter, u32 addr)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
u32 (*_read32)(struct intf_hdl *pintfhdl, u32 addr);
u32 r_val;
_read32 = pintfhdl->io_ops._read32;
r_val = _read32(pintfhdl, addr);
return r_val;
}
void r8712_write8(struct _adapter *adapter, u32 addr, u8 val)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
void (*_write8)(struct intf_hdl *pintfhdl, u32 addr, u8 val);
_write8 = pintfhdl->io_ops._write8;
_write8(pintfhdl, addr, val);
}
void r8712_write16(struct _adapter *adapter, u32 addr, u16 val)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
void (*_write16)(struct intf_hdl *pintfhdl, u32 addr, u16 val);
_write16 = pintfhdl->io_ops._write16;
_write16(pintfhdl, addr, val);
}
void r8712_write32(struct _adapter *adapter, u32 addr, u32 val)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = (struct intf_hdl *)(&(pio_queue->intf));
void (*_write32)(struct intf_hdl *pintfhdl, u32 addr, u32 val);
_write32 = pintfhdl->io_ops._write32;
_write32(pintfhdl, addr, val);
}
void r8712_read_mem(struct _adapter *adapter, u32 addr, u32 cnt, u8 *pmem)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
void (*_read_mem)(struct intf_hdl *pintfhdl, u32 addr, u32 cnt,
u8 *pmem);
if ((adapter->bDriverStopped == true) ||
(adapter->bSurpriseRemoved == true))
return;
_read_mem = pintfhdl->io_ops._read_mem;
_read_mem(pintfhdl, addr, cnt, pmem);
}
void r8712_write_mem(struct _adapter *adapter, u32 addr, u32 cnt, u8 *pmem)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
void (*_write_mem)(struct intf_hdl *pintfhdl, u32 addr, u32 cnt,
u8 *pmem);
_write_mem = pintfhdl->io_ops._write_mem;
_write_mem(pintfhdl, addr, cnt, pmem);
}
void r8712_read_port(struct _adapter *adapter, u32 addr, u32 cnt, u8 *pmem)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
u32 (*_read_port)(struct intf_hdl *pintfhdl, u32 addr, u32 cnt,
u8 *pmem);
if ((adapter->bDriverStopped == true) ||
(adapter->bSurpriseRemoved == true))
return;
_read_port = pintfhdl->io_ops._read_port;
_read_port(pintfhdl, addr, cnt, pmem);
}
void r8712_write_port(struct _adapter *adapter, u32 addr, u32 cnt, u8 *pmem)
{
struct io_queue *pio_queue = (struct io_queue *)adapter->pio_queue;
struct intf_hdl *pintfhdl = &(pio_queue->intf);
u32 (*_write_port)(struct intf_hdl *pintfhdl, u32 addr, u32 cnt,
u8 *pmem);
_write_port = pintfhdl->io_ops._write_port;
_write_port(pintfhdl, addr, cnt, pmem);
}
| gpl-2.0 |
mtk09422/chromiumos-third_party-coreboot | src/mainboard/supermicro/x6dhe_g/watchdog.c | 32 | 2297 | #include <device/pnp_def.h>
#define NSC_WD_DEV PNP_DEV(0x2e, 0xa)
#define NSC_WDBASE 0x600
#define ESB6300_WDBASE 0x400
#define ESB6300_GPIOBASE 0x500
static void disable_sio_watchdog(device_t dev)
{
#if 0
/* FIXME move me somewhere more appropriate */
pnp_set_logical_device(dev);
pnp_set_enable(dev, 1);
pnp_set_iobase(dev, PNP_IDX_IO0, NSC_WDBASE);
/* disable the sio watchdog */
outb(0, NSC_WDBASE + 0);
pnp_set_enable(dev, 0);
#endif
}
static void disable_esb6300_watchdog(void)
{
/* FIXME move me somewhere more appropriate */
device_t dev;
unsigned long value, base;
dev = pci_locate_device(PCI_ID(0x8086, 0x25a1), 0);
if (dev == PCI_DEV_INVALID) {
die("Missing esb6300?");
}
/* Enable I/O space */
value = pci_read_config16(dev, 0x04);
value |= (1 << 10);
pci_write_config16(dev, 0x04, value);
/* Set and enable acpibase */
pci_write_config32(dev, 0x40, ESB6300_WDBASE | 1);
pci_write_config8(dev, 0x44, 0x10);
base = ESB6300_WDBASE + 0x60;
/* Set bit 11 in TCO1_CNT */
value = inw(base + 0x08);
value |= 1 << 11;
outw(value, base + 0x08);
/* Clear TCO timeout status */
outw(0x0008, base + 0x04);
outw(0x0002, base + 0x06);
}
static void disable_jarell_frb3(void)
{
#if 0
device_t dev;
unsigned long value, base;
dev = pci_locate_device(PCI_ID(0x8086, 0x25a1), 0);
if (dev == PCI_DEV_INVALID) {
die("Missing esb6300?");
}
/* Enable I/O space */
value = pci_read_config16(dev, 0x04);
value |= (1 << 0);
pci_write_config16(dev, 0x04, value);
/* Set gpio base */
pci_write_config32(dev, 0x58, ESB6300_GPIOBASE | 1);
base = ESB6300_GPIOBASE;
/* Enable GPIO Bar */
value = pci_read_config32(dev, 0x5c);
value |= 0x10;
pci_write_config32(dev, 0x5c, value);
/* Configure GPIO 48 and 40 as GPIO */
value = inl(base + 0x30);
value |= (1 << 16) | ( 1 << 8);
outl(value, base + 0x30);
/* Configure GPIO 48 as Output */
value = inl(base + 0x34);
value &= ~(1 << 16);
outl(value, base + 0x34);
/* Toggle GPIO 48 high to low */
value = inl(base + 0x38);
value |= (1 << 16);
outl(value, base + 0x38);
value &= ~(1 << 16);
outl(value, base + 0x38);
#endif
}
static void disable_watchdogs(void)
{
// disable_sio_watchdog(NSC_WD_DEV);
disable_esb6300_watchdog();
// disable_jarell_frb3();
print_debug("Watchdogs disabled\n");
}
| gpl-2.0 |
Quadral/335source | src/server/scripts/EasternKingdoms/zone_ghostlands.cpp | 32 | 5228 | /*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.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, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Ghostlands
SD%Complete: 100
SDComment: Quest support: 9212.
SDCategory: Ghostlands
EndScriptData */
/* ContentData
npc_ranger_lilatha
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "ScriptedEscortAI.h"
#include "Player.h"
#include "WorldSession.h"
/*######
## npc_ranger_lilatha
######*/
enum RangerLilatha
{
SAY_START = 0,
SAY_PROGRESS1 = 1,
SAY_PROGRESS2 = 2,
SAY_PROGRESS3 = 3,
SAY_END1 = 4,
SAY_END2 = 5,
SAY_CAPTAIN_ANSWER = 0,
QUEST_ESCAPE_FROM_THE_CATACOMBS = 9212,
GO_CAGE = 181152,
NPC_CAPTAIN_HELIOS = 16220,
NPC_MUMMIFIED_HEADHUNTER = 16342,
NPC_SHADOWPINE_ORACLE = 16343,
FACTION_QUEST_ESCAPE = 113
};
class npc_ranger_lilatha : public CreatureScript
{
public:
npc_ranger_lilatha() : CreatureScript("npc_ranger_lilatha") { }
struct npc_ranger_lilathaAI : public npc_escortAI
{
npc_ranger_lilathaAI(Creature* creature) : npc_escortAI(creature) { }
void WaypointReached(uint32 waypointId) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 0:
me->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
if (GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 20))
Cage->SetGoState(GO_STATE_ACTIVE);
Talk(SAY_START, player);
break;
case 5:
Talk(SAY_PROGRESS1, player);
break;
case 11:
Talk(SAY_PROGRESS2, player);
me->SetFacingTo(4.762841f);
break;
case 18:
{
Talk(SAY_PROGRESS3, player);
Creature* Summ1 = me->SummonCreature(NPC_MUMMIFIED_HEADHUNTER, 7627.083984f, -7532.538086f, 152.128616f, 1.082733f, TEMPSUMMON_DEAD_DESPAWN, 0);
Creature* Summ2 = me->SummonCreature(NPC_SHADOWPINE_ORACLE, 7620.432129f, -7532.550293f, 152.454865f, 0.827478f, TEMPSUMMON_DEAD_DESPAWN, 0);
if (Summ1 && Summ2)
{
Summ1->Attack(me, true);
Summ2->Attack(player, true);
}
AttackStart(Summ1);
}
break;
case 19:
me->SetWalk(false);
break;
case 25:
me->SetWalk(true);
break;
case 30:
player->GroupEventHappens(QUEST_ESCAPE_FROM_THE_CATACOMBS, me);
break;
case 32:
me->SetFacingTo(2.978281f);
Talk(SAY_END1, player);
break;
case 33:
me->SetFacingTo(5.858011f);
Talk(SAY_END2, player);
Creature* CaptainHelios = me->FindNearestCreature(NPC_CAPTAIN_HELIOS, 50);
if (CaptainHelios)
CaptainHelios->AI()->Talk(SAY_CAPTAIN_ANSWER, player);
break;
}
}
void Reset() override
{
if (GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 20))
Cage->SetGoState(GO_STATE_READY);
}
};
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_ESCAPE_FROM_THE_CATACOMBS)
{
creature->setFaction(FACTION_QUEST_ESCAPE);
if (npc_escortAI* pEscortAI = CAST_AI(npc_ranger_lilatha::npc_ranger_lilathaAI, creature->AI()))
pEscortAI->Start(true, false, player->GetGUID());
}
return true;
}
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_ranger_lilathaAI(creature);
}
};
void AddSC_ghostlands()
{
new npc_ranger_lilatha();
}
| gpl-2.0 |
kgilmer/openjdk-7-mermaid | src/share/native/sun/java2d/pipe/SpanClipRenderer.c | 32 | 8750 | /*
* Copyright (c) 1998, 2000, 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 <math.h>
#include "jni.h"
#include "jni_util.h"
#include "sun_java2d_pipe_SpanClipRenderer.h"
#include "sun_java2d_pipe_RegionIterator.h"
jfieldID pBandsArrayID;
jfieldID pEndIndexID;
jfieldID pRegionID;
jfieldID pCurIndexID;
jfieldID pNumXbandsID;
JNIEXPORT void JNICALL
Java_sun_java2d_pipe_SpanClipRenderer_initIDs
(JNIEnv *env, jclass src, jclass rc, jclass ric)
{
/* Region fields */
pBandsArrayID = (*env)->GetFieldID(env, rc, "bands", "[I");
pEndIndexID = (*env)->GetFieldID(env, rc, "endIndex", "I");
/* RegionIterator fields */
pRegionID = (*env)->GetFieldID(env, ric, "region",
"Lsun/java2d/pipe/Region;");
pCurIndexID = (*env)->GetFieldID(env, ric, "curIndex", "I");
pNumXbandsID = (*env)->GetFieldID(env, ric, "numXbands", "I");
if((pBandsArrayID == NULL)
|| (pEndIndexID == NULL)
|| (pRegionID == NULL)
|| (pCurIndexID == NULL)
|| (pNumXbandsID == NULL))
{
JNU_ThrowInternalError(env, "NULL field ID");
}
}
static void
fill(jbyte *alpha, jint offset, jint tsize,
jint x, jint y, jint w, jint h, jbyte value)
{
alpha += offset + y * tsize + x;
tsize -= w;
while (--h >= 0) {
for (x = 0; x < w; x++) {
*alpha++ = value;
}
alpha += tsize;
}
}
static jboolean
nextYRange(jint *box, jint *bands, jint endIndex,
jint *pCurIndex, jint *pNumXbands)
{
jint curIndex = *pCurIndex;
jint numXbands = *pNumXbands;
jboolean ret;
curIndex += numXbands * 2;
ret = (curIndex + 3 < endIndex);
if (ret) {
box[1] = bands[curIndex++];
box[3] = bands[curIndex++];
numXbands = bands[curIndex++];
} else {
numXbands = 0;
}
*pCurIndex = curIndex;
*pNumXbands = numXbands;
return ret;
}
static jboolean
nextXBand(jint *box, jint *bands, jint endIndex,
jint *pCurIndex, jint *pNumXbands)
{
jint curIndex = *pCurIndex;
jint numXbands = *pNumXbands;
if (numXbands <= 0 || curIndex + 2 > endIndex) {
return JNI_FALSE;
}
numXbands--;
box[0] = bands[curIndex++];
box[2] = bands[curIndex++];
*pCurIndex = curIndex;
*pNumXbands = numXbands;
return JNI_TRUE;
}
JNIEXPORT void JNICALL
Java_sun_java2d_pipe_SpanClipRenderer_fillTile
(JNIEnv *env, jobject sr, jobject ri,
jbyteArray alphaTile, jint offset, jint tsize, jintArray boxArray)
{
jbyte *alpha;
jint *box;
jint w, h;
jsize alphalen;
if ((*env)->GetArrayLength(env, boxArray) < 4) {
JNU_ThrowArrayIndexOutOfBoundsException(env, "band array");
}
alphalen = (*env)->GetArrayLength(env, alphaTile);
box = (*env)->GetPrimitiveArrayCritical(env, boxArray, 0);
w = box[2] - box[0];
h = box[3] - box[1];
if (alphalen < offset || (alphalen - offset) / tsize < h) {
(*env)->ReleasePrimitiveArrayCritical(env, boxArray, box, 0);
JNU_ThrowArrayIndexOutOfBoundsException(env, "alpha tile array");
}
alpha = (*env)->GetPrimitiveArrayCritical(env, alphaTile, 0);
fill(alpha, offset, tsize, 0, 0, w, h, (jbyte) 0xff);
(*env)->ReleasePrimitiveArrayCritical(env, alphaTile, alpha, 0);
(*env)->ReleasePrimitiveArrayCritical(env, boxArray, box, 0);
Java_sun_java2d_pipe_SpanClipRenderer_eraseTile(env, sr, ri,
alphaTile, offset, tsize,
boxArray);
}
JNIEXPORT void JNICALL
Java_sun_java2d_pipe_SpanClipRenderer_eraseTile
(JNIEnv *env, jobject sr, jobject ri,
jbyteArray alphaTile, jint offset, jint tsize, jintArray boxArray)
{
jobject region;
jintArray bandsArray;
jint *bands;
jbyte *alpha;
jint *box;
jint endIndex;
jint curIndex;
jint saveCurIndex;
jint numXbands;
jint saveNumXbands;
jint lox;
jint loy;
jint hix;
jint hiy;
jint firstx;
jint firsty;
jint lastx;
jint lasty;
jint curx;
jsize alphalen;
if ((*env)->GetArrayLength(env, boxArray) < 4) {
JNU_ThrowArrayIndexOutOfBoundsException(env, "band array");
}
alphalen = (*env)->GetArrayLength(env, alphaTile);
saveCurIndex = (*env)->GetIntField(env, ri, pCurIndexID);
saveNumXbands = (*env)->GetIntField(env, ri, pNumXbandsID);
region = (*env)->GetObjectField(env, ri, pRegionID);
bandsArray = (*env)->GetObjectField(env, region, pBandsArrayID);
endIndex = (*env)->GetIntField(env, region, pEndIndexID);
if (endIndex > (*env)->GetArrayLength(env, bandsArray)) {
endIndex = (*env)->GetArrayLength(env, bandsArray);
}
box = (*env)->GetPrimitiveArrayCritical(env, boxArray, 0);
lox = box[0];
loy = box[1];
hix = box[2];
hiy = box[3];
if (alphalen < offset ||
alphalen < offset + (hix-lox) ||
(alphalen - offset - (hix-lox)) / tsize < (hiy - loy - 1)) {
(*env)->ReleasePrimitiveArrayCritical(env, boxArray, box, 0);
JNU_ThrowArrayIndexOutOfBoundsException(env, "alpha tile array");
}
bands = (*env)->GetPrimitiveArrayCritical(env, bandsArray, 0);
alpha = (*env)->GetPrimitiveArrayCritical(env, alphaTile, 0);
curIndex = saveCurIndex;
numXbands = saveNumXbands;
firsty = hiy;
lasty = hiy;
firstx = hix;
lastx = lox;
while (nextYRange(box, bands, endIndex, &curIndex, &numXbands)) {
if (box[3] <= loy) {
saveNumXbands = numXbands;
saveCurIndex = curIndex;
continue;
}
if (box[1] >= hiy) {
break;
}
if (box[1] < loy) {
box[1] = loy;
}
if (box[3] > hiy) {
box[3] = hiy;
}
curx = lox;
while (nextXBand(box, bands, endIndex, &curIndex, &numXbands)) {
if (box[2] <= lox) {
continue;
}
if (box[0] >= hix) {
break;
}
if (box[0] < lox) {
box[0] = lox;
}
if (lasty < box[1]) {
fill(alpha, offset, tsize,
0, lasty - loy,
hix - lox, box[1] - lasty, 0);
}
lasty = box[3];
if (firstx > box[0]) {
firstx = box[0];
}
if (curx < box[0]) {
fill(alpha, offset, tsize,
curx - lox, box[1] - loy,
box[0] - curx, box[3] - box[1], 0);
}
curx = box[2];
if (curx >= hix) {
curx = hix;
break;
}
}
if (curx > lox) {
if (curx < hix) {
fill(alpha, offset, tsize,
curx - lox, box[1] - loy,
hix - curx, box[3] - box[1], 0);
}
if (firsty > box[1]) {
firsty = box[1];
}
}
if (lastx < curx) {
lastx = curx;
}
}
box[0] = firstx;
box[1] = firsty;
box[2] = lastx;
box[3] = lasty;
(*env)->ReleasePrimitiveArrayCritical(env, alphaTile, alpha, 0);
(*env)->ReleasePrimitiveArrayCritical(env, bandsArray, bands, 0);
(*env)->ReleasePrimitiveArrayCritical(env, boxArray, box, 0);
(*env)->SetIntField(env, ri, pCurIndexID, saveCurIndex);
(*env)->SetIntField(env, ri, pNumXbandsID, saveNumXbands);
}
| gpl-2.0 |
cedrichu/kernel_tcp_stack_14.04LTS | drivers/gpu/drm/nouveau/nouveau_bo.c | 32 | 39672 | /*
* Copyright 2007 Dave Airlied
* 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
* VA LINUX SYSTEMS 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.
*/
/*
* Authors: Dave Airlied <airlied@linux.ie>
* Ben Skeggs <darktama@iinet.net.au>
* Jeremy Kolb <jkolb@brandeis.edu>
*/
#include <core/engine.h>
#include <linux/swiotlb.h>
#include <subdev/fb.h>
#include <subdev/vm.h>
#include <subdev/bar.h>
#include "nouveau_drm.h"
#include "nouveau_dma.h"
#include "nouveau_fence.h"
#include "nouveau_bo.h"
#include "nouveau_ttm.h"
#include "nouveau_gem.h"
/*
* NV10-NV40 tiling helpers
*/
static void
nv10_bo_update_tile_region(struct drm_device *dev, struct nouveau_drm_tile *reg,
u32 addr, u32 size, u32 pitch, u32 flags)
{
struct nouveau_drm *drm = nouveau_drm(dev);
int i = reg - drm->tile.reg;
struct nouveau_fb *pfb = nouveau_fb(drm->device);
struct nouveau_fb_tile *tile = &pfb->tile.region[i];
struct nouveau_engine *engine;
nouveau_fence_unref(®->fence);
if (tile->pitch)
pfb->tile.fini(pfb, i, tile);
if (pitch)
pfb->tile.init(pfb, i, addr, size, pitch, flags, tile);
pfb->tile.prog(pfb, i, tile);
if ((engine = nouveau_engine(pfb, NVDEV_ENGINE_GR)))
engine->tile_prog(engine, i);
if ((engine = nouveau_engine(pfb, NVDEV_ENGINE_MPEG)))
engine->tile_prog(engine, i);
}
static struct nouveau_drm_tile *
nv10_bo_get_tile_region(struct drm_device *dev, int i)
{
struct nouveau_drm *drm = nouveau_drm(dev);
struct nouveau_drm_tile *tile = &drm->tile.reg[i];
spin_lock(&drm->tile.lock);
if (!tile->used &&
(!tile->fence || nouveau_fence_done(tile->fence)))
tile->used = true;
else
tile = NULL;
spin_unlock(&drm->tile.lock);
return tile;
}
static void
nv10_bo_put_tile_region(struct drm_device *dev, struct nouveau_drm_tile *tile,
struct nouveau_fence *fence)
{
struct nouveau_drm *drm = nouveau_drm(dev);
if (tile) {
spin_lock(&drm->tile.lock);
tile->fence = nouveau_fence_ref(fence);
tile->used = false;
spin_unlock(&drm->tile.lock);
}
}
static struct nouveau_drm_tile *
nv10_bo_set_tiling(struct drm_device *dev, u32 addr,
u32 size, u32 pitch, u32 flags)
{
struct nouveau_drm *drm = nouveau_drm(dev);
struct nouveau_fb *pfb = nouveau_fb(drm->device);
struct nouveau_drm_tile *tile, *found = NULL;
int i;
for (i = 0; i < pfb->tile.regions; i++) {
tile = nv10_bo_get_tile_region(dev, i);
if (pitch && !found) {
found = tile;
continue;
} else if (tile && pfb->tile.region[i].pitch) {
/* Kill an unused tile region. */
nv10_bo_update_tile_region(dev, tile, 0, 0, 0, 0);
}
nv10_bo_put_tile_region(dev, tile, NULL);
}
if (found)
nv10_bo_update_tile_region(dev, found, addr, size,
pitch, flags);
return found;
}
static void
nouveau_bo_del_ttm(struct ttm_buffer_object *bo)
{
struct nouveau_drm *drm = nouveau_bdev(bo->bdev);
struct drm_device *dev = drm->dev;
struct nouveau_bo *nvbo = nouveau_bo(bo);
if (unlikely(nvbo->gem.filp))
DRM_ERROR("bo %p still attached to GEM object\n", bo);
WARN_ON(nvbo->pin_refcnt > 0);
nv10_bo_put_tile_region(dev, nvbo->tile, NULL);
kfree(nvbo);
}
static void
nouveau_bo_fixup_align(struct nouveau_bo *nvbo, u32 flags,
int *align, int *size)
{
struct nouveau_drm *drm = nouveau_bdev(nvbo->bo.bdev);
struct nouveau_device *device = nv_device(drm->device);
if (device->card_type < NV_50) {
if (nvbo->tile_mode) {
if (device->chipset >= 0x40) {
*align = 65536;
*size = roundup(*size, 64 * nvbo->tile_mode);
} else if (device->chipset >= 0x30) {
*align = 32768;
*size = roundup(*size, 64 * nvbo->tile_mode);
} else if (device->chipset >= 0x20) {
*align = 16384;
*size = roundup(*size, 64 * nvbo->tile_mode);
} else if (device->chipset >= 0x10) {
*align = 16384;
*size = roundup(*size, 32 * nvbo->tile_mode);
}
}
} else {
*size = roundup(*size, (1 << nvbo->page_shift));
*align = max((1 << nvbo->page_shift), *align);
}
*size = roundup(*size, PAGE_SIZE);
}
int
nouveau_bo_new(struct drm_device *dev, int size, int align,
uint32_t flags, uint32_t tile_mode, uint32_t tile_flags,
struct sg_table *sg,
struct nouveau_bo **pnvbo)
{
struct nouveau_drm *drm = nouveau_drm(dev);
struct nouveau_bo *nvbo;
size_t acc_size;
int ret;
int type = ttm_bo_type_device;
int lpg_shift = 12;
int max_size;
if (drm->client.base.vm)
lpg_shift = drm->client.base.vm->vmm->lpg_shift;
max_size = INT_MAX & ~((1 << lpg_shift) - 1);
if (size <= 0 || size > max_size) {
nv_warn(drm, "skipped size %x\n", (u32)size);
return -EINVAL;
}
if (sg)
type = ttm_bo_type_sg;
nvbo = kzalloc(sizeof(struct nouveau_bo), GFP_KERNEL);
if (!nvbo)
return -ENOMEM;
INIT_LIST_HEAD(&nvbo->head);
INIT_LIST_HEAD(&nvbo->entry);
INIT_LIST_HEAD(&nvbo->vma_list);
nvbo->tile_mode = tile_mode;
nvbo->tile_flags = tile_flags;
nvbo->bo.bdev = &drm->ttm.bdev;
nvbo->page_shift = 12;
if (drm->client.base.vm) {
if (!(flags & TTM_PL_FLAG_TT) && size > 256 * 1024)
nvbo->page_shift = drm->client.base.vm->vmm->lpg_shift;
}
nouveau_bo_fixup_align(nvbo, flags, &align, &size);
nvbo->bo.mem.num_pages = size >> PAGE_SHIFT;
nouveau_bo_placement_set(nvbo, flags, 0);
acc_size = ttm_bo_dma_acc_size(&drm->ttm.bdev, size,
sizeof(struct nouveau_bo));
ret = ttm_bo_init(&drm->ttm.bdev, &nvbo->bo, size,
type, &nvbo->placement,
align >> PAGE_SHIFT, false, NULL, acc_size, sg,
nouveau_bo_del_ttm);
if (ret) {
/* ttm will call nouveau_bo_del_ttm if it fails.. */
return ret;
}
*pnvbo = nvbo;
return 0;
}
static void
set_placement_list(uint32_t *pl, unsigned *n, uint32_t type, uint32_t flags)
{
*n = 0;
if (type & TTM_PL_FLAG_VRAM)
pl[(*n)++] = TTM_PL_FLAG_VRAM | flags;
if (type & TTM_PL_FLAG_TT)
pl[(*n)++] = TTM_PL_FLAG_TT | flags;
if (type & TTM_PL_FLAG_SYSTEM)
pl[(*n)++] = TTM_PL_FLAG_SYSTEM | flags;
}
static void
set_placement_range(struct nouveau_bo *nvbo, uint32_t type)
{
struct nouveau_drm *drm = nouveau_bdev(nvbo->bo.bdev);
struct nouveau_fb *pfb = nouveau_fb(drm->device);
u32 vram_pages = pfb->ram->size >> PAGE_SHIFT;
if ((nv_device(drm->device)->card_type == NV_10 ||
nv_device(drm->device)->card_type == NV_11) &&
nvbo->tile_mode && (type & TTM_PL_FLAG_VRAM) &&
nvbo->bo.mem.num_pages < vram_pages / 4) {
/*
* Make sure that the color and depth buffers are handled
* by independent memory controller units. Up to a 9x
* speed up when alpha-blending and depth-test are enabled
* at the same time.
*/
if (nvbo->tile_flags & NOUVEAU_GEM_TILE_ZETA) {
nvbo->placement.fpfn = vram_pages / 2;
nvbo->placement.lpfn = ~0;
} else {
nvbo->placement.fpfn = 0;
nvbo->placement.lpfn = vram_pages / 2;
}
}
}
void
nouveau_bo_placement_set(struct nouveau_bo *nvbo, uint32_t type, uint32_t busy)
{
struct ttm_placement *pl = &nvbo->placement;
uint32_t flags = TTM_PL_MASK_CACHING |
(nvbo->pin_refcnt ? TTM_PL_FLAG_NO_EVICT : 0);
pl->placement = nvbo->placements;
set_placement_list(nvbo->placements, &pl->num_placement,
type, flags);
pl->busy_placement = nvbo->busy_placements;
set_placement_list(nvbo->busy_placements, &pl->num_busy_placement,
type | busy, flags);
set_placement_range(nvbo, type);
}
int
nouveau_bo_pin(struct nouveau_bo *nvbo, uint32_t memtype)
{
struct nouveau_drm *drm = nouveau_bdev(nvbo->bo.bdev);
struct ttm_buffer_object *bo = &nvbo->bo;
int ret;
ret = ttm_bo_reserve(bo, false, false, false, 0);
if (ret)
goto out;
if (nvbo->pin_refcnt && !(memtype & (1 << bo->mem.mem_type))) {
NV_ERROR(drm, "bo %p pinned elsewhere: 0x%08x vs 0x%08x\n", bo,
1 << bo->mem.mem_type, memtype);
ret = -EINVAL;
goto out;
}
if (nvbo->pin_refcnt++)
goto out;
nouveau_bo_placement_set(nvbo, memtype, 0);
ret = nouveau_bo_validate(nvbo, false, false);
if (ret == 0) {
switch (bo->mem.mem_type) {
case TTM_PL_VRAM:
drm->gem.vram_available -= bo->mem.size;
break;
case TTM_PL_TT:
drm->gem.gart_available -= bo->mem.size;
break;
default:
break;
}
}
out:
ttm_bo_unreserve(bo);
return ret;
}
int
nouveau_bo_unpin(struct nouveau_bo *nvbo)
{
struct nouveau_drm *drm = nouveau_bdev(nvbo->bo.bdev);
struct ttm_buffer_object *bo = &nvbo->bo;
int ret, ref;
ret = ttm_bo_reserve(bo, false, false, false, 0);
if (ret)
return ret;
ref = --nvbo->pin_refcnt;
WARN_ON_ONCE(ref < 0);
if (ref)
goto out;
nouveau_bo_placement_set(nvbo, bo->mem.placement, 0);
ret = nouveau_bo_validate(nvbo, false, false);
if (ret == 0) {
switch (bo->mem.mem_type) {
case TTM_PL_VRAM:
drm->gem.vram_available += bo->mem.size;
break;
case TTM_PL_TT:
drm->gem.gart_available += bo->mem.size;
break;
default:
break;
}
}
out:
ttm_bo_unreserve(bo);
return ret;
}
int
nouveau_bo_map(struct nouveau_bo *nvbo)
{
int ret;
ret = ttm_bo_reserve(&nvbo->bo, false, false, false, 0);
if (ret)
return ret;
ret = ttm_bo_kmap(&nvbo->bo, 0, nvbo->bo.mem.num_pages, &nvbo->kmap);
ttm_bo_unreserve(&nvbo->bo);
return ret;
}
void
nouveau_bo_unmap(struct nouveau_bo *nvbo)
{
if (nvbo)
ttm_bo_kunmap(&nvbo->kmap);
}
int
nouveau_bo_validate(struct nouveau_bo *nvbo, bool interruptible,
bool no_wait_gpu)
{
int ret;
ret = ttm_bo_validate(&nvbo->bo, &nvbo->placement,
interruptible, no_wait_gpu);
if (ret)
return ret;
return 0;
}
u16
nouveau_bo_rd16(struct nouveau_bo *nvbo, unsigned index)
{
bool is_iomem;
u16 *mem = ttm_kmap_obj_virtual(&nvbo->kmap, &is_iomem);
mem = &mem[index];
if (is_iomem)
return ioread16_native((void __force __iomem *)mem);
else
return *mem;
}
void
nouveau_bo_wr16(struct nouveau_bo *nvbo, unsigned index, u16 val)
{
bool is_iomem;
u16 *mem = ttm_kmap_obj_virtual(&nvbo->kmap, &is_iomem);
mem = &mem[index];
if (is_iomem)
iowrite16_native(val, (void __force __iomem *)mem);
else
*mem = val;
}
u32
nouveau_bo_rd32(struct nouveau_bo *nvbo, unsigned index)
{
bool is_iomem;
u32 *mem = ttm_kmap_obj_virtual(&nvbo->kmap, &is_iomem);
mem = &mem[index];
if (is_iomem)
return ioread32_native((void __force __iomem *)mem);
else
return *mem;
}
void
nouveau_bo_wr32(struct nouveau_bo *nvbo, unsigned index, u32 val)
{
bool is_iomem;
u32 *mem = ttm_kmap_obj_virtual(&nvbo->kmap, &is_iomem);
mem = &mem[index];
if (is_iomem)
iowrite32_native(val, (void __force __iomem *)mem);
else
*mem = val;
}
static struct ttm_tt *
nouveau_ttm_tt_create(struct ttm_bo_device *bdev, unsigned long size,
uint32_t page_flags, struct page *dummy_read)
{
#if __OS_HAS_AGP
struct nouveau_drm *drm = nouveau_bdev(bdev);
struct drm_device *dev = drm->dev;
if (drm->agp.stat == ENABLED) {
return ttm_agp_tt_create(bdev, dev->agp->bridge, size,
page_flags, dummy_read);
}
#endif
return nouveau_sgdma_create_ttm(bdev, size, page_flags, dummy_read);
}
static int
nouveau_bo_invalidate_caches(struct ttm_bo_device *bdev, uint32_t flags)
{
/* We'll do this from user space. */
return 0;
}
static int
nouveau_bo_init_mem_type(struct ttm_bo_device *bdev, uint32_t type,
struct ttm_mem_type_manager *man)
{
struct nouveau_drm *drm = nouveau_bdev(bdev);
switch (type) {
case TTM_PL_SYSTEM:
man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
man->available_caching = TTM_PL_MASK_CACHING;
man->default_caching = TTM_PL_FLAG_CACHED;
break;
case TTM_PL_VRAM:
if (nv_device(drm->device)->card_type >= NV_50) {
man->func = &nouveau_vram_manager;
man->io_reserve_fastpath = false;
man->use_io_reserve_lru = true;
} else {
man->func = &ttm_bo_manager_func;
}
man->flags = TTM_MEMTYPE_FLAG_FIXED |
TTM_MEMTYPE_FLAG_MAPPABLE;
man->available_caching = TTM_PL_FLAG_UNCACHED |
TTM_PL_FLAG_WC;
man->default_caching = TTM_PL_FLAG_WC;
break;
case TTM_PL_TT:
if (nv_device(drm->device)->card_type >= NV_50)
man->func = &nouveau_gart_manager;
else
if (drm->agp.stat != ENABLED)
man->func = &nv04_gart_manager;
else
man->func = &ttm_bo_manager_func;
if (drm->agp.stat == ENABLED) {
man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
man->available_caching = TTM_PL_FLAG_UNCACHED |
TTM_PL_FLAG_WC;
man->default_caching = TTM_PL_FLAG_WC;
} else {
man->flags = TTM_MEMTYPE_FLAG_MAPPABLE |
TTM_MEMTYPE_FLAG_CMA;
man->available_caching = TTM_PL_MASK_CACHING;
man->default_caching = TTM_PL_FLAG_CACHED;
}
break;
default:
return -EINVAL;
}
return 0;
}
static void
nouveau_bo_evict_flags(struct ttm_buffer_object *bo, struct ttm_placement *pl)
{
struct nouveau_bo *nvbo = nouveau_bo(bo);
switch (bo->mem.mem_type) {
case TTM_PL_VRAM:
nouveau_bo_placement_set(nvbo, TTM_PL_FLAG_TT,
TTM_PL_FLAG_SYSTEM);
break;
default:
nouveau_bo_placement_set(nvbo, TTM_PL_FLAG_SYSTEM, 0);
break;
}
*pl = nvbo->placement;
}
/* GPU-assisted copy using NV_MEMORY_TO_MEMORY_FORMAT, can access
* TTM_PL_{VRAM,TT} directly.
*/
static int
nouveau_bo_move_accel_cleanup(struct nouveau_channel *chan,
struct nouveau_bo *nvbo, bool evict,
bool no_wait_gpu, struct ttm_mem_reg *new_mem)
{
struct nouveau_fence *fence = NULL;
int ret;
ret = nouveau_fence_new(chan, false, &fence);
if (ret)
return ret;
ret = ttm_bo_move_accel_cleanup(&nvbo->bo, fence, evict,
no_wait_gpu, new_mem);
nouveau_fence_unref(&fence);
return ret;
}
static int
nve0_bo_move_init(struct nouveau_channel *chan, u32 handle)
{
int ret = RING_SPACE(chan, 2);
if (ret == 0) {
BEGIN_NVC0(chan, NvSubCopy, 0x0000, 1);
OUT_RING (chan, handle & 0x0000ffff);
FIRE_RING (chan);
}
return ret;
}
static int
nve0_bo_move_copy(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
int ret = RING_SPACE(chan, 10);
if (ret == 0) {
BEGIN_NVC0(chan, NvSubCopy, 0x0400, 8);
OUT_RING (chan, upper_32_bits(node->vma[0].offset));
OUT_RING (chan, lower_32_bits(node->vma[0].offset));
OUT_RING (chan, upper_32_bits(node->vma[1].offset));
OUT_RING (chan, lower_32_bits(node->vma[1].offset));
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, new_mem->num_pages);
BEGIN_IMC0(chan, NvSubCopy, 0x0300, 0x0386);
}
return ret;
}
static int
nvc0_bo_move_init(struct nouveau_channel *chan, u32 handle)
{
int ret = RING_SPACE(chan, 2);
if (ret == 0) {
BEGIN_NVC0(chan, NvSubCopy, 0x0000, 1);
OUT_RING (chan, handle);
}
return ret;
}
static int
nvc0_bo_move_copy(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
u64 src_offset = node->vma[0].offset;
u64 dst_offset = node->vma[1].offset;
u32 page_count = new_mem->num_pages;
int ret;
page_count = new_mem->num_pages;
while (page_count) {
int line_count = (page_count > 8191) ? 8191 : page_count;
ret = RING_SPACE(chan, 11);
if (ret)
return ret;
BEGIN_NVC0(chan, NvSubCopy, 0x030c, 8);
OUT_RING (chan, upper_32_bits(src_offset));
OUT_RING (chan, lower_32_bits(src_offset));
OUT_RING (chan, upper_32_bits(dst_offset));
OUT_RING (chan, lower_32_bits(dst_offset));
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, line_count);
BEGIN_NVC0(chan, NvSubCopy, 0x0300, 1);
OUT_RING (chan, 0x00000110);
page_count -= line_count;
src_offset += (PAGE_SIZE * line_count);
dst_offset += (PAGE_SIZE * line_count);
}
return 0;
}
static int
nvc0_bo_move_m2mf(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
u64 src_offset = node->vma[0].offset;
u64 dst_offset = node->vma[1].offset;
u32 page_count = new_mem->num_pages;
int ret;
page_count = new_mem->num_pages;
while (page_count) {
int line_count = (page_count > 2047) ? 2047 : page_count;
ret = RING_SPACE(chan, 12);
if (ret)
return ret;
BEGIN_NVC0(chan, NvSubCopy, 0x0238, 2);
OUT_RING (chan, upper_32_bits(dst_offset));
OUT_RING (chan, lower_32_bits(dst_offset));
BEGIN_NVC0(chan, NvSubCopy, 0x030c, 6);
OUT_RING (chan, upper_32_bits(src_offset));
OUT_RING (chan, lower_32_bits(src_offset));
OUT_RING (chan, PAGE_SIZE); /* src_pitch */
OUT_RING (chan, PAGE_SIZE); /* dst_pitch */
OUT_RING (chan, PAGE_SIZE); /* line_length */
OUT_RING (chan, line_count);
BEGIN_NVC0(chan, NvSubCopy, 0x0300, 1);
OUT_RING (chan, 0x00100110);
page_count -= line_count;
src_offset += (PAGE_SIZE * line_count);
dst_offset += (PAGE_SIZE * line_count);
}
return 0;
}
static int
nva3_bo_move_copy(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
u64 src_offset = node->vma[0].offset;
u64 dst_offset = node->vma[1].offset;
u32 page_count = new_mem->num_pages;
int ret;
page_count = new_mem->num_pages;
while (page_count) {
int line_count = (page_count > 8191) ? 8191 : page_count;
ret = RING_SPACE(chan, 11);
if (ret)
return ret;
BEGIN_NV04(chan, NvSubCopy, 0x030c, 8);
OUT_RING (chan, upper_32_bits(src_offset));
OUT_RING (chan, lower_32_bits(src_offset));
OUT_RING (chan, upper_32_bits(dst_offset));
OUT_RING (chan, lower_32_bits(dst_offset));
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, PAGE_SIZE);
OUT_RING (chan, line_count);
BEGIN_NV04(chan, NvSubCopy, 0x0300, 1);
OUT_RING (chan, 0x00000110);
page_count -= line_count;
src_offset += (PAGE_SIZE * line_count);
dst_offset += (PAGE_SIZE * line_count);
}
return 0;
}
static int
nv98_bo_move_exec(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
int ret = RING_SPACE(chan, 7);
if (ret == 0) {
BEGIN_NV04(chan, NvSubCopy, 0x0320, 6);
OUT_RING (chan, upper_32_bits(node->vma[0].offset));
OUT_RING (chan, lower_32_bits(node->vma[0].offset));
OUT_RING (chan, upper_32_bits(node->vma[1].offset));
OUT_RING (chan, lower_32_bits(node->vma[1].offset));
OUT_RING (chan, 0x00000000 /* COPY */);
OUT_RING (chan, new_mem->num_pages << PAGE_SHIFT);
}
return ret;
}
static int
nv84_bo_move_exec(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
int ret = RING_SPACE(chan, 7);
if (ret == 0) {
BEGIN_NV04(chan, NvSubCopy, 0x0304, 6);
OUT_RING (chan, new_mem->num_pages << PAGE_SHIFT);
OUT_RING (chan, upper_32_bits(node->vma[0].offset));
OUT_RING (chan, lower_32_bits(node->vma[0].offset));
OUT_RING (chan, upper_32_bits(node->vma[1].offset));
OUT_RING (chan, lower_32_bits(node->vma[1].offset));
OUT_RING (chan, 0x00000000 /* MODE_COPY, QUERY_NONE */);
}
return ret;
}
static int
nv50_bo_move_init(struct nouveau_channel *chan, u32 handle)
{
int ret = RING_SPACE(chan, 6);
if (ret == 0) {
BEGIN_NV04(chan, NvSubCopy, 0x0000, 1);
OUT_RING (chan, handle);
BEGIN_NV04(chan, NvSubCopy, 0x0180, 3);
OUT_RING (chan, NvNotify0);
OUT_RING (chan, NvDmaFB);
OUT_RING (chan, NvDmaFB);
}
return ret;
}
static int
nv50_bo_move_m2mf(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
struct nouveau_mem *node = old_mem->mm_node;
u64 length = (new_mem->num_pages << PAGE_SHIFT);
u64 src_offset = node->vma[0].offset;
u64 dst_offset = node->vma[1].offset;
int src_tiled = !!node->memtype;
int dst_tiled = !!((struct nouveau_mem *)new_mem->mm_node)->memtype;
int ret;
while (length) {
u32 amount, stride, height;
ret = RING_SPACE(chan, 18 + 6 * (src_tiled + dst_tiled));
if (ret)
return ret;
amount = min(length, (u64)(4 * 1024 * 1024));
stride = 16 * 4;
height = amount / stride;
if (src_tiled) {
BEGIN_NV04(chan, NvSubCopy, 0x0200, 7);
OUT_RING (chan, 0);
OUT_RING (chan, 0);
OUT_RING (chan, stride);
OUT_RING (chan, height);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, 0);
} else {
BEGIN_NV04(chan, NvSubCopy, 0x0200, 1);
OUT_RING (chan, 1);
}
if (dst_tiled) {
BEGIN_NV04(chan, NvSubCopy, 0x021c, 7);
OUT_RING (chan, 0);
OUT_RING (chan, 0);
OUT_RING (chan, stride);
OUT_RING (chan, height);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, 0);
} else {
BEGIN_NV04(chan, NvSubCopy, 0x021c, 1);
OUT_RING (chan, 1);
}
BEGIN_NV04(chan, NvSubCopy, 0x0238, 2);
OUT_RING (chan, upper_32_bits(src_offset));
OUT_RING (chan, upper_32_bits(dst_offset));
BEGIN_NV04(chan, NvSubCopy, 0x030c, 8);
OUT_RING (chan, lower_32_bits(src_offset));
OUT_RING (chan, lower_32_bits(dst_offset));
OUT_RING (chan, stride);
OUT_RING (chan, stride);
OUT_RING (chan, stride);
OUT_RING (chan, height);
OUT_RING (chan, 0x00000101);
OUT_RING (chan, 0x00000000);
BEGIN_NV04(chan, NvSubCopy, NV_MEMORY_TO_MEMORY_FORMAT_NOP, 1);
OUT_RING (chan, 0);
length -= amount;
src_offset += amount;
dst_offset += amount;
}
return 0;
}
static int
nv04_bo_move_init(struct nouveau_channel *chan, u32 handle)
{
int ret = RING_SPACE(chan, 4);
if (ret == 0) {
BEGIN_NV04(chan, NvSubCopy, 0x0000, 1);
OUT_RING (chan, handle);
BEGIN_NV04(chan, NvSubCopy, 0x0180, 1);
OUT_RING (chan, NvNotify0);
}
return ret;
}
static inline uint32_t
nouveau_bo_mem_ctxdma(struct ttm_buffer_object *bo,
struct nouveau_channel *chan, struct ttm_mem_reg *mem)
{
if (mem->mem_type == TTM_PL_TT)
return NvDmaTT;
return NvDmaFB;
}
static int
nv04_bo_move_m2mf(struct nouveau_channel *chan, struct ttm_buffer_object *bo,
struct ttm_mem_reg *old_mem, struct ttm_mem_reg *new_mem)
{
u32 src_offset = old_mem->start << PAGE_SHIFT;
u32 dst_offset = new_mem->start << PAGE_SHIFT;
u32 page_count = new_mem->num_pages;
int ret;
ret = RING_SPACE(chan, 3);
if (ret)
return ret;
BEGIN_NV04(chan, NvSubCopy, NV_MEMORY_TO_MEMORY_FORMAT_DMA_SOURCE, 2);
OUT_RING (chan, nouveau_bo_mem_ctxdma(bo, chan, old_mem));
OUT_RING (chan, nouveau_bo_mem_ctxdma(bo, chan, new_mem));
page_count = new_mem->num_pages;
while (page_count) {
int line_count = (page_count > 2047) ? 2047 : page_count;
ret = RING_SPACE(chan, 11);
if (ret)
return ret;
BEGIN_NV04(chan, NvSubCopy,
NV_MEMORY_TO_MEMORY_FORMAT_OFFSET_IN, 8);
OUT_RING (chan, src_offset);
OUT_RING (chan, dst_offset);
OUT_RING (chan, PAGE_SIZE); /* src_pitch */
OUT_RING (chan, PAGE_SIZE); /* dst_pitch */
OUT_RING (chan, PAGE_SIZE); /* line_length */
OUT_RING (chan, line_count);
OUT_RING (chan, 0x00000101);
OUT_RING (chan, 0x00000000);
BEGIN_NV04(chan, NvSubCopy, NV_MEMORY_TO_MEMORY_FORMAT_NOP, 1);
OUT_RING (chan, 0);
page_count -= line_count;
src_offset += (PAGE_SIZE * line_count);
dst_offset += (PAGE_SIZE * line_count);
}
return 0;
}
static int
nouveau_vma_getmap(struct nouveau_channel *chan, struct nouveau_bo *nvbo,
struct ttm_mem_reg *mem, struct nouveau_vma *vma)
{
struct nouveau_mem *node = mem->mm_node;
int ret;
ret = nouveau_vm_get(nv_client(chan->cli)->vm, mem->num_pages <<
PAGE_SHIFT, node->page_shift,
NV_MEM_ACCESS_RW, vma);
if (ret)
return ret;
if (mem->mem_type == TTM_PL_VRAM)
nouveau_vm_map(vma, node);
else
nouveau_vm_map_sg(vma, 0, mem->num_pages << PAGE_SHIFT, node);
return 0;
}
static int
nouveau_bo_move_m2mf(struct ttm_buffer_object *bo, int evict, bool intr,
bool no_wait_gpu, struct ttm_mem_reg *new_mem)
{
struct nouveau_drm *drm = nouveau_bdev(bo->bdev);
struct nouveau_channel *chan = drm->ttm.chan;
struct nouveau_bo *nvbo = nouveau_bo(bo);
struct ttm_mem_reg *old_mem = &bo->mem;
int ret;
mutex_lock_nested(&chan->cli->mutex, SINGLE_DEPTH_NESTING);
/* create temporary vmas for the transfer and attach them to the
* old nouveau_mem node, these will get cleaned up after ttm has
* destroyed the ttm_mem_reg
*/
if (nv_device(drm->device)->card_type >= NV_50) {
struct nouveau_mem *node = old_mem->mm_node;
ret = nouveau_vma_getmap(chan, nvbo, old_mem, &node->vma[0]);
if (ret)
goto out;
ret = nouveau_vma_getmap(chan, nvbo, new_mem, &node->vma[1]);
if (ret)
goto out;
}
ret = drm->ttm.move(chan, bo, &bo->mem, new_mem);
if (ret == 0) {
ret = nouveau_bo_move_accel_cleanup(chan, nvbo, evict,
no_wait_gpu, new_mem);
}
out:
mutex_unlock(&chan->cli->mutex);
return ret;
}
void
nouveau_bo_move_init(struct nouveau_drm *drm)
{
static const struct {
const char *name;
int engine;
u32 oclass;
int (*exec)(struct nouveau_channel *,
struct ttm_buffer_object *,
struct ttm_mem_reg *, struct ttm_mem_reg *);
int (*init)(struct nouveau_channel *, u32 handle);
} _methods[] = {
{ "COPY", 4, 0xa0b5, nve0_bo_move_copy, nve0_bo_move_init },
{ "GRCE", 0, 0xa0b5, nve0_bo_move_copy, nvc0_bo_move_init },
{ "COPY1", 5, 0x90b8, nvc0_bo_move_copy, nvc0_bo_move_init },
{ "COPY0", 4, 0x90b5, nvc0_bo_move_copy, nvc0_bo_move_init },
{ "COPY", 0, 0x85b5, nva3_bo_move_copy, nv50_bo_move_init },
{ "CRYPT", 0, 0x74c1, nv84_bo_move_exec, nv50_bo_move_init },
{ "M2MF", 0, 0x9039, nvc0_bo_move_m2mf, nvc0_bo_move_init },
{ "M2MF", 0, 0x5039, nv50_bo_move_m2mf, nv50_bo_move_init },
{ "M2MF", 0, 0x0039, nv04_bo_move_m2mf, nv04_bo_move_init },
{},
{ "CRYPT", 0, 0x88b4, nv98_bo_move_exec, nv50_bo_move_init },
}, *mthd = _methods;
const char *name = "CPU";
int ret;
do {
struct nouveau_object *object;
struct nouveau_channel *chan;
u32 handle = (mthd->engine << 16) | mthd->oclass;
if (mthd->engine)
chan = drm->cechan;
else
chan = drm->channel;
if (chan == NULL)
continue;
ret = nouveau_object_new(nv_object(drm), chan->handle, handle,
mthd->oclass, NULL, 0, &object);
if (ret == 0) {
ret = mthd->init(chan, handle);
if (ret) {
nouveau_object_del(nv_object(drm),
chan->handle, handle);
continue;
}
drm->ttm.move = mthd->exec;
drm->ttm.chan = chan;
name = mthd->name;
break;
}
} while ((++mthd)->exec);
NV_INFO(drm, "MM: using %s for buffer copies\n", name);
}
static int
nouveau_bo_move_flipd(struct ttm_buffer_object *bo, bool evict, bool intr,
bool no_wait_gpu, struct ttm_mem_reg *new_mem)
{
u32 placement_memtype = TTM_PL_FLAG_TT | TTM_PL_MASK_CACHING;
struct ttm_placement placement;
struct ttm_mem_reg tmp_mem;
int ret;
placement.fpfn = placement.lpfn = 0;
placement.num_placement = placement.num_busy_placement = 1;
placement.placement = placement.busy_placement = &placement_memtype;
tmp_mem = *new_mem;
tmp_mem.mm_node = NULL;
ret = ttm_bo_mem_space(bo, &placement, &tmp_mem, intr, no_wait_gpu);
if (ret)
return ret;
ret = ttm_tt_bind(bo->ttm, &tmp_mem);
if (ret)
goto out;
ret = nouveau_bo_move_m2mf(bo, true, intr, no_wait_gpu, &tmp_mem);
if (ret)
goto out;
ret = ttm_bo_move_ttm(bo, true, no_wait_gpu, new_mem);
out:
ttm_bo_mem_put(bo, &tmp_mem);
return ret;
}
static int
nouveau_bo_move_flips(struct ttm_buffer_object *bo, bool evict, bool intr,
bool no_wait_gpu, struct ttm_mem_reg *new_mem)
{
u32 placement_memtype = TTM_PL_FLAG_TT | TTM_PL_MASK_CACHING;
struct ttm_placement placement;
struct ttm_mem_reg tmp_mem;
int ret;
placement.fpfn = placement.lpfn = 0;
placement.num_placement = placement.num_busy_placement = 1;
placement.placement = placement.busy_placement = &placement_memtype;
tmp_mem = *new_mem;
tmp_mem.mm_node = NULL;
ret = ttm_bo_mem_space(bo, &placement, &tmp_mem, intr, no_wait_gpu);
if (ret)
return ret;
ret = ttm_bo_move_ttm(bo, true, no_wait_gpu, &tmp_mem);
if (ret)
goto out;
ret = nouveau_bo_move_m2mf(bo, true, intr, no_wait_gpu, new_mem);
if (ret)
goto out;
out:
ttm_bo_mem_put(bo, &tmp_mem);
return ret;
}
static void
nouveau_bo_move_ntfy(struct ttm_buffer_object *bo, struct ttm_mem_reg *new_mem)
{
struct nouveau_bo *nvbo = nouveau_bo(bo);
struct nouveau_vma *vma;
/* ttm can now (stupidly) pass the driver bos it didn't create... */
if (bo->destroy != nouveau_bo_del_ttm)
return;
list_for_each_entry(vma, &nvbo->vma_list, head) {
if (new_mem && new_mem->mem_type == TTM_PL_VRAM) {
nouveau_vm_map(vma, new_mem->mm_node);
} else
if (new_mem && new_mem->mem_type == TTM_PL_TT &&
nvbo->page_shift == vma->vm->vmm->spg_shift) {
if (((struct nouveau_mem *)new_mem->mm_node)->sg)
nouveau_vm_map_sg_table(vma, 0, new_mem->
num_pages << PAGE_SHIFT,
new_mem->mm_node);
else
nouveau_vm_map_sg(vma, 0, new_mem->
num_pages << PAGE_SHIFT,
new_mem->mm_node);
} else {
nouveau_vm_unmap(vma);
}
}
}
static int
nouveau_bo_vm_bind(struct ttm_buffer_object *bo, struct ttm_mem_reg *new_mem,
struct nouveau_drm_tile **new_tile)
{
struct nouveau_drm *drm = nouveau_bdev(bo->bdev);
struct drm_device *dev = drm->dev;
struct nouveau_bo *nvbo = nouveau_bo(bo);
u64 offset = new_mem->start << PAGE_SHIFT;
*new_tile = NULL;
if (new_mem->mem_type != TTM_PL_VRAM)
return 0;
if (nv_device(drm->device)->card_type >= NV_10) {
*new_tile = nv10_bo_set_tiling(dev, offset, new_mem->size,
nvbo->tile_mode,
nvbo->tile_flags);
}
return 0;
}
static void
nouveau_bo_vm_cleanup(struct ttm_buffer_object *bo,
struct nouveau_drm_tile *new_tile,
struct nouveau_drm_tile **old_tile)
{
struct nouveau_drm *drm = nouveau_bdev(bo->bdev);
struct drm_device *dev = drm->dev;
nv10_bo_put_tile_region(dev, *old_tile, bo->sync_obj);
*old_tile = new_tile;
}
static int
nouveau_bo_move(struct ttm_buffer_object *bo, bool evict, bool intr,
bool no_wait_gpu, struct ttm_mem_reg *new_mem)
{
struct nouveau_drm *drm = nouveau_bdev(bo->bdev);
struct nouveau_bo *nvbo = nouveau_bo(bo);
struct ttm_mem_reg *old_mem = &bo->mem;
struct nouveau_drm_tile *new_tile = NULL;
int ret = 0;
if (nv_device(drm->device)->card_type < NV_50) {
ret = nouveau_bo_vm_bind(bo, new_mem, &new_tile);
if (ret)
return ret;
}
/* Fake bo copy. */
if (old_mem->mem_type == TTM_PL_SYSTEM && !bo->ttm) {
BUG_ON(bo->mem.mm_node != NULL);
bo->mem = *new_mem;
new_mem->mm_node = NULL;
goto out;
}
/* CPU copy if we have no accelerated method available */
if (!drm->ttm.move) {
ret = ttm_bo_move_memcpy(bo, evict, no_wait_gpu, new_mem);
goto out;
}
/* Hardware assisted copy. */
if (new_mem->mem_type == TTM_PL_SYSTEM)
ret = nouveau_bo_move_flipd(bo, evict, intr,
no_wait_gpu, new_mem);
else if (old_mem->mem_type == TTM_PL_SYSTEM)
ret = nouveau_bo_move_flips(bo, evict, intr,
no_wait_gpu, new_mem);
else
ret = nouveau_bo_move_m2mf(bo, evict, intr,
no_wait_gpu, new_mem);
if (!ret)
goto out;
/* Fallback to software copy. */
ret = ttm_bo_move_memcpy(bo, evict, no_wait_gpu, new_mem);
out:
if (nv_device(drm->device)->card_type < NV_50) {
if (ret)
nouveau_bo_vm_cleanup(bo, NULL, &new_tile);
else
nouveau_bo_vm_cleanup(bo, new_tile, &nvbo->tile);
}
return ret;
}
static int
nouveau_bo_verify_access(struct ttm_buffer_object *bo, struct file *filp)
{
struct nouveau_bo *nvbo = nouveau_bo(bo);
return drm_vma_node_verify_access(&nvbo->gem.vma_node, filp);
}
static int
nouveau_ttm_io_mem_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
{
struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
struct nouveau_drm *drm = nouveau_bdev(bdev);
struct drm_device *dev = drm->dev;
int ret;
mem->bus.addr = NULL;
mem->bus.offset = 0;
mem->bus.size = mem->num_pages << PAGE_SHIFT;
mem->bus.base = 0;
mem->bus.is_iomem = false;
if (!(man->flags & TTM_MEMTYPE_FLAG_MAPPABLE))
return -EINVAL;
switch (mem->mem_type) {
case TTM_PL_SYSTEM:
/* System memory */
return 0;
case TTM_PL_TT:
#if __OS_HAS_AGP
if (drm->agp.stat == ENABLED) {
mem->bus.offset = mem->start << PAGE_SHIFT;
mem->bus.base = drm->agp.base;
mem->bus.is_iomem = !dev->agp->cant_use_aperture;
}
#endif
break;
case TTM_PL_VRAM:
mem->bus.offset = mem->start << PAGE_SHIFT;
mem->bus.base = pci_resource_start(dev->pdev, 1);
mem->bus.is_iomem = true;
if (nv_device(drm->device)->card_type >= NV_50) {
struct nouveau_bar *bar = nouveau_bar(drm->device);
struct nouveau_mem *node = mem->mm_node;
ret = bar->umap(bar, node, NV_MEM_ACCESS_RW,
&node->bar_vma);
if (ret)
return ret;
mem->bus.offset = node->bar_vma.offset;
}
break;
default:
return -EINVAL;
}
return 0;
}
static void
nouveau_ttm_io_mem_free(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
{
struct nouveau_drm *drm = nouveau_bdev(bdev);
struct nouveau_bar *bar = nouveau_bar(drm->device);
struct nouveau_mem *node = mem->mm_node;
if (!node->bar_vma.node)
return;
bar->unmap(bar, &node->bar_vma);
}
static int
nouveau_ttm_fault_reserve_notify(struct ttm_buffer_object *bo)
{
struct nouveau_drm *drm = nouveau_bdev(bo->bdev);
struct nouveau_bo *nvbo = nouveau_bo(bo);
struct nouveau_device *device = nv_device(drm->device);
u32 mappable = pci_resource_len(device->pdev, 1) >> PAGE_SHIFT;
/* as long as the bo isn't in vram, and isn't tiled, we've got
* nothing to do here.
*/
if (bo->mem.mem_type != TTM_PL_VRAM) {
if (nv_device(drm->device)->card_type < NV_50 ||
!nouveau_bo_tile_layout(nvbo))
return 0;
}
/* make sure bo is in mappable vram */
if (bo->mem.start + bo->mem.num_pages < mappable)
return 0;
nvbo->placement.fpfn = 0;
nvbo->placement.lpfn = mappable;
nouveau_bo_placement_set(nvbo, TTM_PL_FLAG_VRAM, 0);
return nouveau_bo_validate(nvbo, false, false);
}
static int
nouveau_ttm_tt_populate(struct ttm_tt *ttm)
{
struct ttm_dma_tt *ttm_dma = (void *)ttm;
struct nouveau_drm *drm;
struct drm_device *dev;
unsigned i;
int r;
bool slave = !!(ttm->page_flags & TTM_PAGE_FLAG_SG);
if (ttm->state != tt_unpopulated)
return 0;
if (slave && ttm->sg) {
/* make userspace faulting work */
drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
ttm_dma->dma_address, ttm->num_pages);
ttm->state = tt_unbound;
return 0;
}
drm = nouveau_bdev(ttm->bdev);
dev = drm->dev;
#if __OS_HAS_AGP
if (drm->agp.stat == ENABLED) {
return ttm_agp_tt_populate(ttm);
}
#endif
#ifdef CONFIG_SWIOTLB
if (swiotlb_nr_tbl()) {
return ttm_dma_populate((void *)ttm, dev->dev);
}
#endif
r = ttm_pool_populate(ttm);
if (r) {
return r;
}
for (i = 0; i < ttm->num_pages; i++) {
ttm_dma->dma_address[i] = pci_map_page(dev->pdev, ttm->pages[i],
0, PAGE_SIZE,
PCI_DMA_BIDIRECTIONAL);
if (pci_dma_mapping_error(dev->pdev, ttm_dma->dma_address[i])) {
while (--i) {
pci_unmap_page(dev->pdev, ttm_dma->dma_address[i],
PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
ttm_dma->dma_address[i] = 0;
}
ttm_pool_unpopulate(ttm);
return -EFAULT;
}
}
return 0;
}
static void
nouveau_ttm_tt_unpopulate(struct ttm_tt *ttm)
{
struct ttm_dma_tt *ttm_dma = (void *)ttm;
struct nouveau_drm *drm;
struct drm_device *dev;
unsigned i;
bool slave = !!(ttm->page_flags & TTM_PAGE_FLAG_SG);
if (slave)
return;
drm = nouveau_bdev(ttm->bdev);
dev = drm->dev;
#if __OS_HAS_AGP
if (drm->agp.stat == ENABLED) {
ttm_agp_tt_unpopulate(ttm);
return;
}
#endif
#ifdef CONFIG_SWIOTLB
if (swiotlb_nr_tbl()) {
ttm_dma_unpopulate((void *)ttm, dev->dev);
return;
}
#endif
for (i = 0; i < ttm->num_pages; i++) {
if (ttm_dma->dma_address[i]) {
pci_unmap_page(dev->pdev, ttm_dma->dma_address[i],
PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
}
}
ttm_pool_unpopulate(ttm);
}
void
nouveau_bo_fence(struct nouveau_bo *nvbo, struct nouveau_fence *fence)
{
struct nouveau_fence *new_fence = nouveau_fence_ref(fence);
struct nouveau_fence *old_fence = NULL;
spin_lock(&nvbo->bo.bdev->fence_lock);
old_fence = nvbo->bo.sync_obj;
nvbo->bo.sync_obj = new_fence;
spin_unlock(&nvbo->bo.bdev->fence_lock);
nouveau_fence_unref(&old_fence);
}
static void
nouveau_bo_fence_unref(void **sync_obj)
{
nouveau_fence_unref((struct nouveau_fence **)sync_obj);
}
static void *
nouveau_bo_fence_ref(void *sync_obj)
{
return nouveau_fence_ref(sync_obj);
}
static bool
nouveau_bo_fence_signalled(void *sync_obj)
{
return nouveau_fence_done(sync_obj);
}
static int
nouveau_bo_fence_wait(void *sync_obj, bool lazy, bool intr)
{
return nouveau_fence_wait(sync_obj, lazy, intr);
}
static int
nouveau_bo_fence_flush(void *sync_obj)
{
return 0;
}
struct ttm_bo_driver nouveau_bo_driver = {
.ttm_tt_create = &nouveau_ttm_tt_create,
.ttm_tt_populate = &nouveau_ttm_tt_populate,
.ttm_tt_unpopulate = &nouveau_ttm_tt_unpopulate,
.invalidate_caches = nouveau_bo_invalidate_caches,
.init_mem_type = nouveau_bo_init_mem_type,
.evict_flags = nouveau_bo_evict_flags,
.move_notify = nouveau_bo_move_ntfy,
.move = nouveau_bo_move,
.verify_access = nouveau_bo_verify_access,
.sync_obj_signaled = nouveau_bo_fence_signalled,
.sync_obj_wait = nouveau_bo_fence_wait,
.sync_obj_flush = nouveau_bo_fence_flush,
.sync_obj_unref = nouveau_bo_fence_unref,
.sync_obj_ref = nouveau_bo_fence_ref,
.fault_reserve_notify = &nouveau_ttm_fault_reserve_notify,
.io_mem_reserve = &nouveau_ttm_io_mem_reserve,
.io_mem_free = &nouveau_ttm_io_mem_free,
};
struct nouveau_vma *
nouveau_bo_vma_find(struct nouveau_bo *nvbo, struct nouveau_vm *vm)
{
struct nouveau_vma *vma;
list_for_each_entry(vma, &nvbo->vma_list, head) {
if (vma->vm == vm)
return vma;
}
return NULL;
}
int
nouveau_bo_vma_add(struct nouveau_bo *nvbo, struct nouveau_vm *vm,
struct nouveau_vma *vma)
{
const u32 size = nvbo->bo.mem.num_pages << PAGE_SHIFT;
struct nouveau_mem *node = nvbo->bo.mem.mm_node;
int ret;
ret = nouveau_vm_get(vm, size, nvbo->page_shift,
NV_MEM_ACCESS_RW, vma);
if (ret)
return ret;
if (nvbo->bo.mem.mem_type == TTM_PL_VRAM)
nouveau_vm_map(vma, nvbo->bo.mem.mm_node);
else if (nvbo->bo.mem.mem_type == TTM_PL_TT &&
nvbo->page_shift == vma->vm->vmm->spg_shift) {
if (node->sg)
nouveau_vm_map_sg_table(vma, 0, size, node);
else
nouveau_vm_map_sg(vma, 0, size, node);
}
list_add_tail(&vma->head, &nvbo->vma_list);
vma->refcount = 1;
return 0;
}
void
nouveau_bo_vma_del(struct nouveau_bo *nvbo, struct nouveau_vma *vma)
{
if (vma->node) {
if (nvbo->bo.mem.mem_type != TTM_PL_SYSTEM)
nouveau_vm_unmap(vma);
nouveau_vm_put(vma);
list_del(&vma->head);
}
}
| gpl-2.0 |
angpysha/KitKatExtendedKernel | arch/arm/mach-msm/qdsp6v2/msm_audio_ion.c | 32 | 15275 | /*
* Copyright (c) 2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <mach/subsystem_restart.h>
#include <mach/qdsp6v2/apr.h>
#include <linux/of_device.h>
#include <linux/msm_audio_ion.h>
#include <linux/iommu.h>
#include <mach/iommu_domains.h>
struct msm_audio_ion_private {
bool smmu_enabled;
bool audioheap_enabled;
struct iommu_group *group;
u32 domain_id;
struct iommu_domain *domain;
};
static struct msm_audio_ion_private msm_audio_ion_data = {0,};
static int msm_audio_ion_get_phys(struct ion_client *client,
struct ion_handle *handle,
ion_phys_addr_t *addr, size_t *len);
int msm_audio_ion_alloc(const char *name, struct ion_client **client,
struct ion_handle **handle, size_t bufsz,
ion_phys_addr_t *paddr, size_t *pa_len, void **vaddr)
{
int rc = 0;
if ((msm_audio_ion_data.smmu_enabled == true) &&
(msm_audio_ion_data.group == NULL)) {
pr_debug("%s:probe is not done, deferred\n", __func__);
return -EPROBE_DEFER;
}
if (!name || !client || !handle || !paddr || !vaddr
|| !bufsz || !pa_len) {
pr_err("%s: Invalid params\n", __func__);
return -EINVAL;
}
*client = msm_audio_ion_client_create(UINT_MAX, name);
if (IS_ERR_OR_NULL((void *)(*client))) {
pr_err("%s: ION create client for AUDIO failed\n", __func__);
goto err;
}
*handle = ion_alloc(*client, bufsz, SZ_4K,
ION_HEAP(ION_AUDIO_HEAP_ID), 0);
if (IS_ERR_OR_NULL((void *) (*handle))) {
pr_debug("system heap is used");
msm_audio_ion_data.audioheap_enabled = 0;
*handle = ion_alloc(*client, bufsz, SZ_4K,
ION_HEAP(ION_SYSTEM_HEAP_ID), 0);
} else {
pr_debug("audio heap is used");
msm_audio_ion_data.audioheap_enabled = 1;
}
if (IS_ERR_OR_NULL((void *) (*handle))) {
pr_err("%s: ION memory allocation for AUDIO failed rc=%d, smmu_enabled=%d\n",
__func__, rc, msm_audio_ion_data.smmu_enabled);
goto err_ion_client;
}
rc = msm_audio_ion_get_phys(*client, *handle, paddr, pa_len);
if (rc) {
pr_err("%s: ION Get Physical for AUDIO failed, rc = %d\n",
__func__, rc);
goto err_ion_handle;
}
*vaddr = ion_map_kernel(*client, *handle);
if (IS_ERR_OR_NULL((void *)*vaddr)) {
pr_err("%s: ION memory mapping for AUDIO failed\n", __func__);
goto err_ion_handle;
}
pr_debug("%s: mapped address = %p, size=%d\n", __func__, *vaddr, bufsz);
if (bufsz != 0) {
pr_debug("%s: memset to 0 %p %d\n", __func__, *vaddr, bufsz);
memset((void *)*vaddr, 0, bufsz);
}
return 0;
err_ion_handle:
ion_free(*client, *handle);
err_ion_client:
msm_audio_ion_client_destroy(*client);
*handle = NULL;
*client = NULL;
err:
return -EINVAL;
}
int msm_audio_ion_import(const char *name, struct ion_client **client,
struct ion_handle **handle, int fd,
unsigned long *ionflag, size_t bufsz,
ion_phys_addr_t *paddr, size_t *pa_len, void **vaddr)
{
int rc = 0;
if (!name || !client || !handle || !paddr || !vaddr || !pa_len) {
pr_err("%s: Invalid params\n", __func__);
rc = -EINVAL;
goto err;
}
*client = msm_audio_ion_client_create(UINT_MAX, name);
if (IS_ERR_OR_NULL((void *)(*client))) {
pr_err("%s: ION create client for AUDIO failed\n", __func__);
rc = -EINVAL;
goto err;
}
/* name should be audio_acdb_client or Audio_Dec_Client,
bufsz should be 0 and fd shouldn't be 0 as of now
*/
*handle = ion_import_dma_buf(*client, fd);
pr_err("%s: DMA Buf name=%s, fd=%d handle=%p\n", __func__,
name, fd, *handle);
if (IS_ERR_OR_NULL((void *) (*handle))) {
pr_err("%s: ion import dma buffer failed\n",
__func__);
rc = -EINVAL;
goto err_destroy_client;
}
if (ionflag != NULL) {
rc = ion_handle_get_flags(*client, *handle, ionflag);
if (rc) {
pr_err("%s: could not get flags for the handle\n",
__func__);
goto err_ion_handle;
}
}
rc = msm_audio_ion_get_phys(*client, *handle, paddr, pa_len);
if (rc) {
pr_err("%s: ION Get Physical for AUDIO failed, rc = %d\n",
__func__, rc);
goto err_ion_handle;
}
*vaddr = ion_map_kernel(*client, *handle);
if (IS_ERR_OR_NULL((void *)*vaddr)) {
pr_err("%s: ION memory mapping for AUDIO failed\n", __func__);
rc = -ENOMEM;
goto err_ion_handle;
}
pr_debug("%s: mapped address = %p, size=%d\n", __func__, *vaddr, bufsz);
return 0;
err_ion_handle:
ion_free(*client, *handle);
err_destroy_client:
msm_audio_ion_client_destroy(*client);
*client = NULL;
*handle = NULL;
err:
return rc;
}
int msm_audio_ion_free(struct ion_client *client, struct ion_handle *handle)
{
if (!client || !handle) {
pr_err("%s Invalid params\n", __func__);
return -EINVAL;
}
if (msm_audio_ion_data.smmu_enabled) {
/* Need to populate book kept infomation */
pr_debug("client=%p, domain=%p, domain_id=%d, group=%p",
client, msm_audio_ion_data.domain,
msm_audio_ion_data.domain_id, msm_audio_ion_data.group);
ion_unmap_iommu(client, handle,
msm_audio_ion_data.domain_id, 0);
}
ion_unmap_kernel(client, handle);
ion_free(client, handle);
msm_audio_ion_client_destroy(client);
return 0;
}
int msm_audio_ion_mmap(struct audio_buffer *ab,
struct vm_area_struct *vma)
{
struct sg_table *table;
unsigned long addr = vma->vm_start;
unsigned long offset = vma->vm_pgoff * PAGE_SIZE;
struct scatterlist *sg;
unsigned int i;
struct page *page;
int ret;
pr_debug("%s\n", __func__);
table = ion_sg_table(ab->client, ab->handle);
if (IS_ERR(table)) {
pr_err("%s: Unable to get sg_table from ion: %ld\n",
__func__, PTR_ERR(table));
return PTR_ERR(table);
} else if (!table) {
pr_err("%s: sg_list is NULL\n", __func__);
return -EINVAL;
}
/* uncached */
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
/* We need to check if a page is associated with this sg list because:
* If the allocation came from a carveout we currently don't have
* pages associated with carved out memory. This might change in the
* future and we can remove this check and the else statement.
*/
page = sg_page(table->sgl);
if (page) {
pr_debug("%s: page is NOT null\n", __func__);
for_each_sg(table->sgl, sg, table->nents, i) {
unsigned long remainder = vma->vm_end - addr;
unsigned long len = sg_dma_len(sg);
page = sg_page(sg);
if (offset >= sg_dma_len(sg)) {
offset -= sg_dma_len(sg);
continue;
} else if (offset) {
page += offset / PAGE_SIZE;
len = sg_dma_len(sg) - offset;
offset = 0;
}
len = min(len, remainder);
pr_debug("vma=%p, addr=%x len=%ld vm_start=%x vm_end=%x vm_page_prot=%ld\n",
vma, (unsigned int)addr, len,
(unsigned int)vma->vm_start,
(unsigned int)vma->vm_end,
(unsigned long int)vma->vm_page_prot);
remap_pfn_range(vma, addr, page_to_pfn(page), len,
vma->vm_page_prot);
addr += len;
if (addr >= vma->vm_end)
return 0;
}
} else {
ion_phys_addr_t phys_addr;
size_t phys_len;
size_t va_len = 0;
pr_debug("%s: page is NULL\n", __func__);
ret = ion_phys(ab->client, ab->handle, &phys_addr, &phys_len);
if (ret) {
pr_err("%s: Unable to get phys address from ION buffer: %d\n"
, __func__ , ret);
return ret;
}
pr_debug("phys=%x len=%d\n", (unsigned int)phys_addr, phys_len);
pr_debug("vma=%p, vm_start=%x vm_end=%x vm_pgoff=%ld vm_page_prot=%ld\n",
vma, (unsigned int)vma->vm_start,
(unsigned int)vma->vm_end, vma->vm_pgoff,
(unsigned long int)vma->vm_page_prot);
va_len = vma->vm_end - vma->vm_start;
if ((offset > phys_len) || (va_len > phys_len-offset)) {
pr_err("wrong offset size %ld, lens= %d, va_len=%d\n",
offset, phys_len, va_len);
return -EINVAL;
}
ret = remap_pfn_range(vma, vma->vm_start,
__phys_to_pfn(phys_addr) + vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
return 0;
}
bool msm_audio_ion_is_smmu_available(void)
{
return msm_audio_ion_data.smmu_enabled;
}
/* move to static section again */
struct ion_client *msm_audio_ion_client_create(unsigned int heap_mask,
const char *name)
{
struct ion_client *pclient = NULL;
/*IOMMU group and domain are moved to probe()*/
pclient = msm_ion_client_create(heap_mask, name);
return pclient;
}
void msm_audio_ion_client_destroy(struct ion_client *client)
{
pr_debug("%s: client = %p smmu_enabled = %d\n", __func__,
client, msm_audio_ion_data.smmu_enabled);
ion_client_destroy(client);
}
int msm_audio_ion_import_legacy(const char *name, struct ion_client *client,
struct ion_handle **handle, int fd,
unsigned long *ionflag, size_t bufsz,
ion_phys_addr_t *paddr, size_t *pa_len, void **vaddr)
{
int rc = 0;
if (!name || !client || !handle || !paddr || !vaddr || !pa_len) {
pr_err("%s: Invalid params\n", __func__);
rc = -EINVAL;
goto err;
}
/* client is already created for legacy and given*/
/* name should be audio_acdb_client or Audio_Dec_Client,
bufsz should be 0 and fd shouldn't be 0 as of now
*/
*handle = ion_import_dma_buf(client, fd);
pr_debug("%s: DMA Buf name=%s, fd=%d handle=%p\n", __func__,
name, fd, *handle);
if (IS_ERR_OR_NULL((void *)(*handle))) {
pr_err("%s: ion import dma buffer failed\n",
__func__);
rc = -EINVAL;
goto err_destroy_client;
}
if (ionflag != NULL) {
rc = ion_handle_get_flags(client, *handle, ionflag);
if (rc) {
pr_err("%s: could not get flags for the handle\n",
__func__);
rc = -EINVAL;
goto err_ion_handle;
}
}
rc = msm_audio_ion_get_phys(client, *handle, paddr, pa_len);
if (rc) {
pr_err("%s: ION Get Physical for AUDIO failed, rc = %d\n",
__func__, rc);
rc = -EINVAL;
goto err_ion_handle;
}
/*Need to add condition SMMU enable or not */
*vaddr = ion_map_kernel(client, *handle);
if (IS_ERR_OR_NULL((void *)*vaddr)) {
pr_err("%s: ION memory mapping for AUDIO failed\n", __func__);
rc = -EINVAL;
goto err_ion_handle;
}
if (bufsz != 0)
memset((void *)*vaddr, 0, bufsz);
return 0;
err_ion_handle:
ion_free(client, *handle);
err_destroy_client:
msm_audio_ion_client_destroy(client);
client = NULL;
*handle = NULL;
err:
return rc;
}
int msm_audio_ion_free_legacy(struct ion_client *client,
struct ion_handle *handle)
{
if (msm_audio_ion_data.smmu_enabled)
ion_unmap_iommu(client, handle,
msm_audio_ion_data.domain_id, 0);
/* To add condition for SMMU enabled */
ion_unmap_kernel(client, handle);
ion_free(client, handle);
/* no client_destrody in legacy*/
return 0;
}
int msm_audio_ion_cache_operations(struct audio_buffer *abuff, int cache_op)
{
unsigned long ionflag = 0;
int rc = 0;
int msm_cache_ops = 0;
if (!abuff) {
pr_err("Invalid params: %p, %p\n", __func__, abuff);
return -EINVAL;
}
rc = ion_handle_get_flags(abuff->client, abuff->handle,
&ionflag);
if (rc) {
pr_err("ion_handle_get_flags failed: %d\n", rc);
goto cache_op_failed;
}
/* has to be CACHED */
if (ION_IS_CACHED(ionflag)) {
/* ION_IOC_INV_CACHES or ION_IOC_CLEAN_CACHES */
msm_cache_ops = cache_op;
rc = msm_ion_do_cache_op(abuff->client,
abuff->handle,
(unsigned long *) abuff->data,
(unsigned long)abuff->size,
msm_cache_ops);
if (rc) {
pr_err("cache operation failed %d\n", rc);
goto cache_op_failed;
}
}
cache_op_failed:
return rc;
}
static int msm_audio_ion_get_phys(struct ion_client *client,
struct ion_handle *handle,
ion_phys_addr_t *addr, size_t *len)
{
int rc = 0;
pr_debug("%s: smmu_enabled = %d\n", __func__,
msm_audio_ion_data.smmu_enabled);
if (msm_audio_ion_data.smmu_enabled) {
rc = ion_map_iommu(client, handle, msm_audio_ion_data.domain_id,
0 /*partition_num*/, SZ_4K /*align*/, 0/*iova_length*/,
addr, (unsigned long *)len,
0, 0);
if (rc) {
pr_err("%s: ION map iommu failed %d\n", __func__, rc);
return rc;
}
pr_debug("client=%p, domain=%p, domain_id=%d, group=%p",
client, msm_audio_ion_data.domain,
msm_audio_ion_data.domain_id, msm_audio_ion_data.group);
} else {
/* SMMU is disabled*/
rc = ion_phys(client, handle, addr, len);
}
pr_debug("phys=%x, len=%d, rc=%d\n", (unsigned int)*addr, *len, rc);
return rc;
}
static int msm_audio_ion_probe(struct platform_device *pdev)
{
int rc = 0;
const char *msm_audio_ion_dt = "qcom,smmu-enabled";
bool smmu_enabled;
if (pdev->dev.of_node == NULL) {
pr_err("%s: device tree is not found\n", __func__);
msm_audio_ion_data.smmu_enabled = 0;
return 0;
}
smmu_enabled = of_property_read_bool(pdev->dev.of_node,
msm_audio_ion_dt);
msm_audio_ion_data.smmu_enabled = smmu_enabled;
if (smmu_enabled) {
msm_audio_ion_data.group = iommu_group_find("lpass_audio");
if (!msm_audio_ion_data.group) {
pr_debug("Failed to find group lpass_audio deferred\n");
goto fail_group;
}
msm_audio_ion_data.domain =
iommu_group_get_iommudata(msm_audio_ion_data.group);
if (IS_ERR_OR_NULL(msm_audio_ion_data.domain)) {
pr_err("Failed to get domain data for group %p",
msm_audio_ion_data.group);
goto fail_group;
}
msm_audio_ion_data.domain_id =
msm_find_domain_no(msm_audio_ion_data.domain);
if (msm_audio_ion_data.domain_id < 0) {
pr_err("Failed to get domain index for domain %p",
msm_audio_ion_data.domain);
goto fail_group;
}
pr_debug("domain=%p, domain_id=%d, group=%p",
msm_audio_ion_data.domain,
msm_audio_ion_data.domain_id, msm_audio_ion_data.group);
/* iommu_attach_group() will make AXI clock ON. For future PL
this will require to be called in once per session */
rc = iommu_attach_group(msm_audio_ion_data.domain,
msm_audio_ion_data.group);
if (rc) {
pr_err("%s:ION attach group failed %d\n", __func__, rc);
return rc;
}
}
pr_debug("%s: SMMU-Enabled = %d\n", __func__, smmu_enabled);
return rc;
fail_group:
return -EPROBE_DEFER;
}
static int msm_audio_ion_remove(struct platform_device *pdev)
{
pr_debug("%s: msm audio ion is unloaded, domain=%p, group=%p\n",
__func__, msm_audio_ion_data.domain, msm_audio_ion_data.group);
iommu_detach_group(msm_audio_ion_data.domain, msm_audio_ion_data.group);
return 0;
}
static const struct of_device_id msm_audio_ion_dt_match[] = {
{ .compatible = "qcom,msm-audio-ion" },
{ }
};
MODULE_DEVICE_TABLE(of, msm_audio_ion_dt_match);
static struct platform_driver msm_audio_ion_driver = {
.driver = {
.name = "msm-audio-ion",
.owner = THIS_MODULE,
.of_match_table = msm_audio_ion_dt_match,
},
.probe = msm_audio_ion_probe,
.remove = __devexit_p(msm_audio_ion_remove),
};
static int __init msm_audio_ion_init(void)
{
return platform_driver_register(&msm_audio_ion_driver);
}
module_init(msm_audio_ion_init);
static void __exit msm_audio_ion_exit(void)
{
platform_driver_unregister(&msm_audio_ion_driver);
}
module_exit(msm_audio_ion_exit);
MODULE_DESCRIPTION("MSM Audio ION module");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Validus-Kernel/kernel_oneplus2 | fs/f2fs/namei.c | 32 | 13934 | /*
* fs/f2fs/namei.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include <linux/pagemap.h>
#include <linux/sched.h>
#include <linux/ctype.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include "f2fs.h"
#include "node.h"
#include "xattr.h"
#include "acl.h"
#include <trace/events/f2fs.h>
static struct inode *f2fs_new_inode(struct inode *dir, umode_t mode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
nid_t ino;
struct inode *inode;
bool nid_free = false;
int err;
inode = new_inode(dir->i_sb);
if (!inode)
return ERR_PTR(-ENOMEM);
f2fs_lock_op(sbi);
if (!alloc_nid(sbi, &ino)) {
f2fs_unlock_op(sbi);
err = -ENOSPC;
goto fail;
}
f2fs_unlock_op(sbi);
inode_init_owner(inode, dir, mode);
inode->i_ino = ino;
inode->i_blocks = 0;
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
inode->i_generation = sbi->s_next_generation++;
err = insert_inode_locked(inode);
if (err) {
err = -EINVAL;
nid_free = true;
goto out;
}
if (f2fs_may_inline(inode))
set_inode_flag(F2FS_I(inode), FI_INLINE_DATA);
if (test_opt(sbi, INLINE_DENTRY) && S_ISDIR(inode->i_mode))
set_inode_flag(F2FS_I(inode), FI_INLINE_DENTRY);
trace_f2fs_new_inode(inode, 0);
mark_inode_dirty(inode);
return inode;
out:
clear_nlink(inode);
unlock_new_inode(inode);
fail:
trace_f2fs_new_inode(inode, err);
make_bad_inode(inode);
iput(inode);
if (nid_free)
alloc_nid_failed(sbi, ino);
return ERR_PTR(err);
}
static int is_multimedia_file(const unsigned char *s, const char *sub)
{
size_t slen = strlen(s);
size_t sublen = strlen(sub);
if (sublen > slen)
return 0;
return !strncasecmp(s + slen - sublen, sub, sublen);
}
/*
* Set multimedia files as cold files for hot/cold data separation
*/
static inline void set_cold_files(struct f2fs_sb_info *sbi, struct inode *inode,
const unsigned char *name)
{
int i;
__u8 (*extlist)[8] = sbi->raw_super->extension_list;
int count = le32_to_cpu(sbi->raw_super->extension_count);
for (i = 0; i < count; i++) {
if (is_multimedia_file(name, extlist[i])) {
file_set_cold(inode);
break;
}
}
}
static int f2fs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
bool excl)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
struct inode *inode;
nid_t ino = 0;
int err;
f2fs_balance_fs(sbi);
inode = f2fs_new_inode(dir, mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
if (!test_opt(sbi, DISABLE_EXT_IDENTIFY))
set_cold_files(sbi, inode, dentry->d_name.name);
inode->i_op = &f2fs_file_inode_operations;
inode->i_fop = &f2fs_file_operations;
inode->i_mapping->a_ops = &f2fs_dblock_aops;
ino = inode->i_ino;
f2fs_lock_op(sbi);
err = f2fs_add_link(dentry, inode);
if (err)
goto out;
f2fs_unlock_op(sbi);
alloc_nid_done(sbi, ino);
stat_inc_inline_inode(inode);
d_instantiate(dentry, inode);
unlock_new_inode(inode);
if (IS_DIRSYNC(dir))
f2fs_sync_fs(sbi->sb, 1);
return 0;
out:
handle_failed_inode(inode);
return err;
}
static int f2fs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
struct inode *inode = old_dentry->d_inode;
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
int err;
f2fs_balance_fs(sbi);
inode->i_ctime = CURRENT_TIME;
ihold(inode);
set_inode_flag(F2FS_I(inode), FI_INC_LINK);
f2fs_lock_op(sbi);
err = f2fs_add_link(dentry, inode);
if (err)
goto out;
f2fs_unlock_op(sbi);
d_instantiate(dentry, inode);
if (IS_DIRSYNC(dir))
f2fs_sync_fs(sbi->sb, 1);
return 0;
out:
clear_inode_flag(F2FS_I(inode), FI_INC_LINK);
iput(inode);
f2fs_unlock_op(sbi);
return err;
}
struct dentry *f2fs_get_parent(struct dentry *child)
{
struct qstr dotdot = QSTR_INIT("..", 2);
unsigned long ino = f2fs_inode_by_name(child->d_inode, &dotdot);
if (!ino)
return ERR_PTR(-ENOENT);
return d_obtain_alias(f2fs_iget(child->d_inode->i_sb, ino));
}
static int __recover_dot_dentries(struct inode *dir, nid_t pino)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
struct qstr dot = QSTR_INIT(".", 1);
struct qstr dotdot = QSTR_INIT("..", 2);
struct f2fs_dir_entry *de;
struct page *page;
int err = 0;
f2fs_lock_op(sbi);
de = f2fs_find_entry(dir, &dot, &page);
if (de) {
f2fs_dentry_kunmap(dir, page);
f2fs_put_page(page, 0);
} else {
err = __f2fs_add_link(dir, &dot, NULL, dir->i_ino, S_IFDIR);
if (err)
goto out;
}
de = f2fs_find_entry(dir, &dotdot, &page);
if (de) {
f2fs_dentry_kunmap(dir, page);
f2fs_put_page(page, 0);
} else {
err = __f2fs_add_link(dir, &dotdot, NULL, pino, S_IFDIR);
}
out:
if (!err) {
clear_inode_flag(F2FS_I(dir), FI_INLINE_DOTS);
mark_inode_dirty(dir);
}
f2fs_unlock_op(sbi);
return err;
}
static struct dentry *f2fs_lookup(struct inode *dir, struct dentry *dentry,
unsigned int flags)
{
struct inode *inode = NULL;
struct f2fs_dir_entry *de;
struct page *page;
if (dentry->d_name.len > F2FS_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
de = f2fs_find_entry(dir, &dentry->d_name, &page);
if (de) {
nid_t ino = le32_to_cpu(de->ino);
f2fs_dentry_kunmap(dir, page);
f2fs_put_page(page, 0);
inode = f2fs_iget(dir->i_sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (f2fs_has_inline_dots(inode)) {
int err;
err = __recover_dot_dentries(inode, dir->i_ino);
if (err) {
iget_failed(inode);
return ERR_PTR(err);
}
}
}
return d_splice_alias(inode, dentry);
}
static int f2fs_unlink(struct inode *dir, struct dentry *dentry)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
struct inode *inode = dentry->d_inode;
struct f2fs_dir_entry *de;
struct page *page;
int err = -ENOENT;
trace_f2fs_unlink_enter(dir, dentry);
f2fs_balance_fs(sbi);
de = f2fs_find_entry(dir, &dentry->d_name, &page);
if (!de)
goto fail;
f2fs_lock_op(sbi);
err = acquire_orphan_inode(sbi);
if (err) {
f2fs_unlock_op(sbi);
f2fs_dentry_kunmap(dir, page);
f2fs_put_page(page, 0);
goto fail;
}
f2fs_delete_entry(de, page, dir, inode);
f2fs_unlock_op(sbi);
/* In order to evict this inode, we set it dirty */
mark_inode_dirty(inode);
if (IS_DIRSYNC(dir))
f2fs_sync_fs(sbi->sb, 1);
fail:
trace_f2fs_unlink_exit(inode, err);
return err;
}
static void *f2fs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct page *page;
page = page_follow_link_light(dentry, nd);
if (IS_ERR(page))
return page;
/* this is broken symlink case */
if (*nd_get_link(nd) == 0) {
kunmap(page);
page_cache_release(page);
return ERR_PTR(-ENOENT);
}
return page;
}
static int f2fs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
struct inode *inode;
size_t symlen = strlen(symname) + 1;
int err;
f2fs_balance_fs(sbi);
inode = f2fs_new_inode(dir, S_IFLNK | S_IRWXUGO);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &f2fs_symlink_inode_operations;
inode->i_mapping->a_ops = &f2fs_dblock_aops;
f2fs_lock_op(sbi);
err = f2fs_add_link(dentry, inode);
if (err)
goto out;
f2fs_unlock_op(sbi);
err = page_symlink(inode, symname, symlen);
alloc_nid_done(sbi, inode->i_ino);
d_instantiate(dentry, inode);
unlock_new_inode(inode);
/*
* Let's flush symlink data in order to avoid broken symlink as much as
* possible. Nevertheless, fsyncing is the best way, but there is no
* way to get a file descriptor in order to flush that.
*
* Note that, it needs to do dir->fsync to make this recoverable.
* If the symlink path is stored into inline_data, there is no
* performance regression.
*/
filemap_write_and_wait_range(inode->i_mapping, 0, symlen - 1);
if (IS_DIRSYNC(dir))
f2fs_sync_fs(sbi->sb, 1);
return err;
out:
handle_failed_inode(inode);
return err;
}
static int f2fs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
struct inode *inode;
int err;
f2fs_balance_fs(sbi);
inode = f2fs_new_inode(dir, S_IFDIR | mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &f2fs_dir_inode_operations;
inode->i_fop = &f2fs_dir_operations;
inode->i_mapping->a_ops = &f2fs_dblock_aops;
mapping_set_gfp_mask(inode->i_mapping, GFP_F2FS_HIGH_ZERO);
set_inode_flag(F2FS_I(inode), FI_INC_LINK);
f2fs_lock_op(sbi);
err = f2fs_add_link(dentry, inode);
if (err)
goto out_fail;
f2fs_unlock_op(sbi);
stat_inc_inline_dir(inode);
alloc_nid_done(sbi, inode->i_ino);
d_instantiate(dentry, inode);
unlock_new_inode(inode);
if (IS_DIRSYNC(dir))
f2fs_sync_fs(sbi->sb, 1);
return 0;
out_fail:
clear_inode_flag(F2FS_I(inode), FI_INC_LINK);
handle_failed_inode(inode);
return err;
}
static int f2fs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
if (f2fs_empty_dir(inode))
return f2fs_unlink(dir, dentry);
return -ENOTEMPTY;
}
static int f2fs_mknod(struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t rdev)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
struct inode *inode;
int err = 0;
if (!new_valid_dev(rdev))
return -EINVAL;
f2fs_balance_fs(sbi);
inode = f2fs_new_inode(dir, mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
init_special_inode(inode, inode->i_mode, rdev);
inode->i_op = &f2fs_special_inode_operations;
f2fs_lock_op(sbi);
err = f2fs_add_link(dentry, inode);
if (err)
goto out;
f2fs_unlock_op(sbi);
alloc_nid_done(sbi, inode->i_ino);
d_instantiate(dentry, inode);
unlock_new_inode(inode);
if (IS_DIRSYNC(dir))
f2fs_sync_fs(sbi->sb, 1);
return 0;
out:
handle_failed_inode(inode);
return err;
}
static int f2fs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(old_dir);
struct inode *old_inode = old_dentry->d_inode;
struct inode *new_inode = new_dentry->d_inode;
struct page *old_dir_page;
struct page *old_page, *new_page;
struct f2fs_dir_entry *old_dir_entry = NULL;
struct f2fs_dir_entry *old_entry;
struct f2fs_dir_entry *new_entry;
int err = -ENOENT;
f2fs_balance_fs(sbi);
old_entry = f2fs_find_entry(old_dir, &old_dentry->d_name, &old_page);
if (!old_entry)
goto out;
if (S_ISDIR(old_inode->i_mode)) {
err = -EIO;
old_dir_entry = f2fs_parent_dir(old_inode, &old_dir_page);
if (!old_dir_entry)
goto out_old;
}
if (new_inode) {
err = -ENOTEMPTY;
if (old_dir_entry && !f2fs_empty_dir(new_inode))
goto out_dir;
err = -ENOENT;
new_entry = f2fs_find_entry(new_dir, &new_dentry->d_name,
&new_page);
if (!new_entry)
goto out_dir;
f2fs_lock_op(sbi);
err = acquire_orphan_inode(sbi);
if (err)
goto put_out_dir;
if (update_dent_inode(old_inode, &new_dentry->d_name)) {
release_orphan_inode(sbi);
goto put_out_dir;
}
f2fs_set_link(new_dir, new_entry, new_page, old_inode);
new_inode->i_ctime = CURRENT_TIME;
down_write(&F2FS_I(new_inode)->i_sem);
if (old_dir_entry)
drop_nlink(new_inode);
drop_nlink(new_inode);
up_write(&F2FS_I(new_inode)->i_sem);
mark_inode_dirty(new_inode);
if (!new_inode->i_nlink)
add_orphan_inode(sbi, new_inode->i_ino);
else
release_orphan_inode(sbi);
update_inode_page(old_inode);
update_inode_page(new_inode);
} else {
f2fs_lock_op(sbi);
err = f2fs_add_link(new_dentry, old_inode);
if (err) {
f2fs_unlock_op(sbi);
goto out_dir;
}
if (old_dir_entry) {
inc_nlink(new_dir);
update_inode_page(new_dir);
}
}
down_write(&F2FS_I(old_inode)->i_sem);
file_lost_pino(old_inode);
up_write(&F2FS_I(old_inode)->i_sem);
old_inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(old_inode);
f2fs_delete_entry(old_entry, old_page, old_dir, NULL);
if (old_dir_entry) {
if (old_dir != new_dir) {
f2fs_set_link(old_inode, old_dir_entry,
old_dir_page, new_dir);
update_inode_page(old_inode);
} else {
f2fs_dentry_kunmap(old_inode, old_dir_page);
f2fs_put_page(old_dir_page, 0);
}
drop_nlink(old_dir);
mark_inode_dirty(old_dir);
update_inode_page(old_dir);
}
f2fs_unlock_op(sbi);
if (IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir))
f2fs_sync_fs(sbi->sb, 1);
return 0;
put_out_dir:
f2fs_unlock_op(sbi);
f2fs_dentry_kunmap(new_dir, new_page);
f2fs_put_page(new_page, 0);
out_dir:
if (old_dir_entry) {
f2fs_dentry_kunmap(old_inode, old_dir_page);
f2fs_put_page(old_dir_page, 0);
}
out_old:
f2fs_dentry_kunmap(old_dir, old_page);
f2fs_put_page(old_page, 0);
out:
return err;
}
const struct inode_operations f2fs_dir_inode_operations = {
.create = f2fs_create,
.lookup = f2fs_lookup,
.link = f2fs_link,
.unlink = f2fs_unlink,
.symlink = f2fs_symlink,
.mkdir = f2fs_mkdir,
.rmdir = f2fs_rmdir,
.mknod = f2fs_mknod,
.rename = f2fs_rename,
.getattr = f2fs_getattr,
.setattr = f2fs_setattr,
.get_acl = f2fs_get_acl,
#ifdef CONFIG_F2FS_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = f2fs_listxattr,
.removexattr = generic_removexattr,
#endif
};
const struct inode_operations f2fs_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = f2fs_follow_link,
.put_link = page_put_link,
.getattr = f2fs_getattr,
.setattr = f2fs_setattr,
#ifdef CONFIG_F2FS_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = f2fs_listxattr,
.removexattr = generic_removexattr,
#endif
};
const struct inode_operations f2fs_special_inode_operations = {
.getattr = f2fs_getattr,
.setattr = f2fs_setattr,
.get_acl = f2fs_get_acl,
#ifdef CONFIG_F2FS_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = f2fs_listxattr,
.removexattr = generic_removexattr,
#endif
};
| gpl-2.0 |
Dzenik/kernel-source | drivers/video/sunxi/disp/de_hwc.c | 32 | 3670 | /*
* Copyright (C) 2007-2012 Allwinner Technology 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.
*
* 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 "de_be.h"
__s32 DE_BE_HWC_Enable(__u32 sel, __bool enable)
{
__u32 tmp;
tmp = DE_BE_RUINT32(sel, DE_BE_MODE_CTL_OFF);
tmp &= (~(1 << 16));
DE_BE_WUINT32(sel, DE_BE_MODE_CTL_OFF, tmp | (enable << 16));
return 0;
}
__s32 DE_BE_HWC_Set_Pos(__u32 sel, __disp_pos_t *pos)
{
__u32 tmp;
tmp = DE_BE_RUINT32(sel, DE_BE_HWC_CRD_CTL_OFF);
DE_BE_WUINT32(sel, DE_BE_HWC_CRD_CTL_OFF, (tmp & 0xf800f800) |
(pos->y & 0x7ff) << 16 | (pos->x & 0x7ff));
return 0;
}
__s32 DE_BE_HWC_Get_Pos(__u32 sel, __disp_pos_t *pos)
{
__u32 readval;
readval = DE_BE_RUINT32(sel, DE_BE_HWC_CRD_CTL_OFF);
pos->y = (readval & 0x07ff0000) >> 16;
pos->x = (readval & 0x07ff);
return 0;
}
__s32 DE_BE_HWC_Set_Palette(__u32 sel, __u32 address, __u32 offset, __u32 size)
{
__u16 i;
__u32 read_val;
__u32 reg_addr;
reg_addr = DE_BE_HWC_PALETTE_TABLE_ADDR_OFF + offset;
for (i = 0; i < size; i = i + 4) {
read_val = readl(address + i);
DE_BE_WUINT32(sel, reg_addr, read_val);
reg_addr = reg_addr + 4;
}
return 0;
}
__s32 DE_BE_HWC_Set_Src(__u32 sel, __disp_hwc_pattern_t *hwc_pat)
{
__u32 tmp;
de_pixels_num_t x_size = 0, y_size = 0;
de_inter_fbfmt_e pixel_fmt = 0;
__u32 i;
__u32 size;
switch (hwc_pat->pat_mode) {
case DISP_HWC_MOD_H32_V32_8BPP:
x_size = DE_N32PIXELS;
y_size = DE_N32PIXELS;
pixel_fmt = DE_IF8BPP;
size = 32 * 32;
break;
case DISP_HWC_MOD_H64_V64_2BPP:
x_size = DE_N64PIXELS;
y_size = DE_N64PIXELS;
pixel_fmt = DE_IF2BPP;
size = 64 * 64 / 4;
break;
case DISP_HWC_MOD_H64_V32_4BPP:
x_size = DE_N64PIXELS;
y_size = DE_N32PIXELS;
pixel_fmt = DE_IF4BPP;
size = 64 * 32 / 2;
break;
case DISP_HWC_MOD_H32_V64_4BPP:
x_size = DE_N32PIXELS;
y_size = DE_N64PIXELS;
pixel_fmt = DE_IF4BPP;
size = 32 * 64 / 2;
break;
default:
break;
}
if (hwc_pat->addr & 0x3) { /* Address not 32bit aligned */
for (i = 0; i < size; i += 4) {
__u32 value = 0;
tmp = readb(hwc_pat->addr + i);
value = tmp;
tmp = readb(hwc_pat->addr + i + 1);
value |= (tmp << 8);
tmp = readb(hwc_pat->addr + i + 2);
value |= (tmp << 16);
tmp = readb(hwc_pat->addr + i + 3);
value |= (tmp << 24);
DE_BE_WUINT32(sel, DE_BE_HWC_MEMORY_ADDR_OFF + i,
value);
}
} else {
for (i = 0; i < size; i += 4) {
tmp = readl(hwc_pat->addr + i);
DE_BE_WUINT32(sel, DE_BE_HWC_MEMORY_ADDR_OFF + i, tmp);
}
}
tmp = DE_BE_RUINT32(sel, DE_BE_HWC_FRMBUF_OFF);
DE_BE_WUINT32(sel, DE_BE_HWC_FRMBUF_OFF, (tmp & 0xffffffc3) |
(x_size << 2) | (y_size << 4)); /* xsize and ysize */
tmp = DE_BE_RUINT32(sel, DE_BE_HWC_FRMBUF_OFF);
DE_BE_WUINT32(sel, DE_BE_HWC_FRMBUF_OFF,
(tmp & 0xfffffffc) | pixel_fmt); /* format */
tmp = DE_BE_RUINT32(sel, DE_BE_HWC_CRD_CTL_OFF);
DE_BE_WUINT32(sel, DE_BE_HWC_CRD_CTL_OFF,
(tmp & 0x07ff07ff) | 0 << 27 | 0 << 11); /* offset */
return 0;
}
| gpl-2.0 |
suhailsherif/MySQL-5.1- | storage/ndb/src/common/debugger/signaldata/AlterTrig.cpp | 32 | 1766 | /* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <signaldata/AlterTrig.hpp>
bool printALTER_TRIG_REQ(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
const AlterTrigReq * const sig = (AlterTrigReq *) theData;
fprintf(output, "User: %u, ", sig->getUserRef());
fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
fprintf(output, "\n");
return false;
}
bool printALTER_TRIG_CONF(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
const AlterTrigConf * const sig = (AlterTrigConf *) theData;
fprintf(output, "User: %u, ", sig->getUserRef());
fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
fprintf(output, "\n");
return false;
}
bool printALTER_TRIG_REF(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
const AlterTrigRef * const sig = (AlterTrigRef *) theData;
fprintf(output, "User: %u, ", sig->getUserRef());
fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
fprintf(output, "Error code: %u, ", sig->getErrorCode());
fprintf(output, "\n");
return false;
}
| gpl-2.0 |
gfreewind/latest-fastsocket | kernel/arch/powerpc/platforms/8xx/m8xx_setup.c | 544 | 6604 | /*
* Copyright (C) 1995 Linus Torvalds
* Adapted from 'alpha' version by Gary Thomas
* Modified by Cort Dougan (cort@cs.nmt.edu)
* Modified for MBX using prep/chrp/pmac functions by Dan (dmalek@jlc.net)
* Further modified for generic 8xx by Dan.
*/
/*
* bootup setup stuff..
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/rtc.h>
#include <linux/fsl_devices.h>
#include <asm/io.h>
#include <asm/mpc8xx.h>
#include <asm/8xx_immap.h>
#include <asm/prom.h>
#include <asm/fs_pd.h>
#include <mm/mmu_decl.h>
#include <sysdev/mpc8xx_pic.h>
#include "mpc8xx.h"
struct mpc8xx_pcmcia_ops m8xx_pcmcia_ops;
extern int cpm_pic_init(void);
extern int cpm_get_irq(void);
/* A place holder for time base interrupts, if they are ever enabled. */
static irqreturn_t timebase_interrupt(int irq, void *dev)
{
printk ("timebase_interrupt()\n");
return IRQ_HANDLED;
}
static struct irqaction tbint_irqaction = {
.handler = timebase_interrupt,
.name = "tbint",
};
/* per-board overridable init_internal_rtc() function. */
void __init __attribute__ ((weak))
init_internal_rtc(void)
{
sit8xx_t __iomem *sys_tmr = immr_map(im_sit);
/* Disable the RTC one second and alarm interrupts. */
clrbits16(&sys_tmr->sit_rtcsc, (RTCSC_SIE | RTCSC_ALE));
/* Enable the RTC */
setbits16(&sys_tmr->sit_rtcsc, (RTCSC_RTF | RTCSC_RTE));
immr_unmap(sys_tmr);
}
static int __init get_freq(char *name, unsigned long *val)
{
struct device_node *cpu;
const unsigned int *fp;
int found = 0;
/* The cpu node should have timebase and clock frequency properties */
cpu = of_find_node_by_type(NULL, "cpu");
if (cpu) {
fp = of_get_property(cpu, name, NULL);
if (fp) {
found = 1;
*val = *fp;
}
of_node_put(cpu);
}
return found;
}
/* The decrementer counts at the system (internal) clock frequency divided by
* sixteen, or external oscillator divided by four. We force the processor
* to use system clock divided by sixteen.
*/
void __init mpc8xx_calibrate_decr(void)
{
struct device_node *cpu;
cark8xx_t __iomem *clk_r1;
car8xx_t __iomem *clk_r2;
sitk8xx_t __iomem *sys_tmr1;
sit8xx_t __iomem *sys_tmr2;
int irq, virq;
clk_r1 = immr_map(im_clkrstk);
/* Unlock the SCCR. */
out_be32(&clk_r1->cark_sccrk, ~KAPWR_KEY);
out_be32(&clk_r1->cark_sccrk, KAPWR_KEY);
immr_unmap(clk_r1);
/* Force all 8xx processors to use divide by 16 processor clock. */
clk_r2 = immr_map(im_clkrst);
setbits32(&clk_r2->car_sccr, 0x02000000);
immr_unmap(clk_r2);
/* Processor frequency is MHz.
*/
ppc_proc_freq = 50000000;
if (!get_freq("clock-frequency", &ppc_proc_freq))
printk(KERN_ERR "WARNING: Estimating processor frequency "
"(not found)\n");
ppc_tb_freq = ppc_proc_freq / 16;
printk("Decrementer Frequency = 0x%lx\n", ppc_tb_freq);
/* Perform some more timer/timebase initialization. This used
* to be done elsewhere, but other changes caused it to get
* called more than once....that is a bad thing.
*
* First, unlock all of the registers we are going to modify.
* To protect them from corruption during power down, registers
* that are maintained by keep alive power are "locked". To
* modify these registers we have to write the key value to
* the key location associated with the register.
* Some boards power up with these unlocked, while others
* are locked. Writing anything (including the unlock code?)
* to the unlocked registers will lock them again. So, here
* we guarantee the registers are locked, then we unlock them
* for our use.
*/
sys_tmr1 = immr_map(im_sitk);
out_be32(&sys_tmr1->sitk_tbscrk, ~KAPWR_KEY);
out_be32(&sys_tmr1->sitk_rtcsck, ~KAPWR_KEY);
out_be32(&sys_tmr1->sitk_tbk, ~KAPWR_KEY);
out_be32(&sys_tmr1->sitk_tbscrk, KAPWR_KEY);
out_be32(&sys_tmr1->sitk_rtcsck, KAPWR_KEY);
out_be32(&sys_tmr1->sitk_tbk, KAPWR_KEY);
immr_unmap(sys_tmr1);
init_internal_rtc();
/* Enabling the decrementer also enables the timebase interrupts
* (or from the other point of view, to get decrementer interrupts
* we have to enable the timebase). The decrementer interrupt
* is wired into the vector table, nothing to do here for that.
*/
cpu = of_find_node_by_type(NULL, "cpu");
virq= irq_of_parse_and_map(cpu, 0);
irq = irq_map[virq].hwirq;
sys_tmr2 = immr_map(im_sit);
out_be16(&sys_tmr2->sit_tbscr, ((1 << (7 - (irq/2))) << 8) |
(TBSCR_TBF | TBSCR_TBE));
immr_unmap(sys_tmr2);
if (setup_irq(virq, &tbint_irqaction))
panic("Could not allocate timer IRQ!");
}
/* The RTC on the MPC8xx is an internal register.
* We want to protect this during power down, so we need to unlock,
* modify, and re-lock.
*/
int mpc8xx_set_rtc_time(struct rtc_time *tm)
{
sitk8xx_t __iomem *sys_tmr1;
sit8xx_t __iomem *sys_tmr2;
int time;
sys_tmr1 = immr_map(im_sitk);
sys_tmr2 = immr_map(im_sit);
time = mktime(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
out_be32(&sys_tmr1->sitk_rtck, KAPWR_KEY);
out_be32(&sys_tmr2->sit_rtc, time);
out_be32(&sys_tmr1->sitk_rtck, ~KAPWR_KEY);
immr_unmap(sys_tmr2);
immr_unmap(sys_tmr1);
return 0;
}
void mpc8xx_get_rtc_time(struct rtc_time *tm)
{
unsigned long data;
sit8xx_t __iomem *sys_tmr = immr_map(im_sit);
/* Get time from the RTC. */
data = in_be32(&sys_tmr->sit_rtc);
to_tm(data, tm);
tm->tm_year -= 1900;
tm->tm_mon -= 1;
immr_unmap(sys_tmr);
return;
}
void mpc8xx_restart(char *cmd)
{
car8xx_t __iomem *clk_r = immr_map(im_clkrst);
local_irq_disable();
setbits32(&clk_r->car_plprcr, 0x00000080);
/* Clear the ME bit in MSR to cause checkstop on machine check
*/
mtmsr(mfmsr() & ~0x1000);
in_8(&clk_r->res[0]);
panic("Restart failed\n");
}
static void cpm_cascade(unsigned int irq, struct irq_desc *desc)
{
int cascade_irq;
if ((cascade_irq = cpm_get_irq()) >= 0) {
struct irq_desc *cdesc = irq_desc + cascade_irq;
generic_handle_irq(cascade_irq);
cdesc->chip->eoi(cascade_irq);
}
desc->chip->eoi(irq);
}
/* Initialize the internal interrupt controllers. The number of
* interrupts supported can vary with the processor type, and the
* 82xx family can have up to 64.
* External interrupts can be either edge or level triggered, and
* need to be initialized by the appropriate driver.
*/
void __init mpc8xx_pics_init(void)
{
int irq;
if (mpc8xx_pic_init()) {
printk(KERN_ERR "Failed interrupt 8xx controller initialization\n");
return;
}
irq = cpm_pic_init();
if (irq != NO_IRQ)
set_irq_chained_handler(irq, cpm_cascade);
}
| gpl-2.0 |
Hani-K/H-Vitamin_trlte | drivers/acpi/acpica/dswexec.c | 2080 | 20228 | /******************************************************************************
*
* Module Name: dswexec - Dispatcher method execution callbacks;
* dispatch to interpreter.
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2013, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#include "amlcode.h"
#include "acdispat.h"
#include "acinterp.h"
#include "acnamesp.h"
#include "acdebug.h"
#define _COMPONENT ACPI_DISPATCHER
ACPI_MODULE_NAME("dswexec")
/*
* Dispatch table for opcode classes
*/
static acpi_execute_op acpi_gbl_op_type_dispatch[] = {
acpi_ex_opcode_0A_0T_1R,
acpi_ex_opcode_1A_0T_0R,
acpi_ex_opcode_1A_0T_1R,
acpi_ex_opcode_1A_1T_0R,
acpi_ex_opcode_1A_1T_1R,
acpi_ex_opcode_2A_0T_0R,
acpi_ex_opcode_2A_0T_1R,
acpi_ex_opcode_2A_1T_1R,
acpi_ex_opcode_2A_2T_1R,
acpi_ex_opcode_3A_0T_0R,
acpi_ex_opcode_3A_1T_1R,
acpi_ex_opcode_6A_0T_1R
};
/*****************************************************************************
*
* FUNCTION: acpi_ds_get_predicate_value
*
* PARAMETERS: walk_state - Current state of the parse tree walk
* result_obj - if non-zero, pop result from result stack
*
* RETURN: Status
*
* DESCRIPTION: Get the result of a predicate evaluation
*
****************************************************************************/
acpi_status
acpi_ds_get_predicate_value(struct acpi_walk_state *walk_state,
union acpi_operand_object *result_obj)
{
acpi_status status = AE_OK;
union acpi_operand_object *obj_desc;
union acpi_operand_object *local_obj_desc = NULL;
ACPI_FUNCTION_TRACE_PTR(ds_get_predicate_value, walk_state);
walk_state->control_state->common.state = 0;
if (result_obj) {
status = acpi_ds_result_pop(&obj_desc, walk_state);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Could not get result from predicate evaluation"));
return_ACPI_STATUS(status);
}
} else {
status = acpi_ds_create_operand(walk_state, walk_state->op, 0);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
status =
acpi_ex_resolve_to_value(&walk_state->operands[0],
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
obj_desc = walk_state->operands[0];
}
if (!obj_desc) {
ACPI_ERROR((AE_INFO,
"No predicate ObjDesc=%p State=%p",
obj_desc, walk_state));
return_ACPI_STATUS(AE_AML_NO_OPERAND);
}
/*
* Result of predicate evaluation must be an Integer
* object. Implicitly convert the argument if necessary.
*/
status = acpi_ex_convert_to_integer(obj_desc, &local_obj_desc, 16);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
if (local_obj_desc->common.type != ACPI_TYPE_INTEGER) {
ACPI_ERROR((AE_INFO,
"Bad predicate (not an integer) ObjDesc=%p State=%p Type=0x%X",
obj_desc, walk_state, obj_desc->common.type));
status = AE_AML_OPERAND_TYPE;
goto cleanup;
}
/* Truncate the predicate to 32-bits if necessary */
(void)acpi_ex_truncate_for32bit_table(local_obj_desc);
/*
* Save the result of the predicate evaluation on
* the control stack
*/
if (local_obj_desc->integer.value) {
walk_state->control_state->common.value = TRUE;
} else {
/*
* Predicate is FALSE, we will just toss the
* rest of the package
*/
walk_state->control_state->common.value = FALSE;
status = AE_CTRL_FALSE;
}
/* Predicate can be used for an implicit return value */
(void)acpi_ds_do_implicit_return(local_obj_desc, walk_state, TRUE);
cleanup:
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Completed a predicate eval=%X Op=%p\n",
walk_state->control_state->common.value,
walk_state->op));
/* Break to debugger to display result */
ACPI_DEBUGGER_EXEC(acpi_db_display_result_object
(local_obj_desc, walk_state));
/*
* Delete the predicate result object (we know that
* we don't need it anymore)
*/
if (local_obj_desc != obj_desc) {
acpi_ut_remove_reference(local_obj_desc);
}
acpi_ut_remove_reference(obj_desc);
walk_state->control_state->common.state = ACPI_CONTROL_NORMAL;
return_ACPI_STATUS(status);
}
/*****************************************************************************
*
* FUNCTION: acpi_ds_exec_begin_op
*
* PARAMETERS: walk_state - Current state of the parse tree walk
* out_op - Where to return op if a new one is created
*
* RETURN: Status
*
* DESCRIPTION: Descending callback used during the execution of control
* methods. This is where most operators and operands are
* dispatched to the interpreter.
*
****************************************************************************/
acpi_status
acpi_ds_exec_begin_op(struct acpi_walk_state *walk_state,
union acpi_parse_object **out_op)
{
union acpi_parse_object *op;
acpi_status status = AE_OK;
u32 opcode_class;
ACPI_FUNCTION_TRACE_PTR(ds_exec_begin_op, walk_state);
op = walk_state->op;
if (!op) {
status = acpi_ds_load2_begin_op(walk_state, out_op);
if (ACPI_FAILURE(status)) {
goto error_exit;
}
op = *out_op;
walk_state->op = op;
walk_state->opcode = op->common.aml_opcode;
walk_state->op_info =
acpi_ps_get_opcode_info(op->common.aml_opcode);
if (acpi_ns_opens_scope(walk_state->op_info->object_type)) {
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"(%s) Popping scope for Op %p\n",
acpi_ut_get_type_name(walk_state->
op_info->
object_type),
op));
status = acpi_ds_scope_stack_pop(walk_state);
if (ACPI_FAILURE(status)) {
goto error_exit;
}
}
}
if (op == walk_state->origin) {
if (out_op) {
*out_op = op;
}
return_ACPI_STATUS(AE_OK);
}
/*
* If the previous opcode was a conditional, this opcode
* must be the beginning of the associated predicate.
* Save this knowledge in the current scope descriptor
*/
if ((walk_state->control_state) &&
(walk_state->control_state->common.state ==
ACPI_CONTROL_CONDITIONAL_EXECUTING)) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Exec predicate Op=%p State=%p\n", op,
walk_state));
walk_state->control_state->common.state =
ACPI_CONTROL_PREDICATE_EXECUTING;
/* Save start of predicate */
walk_state->control_state->control.predicate_op = op;
}
opcode_class = walk_state->op_info->class;
/* We want to send namepaths to the load code */
if (op->common.aml_opcode == AML_INT_NAMEPATH_OP) {
opcode_class = AML_CLASS_NAMED_OBJECT;
}
/*
* Handle the opcode based upon the opcode type
*/
switch (opcode_class) {
case AML_CLASS_CONTROL:
status = acpi_ds_exec_begin_control_op(walk_state, op);
break;
case AML_CLASS_NAMED_OBJECT:
if (walk_state->walk_type & ACPI_WALK_METHOD) {
/*
* Found a named object declaration during method execution;
* we must enter this object into the namespace. The created
* object is temporary and will be deleted upon completion of
* the execution of this method.
*
* Note 10/2010: Except for the Scope() op. This opcode does
* not actually create a new object, it refers to an existing
* object. However, for Scope(), we want to indeed open a
* new scope.
*/
if (op->common.aml_opcode != AML_SCOPE_OP) {
status =
acpi_ds_load2_begin_op(walk_state, NULL);
} else {
status =
acpi_ds_scope_stack_push(op->named.node,
op->named.node->
type, walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
}
}
break;
case AML_CLASS_EXECUTE:
case AML_CLASS_CREATE:
break;
default:
break;
}
/* Nothing to do here during method execution */
return_ACPI_STATUS(status);
error_exit:
status = acpi_ds_method_error(status, walk_state);
return_ACPI_STATUS(status);
}
/*****************************************************************************
*
* FUNCTION: acpi_ds_exec_end_op
*
* PARAMETERS: walk_state - Current state of the parse tree walk
*
* RETURN: Status
*
* DESCRIPTION: Ascending callback used during the execution of control
* methods. The only thing we really need to do here is to
* notice the beginning of IF, ELSE, and WHILE blocks.
*
****************************************************************************/
acpi_status acpi_ds_exec_end_op(struct acpi_walk_state *walk_state)
{
union acpi_parse_object *op;
acpi_status status = AE_OK;
u32 op_type;
u32 op_class;
union acpi_parse_object *next_op;
union acpi_parse_object *first_arg;
ACPI_FUNCTION_TRACE_PTR(ds_exec_end_op, walk_state);
op = walk_state->op;
op_type = walk_state->op_info->type;
op_class = walk_state->op_info->class;
if (op_class == AML_CLASS_UNKNOWN) {
ACPI_ERROR((AE_INFO, "Unknown opcode 0x%X",
op->common.aml_opcode));
return_ACPI_STATUS(AE_NOT_IMPLEMENTED);
}
first_arg = op->common.value.arg;
/* Init the walk state */
walk_state->num_operands = 0;
walk_state->operand_index = 0;
walk_state->return_desc = NULL;
walk_state->result_obj = NULL;
/* Call debugger for single step support (DEBUG build only) */
ACPI_DEBUGGER_EXEC(status =
acpi_db_single_step(walk_state, op, op_class));
ACPI_DEBUGGER_EXEC(if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);}
) ;
/* Decode the Opcode Class */
switch (op_class) {
case AML_CLASS_ARGUMENT: /* Constants, literals, etc. */
if (walk_state->opcode == AML_INT_NAMEPATH_OP) {
status = acpi_ds_evaluate_name_path(walk_state);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
}
break;
case AML_CLASS_EXECUTE: /* Most operators with arguments */
/* Build resolved operand stack */
status = acpi_ds_create_operands(walk_state, first_arg);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
/*
* All opcodes require operand resolution, with the only exceptions
* being the object_type and size_of operators.
*/
if (!(walk_state->op_info->flags & AML_NO_OPERAND_RESOLVE)) {
/* Resolve all operands */
status = acpi_ex_resolve_operands(walk_state->opcode,
&(walk_state->
operands
[walk_state->
num_operands - 1]),
walk_state);
}
if (ACPI_SUCCESS(status)) {
/*
* Dispatch the request to the appropriate interpreter handler
* routine. There is one routine per opcode "type" based upon the
* number of opcode arguments and return type.
*/
status =
acpi_gbl_op_type_dispatch[op_type] (walk_state);
} else {
/*
* Treat constructs of the form "Store(LocalX,LocalX)" as noops when the
* Local is uninitialized.
*/
if ((status == AE_AML_UNINITIALIZED_LOCAL) &&
(walk_state->opcode == AML_STORE_OP) &&
(walk_state->operands[0]->common.type ==
ACPI_TYPE_LOCAL_REFERENCE)
&& (walk_state->operands[1]->common.type ==
ACPI_TYPE_LOCAL_REFERENCE)
&& (walk_state->operands[0]->reference.class ==
walk_state->operands[1]->reference.class)
&& (walk_state->operands[0]->reference.value ==
walk_state->operands[1]->reference.value)) {
status = AE_OK;
} else {
ACPI_EXCEPTION((AE_INFO, status,
"While resolving operands for [%s]",
acpi_ps_get_opcode_name
(walk_state->opcode)));
}
}
/* Always delete the argument objects and clear the operand stack */
acpi_ds_clear_operands(walk_state);
/*
* If a result object was returned from above, push it on the
* current result stack
*/
if (ACPI_SUCCESS(status) && walk_state->result_obj) {
status =
acpi_ds_result_push(walk_state->result_obj,
walk_state);
}
break;
default:
switch (op_type) {
case AML_TYPE_CONTROL: /* Type 1 opcode, IF/ELSE/WHILE/NOOP */
/* 1 Operand, 0 external_result, 0 internal_result */
status = acpi_ds_exec_end_control_op(walk_state, op);
break;
case AML_TYPE_METHOD_CALL:
/*
* If the method is referenced from within a package
* declaration, it is not a invocation of the method, just
* a reference to it.
*/
if ((op->asl.parent) &&
((op->asl.parent->asl.aml_opcode == AML_PACKAGE_OP)
|| (op->asl.parent->asl.aml_opcode ==
AML_VAR_PACKAGE_OP))) {
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Method Reference in a Package, Op=%p\n",
op));
op->common.node =
(struct acpi_namespace_node *)op->asl.value.
arg->asl.node;
acpi_ut_add_reference(op->asl.value.arg->asl.
node->object);
return_ACPI_STATUS(AE_OK);
}
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Method invocation, Op=%p\n", op));
/*
* (AML_METHODCALL) Op->Asl.Value.Arg->Asl.Node contains
* the method Node pointer
*/
/* next_op points to the op that holds the method name */
next_op = first_arg;
/* next_op points to first argument op */
next_op = next_op->common.next;
/*
* Get the method's arguments and put them on the operand stack
*/
status = acpi_ds_create_operands(walk_state, next_op);
if (ACPI_FAILURE(status)) {
break;
}
/*
* Since the operands will be passed to another control method,
* we must resolve all local references here (Local variables,
* arguments to *this* method, etc.)
*/
status = acpi_ds_resolve_operands(walk_state);
if (ACPI_FAILURE(status)) {
/* On error, clear all resolved operands */
acpi_ds_clear_operands(walk_state);
break;
}
/*
* Tell the walk loop to preempt this running method and
* execute the new method
*/
status = AE_CTRL_TRANSFER;
/*
* Return now; we don't want to disturb anything,
* especially the operand count!
*/
return_ACPI_STATUS(status);
case AML_TYPE_CREATE_FIELD:
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Executing CreateField Buffer/Index Op=%p\n",
op));
status = acpi_ds_load2_end_op(walk_state);
if (ACPI_FAILURE(status)) {
break;
}
status =
acpi_ds_eval_buffer_field_operands(walk_state, op);
break;
case AML_TYPE_CREATE_OBJECT:
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Executing CreateObject (Buffer/Package) Op=%p\n",
op));
switch (op->common.parent->common.aml_opcode) {
case AML_NAME_OP:
/*
* Put the Node on the object stack (Contains the ACPI Name
* of this object)
*/
walk_state->operands[0] =
(void *)op->common.parent->common.node;
walk_state->num_operands = 1;
status = acpi_ds_create_node(walk_state,
op->common.parent->
common.node,
op->common.parent);
if (ACPI_FAILURE(status)) {
break;
}
/* Fall through */
/*lint -fallthrough */
case AML_INT_EVAL_SUBTREE_OP:
status =
acpi_ds_eval_data_object_operands
(walk_state, op,
acpi_ns_get_attached_object(op->common.
parent->common.
node));
break;
default:
status =
acpi_ds_eval_data_object_operands
(walk_state, op, NULL);
break;
}
/*
* If a result object was returned from above, push it on the
* current result stack
*/
if (walk_state->result_obj) {
status =
acpi_ds_result_push(walk_state->result_obj,
walk_state);
}
break;
case AML_TYPE_NAMED_FIELD:
case AML_TYPE_NAMED_COMPLEX:
case AML_TYPE_NAMED_SIMPLE:
case AML_TYPE_NAMED_NO_OBJ:
status = acpi_ds_load2_end_op(walk_state);
if (ACPI_FAILURE(status)) {
break;
}
if (op->common.aml_opcode == AML_REGION_OP) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Executing OpRegion Address/Length Op=%p\n",
op));
status =
acpi_ds_eval_region_operands(walk_state,
op);
if (ACPI_FAILURE(status)) {
break;
}
} else if (op->common.aml_opcode == AML_DATA_REGION_OP) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Executing DataTableRegion Strings Op=%p\n",
op));
status =
acpi_ds_eval_table_region_operands
(walk_state, op);
if (ACPI_FAILURE(status)) {
break;
}
} else if (op->common.aml_opcode == AML_BANK_FIELD_OP) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Executing BankField Op=%p\n",
op));
status =
acpi_ds_eval_bank_field_operands(walk_state,
op);
if (ACPI_FAILURE(status)) {
break;
}
}
break;
case AML_TYPE_UNDEFINED:
ACPI_ERROR((AE_INFO,
"Undefined opcode type Op=%p", op));
return_ACPI_STATUS(AE_NOT_IMPLEMENTED);
case AML_TYPE_BOGUS:
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Internal opcode=%X type Op=%p\n",
walk_state->opcode, op));
break;
default:
ACPI_ERROR((AE_INFO,
"Unimplemented opcode, class=0x%X type=0x%X Opcode=0x%X Op=%p",
op_class, op_type, op->common.aml_opcode,
op));
status = AE_NOT_IMPLEMENTED;
break;
}
}
/*
* ACPI 2.0 support for 64-bit integers: Truncate numeric
* result value if we are executing from a 32-bit ACPI table
*/
(void)acpi_ex_truncate_for32bit_table(walk_state->result_obj);
/*
* Check if we just completed the evaluation of a
* conditional predicate
*/
if ((ACPI_SUCCESS(status)) &&
(walk_state->control_state) &&
(walk_state->control_state->common.state ==
ACPI_CONTROL_PREDICATE_EXECUTING) &&
(walk_state->control_state->control.predicate_op == op)) {
status =
acpi_ds_get_predicate_value(walk_state,
walk_state->result_obj);
walk_state->result_obj = NULL;
}
cleanup:
if (walk_state->result_obj) {
/* Break to debugger to display result */
ACPI_DEBUGGER_EXEC(acpi_db_display_result_object
(walk_state->result_obj, walk_state));
/*
* Delete the result op if and only if:
* Parent will not use the result -- such as any
* non-nested type2 op in a method (parent will be method)
*/
acpi_ds_delete_result_if_not_used(op, walk_state->result_obj,
walk_state);
}
#ifdef _UNDER_DEVELOPMENT
if (walk_state->parser_state.aml == walk_state->parser_state.aml_end) {
acpi_db_method_end(walk_state);
}
#endif
/* Invoke exception handler on error */
if (ACPI_FAILURE(status)) {
status = acpi_ds_method_error(status, walk_state);
}
/* Always clear the object stack */
walk_state->num_operands = 0;
return_ACPI_STATUS(status);
}
| gpl-2.0 |
vwmofo/vigor_mofokernel | drivers/staging/easycap/easycap_low.c | 3104 | 29705 | /*****************************************************************************
* *
* *
* easycap_low.c *
* *
* *
*****************************************************************************/
/*
*
* Copyright (C) 2010 R.M. Thomas <rmthomas@sciolus.org>
*
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*****************************************************************************/
/*
* ACKNOWLEGEMENTS AND REFERENCES
* ------------------------------
* This driver makes use of register information contained in the Syntek
* Semicon DC-1125 driver hosted at
* http://sourceforge.net/projects/syntekdriver/.
* Particularly useful has been a patch to the latter driver provided by
* Ivor Hewitt in January 2009. The NTSC implementation is taken from the
* work of Ben Trask.
*/
/****************************************************************************/
#include "easycap.h"
#define GET(X, Y, Z) do { \
int __rc; \
*(Z) = (u16)0; \
__rc = regget(X, Y, Z, sizeof(u8)); \
if (0 > __rc) { \
JOT(8, ":-(%i\n", __LINE__); return __rc; \
} \
} while (0)
#define SET(X, Y, Z) do { \
int __rc; \
__rc = regset(X, Y, Z); \
if (0 > __rc) { \
JOT(8, ":-(%i\n", __LINE__); return __rc; \
} \
} while (0)
/*--------------------------------------------------------------------------*/
static const struct stk1160config {
int reg;
int set;
} stk1160configPAL[256] = {
{0x000, 0x0098},
{0x002, 0x0093},
{0x001, 0x0003},
{0x003, 0x0080},
{0x00D, 0x0000},
{0x00F, 0x0002},
{0x018, 0x0010},
{0x019, 0x0000},
{0x01A, 0x0014},
{0x01B, 0x000E},
{0x01C, 0x0046},
{0x100, 0x0033},
{0x103, 0x0000},
{0x104, 0x0000},
{0x105, 0x0000},
{0x106, 0x0000},
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
* RESOLUTION 640x480
*/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
{0x110, 0x0008},
{0x111, 0x0000},
{0x112, 0x0020},
{0x113, 0x0000},
{0x114, 0x0508},
{0x115, 0x0005},
{0x116, 0x0110},
{0x117, 0x0001},
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
{0x202, 0x000F},
{0x203, 0x004A},
{0x2FF, 0x0000},
{0xFFF, 0xFFFF}
};
/*--------------------------------------------------------------------------*/
static const struct stk1160config stk1160configNTSC[256] = {
{0x000, 0x0098},
{0x002, 0x0093},
{0x001, 0x0003},
{0x003, 0x0080},
{0x00D, 0x0000},
{0x00F, 0x0002},
{0x018, 0x0010},
{0x019, 0x0000},
{0x01A, 0x0014},
{0x01B, 0x000E},
{0x01C, 0x0046},
{0x100, 0x0033},
{0x103, 0x0000},
{0x104, 0x0000},
{0x105, 0x0000},
{0x106, 0x0000},
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
* RESOLUTION 640x480
*/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
{0x110, 0x0008},
{0x111, 0x0000},
{0x112, 0x0003},
{0x113, 0x0000},
{0x114, 0x0508},
{0x115, 0x0005},
{0x116, 0x00F3},
{0x117, 0x0000},
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
{0x202, 0x000F},
{0x203, 0x004A},
{0x2FF, 0x0000},
{0xFFF, 0xFFFF}
};
/*--------------------------------------------------------------------------*/
static const struct saa7113config {
int reg;
int set;
} saa7113configPAL[256] = {
{0x01, 0x08},
{0x02, 0x80},
{0x03, 0x33},
{0x04, 0x00},
{0x05, 0x00},
{0x06, 0xE9},
{0x07, 0x0D},
{0x08, 0x38},
{0x09, 0x00},
{0x0A, SAA_0A_DEFAULT},
{0x0B, SAA_0B_DEFAULT},
{0x0C, SAA_0C_DEFAULT},
{0x0D, SAA_0D_DEFAULT},
{0x0E, 0x01},
{0x0F, 0x36},
{0x10, 0x00},
{0x11, 0x0C},
{0x12, 0xE7},
{0x13, 0x00},
{0x15, 0x00},
{0x16, 0x00},
{0x40, 0x02},
{0x41, 0xFF},
{0x42, 0xFF},
{0x43, 0xFF},
{0x44, 0xFF},
{0x45, 0xFF},
{0x46, 0xFF},
{0x47, 0xFF},
{0x48, 0xFF},
{0x49, 0xFF},
{0x4A, 0xFF},
{0x4B, 0xFF},
{0x4C, 0xFF},
{0x4D, 0xFF},
{0x4E, 0xFF},
{0x4F, 0xFF},
{0x50, 0xFF},
{0x51, 0xFF},
{0x52, 0xFF},
{0x53, 0xFF},
{0x54, 0xFF},
{0x55, 0xFF},
{0x56, 0xFF},
{0x57, 0xFF},
{0x58, 0x40},
{0x59, 0x54},
{0x5A, 0x07},
{0x5B, 0x83},
{0xFF, 0xFF}
};
/*--------------------------------------------------------------------------*/
static const struct saa7113config saa7113configNTSC[256] = {
{0x01, 0x08},
{0x02, 0x80},
{0x03, 0x33},
{0x04, 0x00},
{0x05, 0x00},
{0x06, 0xE9},
{0x07, 0x0D},
{0x08, 0x78},
{0x09, 0x00},
{0x0A, SAA_0A_DEFAULT},
{0x0B, SAA_0B_DEFAULT},
{0x0C, SAA_0C_DEFAULT},
{0x0D, SAA_0D_DEFAULT},
{0x0E, 0x01},
{0x0F, 0x36},
{0x10, 0x00},
{0x11, 0x0C},
{0x12, 0xE7},
{0x13, 0x00},
{0x15, 0x00},
{0x16, 0x00},
{0x40, 0x82},
{0x41, 0xFF},
{0x42, 0xFF},
{0x43, 0xFF},
{0x44, 0xFF},
{0x45, 0xFF},
{0x46, 0xFF},
{0x47, 0xFF},
{0x48, 0xFF},
{0x49, 0xFF},
{0x4A, 0xFF},
{0x4B, 0xFF},
{0x4C, 0xFF},
{0x4D, 0xFF},
{0x4E, 0xFF},
{0x4F, 0xFF},
{0x50, 0xFF},
{0x51, 0xFF},
{0x52, 0xFF},
{0x53, 0xFF},
{0x54, 0xFF},
{0x55, 0xFF},
{0x56, 0xFF},
{0x57, 0xFF},
{0x58, 0x40},
{0x59, 0x54},
{0x5A, 0x0A},
{0x5B, 0x83},
{0xFF, 0xFF}
};
static int regget(struct usb_device *pusb_device,
u16 index, void *reg, int reg_size)
{
int rc;
if (!pusb_device)
return -ENODEV;
rc = usb_control_msg(pusb_device, usb_rcvctrlpipe(pusb_device, 0),
0x00,
(USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE),
0x00,
index, reg, reg_size, 50000);
return rc;
}
static int regset(struct usb_device *pusb_device, u16 index, u16 value)
{
int rc;
if (!pusb_device)
return -ENODEV;
rc = usb_control_msg(pusb_device, usb_sndctrlpipe(pusb_device, 0),
0x01,
(USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE),
value, index, NULL, 0, 500);
if (rc < 0)
return rc;
if (easycap_readback) {
u16 igot = 0;
rc = regget(pusb_device, index, &igot, sizeof(igot));
igot = 0xFF & igot;
switch (index) {
case 0x000:
case 0x500:
case 0x502:
case 0x503:
case 0x504:
case 0x506:
case 0x507:
break;
case 0x204:
case 0x205:
case 0x350:
case 0x351:
if (igot)
JOT(8, "unexpected 0x%02X "
"for STK register 0x%03X\n",
igot, index);
break;
default:
if ((0xFF & value) != igot)
JOT(8, "unexpected 0x%02X != 0x%02X "
"for STK register 0x%03X\n",
igot, value, index);
break;
}
}
return rc;
}
/*--------------------------------------------------------------------------*/
/*
* FUNCTION wait_i2c() RETURNS 0 ON SUCCESS
*/
/*--------------------------------------------------------------------------*/
static int wait_i2c(struct usb_device *p)
{
u16 get0;
u8 igot;
const int max = 2;
int k;
if (!p)
return -ENODEV;
for (k = 0; k < max; k++) {
GET(p, 0x0201, &igot); get0 = igot;
switch (get0) {
case 0x04:
case 0x01:
return 0;
case 0x00:
msleep(20);
continue;
default:
return get0 - 1;
}
}
return -1;
}
/****************************************************************************/
int confirm_resolution(struct usb_device *p)
{
u8 get0, get1, get2, get3, get4, get5, get6, get7;
if (!p)
return -ENODEV;
GET(p, 0x0110, &get0);
GET(p, 0x0111, &get1);
GET(p, 0x0112, &get2);
GET(p, 0x0113, &get3);
GET(p, 0x0114, &get4);
GET(p, 0x0115, &get5);
GET(p, 0x0116, &get6);
GET(p, 0x0117, &get7);
JOT(8, "0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X\n",
get0, get1, get2, get3, get4, get5, get6, get7);
JOT(8, "....cf PAL_720x526: "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X\n",
0x000, 0x000, 0x001, 0x000, 0x5A0, 0x005, 0x121, 0x001);
JOT(8, "....cf PAL_704x526: "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X\n",
0x004, 0x000, 0x001, 0x000, 0x584, 0x005, 0x121, 0x001);
JOT(8, "....cf VGA_640x480: "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X, "
"0x%03X, 0x%03X\n",
0x008, 0x000, 0x020, 0x000, 0x508, 0x005, 0x110, 0x001);
return 0;
}
/****************************************************************************/
int confirm_stream(struct usb_device *p)
{
u16 get2;
u8 igot;
if (!p)
return -ENODEV;
GET(p, 0x0100, &igot); get2 = 0x80 & igot;
if (0x80 == get2)
JOT(8, "confirm_stream: OK\n");
else
JOT(8, "confirm_stream: STUCK\n");
return 0;
}
/****************************************************************************/
int setup_stk(struct usb_device *p, bool ntsc)
{
int i;
const struct stk1160config *cfg;
if (!p)
return -ENODEV;
cfg = (ntsc) ? stk1160configNTSC : stk1160configPAL;
for (i = 0; cfg[i].reg != 0xFFF; i++)
SET(p, cfg[i].reg, cfg[i].set);
write_300(p);
return 0;
}
/****************************************************************************/
int setup_saa(struct usb_device *p, bool ntsc)
{
int i, ir;
const struct saa7113config *cfg;
if (!p)
return -ENODEV;
cfg = (ntsc) ? saa7113configNTSC : saa7113configPAL;
for (i = 0; cfg[i].reg != 0xFF; i++)
ir = write_saa(p, cfg[i].reg, cfg[i].set);
return 0;
}
/****************************************************************************/
int write_000(struct usb_device *p, u16 set2, u16 set0)
{
u8 igot0, igot2;
if (!p)
return -ENODEV;
GET(p, 0x0002, &igot2);
GET(p, 0x0000, &igot0);
SET(p, 0x0002, set2);
SET(p, 0x0000, set0);
return 0;
}
/****************************************************************************/
int write_saa(struct usb_device *p, u16 reg0, u16 set0)
{
if (!p)
return -ENODEV;
SET(p, 0x200, 0x00);
SET(p, 0x204, reg0);
SET(p, 0x205, set0);
SET(p, 0x200, 0x01);
return wait_i2c(p);
}
/****************************************************************************/
/*--------------------------------------------------------------------------*/
/*
* REGISTER 500: SETTING VALUE TO 0x008B READS FROM VT1612A (?)
* REGISTER 500: SETTING VALUE TO 0x008C WRITES TO VT1612A
* REGISTER 502: LEAST SIGNIFICANT BYTE OF VALUE TO SET
* REGISTER 503: MOST SIGNIFICANT BYTE OF VALUE TO SET
* REGISTER 504: TARGET ADDRESS ON VT1612A
*/
/*--------------------------------------------------------------------------*/
int
write_vt(struct usb_device *p, u16 reg0, u16 set0)
{
u8 igot;
u16 got502, got503;
u16 set502, set503;
if (!p)
return -ENODEV;
SET(p, 0x0504, reg0);
SET(p, 0x0500, 0x008B);
GET(p, 0x0502, &igot); got502 = (0xFF & igot);
GET(p, 0x0503, &igot); got503 = (0xFF & igot);
JOT(16, "write_vt(., 0x%04X, 0x%04X): was 0x%04X\n",
reg0, set0, ((got503 << 8) | got502));
set502 = (0x00FF & set0);
set503 = ((0xFF00 & set0) >> 8);
SET(p, 0x0504, reg0);
SET(p, 0x0502, set502);
SET(p, 0x0503, set503);
SET(p, 0x0500, 0x008C);
return 0;
}
/****************************************************************************/
/*--------------------------------------------------------------------------*/
/*
* REGISTER 500: SETTING VALUE TO 0x008B READS FROM VT1612A (?)
* REGISTER 500: SETTING VALUE TO 0x008C WRITES TO VT1612A
* REGISTER 502: LEAST SIGNIFICANT BYTE OF VALUE TO GET
* REGISTER 503: MOST SIGNIFICANT BYTE OF VALUE TO GET
* REGISTER 504: TARGET ADDRESS ON VT1612A
*/
/*--------------------------------------------------------------------------*/
int read_vt(struct usb_device *p, u16 reg0)
{
u8 igot;
u16 got502, got503;
if (!p)
return -ENODEV;
SET(p, 0x0504, reg0);
SET(p, 0x0500, 0x008B);
GET(p, 0x0502, &igot); got502 = (0xFF & igot);
GET(p, 0x0503, &igot); got503 = (0xFF & igot);
JOT(16, "read_vt(., 0x%04X): has 0x%04X\n",
reg0, ((got503 << 8) | got502));
return (got503 << 8) | got502;
}
/****************************************************************************/
/*--------------------------------------------------------------------------*/
/*
* THESE APPEAR TO HAVE NO EFFECT ON EITHER VIDEO OR AUDIO.
*/
/*--------------------------------------------------------------------------*/
int write_300(struct usb_device *p)
{
if (!p)
return -ENODEV;
SET(p, 0x300, 0x0012);
SET(p, 0x350, 0x002D);
SET(p, 0x351, 0x0001);
SET(p, 0x352, 0x0000);
SET(p, 0x353, 0x0000);
SET(p, 0x300, 0x0080);
return 0;
}
/****************************************************************************/
/*--------------------------------------------------------------------------*/
/*
* NOTE: THE FOLLOWING IS NOT CHECKED:
* REGISTER 0x0F, WHICH IS INVOLVED IN CHROMINANCE AUTOMATIC GAIN CONTROL.
*/
/*--------------------------------------------------------------------------*/
int check_saa(struct usb_device *p, bool ntsc)
{
int i, ir, rc = 0;
struct saa7113config const *cfg;
if (!p)
return -ENODEV;
cfg = (ntsc) ? saa7113configNTSC : saa7113configPAL;
for (i = 0; cfg[i].reg != 0xFF; i++) {
if (0x0F == cfg[i].reg)
continue;
ir = read_saa(p, cfg[i].reg);
if (ir != cfg[i].set) {
SAY("SAA register 0x%02X has 0x%02X, expected 0x%02X\n",
cfg[i].reg, ir, cfg[i].set);
rc--;
}
}
return (rc < -8) ? rc : 0;
}
/****************************************************************************/
int merit_saa(struct usb_device *p)
{
int rc;
if (!p)
return -ENODEV;
rc = read_saa(p, 0x1F);
return ((0 > rc) || (0x02 & rc)) ? 1 : 0;
}
/****************************************************************************/
int ready_saa(struct usb_device *p)
{
int j, rc, rate;
const int max = 5, marktime = PATIENCE/5;
/*--------------------------------------------------------------------------*/
/*
* RETURNS 0 FOR INTERLACED 50 Hz
* 1 FOR NON-INTERLACED 50 Hz
* 2 FOR INTERLACED 60 Hz
* 3 FOR NON-INTERLACED 60 Hz
*/
/*--------------------------------------------------------------------------*/
if (!p)
return -ENODEV;
j = 0;
while (max > j) {
rc = read_saa(p, 0x1F);
if (0 <= rc) {
if (0 == (0x40 & rc))
break;
if (1 == (0x01 & rc))
break;
}
msleep(marktime);
j++;
}
if (max == j)
return -1;
else {
if (0x20 & rc) {
rate = 2;
JOT(8, "hardware detects 60 Hz\n");
} else {
rate = 0;
JOT(8, "hardware detects 50 Hz\n");
}
if (0x80 & rc)
JOT(8, "hardware detects interlacing\n");
else {
rate++;
JOT(8, "hardware detects no interlacing\n");
}
}
return 0;
}
/****************************************************************************/
/*--------------------------------------------------------------------------*/
/*
* NOTE: THE FOLLOWING ARE NOT CHECKED:
* REGISTERS 0x000, 0x002: FUNCTIONALITY IS NOT KNOWN
* REGISTER 0x100: ACCEPT ALSO (0x80 | stk1160config....[.].set)
*/
/*--------------------------------------------------------------------------*/
int check_stk(struct usb_device *p, bool ntsc)
{
int i, ir;
const struct stk1160config *cfg;
if (!p)
return -ENODEV;
cfg = (ntsc) ? stk1160configNTSC : stk1160configPAL;
for (i = 0; 0xFFF != cfg[i].reg; i++) {
if (0x000 == cfg[i].reg || 0x002 == cfg[i].reg)
continue;
ir = read_stk(p, cfg[i].reg);
if (0x100 == cfg[i].reg) {
if ((ir != (0xFF & cfg[i].set)) &&
(ir != (0x80 | (0xFF & cfg[i].set))) &&
(0xFFFF != cfg[i].set)) {
SAY("STK reg[0x%03X]=0x%02X expected 0x%02X\n",
cfg[i].reg, ir, cfg[i].set);
}
continue;
}
if ((ir != (0xFF & cfg[i].set)) && (0xFFFF != cfg[i].set))
SAY("STK register 0x%03X has 0x%02X,expected 0x%02X\n",
cfg[i].reg, ir, cfg[i].set);
}
return 0;
}
/****************************************************************************/
int read_saa(struct usb_device *p, u16 reg0)
{
u8 igot;
if (!p)
return -ENODEV;
SET(p, 0x208, reg0);
SET(p, 0x200, 0x20);
if (0 != wait_i2c(p))
return -1;
igot = 0;
GET(p, 0x0209, &igot);
return igot;
}
/****************************************************************************/
int read_stk(struct usb_device *p, u32 reg0)
{
u8 igot;
if (!p)
return -ENODEV;
igot = 0;
GET(p, reg0, &igot);
return igot;
}
/****************************************************************************/
/*--------------------------------------------------------------------------*/
/*
* HARDWARE USERSPACE INPUT NUMBER PHYSICAL INPUT DRIVER input VALUE
*
* CVBS+S-VIDEO 0 or 1 CVBS 1
* FOUR-CVBS 0 or 1 CVBS1 1
* FOUR-CVBS 2 CVBS2 2
* FOUR-CVBS 3 CVBS3 3
* FOUR-CVBS 4 CVBS4 4
* CVBS+S-VIDEO 5 S-VIDEO 5
*
* WHEN 5==input THE ARGUMENT mode MUST ALSO BE SUPPLIED:
*
* mode 7 => GAIN TO BE SET EXPLICITLY USING REGISTER 0x05 (UNTESTED)
* mode 9 => USE AUTOMATIC GAIN CONTROL (DEFAULT)
*
*/
/*---------------------------------------------------------------------------*/
int
select_input(struct usb_device *p, int input, int mode)
{
int ir;
if (!p)
return -ENODEV;
stop_100(p);
switch (input) {
case 0:
case 1: {
if (0 != write_saa(p, 0x02, 0x80))
SAY("ERROR: failed to set SAA register 0x02 "
"for input %i\n", input);
SET(p, 0x0000, 0x0098);
SET(p, 0x0002, 0x0078);
break;
}
case 2: {
if (0 != write_saa(p, 0x02, 0x80))
SAY("ERROR: failed to set SAA register 0x02 "
"for input %i\n", input);
SET(p, 0x0000, 0x0090);
SET(p, 0x0002, 0x0078);
break;
}
case 3: {
if (0 != write_saa(p, 0x02, 0x80))
SAY("ERROR: failed to set SAA register 0x02 "
" for input %i\n", input);
SET(p, 0x0000, 0x0088);
SET(p, 0x0002, 0x0078);
break;
}
case 4: {
if (0 != write_saa(p, 0x02, 0x80)) {
SAY("ERROR: failed to set SAA register 0x02 "
"for input %i\n", input);
}
SET(p, 0x0000, 0x0080);
SET(p, 0x0002, 0x0078);
break;
}
case 5: {
if (9 != mode)
mode = 7;
switch (mode) {
case 7: {
if (0 != write_saa(p, 0x02, 0x87))
SAY("ERROR: failed to set SAA register 0x02 "
"for input %i\n", input);
if (0 != write_saa(p, 0x05, 0xFF))
SAY("ERROR: failed to set SAA register 0x05 "
"for input %i\n", input);
break;
}
case 9: {
if (0 != write_saa(p, 0x02, 0x89))
SAY("ERROR: failed to set SAA register 0x02 "
"for input %i\n", input);
if (0 != write_saa(p, 0x05, 0x00))
SAY("ERROR: failed to set SAA register 0x05 "
"for input %i\n", input);
break;
}
default:
SAY("MISTAKE: bad mode: %i\n", mode);
return -1;
}
if (0 != write_saa(p, 0x04, 0x00))
SAY("ERROR: failed to set SAA register 0x04 "
"for input %i\n", input);
if (0 != write_saa(p, 0x09, 0x80))
SAY("ERROR: failed to set SAA register 0x09 "
"for input %i\n", input);
SET(p, 0x0002, 0x0093);
break;
}
default:
SAY("ERROR: bad input: %i\n", input);
return -1;
}
ir = read_stk(p, 0x00);
JOT(8, "STK register 0x00 has 0x%02X\n", ir);
ir = read_saa(p, 0x02);
JOT(8, "SAA register 0x02 has 0x%02X\n", ir);
start_100(p);
return 0;
}
/****************************************************************************/
int set_resolution(struct usb_device *p,
u16 set0, u16 set1, u16 set2, u16 set3)
{
u16 u0x0111, u0x0113, u0x0115, u0x0117;
if (!p)
return -ENODEV;
u0x0111 = ((0xFF00 & set0) >> 8);
u0x0113 = ((0xFF00 & set1) >> 8);
u0x0115 = ((0xFF00 & set2) >> 8);
u0x0117 = ((0xFF00 & set3) >> 8);
SET(p, 0x0110, (0x00FF & set0));
SET(p, 0x0111, u0x0111);
SET(p, 0x0112, (0x00FF & set1));
SET(p, 0x0113, u0x0113);
SET(p, 0x0114, (0x00FF & set2));
SET(p, 0x0115, u0x0115);
SET(p, 0x0116, (0x00FF & set3));
SET(p, 0x0117, u0x0117);
return 0;
}
/****************************************************************************/
int start_100(struct usb_device *p)
{
u16 get116, get117, get0;
u8 igot116, igot117, igot;
if (!p)
return -ENODEV;
GET(p, 0x0116, &igot116);
get116 = igot116;
GET(p, 0x0117, &igot117);
get117 = igot117;
SET(p, 0x0116, 0x0000);
SET(p, 0x0117, 0x0000);
GET(p, 0x0100, &igot);
get0 = igot;
SET(p, 0x0100, (0x80 | get0));
SET(p, 0x0116, get116);
SET(p, 0x0117, get117);
return 0;
}
/****************************************************************************/
int stop_100(struct usb_device *p)
{
u16 get0;
u8 igot;
if (!p)
return -ENODEV;
GET(p, 0x0100, &igot);
get0 = igot;
SET(p, 0x0100, (0x7F & get0));
return 0;
}
/****************************************************************************/
/****************************************************************************/
/*****************************************************************************/
int wakeup_device(struct usb_device *pusb_device)
{
if (!pusb_device)
return -ENODEV;
return usb_control_msg(pusb_device, usb_sndctrlpipe(pusb_device, 0),
USB_REQ_SET_FEATURE,
USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
USB_DEVICE_REMOTE_WAKEUP,
0, NULL, 0, 50000);
}
/*****************************************************************************/
int
audio_setup(struct easycap *peasycap)
{
struct usb_device *pusb_device;
u8 buffer[1];
int rc, id1, id2;
/*---------------------------------------------------------------------------*/
/*
* IMPORTANT:
* THE MESSAGE OF TYPE (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE)
* CAUSES MUTING IF THE VALUE 0x0100 IS SENT.
* TO ENABLE AUDIO THE VALUE 0x0200 MUST BE SENT.
*/
/*---------------------------------------------------------------------------*/
const u8 request = 0x01;
const u8 requesttype = USB_DIR_OUT |
USB_TYPE_CLASS |
USB_RECIP_INTERFACE;
const u16 value_unmute = 0x0200;
const u16 index = 0x0301;
const u16 length = 1;
if (!peasycap)
return -EFAULT;
pusb_device = peasycap->pusb_device;
if (!pusb_device)
return -ENODEV;
JOM(8, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
requesttype, request,
(0x00FF & value_unmute),
(0xFF00 & value_unmute) >> 8,
(0x00FF & index),
(0xFF00 & index) >> 8,
(0x00FF & length),
(0xFF00 & length) >> 8);
buffer[0] = 0x01;
rc = usb_control_msg(pusb_device, usb_sndctrlpipe(pusb_device, 0),
request, requesttype, value_unmute,
index, &buffer[0], length, 50000);
JOT(8, "0x%02X=buffer\n", buffer[0]);
if (rc != (int)length) {
switch (rc) {
case -EPIPE:
SAY("usb_control_msg returned -EPIPE\n");
break;
default:
SAY("ERROR: usb_control_msg returned %i\n", rc);
break;
}
}
/*--------------------------------------------------------------------------*/
/*
* REGISTER 500: SETTING VALUE TO 0x0094 RESETS AUDIO CONFIGURATION ???
* REGISTER 506: ANALOGUE AUDIO ATTENTUATOR ???
* FOR THE CVBS+S-VIDEO HARDWARE:
* SETTING VALUE TO 0x0000 GIVES QUIET SOUND.
* THE UPPER BYTE SEEMS TO HAVE NO EFFECT.
* FOR THE FOUR-CVBS HARDWARE:
* SETTING VALUE TO 0x0000 SEEMS TO HAVE NO EFFECT.
* REGISTER 507: ANALOGUE AUDIO PREAMPLIFIER ON/OFF ???
* FOR THE CVBS-S-VIDEO HARDWARE:
* SETTING VALUE TO 0x0001 GIVES VERY LOUD, DISTORTED SOUND.
* THE UPPER BYTE SEEMS TO HAVE NO EFFECT.
*/
/*--------------------------------------------------------------------------*/
SET(pusb_device, 0x0500, 0x0094);
SET(pusb_device, 0x0500, 0x008C);
SET(pusb_device, 0x0506, 0x0001);
SET(pusb_device, 0x0507, 0x0000);
id1 = read_vt(pusb_device, 0x007C);
id2 = read_vt(pusb_device, 0x007E);
SAM("0x%04X:0x%04X is audio vendor id\n", id1, id2);
/*---------------------------------------------------------------------------*/
/*
* SELECT AUDIO SOURCE "LINE IN" AND SET THE AUDIO GAIN.
*/
/*---------------------------------------------------------------------------*/
if (0 != audio_gainset(pusb_device, peasycap->gain))
SAY("ERROR: audio_gainset() failed\n");
check_vt(pusb_device);
return 0;
}
/*****************************************************************************/
int check_vt(struct usb_device *pusb_device)
{
int igot;
if (!pusb_device)
return -ENODEV;
igot = read_vt(pusb_device, 0x0002);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x02\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x02);
igot = read_vt(pusb_device, 0x000E);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x0E\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x0E);
igot = read_vt(pusb_device, 0x0010);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x10\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x10);
igot = read_vt(pusb_device, 0x0012);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x12\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x12);
igot = read_vt(pusb_device, 0x0014);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x14\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x14);
igot = read_vt(pusb_device, 0x0016);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x16\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x16);
igot = read_vt(pusb_device, 0x0018);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x18\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x18);
igot = read_vt(pusb_device, 0x001C);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x1C\n");
if (0x8000 & igot)
SAY("register 0x%02X muted\n", 0x1C);
return 0;
}
/*****************************************************************************/
/*---------------------------------------------------------------------------*/
/* NOTE: THIS DOES INCREASE THE VOLUME DRAMATICALLY:
* audio_gainset(pusb_device, 0x000F);
*
* loud dB register 0x10 dB register 0x1C dB total
* 0 -34.5 0 -34.5
* .. .... . ....
* 15 10.5 0 10.5
* 16 12.0 0 12.0
* 17 12.0 1.5 13.5
* .. .... .... ....
* 31 12.0 22.5 34.5
*/
/*---------------------------------------------------------------------------*/
int audio_gainset(struct usb_device *pusb_device, s8 loud)
{
int igot;
u8 tmp;
u16 mute;
if (!pusb_device)
return -ENODEV;
if (0 > loud)
loud = 0;
if (31 < loud)
loud = 31;
write_vt(pusb_device, 0x0002, 0x8000);
/*---------------------------------------------------------------------------*/
igot = read_vt(pusb_device, 0x000E);
if (0 > igot) {
SAY("ERROR: failed to read VT1612A register 0x0E\n");
mute = 0x0000;
} else
mute = 0x8000 & ((unsigned int)igot);
mute = 0;
if (16 > loud)
tmp = 0x01 | (0x001F & (((u8)(15 - loud)) << 1));
else
tmp = 0;
JOT(8, "0x%04X=(mute|tmp) for VT1612A register 0x0E\n", mute | tmp);
write_vt(pusb_device, 0x000E, (mute | tmp));
/*---------------------------------------------------------------------------*/
igot = read_vt(pusb_device, 0x0010);
if (0 > igot) {
SAY("ERROR: failed to read VT1612A register 0x10\n");
mute = 0x0000;
} else
mute = 0x8000 & ((unsigned int)igot);
mute = 0;
JOT(8, "0x%04X=(mute|tmp|(tmp<<8)) for VT1612A register 0x10,...0x18\n",
mute | tmp | (tmp << 8));
write_vt(pusb_device, 0x0010, (mute | tmp | (tmp << 8)));
write_vt(pusb_device, 0x0012, (mute | tmp | (tmp << 8)));
write_vt(pusb_device, 0x0014, (mute | tmp | (tmp << 8)));
write_vt(pusb_device, 0x0016, (mute | tmp | (tmp << 8)));
write_vt(pusb_device, 0x0018, (mute | tmp | (tmp << 8)));
/*---------------------------------------------------------------------------*/
igot = read_vt(pusb_device, 0x001C);
if (0 > igot) {
SAY("ERROR: failed to read VT1612A register 0x1C\n");
mute = 0x0000;
} else
mute = 0x8000 & ((unsigned int)igot);
mute = 0;
if (16 <= loud)
tmp = 0x000F & (u8)(loud - 16);
else
tmp = 0;
JOT(8, "0x%04X=(mute|tmp|(tmp<<8)) for VT1612A register 0x1C\n",
mute | tmp | (tmp << 8));
write_vt(pusb_device, 0x001C, (mute | tmp | (tmp << 8)));
write_vt(pusb_device, 0x001A, 0x0404);
write_vt(pusb_device, 0x0002, 0x0000);
return 0;
}
/*****************************************************************************/
int audio_gainget(struct usb_device *pusb_device)
{
int igot;
if (!pusb_device)
return -ENODEV;
igot = read_vt(pusb_device, 0x001C);
if (0 > igot)
SAY("ERROR: failed to read VT1612A register 0x1C\n");
return igot;
}
/*****************************************************************************/
| gpl-2.0 |
ItachiSan/android_kernel_msm_caf | net/mac80211/agg-rx.c | 4384 | 11119 | /*
* HT handling
*
* Copyright 2003, Jouni Malinen <jkmaline@cc.hut.fi>
* Copyright 2002-2005, Instant802 Networks, Inc.
* Copyright 2005-2006, Devicescape Software, Inc.
* Copyright 2006-2007 Jiri Benc <jbenc@suse.cz>
* Copyright 2007, Michael Wu <flamingice@sourmilk.net>
* Copyright 2007-2010, 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.
*/
/**
* DOC: RX A-MPDU aggregation
*
* Aggregation on the RX side requires only implementing the
* @ampdu_action callback that is invoked to start/stop any
* block-ack sessions for RX aggregation.
*
* When RX aggregation is started by the peer, the driver is
* notified via @ampdu_action function, with the
* %IEEE80211_AMPDU_RX_START action, and may reject the request
* in which case a negative response is sent to the peer, if it
* accepts it a positive response is sent.
*
* While the session is active, the device/driver are required
* to de-aggregate frames and pass them up one by one to mac80211,
* which will handle the reorder buffer.
*
* When the aggregation session is stopped again by the peer or
* ourselves, the driver's @ampdu_action function will be called
* with the action %IEEE80211_AMPDU_RX_STOP. In this case, the
* call must not fail.
*/
#include <linux/ieee80211.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <net/mac80211.h>
#include "ieee80211_i.h"
#include "driver-ops.h"
static void ieee80211_free_tid_rx(struct rcu_head *h)
{
struct tid_ampdu_rx *tid_rx =
container_of(h, struct tid_ampdu_rx, rcu_head);
int i;
del_timer_sync(&tid_rx->reorder_timer);
for (i = 0; i < tid_rx->buf_size; i++)
dev_kfree_skb(tid_rx->reorder_buf[i]);
kfree(tid_rx->reorder_buf);
kfree(tid_rx->reorder_time);
kfree(tid_rx);
}
void ___ieee80211_stop_rx_ba_session(struct sta_info *sta, u16 tid,
u16 initiator, u16 reason, bool tx)
{
struct ieee80211_local *local = sta->local;
struct tid_ampdu_rx *tid_rx;
lockdep_assert_held(&sta->ampdu_mlme.mtx);
tid_rx = rcu_dereference_protected(sta->ampdu_mlme.tid_rx[tid],
lockdep_is_held(&sta->ampdu_mlme.mtx));
if (!tid_rx)
return;
RCU_INIT_POINTER(sta->ampdu_mlme.tid_rx[tid], NULL);
#ifdef CONFIG_MAC80211_HT_DEBUG
printk(KERN_DEBUG
"Rx BA session stop requested for %pM tid %u %s reason: %d\n",
sta->sta.addr, tid,
initiator == WLAN_BACK_RECIPIENT ? "recipient" : "inititator",
(int)reason);
#endif /* CONFIG_MAC80211_HT_DEBUG */
if (drv_ampdu_action(local, sta->sdata, IEEE80211_AMPDU_RX_STOP,
&sta->sta, tid, NULL, 0))
printk(KERN_DEBUG "HW problem - can not stop rx "
"aggregation for tid %d\n", tid);
/* check if this is a self generated aggregation halt */
if (initiator == WLAN_BACK_RECIPIENT && tx)
ieee80211_send_delba(sta->sdata, sta->sta.addr,
tid, WLAN_BACK_RECIPIENT, reason);
del_timer_sync(&tid_rx->session_timer);
call_rcu(&tid_rx->rcu_head, ieee80211_free_tid_rx);
}
void __ieee80211_stop_rx_ba_session(struct sta_info *sta, u16 tid,
u16 initiator, u16 reason, bool tx)
{
mutex_lock(&sta->ampdu_mlme.mtx);
___ieee80211_stop_rx_ba_session(sta, tid, initiator, reason, tx);
mutex_unlock(&sta->ampdu_mlme.mtx);
}
void ieee80211_stop_rx_ba_session(struct ieee80211_vif *vif, u16 ba_rx_bitmap,
const u8 *addr)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct sta_info *sta;
int i;
rcu_read_lock();
sta = sta_info_get_bss(sdata, addr);
if (!sta) {
rcu_read_unlock();
return;
}
for (i = 0; i < STA_TID_NUM; i++)
if (ba_rx_bitmap & BIT(i))
set_bit(i, sta->ampdu_mlme.tid_rx_stop_requested);
ieee80211_queue_work(&sta->local->hw, &sta->ampdu_mlme.work);
rcu_read_unlock();
}
EXPORT_SYMBOL(ieee80211_stop_rx_ba_session);
/*
* After accepting the AddBA Request we activated a timer,
* resetting it after each frame that arrives from the originator.
*/
static void sta_rx_agg_session_timer_expired(unsigned long data)
{
/* not an elegant detour, but there is no choice as the timer passes
* only one argument, and various sta_info are needed here, so init
* flow in sta_info_create gives the TID as data, while the timer_to_id
* array gives the sta through container_of */
u8 *ptid = (u8 *)data;
u8 *timer_to_id = ptid - *ptid;
struct sta_info *sta = container_of(timer_to_id, struct sta_info,
timer_to_tid[0]);
#ifdef CONFIG_MAC80211_HT_DEBUG
printk(KERN_DEBUG "rx session timer expired on tid %d\n", (u16)*ptid);
#endif
set_bit(*ptid, sta->ampdu_mlme.tid_rx_timer_expired);
ieee80211_queue_work(&sta->local->hw, &sta->ampdu_mlme.work);
}
static void sta_rx_agg_reorder_timer_expired(unsigned long data)
{
u8 *ptid = (u8 *)data;
u8 *timer_to_id = ptid - *ptid;
struct sta_info *sta = container_of(timer_to_id, struct sta_info,
timer_to_tid[0]);
rcu_read_lock();
ieee80211_release_reorder_timeout(sta, *ptid);
rcu_read_unlock();
}
static void ieee80211_send_addba_resp(struct ieee80211_sub_if_data *sdata, u8 *da, u16 tid,
u8 dialog_token, u16 status, u16 policy,
u16 buf_size, u16 timeout)
{
struct ieee80211_local *local = sdata->local;
struct sk_buff *skb;
struct ieee80211_mgmt *mgmt;
u16 capab;
skb = dev_alloc_skb(sizeof(*mgmt) + local->hw.extra_tx_headroom);
if (!skb)
return;
skb_reserve(skb, local->hw.extra_tx_headroom);
mgmt = (struct ieee80211_mgmt *) skb_put(skb, 24);
memset(mgmt, 0, 24);
memcpy(mgmt->da, da, ETH_ALEN);
memcpy(mgmt->sa, sdata->vif.addr, ETH_ALEN);
if (sdata->vif.type == NL80211_IFTYPE_AP ||
sdata->vif.type == NL80211_IFTYPE_AP_VLAN ||
sdata->vif.type == NL80211_IFTYPE_MESH_POINT)
memcpy(mgmt->bssid, sdata->vif.addr, ETH_ALEN);
else if (sdata->vif.type == NL80211_IFTYPE_STATION)
memcpy(mgmt->bssid, sdata->u.mgd.bssid, ETH_ALEN);
else if (sdata->vif.type == NL80211_IFTYPE_ADHOC)
memcpy(mgmt->bssid, sdata->u.ibss.bssid, ETH_ALEN);
mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_ACTION);
skb_put(skb, 1 + sizeof(mgmt->u.action.u.addba_resp));
mgmt->u.action.category = WLAN_CATEGORY_BACK;
mgmt->u.action.u.addba_resp.action_code = WLAN_ACTION_ADDBA_RESP;
mgmt->u.action.u.addba_resp.dialog_token = dialog_token;
capab = (u16)(policy << 1); /* bit 1 aggregation policy */
capab |= (u16)(tid << 2); /* bit 5:2 TID number */
capab |= (u16)(buf_size << 6); /* bit 15:6 max size of aggregation */
mgmt->u.action.u.addba_resp.capab = cpu_to_le16(capab);
mgmt->u.action.u.addba_resp.timeout = cpu_to_le16(timeout);
mgmt->u.action.u.addba_resp.status = cpu_to_le16(status);
ieee80211_tx_skb(sdata, skb);
}
void ieee80211_process_addba_request(struct ieee80211_local *local,
struct sta_info *sta,
struct ieee80211_mgmt *mgmt,
size_t len)
{
struct tid_ampdu_rx *tid_agg_rx;
u16 capab, tid, timeout, ba_policy, buf_size, start_seq_num, status;
u8 dialog_token;
int ret = -EOPNOTSUPP;
/* extract session parameters from addba request frame */
dialog_token = mgmt->u.action.u.addba_req.dialog_token;
timeout = le16_to_cpu(mgmt->u.action.u.addba_req.timeout);
start_seq_num =
le16_to_cpu(mgmt->u.action.u.addba_req.start_seq_num) >> 4;
capab = le16_to_cpu(mgmt->u.action.u.addba_req.capab);
ba_policy = (capab & IEEE80211_ADDBA_PARAM_POLICY_MASK) >> 1;
tid = (capab & IEEE80211_ADDBA_PARAM_TID_MASK) >> 2;
buf_size = (capab & IEEE80211_ADDBA_PARAM_BUF_SIZE_MASK) >> 6;
status = WLAN_STATUS_REQUEST_DECLINED;
if (test_sta_flag(sta, WLAN_STA_BLOCK_BA)) {
#ifdef CONFIG_MAC80211_HT_DEBUG
printk(KERN_DEBUG "Suspend in progress. "
"Denying ADDBA request\n");
#endif
goto end_no_lock;
}
/* sanity check for incoming parameters:
* check if configuration can support the BA policy
* and if buffer size does not exceeds max value */
/* XXX: check own ht delayed BA capability?? */
if (((ba_policy != 1) &&
(!(sta->sta.ht_cap.cap & IEEE80211_HT_CAP_DELAY_BA))) ||
(buf_size > IEEE80211_MAX_AMPDU_BUF)) {
status = WLAN_STATUS_INVALID_QOS_PARAM;
#ifdef CONFIG_MAC80211_HT_DEBUG
if (net_ratelimit())
printk(KERN_DEBUG "AddBA Req with bad params from "
"%pM on tid %u. policy %d, buffer size %d\n",
mgmt->sa, tid, ba_policy,
buf_size);
#endif /* CONFIG_MAC80211_HT_DEBUG */
goto end_no_lock;
}
/* determine default buffer size */
if (buf_size == 0)
buf_size = IEEE80211_MAX_AMPDU_BUF;
/* make sure the size doesn't exceed the maximum supported by the hw */
if (buf_size > local->hw.max_rx_aggregation_subframes)
buf_size = local->hw.max_rx_aggregation_subframes;
/* examine state machine */
mutex_lock(&sta->ampdu_mlme.mtx);
if (sta->ampdu_mlme.tid_rx[tid]) {
#ifdef CONFIG_MAC80211_HT_DEBUG
if (net_ratelimit())
printk(KERN_DEBUG "unexpected AddBA Req from "
"%pM on tid %u\n",
mgmt->sa, tid);
#endif /* CONFIG_MAC80211_HT_DEBUG */
/* delete existing Rx BA session on the same tid */
___ieee80211_stop_rx_ba_session(sta, tid, WLAN_BACK_RECIPIENT,
WLAN_STATUS_UNSPECIFIED_QOS,
false);
}
/* prepare A-MPDU MLME for Rx aggregation */
tid_agg_rx = kmalloc(sizeof(struct tid_ampdu_rx), GFP_KERNEL);
if (!tid_agg_rx)
goto end;
spin_lock_init(&tid_agg_rx->reorder_lock);
/* rx timer */
tid_agg_rx->session_timer.function = sta_rx_agg_session_timer_expired;
tid_agg_rx->session_timer.data = (unsigned long)&sta->timer_to_tid[tid];
init_timer(&tid_agg_rx->session_timer);
/* rx reorder timer */
tid_agg_rx->reorder_timer.function = sta_rx_agg_reorder_timer_expired;
tid_agg_rx->reorder_timer.data = (unsigned long)&sta->timer_to_tid[tid];
init_timer(&tid_agg_rx->reorder_timer);
/* prepare reordering buffer */
tid_agg_rx->reorder_buf =
kcalloc(buf_size, sizeof(struct sk_buff *), GFP_KERNEL);
tid_agg_rx->reorder_time =
kcalloc(buf_size, sizeof(unsigned long), GFP_KERNEL);
if (!tid_agg_rx->reorder_buf || !tid_agg_rx->reorder_time) {
kfree(tid_agg_rx->reorder_buf);
kfree(tid_agg_rx->reorder_time);
kfree(tid_agg_rx);
goto end;
}
ret = drv_ampdu_action(local, sta->sdata, IEEE80211_AMPDU_RX_START,
&sta->sta, tid, &start_seq_num, 0);
#ifdef CONFIG_MAC80211_HT_DEBUG
printk(KERN_DEBUG "Rx A-MPDU request on tid %d result %d\n", tid, ret);
#endif /* CONFIG_MAC80211_HT_DEBUG */
if (ret) {
kfree(tid_agg_rx->reorder_buf);
kfree(tid_agg_rx->reorder_time);
kfree(tid_agg_rx);
goto end;
}
/* update data */
tid_agg_rx->dialog_token = dialog_token;
tid_agg_rx->ssn = start_seq_num;
tid_agg_rx->head_seq_num = start_seq_num;
tid_agg_rx->buf_size = buf_size;
tid_agg_rx->timeout = timeout;
tid_agg_rx->stored_mpdu_num = 0;
status = WLAN_STATUS_SUCCESS;
/* activate it for RX */
rcu_assign_pointer(sta->ampdu_mlme.tid_rx[tid], tid_agg_rx);
if (timeout)
mod_timer(&tid_agg_rx->session_timer, TU_TO_EXP_TIME(timeout));
end:
mutex_unlock(&sta->ampdu_mlme.mtx);
end_no_lock:
ieee80211_send_addba_resp(sta->sdata, sta->sta.addr, tid,
dialog_token, status, 1, buf_size, timeout);
}
| gpl-2.0 |
CyanogenMod/android_kernel_cyanogen_msm8974 | drivers/video/pxa3xx-gcu.c | 4896 | 17738 | /*
* pxa3xx-gcu.c - Linux kernel module for PXA3xx graphics controllers
*
* This driver needs a DirectFB counterpart in user space, communication
* is handled via mmap()ed memory areas and an ioctl.
*
* Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
* Copyright (c) 2009 Janine Kropp <nin@directfb.org>
* Copyright (c) 2009 Denis Oliver Kropp <dok@directfb.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.
*/
/*
* WARNING: This controller is attached to System Bus 2 of the PXA which
* needs its arbiter to be enabled explicitly (CKENB & 1<<9).
* There is currently no way to do this from Linux, so you need to teach
* your bootloader for now.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/miscdevice.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/ioctl.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/fs.h>
#include <linux/io.h>
#include "pxa3xx-gcu.h"
#define DRV_NAME "pxa3xx-gcu"
#define MISCDEV_MINOR 197
#define REG_GCCR 0x00
#define GCCR_SYNC_CLR (1 << 9)
#define GCCR_BP_RST (1 << 8)
#define GCCR_ABORT (1 << 6)
#define GCCR_STOP (1 << 4)
#define REG_GCISCR 0x04
#define REG_GCIECR 0x08
#define REG_GCRBBR 0x20
#define REG_GCRBLR 0x24
#define REG_GCRBHR 0x28
#define REG_GCRBTR 0x2C
#define REG_GCRBEXHR 0x30
#define IE_EOB (1 << 0)
#define IE_EEOB (1 << 5)
#define IE_ALL 0xff
#define SHARED_SIZE PAGE_ALIGN(sizeof(struct pxa3xx_gcu_shared))
/* #define PXA3XX_GCU_DEBUG */
/* #define PXA3XX_GCU_DEBUG_TIMER */
#ifdef PXA3XX_GCU_DEBUG
#define QDUMP(msg) \
do { \
QPRINT(priv, KERN_DEBUG, msg); \
} while (0)
#else
#define QDUMP(msg) do {} while (0)
#endif
#define QERROR(msg) \
do { \
QPRINT(priv, KERN_ERR, msg); \
} while (0)
struct pxa3xx_gcu_batch {
struct pxa3xx_gcu_batch *next;
u32 *ptr;
dma_addr_t phys;
unsigned long length;
};
struct pxa3xx_gcu_priv {
void __iomem *mmio_base;
struct clk *clk;
struct pxa3xx_gcu_shared *shared;
dma_addr_t shared_phys;
struct resource *resource_mem;
struct miscdevice misc_dev;
struct file_operations misc_fops;
wait_queue_head_t wait_idle;
wait_queue_head_t wait_free;
spinlock_t spinlock;
struct timeval base_time;
struct pxa3xx_gcu_batch *free;
struct pxa3xx_gcu_batch *ready;
struct pxa3xx_gcu_batch *ready_last;
struct pxa3xx_gcu_batch *running;
};
static inline unsigned long
gc_readl(struct pxa3xx_gcu_priv *priv, unsigned int off)
{
return __raw_readl(priv->mmio_base + off);
}
static inline void
gc_writel(struct pxa3xx_gcu_priv *priv, unsigned int off, unsigned long val)
{
__raw_writel(val, priv->mmio_base + off);
}
#define QPRINT(priv, level, msg) \
do { \
struct timeval tv; \
struct pxa3xx_gcu_shared *shared = priv->shared; \
u32 base = gc_readl(priv, REG_GCRBBR); \
\
do_gettimeofday(&tv); \
\
printk(level "%ld.%03ld.%03ld - %-17s: %-21s (%s, " \
"STATUS " \
"0x%02lx, B 0x%08lx [%ld], E %5ld, H %5ld, " \
"T %5ld)\n", \
tv.tv_sec - priv->base_time.tv_sec, \
tv.tv_usec / 1000, tv.tv_usec % 1000, \
__func__, msg, \
shared->hw_running ? "running" : " idle", \
gc_readl(priv, REG_GCISCR), \
gc_readl(priv, REG_GCRBBR), \
gc_readl(priv, REG_GCRBLR), \
(gc_readl(priv, REG_GCRBEXHR) - base) / 4, \
(gc_readl(priv, REG_GCRBHR) - base) / 4, \
(gc_readl(priv, REG_GCRBTR) - base) / 4); \
} while (0)
static void
pxa3xx_gcu_reset(struct pxa3xx_gcu_priv *priv)
{
QDUMP("RESET");
/* disable interrupts */
gc_writel(priv, REG_GCIECR, 0);
/* reset hardware */
gc_writel(priv, REG_GCCR, GCCR_ABORT);
gc_writel(priv, REG_GCCR, 0);
memset(priv->shared, 0, SHARED_SIZE);
priv->shared->buffer_phys = priv->shared_phys;
priv->shared->magic = PXA3XX_GCU_SHARED_MAGIC;
do_gettimeofday(&priv->base_time);
/* set up the ring buffer pointers */
gc_writel(priv, REG_GCRBLR, 0);
gc_writel(priv, REG_GCRBBR, priv->shared_phys);
gc_writel(priv, REG_GCRBTR, priv->shared_phys);
/* enable all IRQs except EOB */
gc_writel(priv, REG_GCIECR, IE_ALL & ~IE_EOB);
}
static void
dump_whole_state(struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_shared *sh = priv->shared;
u32 base = gc_readl(priv, REG_GCRBBR);
QDUMP("DUMP");
printk(KERN_DEBUG "== PXA3XX-GCU DUMP ==\n"
"%s, STATUS 0x%02lx, B 0x%08lx [%ld], E %5ld, H %5ld, T %5ld\n",
sh->hw_running ? "running" : "idle ",
gc_readl(priv, REG_GCISCR),
gc_readl(priv, REG_GCRBBR),
gc_readl(priv, REG_GCRBLR),
(gc_readl(priv, REG_GCRBEXHR) - base) / 4,
(gc_readl(priv, REG_GCRBHR) - base) / 4,
(gc_readl(priv, REG_GCRBTR) - base) / 4);
}
static void
flush_running(struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_batch *running = priv->running;
struct pxa3xx_gcu_batch *next;
while (running) {
next = running->next;
running->next = priv->free;
priv->free = running;
running = next;
}
priv->running = NULL;
}
static void
run_ready(struct pxa3xx_gcu_priv *priv)
{
unsigned int num = 0;
struct pxa3xx_gcu_shared *shared = priv->shared;
struct pxa3xx_gcu_batch *ready = priv->ready;
QDUMP("Start");
BUG_ON(!ready);
shared->buffer[num++] = 0x05000000;
while (ready) {
shared->buffer[num++] = 0x00000001;
shared->buffer[num++] = ready->phys;
ready = ready->next;
}
shared->buffer[num++] = 0x05000000;
priv->running = priv->ready;
priv->ready = priv->ready_last = NULL;
gc_writel(priv, REG_GCRBLR, 0);
shared->hw_running = 1;
/* ring base address */
gc_writel(priv, REG_GCRBBR, shared->buffer_phys);
/* ring tail address */
gc_writel(priv, REG_GCRBTR, shared->buffer_phys + num * 4);
/* ring length */
gc_writel(priv, REG_GCRBLR, ((num + 63) & ~63) * 4);
}
static irqreturn_t
pxa3xx_gcu_handle_irq(int irq, void *ctx)
{
struct pxa3xx_gcu_priv *priv = ctx;
struct pxa3xx_gcu_shared *shared = priv->shared;
u32 status = gc_readl(priv, REG_GCISCR) & IE_ALL;
QDUMP("-Interrupt");
if (!status)
return IRQ_NONE;
spin_lock(&priv->spinlock);
shared->num_interrupts++;
if (status & IE_EEOB) {
QDUMP(" [EEOB]");
flush_running(priv);
wake_up_all(&priv->wait_free);
if (priv->ready) {
run_ready(priv);
} else {
/* There is no more data prepared by the userspace.
* Set hw_running = 0 and wait for the next userspace
* kick-off */
shared->num_idle++;
shared->hw_running = 0;
QDUMP(" '-> Idle.");
/* set ring buffer length to zero */
gc_writel(priv, REG_GCRBLR, 0);
wake_up_all(&priv->wait_idle);
}
shared->num_done++;
} else {
QERROR(" [???]");
dump_whole_state(priv);
}
/* Clear the interrupt */
gc_writel(priv, REG_GCISCR, status);
spin_unlock(&priv->spinlock);
return IRQ_HANDLED;
}
static int
pxa3xx_gcu_wait_idle(struct pxa3xx_gcu_priv *priv)
{
int ret = 0;
QDUMP("Waiting for idle...");
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_wait_idle++;
while (priv->shared->hw_running) {
int num = priv->shared->num_interrupts;
u32 rbexhr = gc_readl(priv, REG_GCRBEXHR);
ret = wait_event_interruptible_timeout(priv->wait_idle,
!priv->shared->hw_running, HZ*4);
if (ret < 0)
break;
if (ret > 0)
continue;
if (gc_readl(priv, REG_GCRBEXHR) == rbexhr &&
priv->shared->num_interrupts == num) {
QERROR("TIMEOUT");
ret = -ETIMEDOUT;
break;
}
}
QDUMP("done");
return ret;
}
static int
pxa3xx_gcu_wait_free(struct pxa3xx_gcu_priv *priv)
{
int ret = 0;
QDUMP("Waiting for free...");
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_wait_free++;
while (!priv->free) {
u32 rbexhr = gc_readl(priv, REG_GCRBEXHR);
ret = wait_event_interruptible_timeout(priv->wait_free,
priv->free, HZ*4);
if (ret < 0)
break;
if (ret > 0)
continue;
if (gc_readl(priv, REG_GCRBEXHR) == rbexhr) {
QERROR("TIMEOUT");
ret = -ETIMEDOUT;
break;
}
}
QDUMP("done");
return ret;
}
/* Misc device layer */
static ssize_t
pxa3xx_gcu_misc_write(struct file *filp, const char *buff,
size_t count, loff_t *offp)
{
int ret;
unsigned long flags;
struct pxa3xx_gcu_batch *buffer;
struct pxa3xx_gcu_priv *priv =
container_of(filp->f_op, struct pxa3xx_gcu_priv, misc_fops);
int words = count / 4;
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_writes++;
priv->shared->num_words += words;
/* Last word reserved for batch buffer end command */
if (words >= PXA3XX_GCU_BATCH_WORDS)
return -E2BIG;
/* Wait for a free buffer */
if (!priv->free) {
ret = pxa3xx_gcu_wait_free(priv);
if (ret < 0)
return ret;
}
/*
* Get buffer from free list
*/
spin_lock_irqsave(&priv->spinlock, flags);
buffer = priv->free;
priv->free = buffer->next;
spin_unlock_irqrestore(&priv->spinlock, flags);
/* Copy data from user into buffer */
ret = copy_from_user(buffer->ptr, buff, words * 4);
if (ret) {
spin_lock_irqsave(&priv->spinlock, flags);
buffer->next = priv->free;
priv->free = buffer;
spin_unlock_irqrestore(&priv->spinlock, flags);
return -EFAULT;
}
buffer->length = words;
/* Append batch buffer end command */
buffer->ptr[words] = 0x01000000;
/*
* Add buffer to ready list
*/
spin_lock_irqsave(&priv->spinlock, flags);
buffer->next = NULL;
if (priv->ready) {
BUG_ON(priv->ready_last == NULL);
priv->ready_last->next = buffer;
} else
priv->ready = buffer;
priv->ready_last = buffer;
if (!priv->shared->hw_running)
run_ready(priv);
spin_unlock_irqrestore(&priv->spinlock, flags);
return words * 4;
}
static long
pxa3xx_gcu_misc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned long flags;
struct pxa3xx_gcu_priv *priv =
container_of(filp->f_op, struct pxa3xx_gcu_priv, misc_fops);
switch (cmd) {
case PXA3XX_GCU_IOCTL_RESET:
spin_lock_irqsave(&priv->spinlock, flags);
pxa3xx_gcu_reset(priv);
spin_unlock_irqrestore(&priv->spinlock, flags);
return 0;
case PXA3XX_GCU_IOCTL_WAIT_IDLE:
return pxa3xx_gcu_wait_idle(priv);
}
return -ENOSYS;
}
static int
pxa3xx_gcu_misc_mmap(struct file *filp, struct vm_area_struct *vma)
{
unsigned int size = vma->vm_end - vma->vm_start;
struct pxa3xx_gcu_priv *priv =
container_of(filp->f_op, struct pxa3xx_gcu_priv, misc_fops);
switch (vma->vm_pgoff) {
case 0:
/* hand out the shared data area */
if (size != SHARED_SIZE)
return -EINVAL;
return dma_mmap_coherent(NULL, vma,
priv->shared, priv->shared_phys, size);
case SHARED_SIZE >> PAGE_SHIFT:
/* hand out the MMIO base for direct register access
* from userspace */
if (size != resource_size(priv->resource_mem))
return -EINVAL;
vma->vm_flags |= VM_IO;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return io_remap_pfn_range(vma, vma->vm_start,
priv->resource_mem->start >> PAGE_SHIFT,
size, vma->vm_page_prot);
}
return -EINVAL;
}
#ifdef PXA3XX_GCU_DEBUG_TIMER
static struct timer_list pxa3xx_gcu_debug_timer;
static void pxa3xx_gcu_debug_timedout(unsigned long ptr)
{
struct pxa3xx_gcu_priv *priv = (struct pxa3xx_gcu_priv *) ptr;
QERROR("Timer DUMP");
/* init the timer structure */
init_timer(&pxa3xx_gcu_debug_timer);
pxa3xx_gcu_debug_timer.function = pxa3xx_gcu_debug_timedout;
pxa3xx_gcu_debug_timer.data = ptr;
pxa3xx_gcu_debug_timer.expires = jiffies + 5*HZ; /* one second */
add_timer(&pxa3xx_gcu_debug_timer);
}
static void pxa3xx_gcu_init_debug_timer(void)
{
pxa3xx_gcu_debug_timedout((unsigned long) &pxa3xx_gcu_debug_timer);
}
#else
static inline void pxa3xx_gcu_init_debug_timer(void) {}
#endif
static int
add_buffer(struct platform_device *dev,
struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_batch *buffer;
buffer = kzalloc(sizeof(struct pxa3xx_gcu_batch), GFP_KERNEL);
if (!buffer)
return -ENOMEM;
buffer->ptr = dma_alloc_coherent(&dev->dev, PXA3XX_GCU_BATCH_WORDS * 4,
&buffer->phys, GFP_KERNEL);
if (!buffer->ptr) {
kfree(buffer);
return -ENOMEM;
}
buffer->next = priv->free;
priv->free = buffer;
return 0;
}
static void
free_buffers(struct platform_device *dev,
struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_batch *next, *buffer = priv->free;
while (buffer) {
next = buffer->next;
dma_free_coherent(&dev->dev, PXA3XX_GCU_BATCH_WORDS * 4,
buffer->ptr, buffer->phys);
kfree(buffer);
buffer = next;
}
priv->free = NULL;
}
static int __devinit
pxa3xx_gcu_probe(struct platform_device *dev)
{
int i, ret, irq;
struct resource *r;
struct pxa3xx_gcu_priv *priv;
priv = kzalloc(sizeof(struct pxa3xx_gcu_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
for (i = 0; i < 8; i++) {
ret = add_buffer(dev, priv);
if (ret) {
dev_err(&dev->dev, "failed to allocate DMA memory\n");
goto err_free_priv;
}
}
init_waitqueue_head(&priv->wait_idle);
init_waitqueue_head(&priv->wait_free);
spin_lock_init(&priv->spinlock);
/* we allocate the misc device structure as part of our own allocation,
* so we can get a pointer to our priv structure later on with
* container_of(). This isn't really necessary as we have a fixed minor
* number anyway, but this is to avoid statics. */
priv->misc_fops.owner = THIS_MODULE;
priv->misc_fops.write = pxa3xx_gcu_misc_write;
priv->misc_fops.unlocked_ioctl = pxa3xx_gcu_misc_ioctl;
priv->misc_fops.mmap = pxa3xx_gcu_misc_mmap;
priv->misc_dev.minor = MISCDEV_MINOR,
priv->misc_dev.name = DRV_NAME,
priv->misc_dev.fops = &priv->misc_fops,
/* register misc device */
ret = misc_register(&priv->misc_dev);
if (ret < 0) {
dev_err(&dev->dev, "misc_register() for minor %d failed\n",
MISCDEV_MINOR);
goto err_free_priv;
}
/* handle IO resources */
r = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (r == NULL) {
dev_err(&dev->dev, "no I/O memory resource defined\n");
ret = -ENODEV;
goto err_misc_deregister;
}
if (!request_mem_region(r->start, resource_size(r), dev->name)) {
dev_err(&dev->dev, "failed to request I/O memory\n");
ret = -EBUSY;
goto err_misc_deregister;
}
priv->mmio_base = ioremap_nocache(r->start, resource_size(r));
if (!priv->mmio_base) {
dev_err(&dev->dev, "failed to map I/O memory\n");
ret = -EBUSY;
goto err_free_mem_region;
}
/* allocate dma memory */
priv->shared = dma_alloc_coherent(&dev->dev, SHARED_SIZE,
&priv->shared_phys, GFP_KERNEL);
if (!priv->shared) {
dev_err(&dev->dev, "failed to allocate DMA memory\n");
ret = -ENOMEM;
goto err_free_io;
}
/* enable the clock */
priv->clk = clk_get(&dev->dev, NULL);
if (IS_ERR(priv->clk)) {
dev_err(&dev->dev, "failed to get clock\n");
ret = -ENODEV;
goto err_free_dma;
}
ret = clk_enable(priv->clk);
if (ret < 0) {
dev_err(&dev->dev, "failed to enable clock\n");
goto err_put_clk;
}
/* request the IRQ */
irq = platform_get_irq(dev, 0);
if (irq < 0) {
dev_err(&dev->dev, "no IRQ defined\n");
ret = -ENODEV;
goto err_put_clk;
}
ret = request_irq(irq, pxa3xx_gcu_handle_irq,
0, DRV_NAME, priv);
if (ret) {
dev_err(&dev->dev, "request_irq failed\n");
ret = -EBUSY;
goto err_put_clk;
}
platform_set_drvdata(dev, priv);
priv->resource_mem = r;
pxa3xx_gcu_reset(priv);
pxa3xx_gcu_init_debug_timer();
dev_info(&dev->dev, "registered @0x%p, DMA 0x%p (%d bytes), IRQ %d\n",
(void *) r->start, (void *) priv->shared_phys,
SHARED_SIZE, irq);
return 0;
err_put_clk:
clk_disable(priv->clk);
clk_put(priv->clk);
err_free_dma:
dma_free_coherent(&dev->dev, SHARED_SIZE,
priv->shared, priv->shared_phys);
err_free_io:
iounmap(priv->mmio_base);
err_free_mem_region:
release_mem_region(r->start, resource_size(r));
err_misc_deregister:
misc_deregister(&priv->misc_dev);
err_free_priv:
platform_set_drvdata(dev, NULL);
free_buffers(dev, priv);
kfree(priv);
return ret;
}
static int __devexit
pxa3xx_gcu_remove(struct platform_device *dev)
{
struct pxa3xx_gcu_priv *priv = platform_get_drvdata(dev);
struct resource *r = priv->resource_mem;
pxa3xx_gcu_wait_idle(priv);
misc_deregister(&priv->misc_dev);
dma_free_coherent(&dev->dev, SHARED_SIZE,
priv->shared, priv->shared_phys);
iounmap(priv->mmio_base);
release_mem_region(r->start, resource_size(r));
platform_set_drvdata(dev, NULL);
clk_disable(priv->clk);
free_buffers(dev, priv);
kfree(priv);
return 0;
}
static struct platform_driver pxa3xx_gcu_driver = {
.probe = pxa3xx_gcu_probe,
.remove = __devexit_p(pxa3xx_gcu_remove),
.driver = {
.owner = THIS_MODULE,
.name = DRV_NAME,
},
};
module_platform_driver(pxa3xx_gcu_driver);
MODULE_DESCRIPTION("PXA3xx graphics controller unit driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(MISCDEV_MINOR);
MODULE_AUTHOR("Janine Kropp <nin@directfb.org>, "
"Denis Oliver Kropp <dok@directfb.org>, "
"Daniel Mack <daniel@caiaq.de>");
| gpl-2.0 |
Minia89/one_plus_one | drivers/net/ethernet/stmicro/stmmac/dwmac_lib.c | 4896 | 7522 | /*******************************************************************************
Copyright (C) 2007-2009 STMicroelectronics Ltd
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*******************************************************************************/
#include <linux/io.h>
#include "common.h"
#include "dwmac_dma.h"
#undef DWMAC_DMA_DEBUG
#ifdef DWMAC_DMA_DEBUG
#define DWMAC_LIB_DBG(fmt, args...) printk(fmt, ## args)
#else
#define DWMAC_LIB_DBG(fmt, args...) do { } while (0)
#endif
/* CSR1 enables the transmit DMA to check for new descriptor */
void dwmac_enable_dma_transmission(void __iomem *ioaddr)
{
writel(1, ioaddr + DMA_XMT_POLL_DEMAND);
}
void dwmac_enable_dma_irq(void __iomem *ioaddr)
{
writel(DMA_INTR_DEFAULT_MASK, ioaddr + DMA_INTR_ENA);
}
void dwmac_disable_dma_irq(void __iomem *ioaddr)
{
writel(0, ioaddr + DMA_INTR_ENA);
}
void dwmac_dma_start_tx(void __iomem *ioaddr)
{
u32 value = readl(ioaddr + DMA_CONTROL);
value |= DMA_CONTROL_ST;
writel(value, ioaddr + DMA_CONTROL);
}
void dwmac_dma_stop_tx(void __iomem *ioaddr)
{
u32 value = readl(ioaddr + DMA_CONTROL);
value &= ~DMA_CONTROL_ST;
writel(value, ioaddr + DMA_CONTROL);
}
void dwmac_dma_start_rx(void __iomem *ioaddr)
{
u32 value = readl(ioaddr + DMA_CONTROL);
value |= DMA_CONTROL_SR;
writel(value, ioaddr + DMA_CONTROL);
}
void dwmac_dma_stop_rx(void __iomem *ioaddr)
{
u32 value = readl(ioaddr + DMA_CONTROL);
value &= ~DMA_CONTROL_SR;
writel(value, ioaddr + DMA_CONTROL);
}
#ifdef DWMAC_DMA_DEBUG
static void show_tx_process_state(unsigned int status)
{
unsigned int state;
state = (status & DMA_STATUS_TS_MASK) >> DMA_STATUS_TS_SHIFT;
switch (state) {
case 0:
pr_info("- TX (Stopped): Reset or Stop command\n");
break;
case 1:
pr_info("- TX (Running):Fetching the Tx desc\n");
break;
case 2:
pr_info("- TX (Running): Waiting for end of tx\n");
break;
case 3:
pr_info("- TX (Running): Reading the data "
"and queuing the data into the Tx buf\n");
break;
case 6:
pr_info("- TX (Suspended): Tx Buff Underflow "
"or an unavailable Transmit descriptor\n");
break;
case 7:
pr_info("- TX (Running): Closing Tx descriptor\n");
break;
default:
break;
}
}
static void show_rx_process_state(unsigned int status)
{
unsigned int state;
state = (status & DMA_STATUS_RS_MASK) >> DMA_STATUS_RS_SHIFT;
switch (state) {
case 0:
pr_info("- RX (Stopped): Reset or Stop command\n");
break;
case 1:
pr_info("- RX (Running): Fetching the Rx desc\n");
break;
case 2:
pr_info("- RX (Running):Checking for end of pkt\n");
break;
case 3:
pr_info("- RX (Running): Waiting for Rx pkt\n");
break;
case 4:
pr_info("- RX (Suspended): Unavailable Rx buf\n");
break;
case 5:
pr_info("- RX (Running): Closing Rx descriptor\n");
break;
case 6:
pr_info("- RX(Running): Flushing the current frame"
" from the Rx buf\n");
break;
case 7:
pr_info("- RX (Running): Queuing the Rx frame"
" from the Rx buf into memory\n");
break;
default:
break;
}
}
#endif
int dwmac_dma_interrupt(void __iomem *ioaddr,
struct stmmac_extra_stats *x)
{
int ret = 0;
/* read the status register (CSR5) */
u32 intr_status = readl(ioaddr + DMA_STATUS);
DWMAC_LIB_DBG(KERN_INFO "%s: [CSR5: 0x%08x]\n", __func__, intr_status);
#ifdef DWMAC_DMA_DEBUG
/* It displays the DMA process states (CSR5 register) */
show_tx_process_state(intr_status);
show_rx_process_state(intr_status);
#endif
/* ABNORMAL interrupts */
if (unlikely(intr_status & DMA_STATUS_AIS)) {
DWMAC_LIB_DBG(KERN_INFO "CSR5[15] DMA ABNORMAL IRQ: ");
if (unlikely(intr_status & DMA_STATUS_UNF)) {
DWMAC_LIB_DBG(KERN_INFO "transmit underflow\n");
ret = tx_hard_error_bump_tc;
x->tx_undeflow_irq++;
}
if (unlikely(intr_status & DMA_STATUS_TJT)) {
DWMAC_LIB_DBG(KERN_INFO "transmit jabber\n");
x->tx_jabber_irq++;
}
if (unlikely(intr_status & DMA_STATUS_OVF)) {
DWMAC_LIB_DBG(KERN_INFO "recv overflow\n");
x->rx_overflow_irq++;
}
if (unlikely(intr_status & DMA_STATUS_RU)) {
DWMAC_LIB_DBG(KERN_INFO "receive buffer unavailable\n");
x->rx_buf_unav_irq++;
}
if (unlikely(intr_status & DMA_STATUS_RPS)) {
DWMAC_LIB_DBG(KERN_INFO "receive process stopped\n");
x->rx_process_stopped_irq++;
}
if (unlikely(intr_status & DMA_STATUS_RWT)) {
DWMAC_LIB_DBG(KERN_INFO "receive watchdog\n");
x->rx_watchdog_irq++;
}
if (unlikely(intr_status & DMA_STATUS_ETI)) {
DWMAC_LIB_DBG(KERN_INFO "transmit early interrupt\n");
x->tx_early_irq++;
}
if (unlikely(intr_status & DMA_STATUS_TPS)) {
DWMAC_LIB_DBG(KERN_INFO "transmit process stopped\n");
x->tx_process_stopped_irq++;
ret = tx_hard_error;
}
if (unlikely(intr_status & DMA_STATUS_FBI)) {
DWMAC_LIB_DBG(KERN_INFO "fatal bus error\n");
x->fatal_bus_error_irq++;
ret = tx_hard_error;
}
}
/* TX/RX NORMAL interrupts */
if (intr_status & DMA_STATUS_NIS) {
x->normal_irq_n++;
if (likely((intr_status & DMA_STATUS_RI) ||
(intr_status & (DMA_STATUS_TI))))
ret = handle_tx_rx;
}
/* Optional hardware blocks, interrupts should be disabled */
if (unlikely(intr_status &
(DMA_STATUS_GPI | DMA_STATUS_GMI | DMA_STATUS_GLI)))
pr_info("%s: unexpected status %08x\n", __func__, intr_status);
/* Clear the interrupt by writing a logic 1 to the CSR5[15-0] */
writel((intr_status & 0x1ffff), ioaddr + DMA_STATUS);
DWMAC_LIB_DBG(KERN_INFO "\n\n");
return ret;
}
void dwmac_dma_flush_tx_fifo(void __iomem *ioaddr)
{
u32 csr6 = readl(ioaddr + DMA_CONTROL);
writel((csr6 | DMA_CONTROL_FTF), ioaddr + DMA_CONTROL);
do {} while ((readl(ioaddr + DMA_CONTROL) & DMA_CONTROL_FTF));
}
void stmmac_set_mac_addr(void __iomem *ioaddr, u8 addr[6],
unsigned int high, unsigned int low)
{
unsigned long data;
data = (addr[5] << 8) | addr[4];
writel(data, ioaddr + high);
data = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
writel(data, ioaddr + low);
}
/* Enable disable MAC RX/TX */
void stmmac_set_mac(void __iomem *ioaddr, bool enable)
{
u32 value = readl(ioaddr + MAC_CTRL_REG);
if (enable)
value |= MAC_RNABLE_RX | MAC_ENABLE_TX;
else
value &= ~(MAC_ENABLE_TX | MAC_RNABLE_RX);
writel(value, ioaddr + MAC_CTRL_REG);
}
void stmmac_get_mac_addr(void __iomem *ioaddr, unsigned char *addr,
unsigned int high, unsigned int low)
{
unsigned int hi_addr, lo_addr;
/* Read the MAC address from the hardware */
hi_addr = readl(ioaddr + high);
lo_addr = readl(ioaddr + low);
/* Extract the MAC address from the high and low words */
addr[0] = lo_addr & 0xff;
addr[1] = (lo_addr >> 8) & 0xff;
addr[2] = (lo_addr >> 16) & 0xff;
addr[3] = (lo_addr >> 24) & 0xff;
addr[4] = hi_addr & 0xff;
addr[5] = (hi_addr >> 8) & 0xff;
}
| gpl-2.0 |
justin0406/MiRaGe-GEE | drivers/scsi/mpt2sas/mpt2sas_transport.c | 4896 | 61581 | /*
* SAS Transport Layer for MPT (Message Passing Technology) based controllers
*
* This code is based on drivers/scsi/mpt2sas/mpt2_transport.c
* Copyright (C) 2007-2010 LSI Corporation
* (mailto:DL-MPTFusionLinux@lsi.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* NO WARRANTY
* THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
* LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
* solely responsible for determining the appropriateness of using and
* distributing the Program and assumes all risks associated with its
* exercise of rights under this Agreement, including but not limited to
* the risks and costs of program errors, damage to or loss of data,
* programs or equipment, and unavailability or interruption of operations.
* DISCLAIMER OF LIABILITY
* NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
* HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_sas.h>
#include <scsi/scsi_dbg.h>
#include "mpt2sas_base.h"
/**
* _transport_sas_node_find_by_sas_address - sas node search
* @ioc: per adapter object
* @sas_address: sas address of expander or sas host
* Context: Calling function should acquire ioc->sas_node_lock.
*
* Search for either hba phys or expander device based on handle, then returns
* the sas_node object.
*/
static struct _sas_node *
_transport_sas_node_find_by_sas_address(struct MPT2SAS_ADAPTER *ioc,
u64 sas_address)
{
if (ioc->sas_hba.sas_address == sas_address)
return &ioc->sas_hba;
else
return mpt2sas_scsih_expander_find_by_sas_address(ioc,
sas_address);
}
/**
* _transport_convert_phy_link_rate -
* @link_rate: link rate returned from mpt firmware
*
* Convert link_rate from mpi fusion into sas_transport form.
*/
static enum sas_linkrate
_transport_convert_phy_link_rate(u8 link_rate)
{
enum sas_linkrate rc;
switch (link_rate) {
case MPI2_SAS_NEG_LINK_RATE_1_5:
rc = SAS_LINK_RATE_1_5_GBPS;
break;
case MPI2_SAS_NEG_LINK_RATE_3_0:
rc = SAS_LINK_RATE_3_0_GBPS;
break;
case MPI2_SAS_NEG_LINK_RATE_6_0:
rc = SAS_LINK_RATE_6_0_GBPS;
break;
case MPI2_SAS_NEG_LINK_RATE_PHY_DISABLED:
rc = SAS_PHY_DISABLED;
break;
case MPI2_SAS_NEG_LINK_RATE_NEGOTIATION_FAILED:
rc = SAS_LINK_RATE_FAILED;
break;
case MPI2_SAS_NEG_LINK_RATE_PORT_SELECTOR:
rc = SAS_SATA_PORT_SELECTOR;
break;
case MPI2_SAS_NEG_LINK_RATE_SMP_RESET_IN_PROGRESS:
rc = SAS_PHY_RESET_IN_PROGRESS;
break;
default:
case MPI2_SAS_NEG_LINK_RATE_SATA_OOB_COMPLETE:
case MPI2_SAS_NEG_LINK_RATE_UNKNOWN_LINK_RATE:
rc = SAS_LINK_RATE_UNKNOWN;
break;
}
return rc;
}
/**
* _transport_set_identify - set identify for phys and end devices
* @ioc: per adapter object
* @handle: device handle
* @identify: sas identify info
*
* Populates sas identify info.
*
* Returns 0 for success, non-zero for failure.
*/
static int
_transport_set_identify(struct MPT2SAS_ADAPTER *ioc, u16 handle,
struct sas_identify *identify)
{
Mpi2SasDevicePage0_t sas_device_pg0;
Mpi2ConfigReply_t mpi_reply;
u32 device_info;
u32 ioc_status;
if (ioc->shost_recovery || ioc->pci_error_recovery) {
printk(MPT2SAS_INFO_FMT "%s: host reset in progress!\n",
__func__, ioc->name);
return -EFAULT;
}
if ((mpt2sas_config_get_sas_device_pg0(ioc, &mpi_reply, &sas_device_pg0,
MPI2_SAS_DEVICE_PGAD_FORM_HANDLE, handle))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -ENXIO;
}
ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
MPI2_IOCSTATUS_MASK;
if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
printk(MPT2SAS_ERR_FMT "handle(0x%04x), ioc_status(0x%04x)"
"\nfailure at %s:%d/%s()!\n", ioc->name, handle, ioc_status,
__FILE__, __LINE__, __func__);
return -EIO;
}
memset(identify, 0, sizeof(*identify));
device_info = le32_to_cpu(sas_device_pg0.DeviceInfo);
/* sas_address */
identify->sas_address = le64_to_cpu(sas_device_pg0.SASAddress);
/* device_type */
switch (device_info & MPI2_SAS_DEVICE_INFO_MASK_DEVICE_TYPE) {
case MPI2_SAS_DEVICE_INFO_NO_DEVICE:
identify->device_type = SAS_PHY_UNUSED;
break;
case MPI2_SAS_DEVICE_INFO_END_DEVICE:
identify->device_type = SAS_END_DEVICE;
break;
case MPI2_SAS_DEVICE_INFO_EDGE_EXPANDER:
identify->device_type = SAS_EDGE_EXPANDER_DEVICE;
break;
case MPI2_SAS_DEVICE_INFO_FANOUT_EXPANDER:
identify->device_type = SAS_FANOUT_EXPANDER_DEVICE;
break;
}
/* initiator_port_protocols */
if (device_info & MPI2_SAS_DEVICE_INFO_SSP_INITIATOR)
identify->initiator_port_protocols |= SAS_PROTOCOL_SSP;
if (device_info & MPI2_SAS_DEVICE_INFO_STP_INITIATOR)
identify->initiator_port_protocols |= SAS_PROTOCOL_STP;
if (device_info & MPI2_SAS_DEVICE_INFO_SMP_INITIATOR)
identify->initiator_port_protocols |= SAS_PROTOCOL_SMP;
if (device_info & MPI2_SAS_DEVICE_INFO_SATA_HOST)
identify->initiator_port_protocols |= SAS_PROTOCOL_SATA;
/* target_port_protocols */
if (device_info & MPI2_SAS_DEVICE_INFO_SSP_TARGET)
identify->target_port_protocols |= SAS_PROTOCOL_SSP;
if (device_info & MPI2_SAS_DEVICE_INFO_STP_TARGET)
identify->target_port_protocols |= SAS_PROTOCOL_STP;
if (device_info & MPI2_SAS_DEVICE_INFO_SMP_TARGET)
identify->target_port_protocols |= SAS_PROTOCOL_SMP;
if (device_info & MPI2_SAS_DEVICE_INFO_SATA_DEVICE)
identify->target_port_protocols |= SAS_PROTOCOL_SATA;
return 0;
}
/**
* mpt2sas_transport_done - internal transport layer callback handler.
* @ioc: per adapter object
* @smid: system request message index
* @msix_index: MSIX table index supplied by the OS
* @reply: reply message frame(lower 32bit addr)
*
* Callback handler when sending internal generated transport cmds.
* The callback index passed is `ioc->transport_cb_idx`
*
* Return 1 meaning mf should be freed from _base_interrupt
* 0 means the mf is freed from this function.
*/
u8
mpt2sas_transport_done(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
u32 reply)
{
MPI2DefaultReply_t *mpi_reply;
mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
if (ioc->transport_cmds.status == MPT2_CMD_NOT_USED)
return 1;
if (ioc->transport_cmds.smid != smid)
return 1;
ioc->transport_cmds.status |= MPT2_CMD_COMPLETE;
if (mpi_reply) {
memcpy(ioc->transport_cmds.reply, mpi_reply,
mpi_reply->MsgLength*4);
ioc->transport_cmds.status |= MPT2_CMD_REPLY_VALID;
}
ioc->transport_cmds.status &= ~MPT2_CMD_PENDING;
complete(&ioc->transport_cmds.done);
return 1;
}
/* report manufacture request structure */
struct rep_manu_request{
u8 smp_frame_type;
u8 function;
u8 reserved;
u8 request_length;
};
/* report manufacture reply structure */
struct rep_manu_reply{
u8 smp_frame_type; /* 0x41 */
u8 function; /* 0x01 */
u8 function_result;
u8 response_length;
u16 expander_change_count;
u8 reserved0[2];
u8 sas_format;
u8 reserved2[3];
u8 vendor_id[SAS_EXPANDER_VENDOR_ID_LEN];
u8 product_id[SAS_EXPANDER_PRODUCT_ID_LEN];
u8 product_rev[SAS_EXPANDER_PRODUCT_REV_LEN];
u8 component_vendor_id[SAS_EXPANDER_COMPONENT_VENDOR_ID_LEN];
u16 component_id;
u8 component_revision_id;
u8 reserved3;
u8 vendor_specific[8];
};
/**
* _transport_expander_report_manufacture - obtain SMP report_manufacture
* @ioc: per adapter object
* @sas_address: expander sas address
* @edev: the sas_expander_device object
*
* Fills in the sas_expander_device object when SMP port is created.
*
* Returns 0 for success, non-zero for failure.
*/
static int
_transport_expander_report_manufacture(struct MPT2SAS_ADAPTER *ioc,
u64 sas_address, struct sas_expander_device *edev)
{
Mpi2SmpPassthroughRequest_t *mpi_request;
Mpi2SmpPassthroughReply_t *mpi_reply;
struct rep_manu_reply *manufacture_reply;
struct rep_manu_request *manufacture_request;
int rc;
u16 smid;
u32 ioc_state;
unsigned long timeleft;
void *psge;
u32 sgl_flags;
u8 issue_reset = 0;
void *data_out = NULL;
dma_addr_t data_out_dma;
u32 sz;
u16 wait_state_count;
if (ioc->shost_recovery || ioc->pci_error_recovery) {
printk(MPT2SAS_INFO_FMT "%s: host reset in progress!\n",
__func__, ioc->name);
return -EFAULT;
}
mutex_lock(&ioc->transport_cmds.mutex);
if (ioc->transport_cmds.status != MPT2_CMD_NOT_USED) {
printk(MPT2SAS_ERR_FMT "%s: transport_cmds in use\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
ioc->transport_cmds.status = MPT2_CMD_PENDING;
wait_state_count = 0;
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
if (wait_state_count++ == 10) {
printk(MPT2SAS_ERR_FMT
"%s: failed due to ioc not operational\n",
ioc->name, __func__);
rc = -EFAULT;
goto out;
}
ssleep(1);
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
printk(MPT2SAS_INFO_FMT "%s: waiting for "
"operational state(count=%d)\n", ioc->name,
__func__, wait_state_count);
}
if (wait_state_count)
printk(MPT2SAS_INFO_FMT "%s: ioc is operational\n",
ioc->name, __func__);
smid = mpt2sas_base_get_smid(ioc, ioc->transport_cb_idx);
if (!smid) {
printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
rc = 0;
mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
ioc->transport_cmds.smid = smid;
sz = sizeof(struct rep_manu_request) + sizeof(struct rep_manu_reply);
data_out = pci_alloc_consistent(ioc->pdev, sz, &data_out_dma);
if (!data_out) {
printk(KERN_ERR "failure at %s:%d/%s()!\n", __FILE__,
__LINE__, __func__);
rc = -ENOMEM;
mpt2sas_base_free_smid(ioc, smid);
goto out;
}
manufacture_request = data_out;
manufacture_request->smp_frame_type = 0x40;
manufacture_request->function = 1;
manufacture_request->reserved = 0;
manufacture_request->request_length = 0;
memset(mpi_request, 0, sizeof(Mpi2SmpPassthroughRequest_t));
mpi_request->Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
mpi_request->PhysicalPort = 0xFF;
mpi_request->VF_ID = 0; /* TODO */
mpi_request->VP_ID = 0;
mpi_request->SASAddress = cpu_to_le64(sas_address);
mpi_request->RequestDataLength =
cpu_to_le16(sizeof(struct rep_manu_request));
psge = &mpi_request->SGL;
/* WRITE sgel first */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
ioc->base_add_sg_single(psge, sgl_flags |
sizeof(struct rep_manu_request), data_out_dma);
/* incr sgel */
psge += ioc->sge_size;
/* READ sgel last */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
MPI2_SGE_FLAGS_END_OF_LIST);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
ioc->base_add_sg_single(psge, sgl_flags |
sizeof(struct rep_manu_reply), data_out_dma +
sizeof(struct rep_manu_request));
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "report_manufacture - "
"send to sas_addr(0x%016llx)\n", ioc->name,
(unsigned long long)sas_address));
init_completion(&ioc->transport_cmds.done);
mpt2sas_base_put_smid_default(ioc, smid);
timeleft = wait_for_completion_timeout(&ioc->transport_cmds.done,
10*HZ);
if (!(ioc->transport_cmds.status & MPT2_CMD_COMPLETE)) {
printk(MPT2SAS_ERR_FMT "%s: timeout\n",
ioc->name, __func__);
_debug_dump_mf(mpi_request,
sizeof(Mpi2SmpPassthroughRequest_t)/4);
if (!(ioc->transport_cmds.status & MPT2_CMD_RESET))
issue_reset = 1;
goto issue_host_reset;
}
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "report_manufacture - "
"complete\n", ioc->name));
if (ioc->transport_cmds.status & MPT2_CMD_REPLY_VALID) {
u8 *tmp;
mpi_reply = ioc->transport_cmds.reply;
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"report_manufacture - reply data transfer size(%d)\n",
ioc->name, le16_to_cpu(mpi_reply->ResponseDataLength)));
if (le16_to_cpu(mpi_reply->ResponseDataLength) !=
sizeof(struct rep_manu_reply))
goto out;
manufacture_reply = data_out + sizeof(struct rep_manu_request);
strncpy(edev->vendor_id, manufacture_reply->vendor_id,
SAS_EXPANDER_VENDOR_ID_LEN);
strncpy(edev->product_id, manufacture_reply->product_id,
SAS_EXPANDER_PRODUCT_ID_LEN);
strncpy(edev->product_rev, manufacture_reply->product_rev,
SAS_EXPANDER_PRODUCT_REV_LEN);
edev->level = manufacture_reply->sas_format & 1;
if (edev->level) {
strncpy(edev->component_vendor_id,
manufacture_reply->component_vendor_id,
SAS_EXPANDER_COMPONENT_VENDOR_ID_LEN);
tmp = (u8 *)&manufacture_reply->component_id;
edev->component_id = tmp[0] << 8 | tmp[1];
edev->component_revision_id =
manufacture_reply->component_revision_id;
}
} else
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"report_manufacture - no reply\n", ioc->name));
issue_host_reset:
if (issue_reset)
mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
FORCE_BIG_HAMMER);
out:
ioc->transport_cmds.status = MPT2_CMD_NOT_USED;
if (data_out)
pci_free_consistent(ioc->pdev, sz, data_out, data_out_dma);
mutex_unlock(&ioc->transport_cmds.mutex);
return rc;
}
/**
* _transport_delete_port - helper function to removing a port
* @ioc: per adapter object
* @mpt2sas_port: mpt2sas per port object
*
* Returns nothing.
*/
static void
_transport_delete_port(struct MPT2SAS_ADAPTER *ioc,
struct _sas_port *mpt2sas_port)
{
u64 sas_address = mpt2sas_port->remote_identify.sas_address;
enum sas_device_type device_type =
mpt2sas_port->remote_identify.device_type;
dev_printk(KERN_INFO, &mpt2sas_port->port->dev,
"remove: sas_addr(0x%016llx)\n",
(unsigned long long) sas_address);
ioc->logging_level |= MPT_DEBUG_TRANSPORT;
if (device_type == SAS_END_DEVICE)
mpt2sas_device_remove(ioc, sas_address);
else if (device_type == SAS_EDGE_EXPANDER_DEVICE ||
device_type == SAS_FANOUT_EXPANDER_DEVICE)
mpt2sas_expander_remove(ioc, sas_address);
ioc->logging_level &= ~MPT_DEBUG_TRANSPORT;
}
/**
* _transport_delete_phy - helper function to removing single phy from port
* @ioc: per adapter object
* @mpt2sas_port: mpt2sas per port object
* @mpt2sas_phy: mpt2sas per phy object
*
* Returns nothing.
*/
static void
_transport_delete_phy(struct MPT2SAS_ADAPTER *ioc,
struct _sas_port *mpt2sas_port, struct _sas_phy *mpt2sas_phy)
{
u64 sas_address = mpt2sas_port->remote_identify.sas_address;
dev_printk(KERN_INFO, &mpt2sas_phy->phy->dev,
"remove: sas_addr(0x%016llx), phy(%d)\n",
(unsigned long long) sas_address, mpt2sas_phy->phy_id);
list_del(&mpt2sas_phy->port_siblings);
mpt2sas_port->num_phys--;
sas_port_delete_phy(mpt2sas_port->port, mpt2sas_phy->phy);
mpt2sas_phy->phy_belongs_to_port = 0;
}
/**
* _transport_add_phy - helper function to adding single phy to port
* @ioc: per adapter object
* @mpt2sas_port: mpt2sas per port object
* @mpt2sas_phy: mpt2sas per phy object
*
* Returns nothing.
*/
static void
_transport_add_phy(struct MPT2SAS_ADAPTER *ioc, struct _sas_port *mpt2sas_port,
struct _sas_phy *mpt2sas_phy)
{
u64 sas_address = mpt2sas_port->remote_identify.sas_address;
dev_printk(KERN_INFO, &mpt2sas_phy->phy->dev,
"add: sas_addr(0x%016llx), phy(%d)\n", (unsigned long long)
sas_address, mpt2sas_phy->phy_id);
list_add_tail(&mpt2sas_phy->port_siblings, &mpt2sas_port->phy_list);
mpt2sas_port->num_phys++;
sas_port_add_phy(mpt2sas_port->port, mpt2sas_phy->phy);
mpt2sas_phy->phy_belongs_to_port = 1;
}
/**
* _transport_add_phy_to_an_existing_port - adding new phy to existing port
* @ioc: per adapter object
* @sas_node: sas node object (either expander or sas host)
* @mpt2sas_phy: mpt2sas per phy object
* @sas_address: sas address of device/expander were phy needs to be added to
*
* Returns nothing.
*/
static void
_transport_add_phy_to_an_existing_port(struct MPT2SAS_ADAPTER *ioc,
struct _sas_node *sas_node, struct _sas_phy *mpt2sas_phy, u64 sas_address)
{
struct _sas_port *mpt2sas_port;
struct _sas_phy *phy_srch;
if (mpt2sas_phy->phy_belongs_to_port == 1)
return;
list_for_each_entry(mpt2sas_port, &sas_node->sas_port_list,
port_list) {
if (mpt2sas_port->remote_identify.sas_address !=
sas_address)
continue;
list_for_each_entry(phy_srch, &mpt2sas_port->phy_list,
port_siblings) {
if (phy_srch == mpt2sas_phy)
return;
}
_transport_add_phy(ioc, mpt2sas_port, mpt2sas_phy);
return;
}
}
/**
* _transport_del_phy_from_an_existing_port - delete phy from existing port
* @ioc: per adapter object
* @sas_node: sas node object (either expander or sas host)
* @mpt2sas_phy: mpt2sas per phy object
*
* Returns nothing.
*/
static void
_transport_del_phy_from_an_existing_port(struct MPT2SAS_ADAPTER *ioc,
struct _sas_node *sas_node, struct _sas_phy *mpt2sas_phy)
{
struct _sas_port *mpt2sas_port, *next;
struct _sas_phy *phy_srch;
if (mpt2sas_phy->phy_belongs_to_port == 0)
return;
list_for_each_entry_safe(mpt2sas_port, next, &sas_node->sas_port_list,
port_list) {
list_for_each_entry(phy_srch, &mpt2sas_port->phy_list,
port_siblings) {
if (phy_srch != mpt2sas_phy)
continue;
if (mpt2sas_port->num_phys == 1)
_transport_delete_port(ioc, mpt2sas_port);
else
_transport_delete_phy(ioc, mpt2sas_port,
mpt2sas_phy);
return;
}
}
}
/**
* _transport_sanity_check - sanity check when adding a new port
* @ioc: per adapter object
* @sas_node: sas node object (either expander or sas host)
* @sas_address: sas address of device being added
*
* See the explanation above from _transport_delete_duplicate_port
*/
static void
_transport_sanity_check(struct MPT2SAS_ADAPTER *ioc, struct _sas_node *sas_node,
u64 sas_address)
{
int i;
for (i = 0; i < sas_node->num_phys; i++) {
if (sas_node->phy[i].remote_identify.sas_address != sas_address)
continue;
if (sas_node->phy[i].phy_belongs_to_port == 1)
_transport_del_phy_from_an_existing_port(ioc, sas_node,
&sas_node->phy[i]);
}
}
/**
* mpt2sas_transport_port_add - insert port to the list
* @ioc: per adapter object
* @handle: handle of attached device
* @sas_address: sas address of parent expander or sas host
* Context: This function will acquire ioc->sas_node_lock.
*
* Adding new port object to the sas_node->sas_port_list.
*
* Returns mpt2sas_port.
*/
struct _sas_port *
mpt2sas_transport_port_add(struct MPT2SAS_ADAPTER *ioc, u16 handle,
u64 sas_address)
{
struct _sas_phy *mpt2sas_phy, *next;
struct _sas_port *mpt2sas_port;
unsigned long flags;
struct _sas_node *sas_node;
struct sas_rphy *rphy;
int i;
struct sas_port *port;
mpt2sas_port = kzalloc(sizeof(struct _sas_port),
GFP_KERNEL);
if (!mpt2sas_port) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return NULL;
}
INIT_LIST_HEAD(&mpt2sas_port->port_list);
INIT_LIST_HEAD(&mpt2sas_port->phy_list);
spin_lock_irqsave(&ioc->sas_node_lock, flags);
sas_node = _transport_sas_node_find_by_sas_address(ioc, sas_address);
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
if (!sas_node) {
printk(MPT2SAS_ERR_FMT "%s: Could not find "
"parent sas_address(0x%016llx)!\n", ioc->name,
__func__, (unsigned long long)sas_address);
goto out_fail;
}
if ((_transport_set_identify(ioc, handle,
&mpt2sas_port->remote_identify))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
goto out_fail;
}
if (mpt2sas_port->remote_identify.device_type == SAS_PHY_UNUSED) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
goto out_fail;
}
_transport_sanity_check(ioc, sas_node,
mpt2sas_port->remote_identify.sas_address);
for (i = 0; i < sas_node->num_phys; i++) {
if (sas_node->phy[i].remote_identify.sas_address !=
mpt2sas_port->remote_identify.sas_address)
continue;
list_add_tail(&sas_node->phy[i].port_siblings,
&mpt2sas_port->phy_list);
mpt2sas_port->num_phys++;
}
if (!mpt2sas_port->num_phys) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
goto out_fail;
}
port = sas_port_alloc_num(sas_node->parent_dev);
if ((sas_port_add(port))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
goto out_fail;
}
list_for_each_entry(mpt2sas_phy, &mpt2sas_port->phy_list,
port_siblings) {
if ((ioc->logging_level & MPT_DEBUG_TRANSPORT))
dev_printk(KERN_INFO, &port->dev, "add: handle(0x%04x)"
", sas_addr(0x%016llx), phy(%d)\n", handle,
(unsigned long long)
mpt2sas_port->remote_identify.sas_address,
mpt2sas_phy->phy_id);
sas_port_add_phy(port, mpt2sas_phy->phy);
mpt2sas_phy->phy_belongs_to_port = 1;
}
mpt2sas_port->port = port;
if (mpt2sas_port->remote_identify.device_type == SAS_END_DEVICE)
rphy = sas_end_device_alloc(port);
else
rphy = sas_expander_alloc(port,
mpt2sas_port->remote_identify.device_type);
rphy->identify = mpt2sas_port->remote_identify;
if ((sas_rphy_add(rphy))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
}
if ((ioc->logging_level & MPT_DEBUG_TRANSPORT))
dev_printk(KERN_INFO, &rphy->dev, "add: handle(0x%04x), "
"sas_addr(0x%016llx)\n", handle,
(unsigned long long)
mpt2sas_port->remote_identify.sas_address);
mpt2sas_port->rphy = rphy;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
list_add_tail(&mpt2sas_port->port_list, &sas_node->sas_port_list);
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
/* fill in report manufacture */
if (mpt2sas_port->remote_identify.device_type ==
MPI2_SAS_DEVICE_INFO_EDGE_EXPANDER ||
mpt2sas_port->remote_identify.device_type ==
MPI2_SAS_DEVICE_INFO_FANOUT_EXPANDER)
_transport_expander_report_manufacture(ioc,
mpt2sas_port->remote_identify.sas_address,
rphy_to_expander_device(rphy));
return mpt2sas_port;
out_fail:
list_for_each_entry_safe(mpt2sas_phy, next, &mpt2sas_port->phy_list,
port_siblings)
list_del(&mpt2sas_phy->port_siblings);
kfree(mpt2sas_port);
return NULL;
}
/**
* mpt2sas_transport_port_remove - remove port from the list
* @ioc: per adapter object
* @sas_address: sas address of attached device
* @sas_address_parent: sas address of parent expander or sas host
* Context: This function will acquire ioc->sas_node_lock.
*
* Removing object and freeing associated memory from the
* ioc->sas_port_list.
*
* Return nothing.
*/
void
mpt2sas_transport_port_remove(struct MPT2SAS_ADAPTER *ioc, u64 sas_address,
u64 sas_address_parent)
{
int i;
unsigned long flags;
struct _sas_port *mpt2sas_port, *next;
struct _sas_node *sas_node;
u8 found = 0;
struct _sas_phy *mpt2sas_phy, *next_phy;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
sas_node = _transport_sas_node_find_by_sas_address(ioc,
sas_address_parent);
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
if (!sas_node)
return;
list_for_each_entry_safe(mpt2sas_port, next, &sas_node->sas_port_list,
port_list) {
if (mpt2sas_port->remote_identify.sas_address != sas_address)
continue;
found = 1;
list_del(&mpt2sas_port->port_list);
goto out;
}
out:
if (!found)
return;
for (i = 0; i < sas_node->num_phys; i++) {
if (sas_node->phy[i].remote_identify.sas_address == sas_address)
memset(&sas_node->phy[i].remote_identify, 0 ,
sizeof(struct sas_identify));
}
list_for_each_entry_safe(mpt2sas_phy, next_phy,
&mpt2sas_port->phy_list, port_siblings) {
if ((ioc->logging_level & MPT_DEBUG_TRANSPORT))
dev_printk(KERN_INFO, &mpt2sas_port->port->dev,
"remove: sas_addr(0x%016llx), phy(%d)\n",
(unsigned long long)
mpt2sas_port->remote_identify.sas_address,
mpt2sas_phy->phy_id);
mpt2sas_phy->phy_belongs_to_port = 0;
sas_port_delete_phy(mpt2sas_port->port, mpt2sas_phy->phy);
list_del(&mpt2sas_phy->port_siblings);
}
sas_port_delete(mpt2sas_port->port);
kfree(mpt2sas_port);
}
/**
* mpt2sas_transport_add_host_phy - report sas_host phy to transport
* @ioc: per adapter object
* @mpt2sas_phy: mpt2sas per phy object
* @phy_pg0: sas phy page 0
* @parent_dev: parent device class object
*
* Returns 0 for success, non-zero for failure.
*/
int
mpt2sas_transport_add_host_phy(struct MPT2SAS_ADAPTER *ioc, struct _sas_phy
*mpt2sas_phy, Mpi2SasPhyPage0_t phy_pg0, struct device *parent_dev)
{
struct sas_phy *phy;
int phy_index = mpt2sas_phy->phy_id;
INIT_LIST_HEAD(&mpt2sas_phy->port_siblings);
phy = sas_phy_alloc(parent_dev, phy_index);
if (!phy) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -1;
}
if ((_transport_set_identify(ioc, mpt2sas_phy->handle,
&mpt2sas_phy->identify))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -1;
}
phy->identify = mpt2sas_phy->identify;
mpt2sas_phy->attached_handle = le16_to_cpu(phy_pg0.AttachedDevHandle);
if (mpt2sas_phy->attached_handle)
_transport_set_identify(ioc, mpt2sas_phy->attached_handle,
&mpt2sas_phy->remote_identify);
phy->identify.phy_identifier = mpt2sas_phy->phy_id;
phy->negotiated_linkrate = _transport_convert_phy_link_rate(
phy_pg0.NegotiatedLinkRate & MPI2_SAS_NEG_LINK_RATE_MASK_PHYSICAL);
phy->minimum_linkrate_hw = _transport_convert_phy_link_rate(
phy_pg0.HwLinkRate & MPI2_SAS_HWRATE_MIN_RATE_MASK);
phy->maximum_linkrate_hw = _transport_convert_phy_link_rate(
phy_pg0.HwLinkRate >> 4);
phy->minimum_linkrate = _transport_convert_phy_link_rate(
phy_pg0.ProgrammedLinkRate & MPI2_SAS_PRATE_MIN_RATE_MASK);
phy->maximum_linkrate = _transport_convert_phy_link_rate(
phy_pg0.ProgrammedLinkRate >> 4);
if ((sas_phy_add(phy))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
sas_phy_free(phy);
return -1;
}
if ((ioc->logging_level & MPT_DEBUG_TRANSPORT))
dev_printk(KERN_INFO, &phy->dev,
"add: handle(0x%04x), sas_addr(0x%016llx)\n"
"\tattached_handle(0x%04x), sas_addr(0x%016llx)\n",
mpt2sas_phy->handle, (unsigned long long)
mpt2sas_phy->identify.sas_address,
mpt2sas_phy->attached_handle,
(unsigned long long)
mpt2sas_phy->remote_identify.sas_address);
mpt2sas_phy->phy = phy;
return 0;
}
/**
* mpt2sas_transport_add_expander_phy - report expander phy to transport
* @ioc: per adapter object
* @mpt2sas_phy: mpt2sas per phy object
* @expander_pg1: expander page 1
* @parent_dev: parent device class object
*
* Returns 0 for success, non-zero for failure.
*/
int
mpt2sas_transport_add_expander_phy(struct MPT2SAS_ADAPTER *ioc, struct _sas_phy
*mpt2sas_phy, Mpi2ExpanderPage1_t expander_pg1, struct device *parent_dev)
{
struct sas_phy *phy;
int phy_index = mpt2sas_phy->phy_id;
INIT_LIST_HEAD(&mpt2sas_phy->port_siblings);
phy = sas_phy_alloc(parent_dev, phy_index);
if (!phy) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -1;
}
if ((_transport_set_identify(ioc, mpt2sas_phy->handle,
&mpt2sas_phy->identify))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -1;
}
phy->identify = mpt2sas_phy->identify;
mpt2sas_phy->attached_handle =
le16_to_cpu(expander_pg1.AttachedDevHandle);
if (mpt2sas_phy->attached_handle)
_transport_set_identify(ioc, mpt2sas_phy->attached_handle,
&mpt2sas_phy->remote_identify);
phy->identify.phy_identifier = mpt2sas_phy->phy_id;
phy->negotiated_linkrate = _transport_convert_phy_link_rate(
expander_pg1.NegotiatedLinkRate &
MPI2_SAS_NEG_LINK_RATE_MASK_PHYSICAL);
phy->minimum_linkrate_hw = _transport_convert_phy_link_rate(
expander_pg1.HwLinkRate & MPI2_SAS_HWRATE_MIN_RATE_MASK);
phy->maximum_linkrate_hw = _transport_convert_phy_link_rate(
expander_pg1.HwLinkRate >> 4);
phy->minimum_linkrate = _transport_convert_phy_link_rate(
expander_pg1.ProgrammedLinkRate & MPI2_SAS_PRATE_MIN_RATE_MASK);
phy->maximum_linkrate = _transport_convert_phy_link_rate(
expander_pg1.ProgrammedLinkRate >> 4);
if ((sas_phy_add(phy))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
sas_phy_free(phy);
return -1;
}
if ((ioc->logging_level & MPT_DEBUG_TRANSPORT))
dev_printk(KERN_INFO, &phy->dev,
"add: handle(0x%04x), sas_addr(0x%016llx)\n"
"\tattached_handle(0x%04x), sas_addr(0x%016llx)\n",
mpt2sas_phy->handle, (unsigned long long)
mpt2sas_phy->identify.sas_address,
mpt2sas_phy->attached_handle,
(unsigned long long)
mpt2sas_phy->remote_identify.sas_address);
mpt2sas_phy->phy = phy;
return 0;
}
/**
* mpt2sas_transport_update_links - refreshing phy link changes
* @ioc: per adapter object
* @sas_address: sas address of parent expander or sas host
* @handle: attached device handle
* @phy_numberv: phy number
* @link_rate: new link rate
*
* Returns nothing.
*/
void
mpt2sas_transport_update_links(struct MPT2SAS_ADAPTER *ioc,
u64 sas_address, u16 handle, u8 phy_number, u8 link_rate)
{
unsigned long flags;
struct _sas_node *sas_node;
struct _sas_phy *mpt2sas_phy;
if (ioc->shost_recovery || ioc->pci_error_recovery)
return;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
sas_node = _transport_sas_node_find_by_sas_address(ioc, sas_address);
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
if (!sas_node)
return;
mpt2sas_phy = &sas_node->phy[phy_number];
mpt2sas_phy->attached_handle = handle;
if (handle && (link_rate >= MPI2_SAS_NEG_LINK_RATE_1_5)) {
_transport_set_identify(ioc, handle,
&mpt2sas_phy->remote_identify);
_transport_add_phy_to_an_existing_port(ioc, sas_node,
mpt2sas_phy, mpt2sas_phy->remote_identify.sas_address);
} else
memset(&mpt2sas_phy->remote_identify, 0 , sizeof(struct
sas_identify));
if (mpt2sas_phy->phy)
mpt2sas_phy->phy->negotiated_linkrate =
_transport_convert_phy_link_rate(link_rate);
if ((ioc->logging_level & MPT_DEBUG_TRANSPORT))
dev_printk(KERN_INFO, &mpt2sas_phy->phy->dev,
"refresh: parent sas_addr(0x%016llx),\n"
"\tlink_rate(0x%02x), phy(%d)\n"
"\tattached_handle(0x%04x), sas_addr(0x%016llx)\n",
(unsigned long long)sas_address,
link_rate, phy_number, handle, (unsigned long long)
mpt2sas_phy->remote_identify.sas_address);
}
static inline void *
phy_to_ioc(struct sas_phy *phy)
{
struct Scsi_Host *shost = dev_to_shost(phy->dev.parent);
return shost_priv(shost);
}
static inline void *
rphy_to_ioc(struct sas_rphy *rphy)
{
struct Scsi_Host *shost = dev_to_shost(rphy->dev.parent->parent);
return shost_priv(shost);
}
/* report phy error log structure */
struct phy_error_log_request{
u8 smp_frame_type; /* 0x40 */
u8 function; /* 0x11 */
u8 allocated_response_length;
u8 request_length; /* 02 */
u8 reserved_1[5];
u8 phy_identifier;
u8 reserved_2[2];
};
/* report phy error log reply structure */
struct phy_error_log_reply{
u8 smp_frame_type; /* 0x41 */
u8 function; /* 0x11 */
u8 function_result;
u8 response_length;
__be16 expander_change_count;
u8 reserved_1[3];
u8 phy_identifier;
u8 reserved_2[2];
__be32 invalid_dword;
__be32 running_disparity_error;
__be32 loss_of_dword_sync;
__be32 phy_reset_problem;
};
/**
* _transport_get_expander_phy_error_log - return expander counters
* @ioc: per adapter object
* @phy: The sas phy object
*
* Returns 0 for success, non-zero for failure.
*
*/
static int
_transport_get_expander_phy_error_log(struct MPT2SAS_ADAPTER *ioc,
struct sas_phy *phy)
{
Mpi2SmpPassthroughRequest_t *mpi_request;
Mpi2SmpPassthroughReply_t *mpi_reply;
struct phy_error_log_request *phy_error_log_request;
struct phy_error_log_reply *phy_error_log_reply;
int rc;
u16 smid;
u32 ioc_state;
unsigned long timeleft;
void *psge;
u32 sgl_flags;
u8 issue_reset = 0;
void *data_out = NULL;
dma_addr_t data_out_dma;
u32 sz;
u16 wait_state_count;
if (ioc->shost_recovery || ioc->pci_error_recovery) {
printk(MPT2SAS_INFO_FMT "%s: host reset in progress!\n",
__func__, ioc->name);
return -EFAULT;
}
mutex_lock(&ioc->transport_cmds.mutex);
if (ioc->transport_cmds.status != MPT2_CMD_NOT_USED) {
printk(MPT2SAS_ERR_FMT "%s: transport_cmds in use\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
ioc->transport_cmds.status = MPT2_CMD_PENDING;
wait_state_count = 0;
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
if (wait_state_count++ == 10) {
printk(MPT2SAS_ERR_FMT
"%s: failed due to ioc not operational\n",
ioc->name, __func__);
rc = -EFAULT;
goto out;
}
ssleep(1);
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
printk(MPT2SAS_INFO_FMT "%s: waiting for "
"operational state(count=%d)\n", ioc->name,
__func__, wait_state_count);
}
if (wait_state_count)
printk(MPT2SAS_INFO_FMT "%s: ioc is operational\n",
ioc->name, __func__);
smid = mpt2sas_base_get_smid(ioc, ioc->transport_cb_idx);
if (!smid) {
printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
ioc->transport_cmds.smid = smid;
sz = sizeof(struct phy_error_log_request) +
sizeof(struct phy_error_log_reply);
data_out = pci_alloc_consistent(ioc->pdev, sz, &data_out_dma);
if (!data_out) {
printk(KERN_ERR "failure at %s:%d/%s()!\n", __FILE__,
__LINE__, __func__);
rc = -ENOMEM;
mpt2sas_base_free_smid(ioc, smid);
goto out;
}
rc = -EINVAL;
memset(data_out, 0, sz);
phy_error_log_request = data_out;
phy_error_log_request->smp_frame_type = 0x40;
phy_error_log_request->function = 0x11;
phy_error_log_request->request_length = 2;
phy_error_log_request->allocated_response_length = 0;
phy_error_log_request->phy_identifier = phy->number;
memset(mpi_request, 0, sizeof(Mpi2SmpPassthroughRequest_t));
mpi_request->Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
mpi_request->PhysicalPort = 0xFF;
mpi_request->VF_ID = 0; /* TODO */
mpi_request->VP_ID = 0;
mpi_request->SASAddress = cpu_to_le64(phy->identify.sas_address);
mpi_request->RequestDataLength =
cpu_to_le16(sizeof(struct phy_error_log_request));
psge = &mpi_request->SGL;
/* WRITE sgel first */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
ioc->base_add_sg_single(psge, sgl_flags |
sizeof(struct phy_error_log_request), data_out_dma);
/* incr sgel */
psge += ioc->sge_size;
/* READ sgel last */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
MPI2_SGE_FLAGS_END_OF_LIST);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
ioc->base_add_sg_single(psge, sgl_flags |
sizeof(struct phy_error_log_reply), data_out_dma +
sizeof(struct phy_error_log_request));
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "phy_error_log - "
"send to sas_addr(0x%016llx), phy(%d)\n", ioc->name,
(unsigned long long)phy->identify.sas_address, phy->number));
init_completion(&ioc->transport_cmds.done);
mpt2sas_base_put_smid_default(ioc, smid);
timeleft = wait_for_completion_timeout(&ioc->transport_cmds.done,
10*HZ);
if (!(ioc->transport_cmds.status & MPT2_CMD_COMPLETE)) {
printk(MPT2SAS_ERR_FMT "%s: timeout\n",
ioc->name, __func__);
_debug_dump_mf(mpi_request,
sizeof(Mpi2SmpPassthroughRequest_t)/4);
if (!(ioc->transport_cmds.status & MPT2_CMD_RESET))
issue_reset = 1;
goto issue_host_reset;
}
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "phy_error_log - "
"complete\n", ioc->name));
if (ioc->transport_cmds.status & MPT2_CMD_REPLY_VALID) {
mpi_reply = ioc->transport_cmds.reply;
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"phy_error_log - reply data transfer size(%d)\n",
ioc->name, le16_to_cpu(mpi_reply->ResponseDataLength)));
if (le16_to_cpu(mpi_reply->ResponseDataLength) !=
sizeof(struct phy_error_log_reply))
goto out;
phy_error_log_reply = data_out +
sizeof(struct phy_error_log_request);
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"phy_error_log - function_result(%d)\n",
ioc->name, phy_error_log_reply->function_result));
phy->invalid_dword_count =
be32_to_cpu(phy_error_log_reply->invalid_dword);
phy->running_disparity_error_count =
be32_to_cpu(phy_error_log_reply->running_disparity_error);
phy->loss_of_dword_sync_count =
be32_to_cpu(phy_error_log_reply->loss_of_dword_sync);
phy->phy_reset_problem_count =
be32_to_cpu(phy_error_log_reply->phy_reset_problem);
rc = 0;
} else
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"phy_error_log - no reply\n", ioc->name));
issue_host_reset:
if (issue_reset)
mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
FORCE_BIG_HAMMER);
out:
ioc->transport_cmds.status = MPT2_CMD_NOT_USED;
if (data_out)
pci_free_consistent(ioc->pdev, sz, data_out, data_out_dma);
mutex_unlock(&ioc->transport_cmds.mutex);
return rc;
}
/**
* _transport_get_linkerrors - return phy counters for both hba and expanders
* @phy: The sas phy object
*
* Returns 0 for success, non-zero for failure.
*
*/
static int
_transport_get_linkerrors(struct sas_phy *phy)
{
struct MPT2SAS_ADAPTER *ioc = phy_to_ioc(phy);
unsigned long flags;
Mpi2ConfigReply_t mpi_reply;
Mpi2SasPhyPage1_t phy_pg1;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
if (_transport_sas_node_find_by_sas_address(ioc,
phy->identify.sas_address) == NULL) {
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
return -EINVAL;
}
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
if (phy->identify.sas_address != ioc->sas_hba.sas_address)
return _transport_get_expander_phy_error_log(ioc, phy);
/* get hba phy error logs */
if ((mpt2sas_config_get_phy_pg1(ioc, &mpi_reply, &phy_pg1,
phy->number))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -ENXIO;
}
if (mpi_reply.IOCStatus || mpi_reply.IOCLogInfo)
printk(MPT2SAS_INFO_FMT "phy(%d), ioc_status"
"(0x%04x), loginfo(0x%08x)\n", ioc->name,
phy->number, le16_to_cpu(mpi_reply.IOCStatus),
le32_to_cpu(mpi_reply.IOCLogInfo));
phy->invalid_dword_count = le32_to_cpu(phy_pg1.InvalidDwordCount);
phy->running_disparity_error_count =
le32_to_cpu(phy_pg1.RunningDisparityErrorCount);
phy->loss_of_dword_sync_count =
le32_to_cpu(phy_pg1.LossDwordSynchCount);
phy->phy_reset_problem_count =
le32_to_cpu(phy_pg1.PhyResetProblemCount);
return 0;
}
/**
* _transport_get_enclosure_identifier -
* @phy: The sas phy object
*
* Obtain the enclosure logical id for an expander.
* Returns 0 for success, non-zero for failure.
*/
static int
_transport_get_enclosure_identifier(struct sas_rphy *rphy, u64 *identifier)
{
struct MPT2SAS_ADAPTER *ioc = rphy_to_ioc(rphy);
struct _sas_device *sas_device;
unsigned long flags;
spin_lock_irqsave(&ioc->sas_device_lock, flags);
sas_device = mpt2sas_scsih_sas_device_find_by_sas_address(ioc,
rphy->identify.sas_address);
spin_unlock_irqrestore(&ioc->sas_device_lock, flags);
if (!sas_device)
return -ENXIO;
*identifier = sas_device->enclosure_logical_id;
return 0;
}
/**
* _transport_get_bay_identifier -
* @phy: The sas phy object
*
* Returns the slot id for a device that resides inside an enclosure.
*/
static int
_transport_get_bay_identifier(struct sas_rphy *rphy)
{
struct MPT2SAS_ADAPTER *ioc = rphy_to_ioc(rphy);
struct _sas_device *sas_device;
unsigned long flags;
spin_lock_irqsave(&ioc->sas_device_lock, flags);
sas_device = mpt2sas_scsih_sas_device_find_by_sas_address(ioc,
rphy->identify.sas_address);
spin_unlock_irqrestore(&ioc->sas_device_lock, flags);
if (!sas_device)
return -ENXIO;
return sas_device->slot;
}
/* phy control request structure */
struct phy_control_request{
u8 smp_frame_type; /* 0x40 */
u8 function; /* 0x91 */
u8 allocated_response_length;
u8 request_length; /* 0x09 */
u16 expander_change_count;
u8 reserved_1[3];
u8 phy_identifier;
u8 phy_operation;
u8 reserved_2[13];
u64 attached_device_name;
u8 programmed_min_physical_link_rate;
u8 programmed_max_physical_link_rate;
u8 reserved_3[6];
};
/* phy control reply structure */
struct phy_control_reply{
u8 smp_frame_type; /* 0x41 */
u8 function; /* 0x11 */
u8 function_result;
u8 response_length;
};
#define SMP_PHY_CONTROL_LINK_RESET (0x01)
#define SMP_PHY_CONTROL_HARD_RESET (0x02)
#define SMP_PHY_CONTROL_DISABLE (0x03)
/**
* _transport_expander_phy_control - expander phy control
* @ioc: per adapter object
* @phy: The sas phy object
*
* Returns 0 for success, non-zero for failure.
*
*/
static int
_transport_expander_phy_control(struct MPT2SAS_ADAPTER *ioc,
struct sas_phy *phy, u8 phy_operation)
{
Mpi2SmpPassthroughRequest_t *mpi_request;
Mpi2SmpPassthroughReply_t *mpi_reply;
struct phy_control_request *phy_control_request;
struct phy_control_reply *phy_control_reply;
int rc;
u16 smid;
u32 ioc_state;
unsigned long timeleft;
void *psge;
u32 sgl_flags;
u8 issue_reset = 0;
void *data_out = NULL;
dma_addr_t data_out_dma;
u32 sz;
u16 wait_state_count;
if (ioc->shost_recovery) {
printk(MPT2SAS_INFO_FMT "%s: host reset in progress!\n",
__func__, ioc->name);
return -EFAULT;
}
mutex_lock(&ioc->transport_cmds.mutex);
if (ioc->transport_cmds.status != MPT2_CMD_NOT_USED) {
printk(MPT2SAS_ERR_FMT "%s: transport_cmds in use\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
ioc->transport_cmds.status = MPT2_CMD_PENDING;
wait_state_count = 0;
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
if (wait_state_count++ == 10) {
printk(MPT2SAS_ERR_FMT
"%s: failed due to ioc not operational\n",
ioc->name, __func__);
rc = -EFAULT;
goto out;
}
ssleep(1);
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
printk(MPT2SAS_INFO_FMT "%s: waiting for "
"operational state(count=%d)\n", ioc->name,
__func__, wait_state_count);
}
if (wait_state_count)
printk(MPT2SAS_INFO_FMT "%s: ioc is operational\n",
ioc->name, __func__);
smid = mpt2sas_base_get_smid(ioc, ioc->transport_cb_idx);
if (!smid) {
printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
ioc->transport_cmds.smid = smid;
sz = sizeof(struct phy_control_request) +
sizeof(struct phy_control_reply);
data_out = pci_alloc_consistent(ioc->pdev, sz, &data_out_dma);
if (!data_out) {
printk(KERN_ERR "failure at %s:%d/%s()!\n", __FILE__,
__LINE__, __func__);
rc = -ENOMEM;
mpt2sas_base_free_smid(ioc, smid);
goto out;
}
rc = -EINVAL;
memset(data_out, 0, sz);
phy_control_request = data_out;
phy_control_request->smp_frame_type = 0x40;
phy_control_request->function = 0x91;
phy_control_request->request_length = 9;
phy_control_request->allocated_response_length = 0;
phy_control_request->phy_identifier = phy->number;
phy_control_request->phy_operation = phy_operation;
phy_control_request->programmed_min_physical_link_rate =
phy->minimum_linkrate << 4;
phy_control_request->programmed_max_physical_link_rate =
phy->maximum_linkrate << 4;
memset(mpi_request, 0, sizeof(Mpi2SmpPassthroughRequest_t));
mpi_request->Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
mpi_request->PhysicalPort = 0xFF;
mpi_request->VF_ID = 0; /* TODO */
mpi_request->VP_ID = 0;
mpi_request->SASAddress = cpu_to_le64(phy->identify.sas_address);
mpi_request->RequestDataLength =
cpu_to_le16(sizeof(struct phy_error_log_request));
psge = &mpi_request->SGL;
/* WRITE sgel first */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
ioc->base_add_sg_single(psge, sgl_flags |
sizeof(struct phy_control_request), data_out_dma);
/* incr sgel */
psge += ioc->sge_size;
/* READ sgel last */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
MPI2_SGE_FLAGS_END_OF_LIST);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
ioc->base_add_sg_single(psge, sgl_flags |
sizeof(struct phy_control_reply), data_out_dma +
sizeof(struct phy_control_request));
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "phy_control - "
"send to sas_addr(0x%016llx), phy(%d), opcode(%d)\n", ioc->name,
(unsigned long long)phy->identify.sas_address, phy->number,
phy_operation));
init_completion(&ioc->transport_cmds.done);
mpt2sas_base_put_smid_default(ioc, smid);
timeleft = wait_for_completion_timeout(&ioc->transport_cmds.done,
10*HZ);
if (!(ioc->transport_cmds.status & MPT2_CMD_COMPLETE)) {
printk(MPT2SAS_ERR_FMT "%s: timeout\n",
ioc->name, __func__);
_debug_dump_mf(mpi_request,
sizeof(Mpi2SmpPassthroughRequest_t)/4);
if (!(ioc->transport_cmds.status & MPT2_CMD_RESET))
issue_reset = 1;
goto issue_host_reset;
}
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "phy_control - "
"complete\n", ioc->name));
if (ioc->transport_cmds.status & MPT2_CMD_REPLY_VALID) {
mpi_reply = ioc->transport_cmds.reply;
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"phy_control - reply data transfer size(%d)\n",
ioc->name, le16_to_cpu(mpi_reply->ResponseDataLength)));
if (le16_to_cpu(mpi_reply->ResponseDataLength) !=
sizeof(struct phy_control_reply))
goto out;
phy_control_reply = data_out +
sizeof(struct phy_control_request);
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"phy_control - function_result(%d)\n",
ioc->name, phy_control_reply->function_result));
rc = 0;
} else
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"phy_control - no reply\n", ioc->name));
issue_host_reset:
if (issue_reset)
mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
FORCE_BIG_HAMMER);
out:
ioc->transport_cmds.status = MPT2_CMD_NOT_USED;
if (data_out)
pci_free_consistent(ioc->pdev, sz, data_out, data_out_dma);
mutex_unlock(&ioc->transport_cmds.mutex);
return rc;
}
/**
* _transport_phy_reset -
* @phy: The sas phy object
* @hard_reset:
*
* Returns 0 for success, non-zero for failure.
*/
static int
_transport_phy_reset(struct sas_phy *phy, int hard_reset)
{
struct MPT2SAS_ADAPTER *ioc = phy_to_ioc(phy);
Mpi2SasIoUnitControlReply_t mpi_reply;
Mpi2SasIoUnitControlRequest_t mpi_request;
unsigned long flags;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
if (_transport_sas_node_find_by_sas_address(ioc,
phy->identify.sas_address) == NULL) {
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
return -EINVAL;
}
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
/* handle expander phys */
if (phy->identify.sas_address != ioc->sas_hba.sas_address)
return _transport_expander_phy_control(ioc, phy,
(hard_reset == 1) ? SMP_PHY_CONTROL_HARD_RESET :
SMP_PHY_CONTROL_LINK_RESET);
/* handle hba phys */
memset(&mpi_request, 0, sizeof(Mpi2SasIoUnitControlReply_t));
mpi_request.Function = MPI2_FUNCTION_SAS_IO_UNIT_CONTROL;
mpi_request.Operation = hard_reset ?
MPI2_SAS_OP_PHY_HARD_RESET : MPI2_SAS_OP_PHY_LINK_RESET;
mpi_request.PhyNum = phy->number;
if ((mpt2sas_base_sas_iounit_control(ioc, &mpi_reply, &mpi_request))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
return -ENXIO;
}
if (mpi_reply.IOCStatus || mpi_reply.IOCLogInfo)
printk(MPT2SAS_INFO_FMT "phy(%d), ioc_status"
"(0x%04x), loginfo(0x%08x)\n", ioc->name,
phy->number, le16_to_cpu(mpi_reply.IOCStatus),
le32_to_cpu(mpi_reply.IOCLogInfo));
return 0;
}
/**
* _transport_phy_enable - enable/disable phys
* @phy: The sas phy object
* @enable: enable phy when true
*
* Only support sas_host direct attached phys.
* Returns 0 for success, non-zero for failure.
*/
static int
_transport_phy_enable(struct sas_phy *phy, int enable)
{
struct MPT2SAS_ADAPTER *ioc = phy_to_ioc(phy);
Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
Mpi2ConfigReply_t mpi_reply;
u16 ioc_status;
u16 sz;
int rc = 0;
unsigned long flags;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
if (_transport_sas_node_find_by_sas_address(ioc,
phy->identify.sas_address) == NULL) {
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
return -EINVAL;
}
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
/* handle expander phys */
if (phy->identify.sas_address != ioc->sas_hba.sas_address)
return _transport_expander_phy_control(ioc, phy,
(enable == 1) ? SMP_PHY_CONTROL_LINK_RESET :
SMP_PHY_CONTROL_DISABLE);
/* handle hba phys */
/* sas_iounit page 1 */
sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (ioc->sas_hba.num_phys *
sizeof(Mpi2SasIOUnit1PhyData_t));
sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
if (!sas_iounit_pg1) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -ENOMEM;
goto out;
}
if ((mpt2sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
sas_iounit_pg1, sz))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -ENXIO;
goto out;
}
ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
MPI2_IOCSTATUS_MASK;
if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -EIO;
goto out;
}
if (enable)
sas_iounit_pg1->PhyData[phy->number].PhyFlags
&= ~MPI2_SASIOUNIT1_PHYFLAGS_PHY_DISABLE;
else
sas_iounit_pg1->PhyData[phy->number].PhyFlags
|= MPI2_SASIOUNIT1_PHYFLAGS_PHY_DISABLE;
mpt2sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1, sz);
/* link reset */
if (enable)
_transport_phy_reset(phy, 0);
out:
kfree(sas_iounit_pg1);
return rc;
}
/**
* _transport_phy_speed - set phy min/max link rates
* @phy: The sas phy object
* @rates: rates defined in sas_phy_linkrates
*
* Only support sas_host direct attached phys.
* Returns 0 for success, non-zero for failure.
*/
static int
_transport_phy_speed(struct sas_phy *phy, struct sas_phy_linkrates *rates)
{
struct MPT2SAS_ADAPTER *ioc = phy_to_ioc(phy);
Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
Mpi2SasPhyPage0_t phy_pg0;
Mpi2ConfigReply_t mpi_reply;
u16 ioc_status;
u16 sz;
int i;
int rc = 0;
unsigned long flags;
spin_lock_irqsave(&ioc->sas_node_lock, flags);
if (_transport_sas_node_find_by_sas_address(ioc,
phy->identify.sas_address) == NULL) {
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
return -EINVAL;
}
spin_unlock_irqrestore(&ioc->sas_node_lock, flags);
if (!rates->minimum_linkrate)
rates->minimum_linkrate = phy->minimum_linkrate;
else if (rates->minimum_linkrate < phy->minimum_linkrate_hw)
rates->minimum_linkrate = phy->minimum_linkrate_hw;
if (!rates->maximum_linkrate)
rates->maximum_linkrate = phy->maximum_linkrate;
else if (rates->maximum_linkrate > phy->maximum_linkrate_hw)
rates->maximum_linkrate = phy->maximum_linkrate_hw;
/* handle expander phys */
if (phy->identify.sas_address != ioc->sas_hba.sas_address) {
phy->minimum_linkrate = rates->minimum_linkrate;
phy->maximum_linkrate = rates->maximum_linkrate;
return _transport_expander_phy_control(ioc, phy,
SMP_PHY_CONTROL_LINK_RESET);
}
/* handle hba phys */
/* sas_iounit page 1 */
sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (ioc->sas_hba.num_phys *
sizeof(Mpi2SasIOUnit1PhyData_t));
sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
if (!sas_iounit_pg1) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -ENOMEM;
goto out;
}
if ((mpt2sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
sas_iounit_pg1, sz))) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -ENXIO;
goto out;
}
ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
MPI2_IOCSTATUS_MASK;
if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -EIO;
goto out;
}
for (i = 0; i < ioc->sas_hba.num_phys; i++) {
if (phy->number != i) {
sas_iounit_pg1->PhyData[i].MaxMinLinkRate =
(ioc->sas_hba.phy[i].phy->minimum_linkrate +
(ioc->sas_hba.phy[i].phy->maximum_linkrate << 4));
} else {
sas_iounit_pg1->PhyData[i].MaxMinLinkRate =
(rates->minimum_linkrate +
(rates->maximum_linkrate << 4));
}
}
if (mpt2sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1,
sz)) {
printk(MPT2SAS_ERR_FMT "failure at %s:%d/%s()!\n",
ioc->name, __FILE__, __LINE__, __func__);
rc = -ENXIO;
goto out;
}
/* link reset */
_transport_phy_reset(phy, 0);
/* read phy page 0, then update the rates in the sas transport phy */
if (!mpt2sas_config_get_phy_pg0(ioc, &mpi_reply, &phy_pg0,
phy->number)) {
phy->minimum_linkrate = _transport_convert_phy_link_rate(
phy_pg0.ProgrammedLinkRate & MPI2_SAS_PRATE_MIN_RATE_MASK);
phy->maximum_linkrate = _transport_convert_phy_link_rate(
phy_pg0.ProgrammedLinkRate >> 4);
phy->negotiated_linkrate = _transport_convert_phy_link_rate(
phy_pg0.NegotiatedLinkRate &
MPI2_SAS_NEG_LINK_RATE_MASK_PHYSICAL);
}
out:
kfree(sas_iounit_pg1);
return rc;
}
/**
* _transport_smp_handler - transport portal for smp passthru
* @shost: shost object
* @rphy: sas transport rphy object
* @req:
*
* This used primarily for smp_utils.
* Example:
* smp_rep_general /sys/class/bsg/expander-5:0
*/
static int
_transport_smp_handler(struct Scsi_Host *shost, struct sas_rphy *rphy,
struct request *req)
{
struct MPT2SAS_ADAPTER *ioc = shost_priv(shost);
Mpi2SmpPassthroughRequest_t *mpi_request;
Mpi2SmpPassthroughReply_t *mpi_reply;
int rc;
u16 smid;
u32 ioc_state;
unsigned long timeleft;
void *psge;
u32 sgl_flags;
u8 issue_reset = 0;
dma_addr_t dma_addr_in = 0;
dma_addr_t dma_addr_out = 0;
u16 wait_state_count;
struct request *rsp = req->next_rq;
if (!rsp) {
printk(MPT2SAS_ERR_FMT "%s: the smp response space is "
"missing\n", ioc->name, __func__);
return -EINVAL;
}
/* do we need to support multiple segments? */
if (req->bio->bi_vcnt > 1 || rsp->bio->bi_vcnt > 1) {
printk(MPT2SAS_ERR_FMT "%s: multiple segments req %u %u, "
"rsp %u %u\n", ioc->name, __func__, req->bio->bi_vcnt,
blk_rq_bytes(req), rsp->bio->bi_vcnt, blk_rq_bytes(rsp));
return -EINVAL;
}
if (ioc->shost_recovery) {
printk(MPT2SAS_INFO_FMT "%s: host reset in progress!\n",
__func__, ioc->name);
return -EFAULT;
}
rc = mutex_lock_interruptible(&ioc->transport_cmds.mutex);
if (rc)
return rc;
if (ioc->transport_cmds.status != MPT2_CMD_NOT_USED) {
printk(MPT2SAS_ERR_FMT "%s: transport_cmds in use\n", ioc->name,
__func__);
rc = -EAGAIN;
goto out;
}
ioc->transport_cmds.status = MPT2_CMD_PENDING;
wait_state_count = 0;
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
if (wait_state_count++ == 10) {
printk(MPT2SAS_ERR_FMT
"%s: failed due to ioc not operational\n",
ioc->name, __func__);
rc = -EFAULT;
goto out;
}
ssleep(1);
ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
printk(MPT2SAS_INFO_FMT "%s: waiting for "
"operational state(count=%d)\n", ioc->name,
__func__, wait_state_count);
}
if (wait_state_count)
printk(MPT2SAS_INFO_FMT "%s: ioc is operational\n",
ioc->name, __func__);
smid = mpt2sas_base_get_smid(ioc, ioc->transport_cb_idx);
if (!smid) {
printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
ioc->name, __func__);
rc = -EAGAIN;
goto out;
}
rc = 0;
mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
ioc->transport_cmds.smid = smid;
memset(mpi_request, 0, sizeof(Mpi2SmpPassthroughRequest_t));
mpi_request->Function = MPI2_FUNCTION_SMP_PASSTHROUGH;
mpi_request->PhysicalPort = 0xFF;
mpi_request->VF_ID = 0; /* TODO */
mpi_request->VP_ID = 0;
mpi_request->SASAddress = (rphy) ?
cpu_to_le64(rphy->identify.sas_address) :
cpu_to_le64(ioc->sas_hba.sas_address);
mpi_request->RequestDataLength = cpu_to_le16(blk_rq_bytes(req) - 4);
psge = &mpi_request->SGL;
/* WRITE sgel first */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
dma_addr_out = pci_map_single(ioc->pdev, bio_data(req->bio),
blk_rq_bytes(req), PCI_DMA_BIDIRECTIONAL);
if (!dma_addr_out) {
mpt2sas_base_free_smid(ioc, smid);
goto unmap;
}
ioc->base_add_sg_single(psge, sgl_flags | (blk_rq_bytes(req) - 4),
dma_addr_out);
/* incr sgel */
psge += ioc->sge_size;
/* READ sgel last */
sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
MPI2_SGE_FLAGS_END_OF_LIST);
sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
dma_addr_in = pci_map_single(ioc->pdev, bio_data(rsp->bio),
blk_rq_bytes(rsp), PCI_DMA_BIDIRECTIONAL);
if (!dma_addr_in) {
mpt2sas_base_free_smid(ioc, smid);
goto unmap;
}
ioc->base_add_sg_single(psge, sgl_flags | (blk_rq_bytes(rsp) + 4),
dma_addr_in);
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "%s - "
"sending smp request\n", ioc->name, __func__));
init_completion(&ioc->transport_cmds.done);
mpt2sas_base_put_smid_default(ioc, smid);
timeleft = wait_for_completion_timeout(&ioc->transport_cmds.done,
10*HZ);
if (!(ioc->transport_cmds.status & MPT2_CMD_COMPLETE)) {
printk(MPT2SAS_ERR_FMT "%s : timeout\n",
__func__, ioc->name);
_debug_dump_mf(mpi_request,
sizeof(Mpi2SmpPassthroughRequest_t)/4);
if (!(ioc->transport_cmds.status & MPT2_CMD_RESET))
issue_reset = 1;
goto issue_host_reset;
}
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT "%s - "
"complete\n", ioc->name, __func__));
if (ioc->transport_cmds.status & MPT2_CMD_REPLY_VALID) {
mpi_reply = ioc->transport_cmds.reply;
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"%s - reply data transfer size(%d)\n",
ioc->name, __func__,
le16_to_cpu(mpi_reply->ResponseDataLength)));
memcpy(req->sense, mpi_reply, sizeof(*mpi_reply));
req->sense_len = sizeof(*mpi_reply);
req->resid_len = 0;
rsp->resid_len -=
le16_to_cpu(mpi_reply->ResponseDataLength);
} else {
dtransportprintk(ioc, printk(MPT2SAS_INFO_FMT
"%s - no reply\n", ioc->name, __func__));
rc = -ENXIO;
}
issue_host_reset:
if (issue_reset) {
mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
FORCE_BIG_HAMMER);
rc = -ETIMEDOUT;
}
unmap:
if (dma_addr_out)
pci_unmap_single(ioc->pdev, dma_addr_out, blk_rq_bytes(req),
PCI_DMA_BIDIRECTIONAL);
if (dma_addr_in)
pci_unmap_single(ioc->pdev, dma_addr_in, blk_rq_bytes(rsp),
PCI_DMA_BIDIRECTIONAL);
out:
ioc->transport_cmds.status = MPT2_CMD_NOT_USED;
mutex_unlock(&ioc->transport_cmds.mutex);
return rc;
}
struct sas_function_template mpt2sas_transport_functions = {
.get_linkerrors = _transport_get_linkerrors,
.get_enclosure_identifier = _transport_get_enclosure_identifier,
.get_bay_identifier = _transport_get_bay_identifier,
.phy_reset = _transport_phy_reset,
.phy_enable = _transport_phy_enable,
.set_phy_speed = _transport_phy_speed,
.smp_handler = _transport_smp_handler,
};
struct scsi_transport_template *mpt2sas_transport_template;
| gpl-2.0 |
duynhat1902/lte_kernel_f260s | net/netfilter/ipvs/ip_vs_sh.c | 4896 | 6698 | /*
* IPVS: Source Hashing scheduling module
*
* Authors: Wensong Zhang <wensong@gnuchina.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:
*
*/
/*
* The sh algorithm is to select server by the hash key of source IP
* address. The pseudo code is as follows:
*
* n <- servernode[src_ip];
* if (n is dead) OR
* (n is overloaded) or (n.weight <= 0) then
* return NULL;
*
* return n;
*
* Notes that servernode is a 256-bucket hash table that maps the hash
* index derived from packet source IP address to the current server
* array. If the sh scheduler is used in cache cluster, it is good to
* combine it with cache_bypass feature. When the statically assigned
* server is dead or overloaded, the load balancer can bypass the cache
* server and send requests to the original server directly.
*
* The weight destination attribute can be used to control the
* distribution of connections to the destinations in servernode. The
* greater the weight, the more connections the destination
* will receive.
*
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/ip.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <net/ip_vs.h>
/*
* IPVS SH bucket
*/
struct ip_vs_sh_bucket {
struct ip_vs_dest *dest; /* real server (cache) */
};
/*
* for IPVS SH entry hash table
*/
#ifndef CONFIG_IP_VS_SH_TAB_BITS
#define CONFIG_IP_VS_SH_TAB_BITS 8
#endif
#define IP_VS_SH_TAB_BITS CONFIG_IP_VS_SH_TAB_BITS
#define IP_VS_SH_TAB_SIZE (1 << IP_VS_SH_TAB_BITS)
#define IP_VS_SH_TAB_MASK (IP_VS_SH_TAB_SIZE - 1)
/*
* Returns hash value for IPVS SH entry
*/
static inline unsigned ip_vs_sh_hashkey(int af, const union nf_inet_addr *addr)
{
__be32 addr_fold = addr->ip;
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6)
addr_fold = addr->ip6[0]^addr->ip6[1]^
addr->ip6[2]^addr->ip6[3];
#endif
return (ntohl(addr_fold)*2654435761UL) & IP_VS_SH_TAB_MASK;
}
/*
* Get ip_vs_dest associated with supplied parameters.
*/
static inline struct ip_vs_dest *
ip_vs_sh_get(int af, struct ip_vs_sh_bucket *tbl,
const union nf_inet_addr *addr)
{
return (tbl[ip_vs_sh_hashkey(af, addr)]).dest;
}
/*
* Assign all the hash buckets of the specified table with the service.
*/
static int
ip_vs_sh_assign(struct ip_vs_sh_bucket *tbl, struct ip_vs_service *svc)
{
int i;
struct ip_vs_sh_bucket *b;
struct list_head *p;
struct ip_vs_dest *dest;
int d_count;
b = tbl;
p = &svc->destinations;
d_count = 0;
for (i=0; i<IP_VS_SH_TAB_SIZE; i++) {
if (list_empty(p)) {
b->dest = NULL;
} else {
if (p == &svc->destinations)
p = p->next;
dest = list_entry(p, struct ip_vs_dest, n_list);
atomic_inc(&dest->refcnt);
b->dest = dest;
IP_VS_DBG_BUF(6, "assigned i: %d dest: %s weight: %d\n",
i, IP_VS_DBG_ADDR(svc->af, &dest->addr),
atomic_read(&dest->weight));
/* Don't move to next dest until filling weight */
if (++d_count >= atomic_read(&dest->weight)) {
p = p->next;
d_count = 0;
}
}
b++;
}
return 0;
}
/*
* Flush all the hash buckets of the specified table.
*/
static void ip_vs_sh_flush(struct ip_vs_sh_bucket *tbl)
{
int i;
struct ip_vs_sh_bucket *b;
b = tbl;
for (i=0; i<IP_VS_SH_TAB_SIZE; i++) {
if (b->dest) {
atomic_dec(&b->dest->refcnt);
b->dest = NULL;
}
b++;
}
}
static int ip_vs_sh_init_svc(struct ip_vs_service *svc)
{
struct ip_vs_sh_bucket *tbl;
/* allocate the SH table for this service */
tbl = kmalloc(sizeof(struct ip_vs_sh_bucket)*IP_VS_SH_TAB_SIZE,
GFP_ATOMIC);
if (tbl == NULL)
return -ENOMEM;
svc->sched_data = tbl;
IP_VS_DBG(6, "SH hash table (memory=%Zdbytes) allocated for "
"current service\n",
sizeof(struct ip_vs_sh_bucket)*IP_VS_SH_TAB_SIZE);
/* assign the hash buckets with the updated service */
ip_vs_sh_assign(tbl, svc);
return 0;
}
static int ip_vs_sh_done_svc(struct ip_vs_service *svc)
{
struct ip_vs_sh_bucket *tbl = svc->sched_data;
/* got to clean up hash buckets here */
ip_vs_sh_flush(tbl);
/* release the table itself */
kfree(svc->sched_data);
IP_VS_DBG(6, "SH hash table (memory=%Zdbytes) released\n",
sizeof(struct ip_vs_sh_bucket)*IP_VS_SH_TAB_SIZE);
return 0;
}
static int ip_vs_sh_update_svc(struct ip_vs_service *svc)
{
struct ip_vs_sh_bucket *tbl = svc->sched_data;
/* got to clean up hash buckets here */
ip_vs_sh_flush(tbl);
/* assign the hash buckets with the updated service */
ip_vs_sh_assign(tbl, svc);
return 0;
}
/*
* If the dest flags is set with IP_VS_DEST_F_OVERLOAD,
* consider that the server is overloaded here.
*/
static inline int is_overloaded(struct ip_vs_dest *dest)
{
return dest->flags & IP_VS_DEST_F_OVERLOAD;
}
/*
* Source Hashing scheduling
*/
static struct ip_vs_dest *
ip_vs_sh_schedule(struct ip_vs_service *svc, const struct sk_buff *skb)
{
struct ip_vs_dest *dest;
struct ip_vs_sh_bucket *tbl;
struct ip_vs_iphdr iph;
ip_vs_fill_iphdr(svc->af, skb_network_header(skb), &iph);
IP_VS_DBG(6, "ip_vs_sh_schedule(): Scheduling...\n");
tbl = (struct ip_vs_sh_bucket *)svc->sched_data;
dest = ip_vs_sh_get(svc->af, tbl, &iph.saddr);
if (!dest
|| !(dest->flags & IP_VS_DEST_F_AVAILABLE)
|| atomic_read(&dest->weight) <= 0
|| is_overloaded(dest)) {
ip_vs_scheduler_err(svc, "no destination available");
return NULL;
}
IP_VS_DBG_BUF(6, "SH: source IP address %s --> server %s:%d\n",
IP_VS_DBG_ADDR(svc->af, &iph.saddr),
IP_VS_DBG_ADDR(svc->af, &dest->addr),
ntohs(dest->port));
return dest;
}
/*
* IPVS SH Scheduler structure
*/
static struct ip_vs_scheduler ip_vs_sh_scheduler =
{
.name = "sh",
.refcnt = ATOMIC_INIT(0),
.module = THIS_MODULE,
.n_list = LIST_HEAD_INIT(ip_vs_sh_scheduler.n_list),
.init_service = ip_vs_sh_init_svc,
.done_service = ip_vs_sh_done_svc,
.update_service = ip_vs_sh_update_svc,
.schedule = ip_vs_sh_schedule,
};
static int __init ip_vs_sh_init(void)
{
return register_ip_vs_scheduler(&ip_vs_sh_scheduler);
}
static void __exit ip_vs_sh_cleanup(void)
{
unregister_ip_vs_scheduler(&ip_vs_sh_scheduler);
}
module_init(ip_vs_sh_init);
module_exit(ip_vs_sh_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
zombi-x/android_kernel_asus_tf701t | sound/soc/sh/fsi-da7210.c | 4896 | 2036 | /*
* fsi-da7210.c
*
* Copyright (C) 2009 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.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/platform_device.h>
#include <linux/module.h>
#include <sound/sh_fsi.h>
static int fsi_da7210_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_dai *codec = rtd->codec_dai;
struct snd_soc_dai *cpu = rtd->cpu_dai;
int ret;
ret = snd_soc_dai_set_fmt(codec,
SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_CBM_CFM);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(cpu, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_CBS_CFS);
return ret;
}
static struct snd_soc_dai_link fsi_da7210_dai = {
.name = "DA7210",
.stream_name = "DA7210",
.cpu_dai_name = "fsib-dai", /* FSI B */
.codec_dai_name = "da7210-hifi",
.platform_name = "sh_fsi.0",
.codec_name = "da7210-codec.0-001a",
.init = fsi_da7210_init,
};
static struct snd_soc_card fsi_soc_card = {
.name = "FSI-DA7210",
.owner = THIS_MODULE,
.dai_link = &fsi_da7210_dai,
.num_links = 1,
};
static struct platform_device *fsi_da7210_snd_device;
static int __init fsi_da7210_sound_init(void)
{
int ret;
fsi_da7210_snd_device = platform_device_alloc("soc-audio", FSI_PORT_B);
if (!fsi_da7210_snd_device)
return -ENOMEM;
platform_set_drvdata(fsi_da7210_snd_device, &fsi_soc_card);
ret = platform_device_add(fsi_da7210_snd_device);
if (ret)
platform_device_put(fsi_da7210_snd_device);
return ret;
}
static void __exit fsi_da7210_sound_exit(void)
{
platform_device_unregister(fsi_da7210_snd_device);
}
module_init(fsi_da7210_sound_init);
module_exit(fsi_da7210_sound_exit);
/* Module information */
MODULE_DESCRIPTION("ALSA SoC FSI DA2710");
MODULE_AUTHOR("Kuninori Morimoto <morimoto.kuninori@renesas.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
tkawajir/android_kernel_lg_l04e | drivers/staging/rtl8712/rtl871x_mlme.c | 4896 | 55627 | /******************************************************************************
* rtl871x_mlme.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_MLME_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "recv_osdep.h"
#include "xmit_osdep.h"
#include "mlme_osdep.h"
#include "sta_info.h"
#include "wifi.h"
#include "wlan_bssdef.h"
static void update_ht_cap(struct _adapter *padapter, u8 *pie, uint ie_len);
static sint _init_mlme_priv(struct _adapter *padapter)
{
sint i;
u8 *pbuf;
struct wlan_network *pnetwork;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
memset((u8 *)pmlmepriv, 0, sizeof(struct mlme_priv));
pmlmepriv->nic_hdl = (u8 *)padapter;
pmlmepriv->pscanned = NULL;
pmlmepriv->fw_state = 0;
pmlmepriv->cur_network.network.InfrastructureMode =
Ndis802_11AutoUnknown;
/* Maybe someday we should rename this variable to "active_mode"(Jeff)*/
pmlmepriv->passive_mode = 1; /* 1: active, 0: passive. */
spin_lock_init(&(pmlmepriv->lock));
spin_lock_init(&(pmlmepriv->lock2));
_init_queue(&(pmlmepriv->free_bss_pool));
_init_queue(&(pmlmepriv->scanned_queue));
set_scanned_network_val(pmlmepriv, 0);
memset(&pmlmepriv->assoc_ssid, 0, sizeof(struct ndis_802_11_ssid));
pbuf = _malloc(MAX_BSS_CNT * (sizeof(struct wlan_network)));
if (pbuf == NULL)
return _FAIL;
pmlmepriv->free_bss_buf = pbuf;
pnetwork = (struct wlan_network *)pbuf;
for (i = 0; i < MAX_BSS_CNT; i++) {
_init_listhead(&(pnetwork->list));
list_insert_tail(&(pnetwork->list),
&(pmlmepriv->free_bss_pool.queue));
pnetwork++;
}
pmlmepriv->sitesurveyctrl.last_rx_pkts = 0;
pmlmepriv->sitesurveyctrl.last_tx_pkts = 0;
pmlmepriv->sitesurveyctrl.traffic_busy = false;
/* allocate DMA-able/Non-Page memory for cmd_buf and rsp_buf */
r8712_init_mlme_timer(padapter);
return _SUCCESS;
}
struct wlan_network *_r8712_alloc_network(struct mlme_priv *pmlmepriv)
{
unsigned long irqL;
struct wlan_network *pnetwork;
struct __queue *free_queue = &pmlmepriv->free_bss_pool;
struct list_head *plist = NULL;
if (_queue_empty(free_queue) == true)
return NULL;
spin_lock_irqsave(&free_queue->lock, irqL);
plist = get_next(&(free_queue->queue));
pnetwork = LIST_CONTAINOR(plist , struct wlan_network, list);
list_delete(&pnetwork->list);
pnetwork->last_scanned = jiffies;
pmlmepriv->num_of_scanned++;
spin_unlock_irqrestore(&free_queue->lock, irqL);
return pnetwork;
}
static void _free_network(struct mlme_priv *pmlmepriv,
struct wlan_network *pnetwork)
{
u32 curr_time, delta_time;
unsigned long irqL;
struct __queue *free_queue = &(pmlmepriv->free_bss_pool);
if (pnetwork == NULL)
return;
if (pnetwork->fixed == true)
return;
curr_time = jiffies;
delta_time = (curr_time - (u32)pnetwork->last_scanned) / HZ;
if (delta_time < SCANQUEUE_LIFETIME)
return;
spin_lock_irqsave(&free_queue->lock, irqL);
list_delete(&pnetwork->list);
list_insert_tail(&pnetwork->list, &free_queue->queue);
pmlmepriv->num_of_scanned--;
spin_unlock_irqrestore(&free_queue->lock, irqL);
}
static void _free_network_nolock(struct mlme_priv *pmlmepriv,
struct wlan_network *pnetwork)
{
struct __queue *free_queue = &pmlmepriv->free_bss_pool;
if (pnetwork == NULL)
return;
if (pnetwork->fixed == true)
return;
list_delete(&pnetwork->list);
list_insert_tail(&pnetwork->list, get_list_head(free_queue));
pmlmepriv->num_of_scanned--;
}
/*
return the wlan_network with the matching addr
Shall be calle under atomic context...
to avoid possible racing condition...
*/
static struct wlan_network *_r8712_find_network(struct __queue *scanned_queue,
u8 *addr)
{
unsigned long irqL;
struct list_head *phead, *plist;
struct wlan_network *pnetwork = NULL;
u8 zero_addr[ETH_ALEN] = {0, 0, 0, 0, 0, 0};
if (!memcmp(zero_addr, addr, ETH_ALEN))
return NULL;
spin_lock_irqsave(&scanned_queue->lock, irqL);
phead = get_list_head(scanned_queue);
plist = get_next(phead);
while (plist != phead) {
pnetwork = LIST_CONTAINOR(plist, struct wlan_network, list);
plist = get_next(plist);
if (!memcmp(addr, pnetwork->network.MacAddress, ETH_ALEN))
break;
}
spin_unlock_irqrestore(&scanned_queue->lock, irqL);
return pnetwork;
}
static void _free_network_queue(struct _adapter *padapter)
{
unsigned long irqL;
struct list_head *phead, *plist;
struct wlan_network *pnetwork;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct __queue *scanned_queue = &pmlmepriv->scanned_queue;
spin_lock_irqsave(&scanned_queue->lock, irqL);
phead = get_list_head(scanned_queue);
plist = get_next(phead);
while (end_of_queue_search(phead, plist) == false) {
pnetwork = LIST_CONTAINOR(plist, struct wlan_network, list);
plist = get_next(plist);
_free_network(pmlmepriv, pnetwork);
}
spin_unlock_irqrestore(&scanned_queue->lock, irqL);
}
sint r8712_if_up(struct _adapter *padapter)
{
sint res;
if (padapter->bDriverStopped || padapter->bSurpriseRemoved ||
(check_fwstate(&padapter->mlmepriv, _FW_LINKED) == false)) {
res = false;
} else
res = true;
return res;
}
void r8712_generate_random_ibss(u8 *pibss)
{
u32 curtime = jiffies;
pibss[0] = 0x02; /*in ad-hoc mode bit1 must set to 1 */
pibss[1] = 0x11;
pibss[2] = 0x87;
pibss[3] = (u8)(curtime & 0xff);
pibss[4] = (u8)((curtime>>8) & 0xff);
pibss[5] = (u8)((curtime>>16) & 0xff);
}
uint r8712_get_ndis_wlan_bssid_ex_sz(struct ndis_wlan_bssid_ex *bss)
{
uint t_len;
t_len = sizeof(u32) + 6 * sizeof(unsigned long) + 2 +
sizeof(struct ndis_802_11_ssid) + sizeof(u32) +
sizeof(s32) +
sizeof(enum NDIS_802_11_NETWORK_TYPE) +
sizeof(struct NDIS_802_11_CONFIGURATION) +
sizeof(enum NDIS_802_11_NETWORK_INFRASTRUCTURE) +
sizeof(NDIS_802_11_RATES_EX) +
sizeof(u32) + bss->IELength;
return t_len;
}
u8 *r8712_get_capability_from_ie(u8 *ie)
{
return ie + 8 + 2;
}
int r8712_init_mlme_priv(struct _adapter *padapter)
{
return _init_mlme_priv(padapter);
}
void r8712_free_mlme_priv(struct mlme_priv *pmlmepriv)
{
kfree(pmlmepriv->free_bss_buf);
}
static struct wlan_network *alloc_network(struct mlme_priv *pmlmepriv)
{
return _r8712_alloc_network(pmlmepriv);
}
static void free_network_nolock(struct mlme_priv *pmlmepriv,
struct wlan_network *pnetwork)
{
_free_network_nolock(pmlmepriv, pnetwork);
}
void r8712_free_network_queue(struct _adapter *dev)
{
_free_network_queue(dev);
}
/*
return the wlan_network with the matching addr
Shall be calle under atomic context...
to avoid possible racing condition...
*/
static struct wlan_network *r8712_find_network(struct __queue *scanned_queue,
u8 *addr)
{
struct wlan_network *pnetwork = _r8712_find_network(scanned_queue,
addr);
return pnetwork;
}
int r8712_is_same_ibss(struct _adapter *adapter, struct wlan_network *pnetwork)
{
int ret = true;
struct security_priv *psecuritypriv = &adapter->securitypriv;
if ((psecuritypriv->PrivacyAlgrthm != _NO_PRIVACY_) &&
(pnetwork->network.Privacy == 0))
ret = false;
else if ((psecuritypriv->PrivacyAlgrthm == _NO_PRIVACY_) &&
(pnetwork->network.Privacy == 1))
ret = false;
else
ret = true;
return ret;
}
static int is_same_network(struct ndis_wlan_bssid_ex *src,
struct ndis_wlan_bssid_ex *dst)
{
u16 s_cap, d_cap;
memcpy((u8 *)&s_cap, r8712_get_capability_from_ie(src->IEs), 2);
memcpy((u8 *)&d_cap, r8712_get_capability_from_ie(dst->IEs), 2);
return (src->Ssid.SsidLength == dst->Ssid.SsidLength) &&
(src->Configuration.DSConfig ==
dst->Configuration.DSConfig) &&
((!memcmp(src->MacAddress, dst->MacAddress,
ETH_ALEN))) &&
((!memcmp(src->Ssid.Ssid,
dst->Ssid.Ssid,
src->Ssid.SsidLength))) &&
((s_cap & WLAN_CAPABILITY_IBSS) ==
(d_cap & WLAN_CAPABILITY_IBSS)) &&
((s_cap & WLAN_CAPABILITY_BSS) ==
(d_cap & WLAN_CAPABILITY_BSS));
}
struct wlan_network *r8712_get_oldest_wlan_network(
struct __queue *scanned_queue)
{
struct list_head *plist, *phead;
struct wlan_network *pwlan = NULL;
struct wlan_network *oldest = NULL;
phead = get_list_head(scanned_queue);
plist = get_next(phead);
while (1) {
if (end_of_queue_search(phead, plist) == true)
break;
pwlan = LIST_CONTAINOR(plist, struct wlan_network, list);
if (pwlan->fixed != true) {
if (oldest == NULL ||
time_after((unsigned long)oldest->last_scanned,
(unsigned long)pwlan->last_scanned))
oldest = pwlan;
}
plist = get_next(plist);
}
return oldest;
}
static void update_network(struct ndis_wlan_bssid_ex *dst,
struct ndis_wlan_bssid_ex *src,
struct _adapter *padapter)
{
u32 last_evm = 0, tmpVal;
if (check_fwstate(&padapter->mlmepriv, _FW_LINKED) &&
is_same_network(&(padapter->mlmepriv.cur_network.network), src)) {
if (padapter->recvpriv.signal_qual_data.total_num++ >=
PHY_LINKQUALITY_SLID_WIN_MAX) {
padapter->recvpriv.signal_qual_data.total_num =
PHY_LINKQUALITY_SLID_WIN_MAX;
last_evm = padapter->recvpriv.signal_qual_data.
elements[padapter->recvpriv.
signal_qual_data.index];
padapter->recvpriv.signal_qual_data.total_val -=
last_evm;
}
padapter->recvpriv.signal_qual_data.total_val += src->Rssi;
padapter->recvpriv.signal_qual_data.
elements[padapter->recvpriv.signal_qual_data.
index++] = src->Rssi;
if (padapter->recvpriv.signal_qual_data.index >=
PHY_LINKQUALITY_SLID_WIN_MAX)
padapter->recvpriv.signal_qual_data.index = 0;
/* <1> Showed on UI for user, in percentage. */
tmpVal = padapter->recvpriv.signal_qual_data.total_val /
padapter->recvpriv.signal_qual_data.total_num;
padapter->recvpriv.signal = (u8)tmpVal;
src->Rssi = padapter->recvpriv.signal;
} else
src->Rssi = (src->Rssi + dst->Rssi) / 2;
memcpy((u8 *)dst, (u8 *)src, r8712_get_ndis_wlan_bssid_ex_sz(src));
}
static void update_current_network(struct _adapter *adapter,
struct ndis_wlan_bssid_ex *pnetwork)
{
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
if (is_same_network(&(pmlmepriv->cur_network.network), pnetwork)) {
update_network(&(pmlmepriv->cur_network.network),
pnetwork, adapter);
r8712_update_protection(adapter,
(pmlmepriv->cur_network.network.IEs) +
sizeof(struct NDIS_802_11_FIXED_IEs),
pmlmepriv->cur_network.network.IELength);
}
}
/*
Caller must hold pmlmepriv->lock first.
*/
static void update_scanned_network(struct _adapter *adapter,
struct ndis_wlan_bssid_ex *target)
{
struct list_head *plist, *phead;
u32 bssid_ex_sz;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
struct __queue *queue = &pmlmepriv->scanned_queue;
struct wlan_network *pnetwork = NULL;
struct wlan_network *oldest = NULL;
phead = get_list_head(queue);
plist = get_next(phead);
while (1) {
if (end_of_queue_search(phead, plist) == true)
break;
pnetwork = LIST_CONTAINOR(plist, struct wlan_network, list);
if (is_same_network(&pnetwork->network, target))
break;
if ((oldest == ((struct wlan_network *)0)) ||
time_after((unsigned long)oldest->last_scanned,
(unsigned long)pnetwork->last_scanned))
oldest = pnetwork;
plist = get_next(plist);
}
/* If we didn't find a match, then get a new network slot to initialize
* with this beacon's information */
if (end_of_queue_search(phead, plist) == true) {
if (_queue_empty(&pmlmepriv->free_bss_pool) == true) {
/* If there are no more slots, expire the oldest */
pnetwork = oldest;
target->Rssi = (pnetwork->network.Rssi +
target->Rssi) / 2;
memcpy(&pnetwork->network, target,
r8712_get_ndis_wlan_bssid_ex_sz(target));
pnetwork->last_scanned = jiffies;
} else {
/* Otherwise just pull from the free list */
/* update scan_time */
pnetwork = alloc_network(pmlmepriv);
if (pnetwork == NULL)
return;
bssid_ex_sz = r8712_get_ndis_wlan_bssid_ex_sz(target);
target->Length = bssid_ex_sz;
memcpy(&pnetwork->network, target, bssid_ex_sz);
list_insert_tail(&pnetwork->list, &queue->queue);
}
} else {
/* we have an entry and we are going to update it. But
* this entry may be already expired. In this case we
* do the same as we found a new net and call the new_net
* handler
*/
update_network(&pnetwork->network, target, adapter);
pnetwork->last_scanned = jiffies;
}
}
static void rtl8711_add_network(struct _adapter *adapter,
struct ndis_wlan_bssid_ex *pnetwork)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &(((struct _adapter *)adapter)->mlmepriv);
struct __queue *queue = &pmlmepriv->scanned_queue;
spin_lock_irqsave(&queue->lock, irqL);
update_current_network(adapter, pnetwork);
update_scanned_network(adapter, pnetwork);
spin_unlock_irqrestore(&queue->lock, irqL);
}
/*select the desired network based on the capability of the (i)bss.
* check items: (1) security
* (2) network_type
* (3) WMM
* (4) HT
* (5) others
*/
static int is_desired_network(struct _adapter *adapter,
struct wlan_network *pnetwork)
{
u8 wps_ie[512];
uint wps_ielen;
int bselected = true;
struct security_priv *psecuritypriv = &adapter->securitypriv;
if (psecuritypriv->wps_phase == true) {
if (r8712_get_wps_ie(pnetwork->network.IEs,
pnetwork->network.IELength, wps_ie,
&wps_ielen) == true)
return true;
else
return false;
}
if ((psecuritypriv->PrivacyAlgrthm != _NO_PRIVACY_) &&
(pnetwork->network.Privacy == 0))
bselected = false;
if (check_fwstate(&adapter->mlmepriv, WIFI_ADHOC_STATE) == true) {
if (pnetwork->network.InfrastructureMode !=
adapter->mlmepriv.cur_network.network.
InfrastructureMode)
bselected = false;
}
return bselected;
}
/* TODO: Perry : For Power Management */
void r8712_atimdone_event_callback(struct _adapter *adapter , u8 *pbuf)
{
}
void r8712_survey_event_callback(struct _adapter *adapter, u8 *pbuf)
{
unsigned long flags;
u32 len;
struct ndis_wlan_bssid_ex *pnetwork;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
pnetwork = (struct ndis_wlan_bssid_ex *)pbuf;
#ifdef __BIG_ENDIAN
/* endian_convert */
pnetwork->Length = le32_to_cpu(pnetwork->Length);
pnetwork->Ssid.SsidLength = le32_to_cpu(pnetwork->Ssid.SsidLength);
pnetwork->Privacy = le32_to_cpu(pnetwork->Privacy);
pnetwork->Rssi = le32_to_cpu(pnetwork->Rssi);
pnetwork->NetworkTypeInUse = le32_to_cpu(pnetwork->NetworkTypeInUse);
pnetwork->Configuration.ATIMWindow =
le32_to_cpu(pnetwork->Configuration.ATIMWindow);
pnetwork->Configuration.BeaconPeriod =
le32_to_cpu(pnetwork->Configuration.BeaconPeriod);
pnetwork->Configuration.DSConfig =
le32_to_cpu(pnetwork->Configuration.DSConfig);
pnetwork->Configuration.FHConfig.DwellTime =
le32_to_cpu(pnetwork->Configuration.FHConfig.DwellTime);
pnetwork->Configuration.FHConfig.HopPattern =
le32_to_cpu(pnetwork->Configuration.FHConfig.HopPattern);
pnetwork->Configuration.FHConfig.HopSet =
le32_to_cpu(pnetwork->Configuration.FHConfig.HopSet);
pnetwork->Configuration.FHConfig.Length =
le32_to_cpu(pnetwork->Configuration.FHConfig.Length);
pnetwork->Configuration.Length =
le32_to_cpu(pnetwork->Configuration.Length);
pnetwork->InfrastructureMode =
le32_to_cpu(pnetwork->InfrastructureMode);
pnetwork->IELength = le32_to_cpu(pnetwork->IELength);
#endif
len = r8712_get_ndis_wlan_bssid_ex_sz(pnetwork);
if (len > sizeof(struct wlan_bssid_ex))
return;
spin_lock_irqsave(&pmlmepriv->lock2, flags);
/* update IBSS_network 's timestamp */
if (check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == true) {
if (!memcmp(&(pmlmepriv->cur_network.network.MacAddress),
pnetwork->MacAddress, ETH_ALEN)) {
struct wlan_network *ibss_wlan = NULL;
memcpy(pmlmepriv->cur_network.network.IEs,
pnetwork->IEs, 8);
ibss_wlan = r8712_find_network(
&pmlmepriv->scanned_queue,
pnetwork->MacAddress);
if (ibss_wlan) {
memcpy(ibss_wlan->network.IEs,
pnetwork->IEs, 8);
goto exit;
}
}
}
/* lock pmlmepriv->lock when you accessing network_q */
if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING) == false) {
if (pnetwork->Ssid.Ssid[0] != 0)
rtl8711_add_network(adapter, pnetwork);
else {
pnetwork->Ssid.SsidLength = 8;
memcpy(pnetwork->Ssid.Ssid, "<hidden>", 8);
rtl8711_add_network(adapter, pnetwork);
}
}
exit:
spin_unlock_irqrestore(&pmlmepriv->lock2, flags);
}
void r8712_surveydone_event_callback(struct _adapter *adapter, u8 *pbuf)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == true) {
u8 timer_cancelled;
_cancel_timer(&pmlmepriv->scan_to_timer, &timer_cancelled);
_clr_fwstate_(pmlmepriv, _FW_UNDER_SURVEY);
}
if (pmlmepriv->to_join == true) {
if ((check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) == true)) {
if (check_fwstate(pmlmepriv, _FW_LINKED) == false) {
set_fwstate(pmlmepriv, _FW_UNDER_LINKING);
if (r8712_select_and_join_from_scan(pmlmepriv)
== _SUCCESS)
_set_timer(&pmlmepriv->assoc_timer,
MAX_JOIN_TIMEOUT);
else {
struct wlan_bssid_ex *pdev_network =
&(adapter->registrypriv.dev_network);
u8 *pibss =
adapter->registrypriv.
dev_network.MacAddress;
pmlmepriv->fw_state ^= _FW_UNDER_SURVEY;
memset(&pdev_network->Ssid, 0,
sizeof(struct
ndis_802_11_ssid));
memcpy(&pdev_network->Ssid,
&pmlmepriv->assoc_ssid,
sizeof(struct
ndis_802_11_ssid));
r8712_update_registrypriv_dev_network
(adapter);
r8712_generate_random_ibss(pibss);
pmlmepriv->fw_state =
WIFI_ADHOC_MASTER_STATE;
pmlmepriv->to_join = false;
}
}
} else {
pmlmepriv->to_join = false;
set_fwstate(pmlmepriv, _FW_UNDER_LINKING);
if (r8712_select_and_join_from_scan(pmlmepriv) ==
_SUCCESS)
_set_timer(&pmlmepriv->assoc_timer,
MAX_JOIN_TIMEOUT);
else
_clr_fwstate_(pmlmepriv, _FW_UNDER_LINKING);
}
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
/*
*r8712_free_assoc_resources: the caller has to lock pmlmepriv->lock
*/
void r8712_free_assoc_resources(struct _adapter *adapter)
{
unsigned long irqL;
struct wlan_network *pwlan = NULL;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
struct sta_priv *pstapriv = &adapter->stapriv;
struct wlan_network *tgt_network = &pmlmepriv->cur_network;
pwlan = r8712_find_network(&pmlmepriv->scanned_queue,
tgt_network->network.MacAddress);
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE|WIFI_AP_STATE)) {
struct sta_info *psta;
psta = r8712_get_stainfo(&adapter->stapriv,
tgt_network->network.MacAddress);
spin_lock_irqsave(&pstapriv->sta_hash_lock, irqL);
r8712_free_stainfo(adapter, psta);
spin_unlock_irqrestore(&pstapriv->sta_hash_lock, irqL);
}
if (check_fwstate(pmlmepriv,
WIFI_ADHOC_STATE|WIFI_ADHOC_MASTER_STATE|WIFI_AP_STATE))
r8712_free_all_stainfo(adapter);
if (pwlan)
pwlan->fixed = false;
if (((check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE)) &&
(adapter->stapriv.asoc_sta_count == 1)))
free_network_nolock(pmlmepriv, pwlan);
}
/*
*r8712_indicate_connect: the caller has to lock pmlmepriv->lock
*/
void r8712_indicate_connect(struct _adapter *padapter)
{
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
pmlmepriv->to_join = false;
set_fwstate(pmlmepriv, _FW_LINKED);
padapter->ledpriv.LedControlHandler(padapter, LED_CTL_LINK);
r8712_os_indicate_connect(padapter);
if (padapter->registrypriv.power_mgnt > PS_MODE_ACTIVE)
_set_timer(&pmlmepriv->dhcp_timer, 60000);
}
/*
*r8712_ind_disconnect: the caller has to lock pmlmepriv->lock
*/
void r8712_ind_disconnect(struct _adapter *padapter)
{
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if (check_fwstate(pmlmepriv, _FW_LINKED) == true) {
_clr_fwstate_(pmlmepriv, _FW_LINKED);
padapter->ledpriv.LedControlHandler(padapter, LED_CTL_NO_LINK);
r8712_os_indicate_disconnect(padapter);
}
if (padapter->pwrctrlpriv.pwr_mode !=
padapter->registrypriv.power_mgnt) {
_cancel_timer_ex(&pmlmepriv->dhcp_timer);
r8712_set_ps_mode(padapter, padapter->registrypriv.power_mgnt,
padapter->registrypriv.smart_ps);
}
}
/*Notes:
*pnetwork : returns from r8712_joinbss_event_callback
*ptarget_wlan: found from scanned_queue
*if join_res > 0, for (fw_state==WIFI_STATION_STATE), we check if
* "ptarget_sta" & "ptarget_wlan" exist.
*if join_res > 0, for (fw_state==WIFI_ADHOC_STATE), we only check
* if "ptarget_wlan" exist.
*if join_res > 0, update "cur_network->network" from
* "pnetwork->network" if (ptarget_wlan !=NULL).
*/
void r8712_joinbss_event_callback(struct _adapter *adapter, u8 *pbuf)
{
unsigned long irqL = 0, irqL2;
u8 timer_cancelled;
struct sta_info *ptarget_sta = NULL, *pcur_sta = NULL;
struct sta_priv *pstapriv = &adapter->stapriv;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
struct wlan_network *cur_network = &pmlmepriv->cur_network;
struct wlan_network *pcur_wlan = NULL, *ptarget_wlan = NULL;
unsigned int the_same_macaddr = false;
struct wlan_network *pnetwork;
if (sizeof(struct list_head) == 4 * sizeof(u32)) {
pnetwork = (struct wlan_network *)
_malloc(sizeof(struct wlan_network));
memcpy((u8 *)pnetwork+16, (u8 *)pbuf + 8,
sizeof(struct wlan_network) - 16);
} else
pnetwork = (struct wlan_network *)pbuf;
#ifdef __BIG_ENDIAN
/* endian_convert */
pnetwork->join_res = le32_to_cpu(pnetwork->join_res);
pnetwork->network_type = le32_to_cpu(pnetwork->network_type);
pnetwork->network.Length = le32_to_cpu(pnetwork->network.Length);
pnetwork->network.Ssid.SsidLength =
le32_to_cpu(pnetwork->network.Ssid.SsidLength);
pnetwork->network.Privacy = le32_to_cpu(pnetwork->network.Privacy);
pnetwork->network.Rssi = le32_to_cpu(pnetwork->network.Rssi);
pnetwork->network.NetworkTypeInUse =
le32_to_cpu(pnetwork->network.NetworkTypeInUse);
pnetwork->network.Configuration.ATIMWindow =
le32_to_cpu(pnetwork->network.Configuration.ATIMWindow);
pnetwork->network.Configuration.BeaconPeriod =
le32_to_cpu(pnetwork->network.Configuration.BeaconPeriod);
pnetwork->network.Configuration.DSConfig =
le32_to_cpu(pnetwork->network.Configuration.DSConfig);
pnetwork->network.Configuration.FHConfig.DwellTime =
le32_to_cpu(pnetwork->network.Configuration.FHConfig.
DwellTime);
pnetwork->network.Configuration.FHConfig.HopPattern =
le32_to_cpu(pnetwork->network.Configuration.
FHConfig.HopPattern);
pnetwork->network.Configuration.FHConfig.HopSet =
le32_to_cpu(pnetwork->network.Configuration.FHConfig.HopSet);
pnetwork->network.Configuration.FHConfig.Length =
le32_to_cpu(pnetwork->network.Configuration.FHConfig.Length);
pnetwork->network.Configuration.Length =
le32_to_cpu(pnetwork->network.Configuration.Length);
pnetwork->network.InfrastructureMode =
le32_to_cpu(pnetwork->network.InfrastructureMode);
pnetwork->network.IELength = le32_to_cpu(pnetwork->network.IELength);
#endif
the_same_macaddr = !memcmp(pnetwork->network.MacAddress,
cur_network->network.MacAddress, ETH_ALEN);
pnetwork->network.Length =
r8712_get_ndis_wlan_bssid_ex_sz(&pnetwork->network);
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if (pnetwork->network.Length > sizeof(struct wlan_bssid_ex))
goto ignore_joinbss_callback;
if (pnetwork->join_res > 0) {
if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING) == true) {
/*s1. find ptarget_wlan*/
if (check_fwstate(pmlmepriv, _FW_LINKED) == true) {
if (the_same_macaddr == true)
ptarget_wlan =
r8712_find_network(&pmlmepriv->
scanned_queue,
cur_network->network.MacAddress);
else {
pcur_wlan =
r8712_find_network(&pmlmepriv->
scanned_queue,
cur_network->network.MacAddress);
pcur_wlan->fixed = false;
pcur_sta = r8712_get_stainfo(pstapriv,
cur_network->network.MacAddress);
spin_lock_irqsave(&pstapriv->
sta_hash_lock, irqL2);
r8712_free_stainfo(adapter, pcur_sta);
spin_unlock_irqrestore(&(pstapriv->
sta_hash_lock), irqL2);
ptarget_wlan =
r8712_find_network(&pmlmepriv->
scanned_queue,
pnetwork->network.
MacAddress);
if (ptarget_wlan)
ptarget_wlan->fixed = true;
}
} else {
ptarget_wlan = r8712_find_network(&pmlmepriv->
scanned_queue,
pnetwork->network.MacAddress);
if (ptarget_wlan)
ptarget_wlan->fixed = true;
}
if (ptarget_wlan == NULL) {
if (check_fwstate(pmlmepriv,
_FW_UNDER_LINKING))
pmlmepriv->fw_state ^=
_FW_UNDER_LINKING;
goto ignore_joinbss_callback;
}
/*s2. find ptarget_sta & update ptarget_sta*/
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE)) {
if (the_same_macaddr == true) {
ptarget_sta =
r8712_get_stainfo(pstapriv,
pnetwork->network.MacAddress);
if (ptarget_sta == NULL)
ptarget_sta =
r8712_alloc_stainfo(pstapriv,
pnetwork->network.MacAddress);
} else
ptarget_sta =
r8712_alloc_stainfo(pstapriv,
pnetwork->network.MacAddress);
if (ptarget_sta) /*update ptarget_sta*/ {
ptarget_sta->aid = pnetwork->join_res;
ptarget_sta->qos_option = 1;
ptarget_sta->mac_id = 5;
if (adapter->securitypriv.
AuthAlgrthm == 2) {
adapter->securitypriv.
binstallGrpkey =
false;
adapter->securitypriv.
busetkipkey =
false;
adapter->securitypriv.
bgrpkey_handshake =
false;
ptarget_sta->ieee8021x_blocked
= true;
ptarget_sta->XPrivacy =
adapter->securitypriv.
PrivacyAlgrthm;
memset((u8 *)&ptarget_sta->
x_UncstKey,
0,
sizeof(union Keytype));
memset((u8 *)&ptarget_sta->
tkiprxmickey,
0,
sizeof(union Keytype));
memset((u8 *)&ptarget_sta->
tkiptxmickey,
0,
sizeof(union Keytype));
memset((u8 *)&ptarget_sta->
txpn, 0,
sizeof(union pn48));
memset((u8 *)&ptarget_sta->
rxpn, 0,
sizeof(union pn48));
}
} else {
if (check_fwstate(pmlmepriv,
_FW_UNDER_LINKING))
pmlmepriv->fw_state ^=
_FW_UNDER_LINKING;
goto ignore_joinbss_callback;
}
}
/*s3. update cur_network & indicate connect*/
memcpy(&cur_network->network, &pnetwork->network,
pnetwork->network.Length);
cur_network->aid = pnetwork->join_res;
/*update fw_state will clr _FW_UNDER_LINKING*/
switch (pnetwork->network.InfrastructureMode) {
case Ndis802_11Infrastructure:
pmlmepriv->fw_state = WIFI_STATION_STATE;
break;
case Ndis802_11IBSS:
pmlmepriv->fw_state = WIFI_ADHOC_STATE;
break;
default:
pmlmepriv->fw_state = WIFI_NULL_STATE;
break;
}
r8712_update_protection(adapter,
(cur_network->network.IEs) +
sizeof(struct NDIS_802_11_FIXED_IEs),
(cur_network->network.IELength));
/*TODO: update HT_Capability*/
update_ht_cap(adapter, cur_network->network.IEs,
cur_network->network.IELength);
/*indicate connect*/
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE)
== true)
r8712_indicate_connect(adapter);
_cancel_timer(&pmlmepriv->assoc_timer,
&timer_cancelled);
} else
goto ignore_joinbss_callback;
} else {
if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING) == true) {
_set_timer(&pmlmepriv->assoc_timer, 1);
_clr_fwstate_(pmlmepriv, _FW_UNDER_LINKING);
}
}
ignore_joinbss_callback:
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
if (sizeof(struct list_head) == 4 * sizeof(u32))
kfree((u8 *)pnetwork);
}
void r8712_stassoc_event_callback(struct _adapter *adapter, u8 *pbuf)
{
unsigned long irqL;
struct sta_info *psta;
struct mlme_priv *pmlmepriv = &(adapter->mlmepriv);
struct stassoc_event *pstassoc = (struct stassoc_event *)pbuf;
/* to do: */
if (r8712_access_ctrl(&adapter->acl_list, pstassoc->macaddr) == false)
return;
psta = r8712_get_stainfo(&adapter->stapriv, pstassoc->macaddr);
if (psta != NULL) {
/*the sta have been in sta_info_queue => do nothing
*(between drv has received this event before and
* fw have not yet to set key to CAM_ENTRY) */
return;
}
psta = r8712_alloc_stainfo(&adapter->stapriv, pstassoc->macaddr);
if (psta == NULL)
return;
/* to do : init sta_info variable */
psta->qos_option = 0;
psta->mac_id = le32_to_cpu((uint)pstassoc->cam_id);
/* psta->aid = (uint)pstassoc->cam_id; */
if (adapter->securitypriv.AuthAlgrthm == 2)
psta->XPrivacy = adapter->securitypriv.PrivacyAlgrthm;
psta->ieee8021x_blocked = false;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if ((check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == true) ||
(check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) == true)) {
if (adapter->stapriv.asoc_sta_count == 2) {
/* a sta + bc/mc_stainfo (not Ibss_stainfo) */
r8712_indicate_connect(adapter);
}
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
void r8712_stadel_event_callback(struct _adapter *adapter, u8 *pbuf)
{
unsigned long irqL, irqL2;
struct sta_info *psta;
struct wlan_network *pwlan = NULL;
struct wlan_bssid_ex *pdev_network = NULL;
u8 *pibss = NULL;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
struct stadel_event *pstadel = (struct stadel_event *)pbuf;
struct sta_priv *pstapriv = &adapter->stapriv;
struct wlan_network *tgt_network = &pmlmepriv->cur_network;
spin_lock_irqsave(&pmlmepriv->lock, irqL2);
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE) == true) {
r8712_ind_disconnect(adapter);
r8712_free_assoc_resources(adapter);
}
if (check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE |
WIFI_ADHOC_STATE)) {
psta = r8712_get_stainfo(&adapter->stapriv, pstadel->macaddr);
spin_lock_irqsave(&pstapriv->sta_hash_lock, irqL);
r8712_free_stainfo(adapter, psta);
spin_unlock_irqrestore(&pstapriv->sta_hash_lock, irqL);
if (adapter->stapriv.asoc_sta_count == 1) {
/*a sta + bc/mc_stainfo (not Ibss_stainfo) */
pwlan = r8712_find_network(&pmlmepriv->scanned_queue,
tgt_network->network.MacAddress);
if (pwlan) {
pwlan->fixed = false;
free_network_nolock(pmlmepriv, pwlan);
}
/*re-create ibss*/
pdev_network = &(adapter->registrypriv.dev_network);
pibss = adapter->registrypriv.dev_network.MacAddress;
memcpy(pdev_network, &tgt_network->network,
r8712_get_ndis_wlan_bssid_ex_sz(&tgt_network->
network));
memset(&pdev_network->Ssid, 0,
sizeof(struct ndis_802_11_ssid));
memcpy(&pdev_network->Ssid,
&pmlmepriv->assoc_ssid,
sizeof(struct ndis_802_11_ssid));
r8712_update_registrypriv_dev_network(adapter);
r8712_generate_random_ibss(pibss);
if (check_fwstate(pmlmepriv, WIFI_ADHOC_STATE)) {
_clr_fwstate_(pmlmepriv, WIFI_ADHOC_STATE);
set_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE);
}
}
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL2);
}
void r8712_cpwm_event_callback(struct _adapter *adapter, u8 *pbuf)
{
struct reportpwrstate_parm *preportpwrstate =
(struct reportpwrstate_parm *)pbuf;
preportpwrstate->state |= (u8)(adapter->pwrctrlpriv.cpwm_tog + 0x80);
r8712_cpwm_int_hdl(adapter, preportpwrstate);
}
/* When the Netgear 3500 AP is with WPA2PSK-AES mode, it will send
* the ADDBA req frame with start seq control = 0 to wifi client after
* the WPA handshake and the seqence number of following data packet
* will be 0. In this case, the Rx reorder sequence is not longer than 0
* and the WiFi client will drop the data with seq number 0.
* So, the 8712 firmware has to inform driver with receiving the
* ADDBA-Req frame so that the driver can reset the
* sequence value of Rx reorder contorl.
*/
void r8712_got_addbareq_event_callback(struct _adapter *adapter, u8 *pbuf)
{
struct ADDBA_Req_Report_parm *pAddbareq_pram =
(struct ADDBA_Req_Report_parm *)pbuf;
struct sta_info *psta;
struct sta_priv *pstapriv = &adapter->stapriv;
struct recv_reorder_ctrl *precvreorder_ctrl = NULL;
printk(KERN_INFO "r8712u: [%s] mac = %pM, seq = %d, tid = %d\n",
__func__, pAddbareq_pram->MacAddress,
pAddbareq_pram->StartSeqNum, pAddbareq_pram->tid);
psta = r8712_get_stainfo(pstapriv, pAddbareq_pram->MacAddress);
if (psta) {
precvreorder_ctrl =
&psta->recvreorder_ctrl[pAddbareq_pram->tid];
/* set the indicate_seq to 0xffff so that the rx reorder
* can store any following data packet.
*/
precvreorder_ctrl->indicate_seq = 0xffff;
}
}
void r8712_wpspbc_event_callback(struct _adapter *adapter, u8 *pbuf)
{
if (adapter->securitypriv.wps_hw_pbc_pressed == false)
adapter->securitypriv.wps_hw_pbc_pressed = true;
}
void _r8712_sitesurvey_ctrl_handler(struct _adapter *adapter)
{
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
struct sitesurvey_ctrl *psitesurveyctrl = &pmlmepriv->sitesurveyctrl;
struct registry_priv *pregistrypriv = &adapter->registrypriv;
u64 current_tx_pkts;
uint current_rx_pkts;
current_tx_pkts = (adapter->xmitpriv.tx_pkts) -
(psitesurveyctrl->last_tx_pkts);
current_rx_pkts = (adapter->recvpriv.rx_pkts) -
(psitesurveyctrl->last_rx_pkts);
psitesurveyctrl->last_tx_pkts = adapter->xmitpriv.tx_pkts;
psitesurveyctrl->last_rx_pkts = adapter->recvpriv.rx_pkts;
if ((current_tx_pkts > pregistrypriv->busy_thresh) ||
(current_rx_pkts > pregistrypriv->busy_thresh))
psitesurveyctrl->traffic_busy = true;
else
psitesurveyctrl->traffic_busy = false;
}
void _r8712_join_timeout_handler(struct _adapter *adapter)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
if (adapter->bDriverStopped || adapter->bSurpriseRemoved)
return;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
_clr_fwstate_(pmlmepriv, _FW_UNDER_LINKING);
pmlmepriv->to_join = false;
if (check_fwstate(pmlmepriv, _FW_LINKED) == true) {
r8712_os_indicate_disconnect(adapter);
_clr_fwstate_(pmlmepriv, _FW_LINKED);
}
if (adapter->pwrctrlpriv.pwr_mode != adapter->registrypriv.power_mgnt) {
r8712_set_ps_mode(adapter, adapter->registrypriv.power_mgnt,
adapter->registrypriv.smart_ps);
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
void r8712_scan_timeout_handler (struct _adapter *adapter)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
_clr_fwstate_(pmlmepriv, _FW_UNDER_SURVEY);
pmlmepriv->to_join = false; /* scan fail, so clear to_join flag */
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
void _r8712_dhcp_timeout_handler (struct _adapter *adapter)
{
if (adapter->bDriverStopped || adapter->bSurpriseRemoved)
return;
if (adapter->pwrctrlpriv.pwr_mode != adapter->registrypriv.power_mgnt)
r8712_set_ps_mode(adapter, adapter->registrypriv.power_mgnt,
adapter->registrypriv.smart_ps);
}
void _r8712_wdg_timeout_handler(struct _adapter *adapter)
{
r8712_wdg_wk_cmd(adapter);
}
int r8712_select_and_join_from_scan(struct mlme_priv *pmlmepriv)
{
struct list_head *phead;
unsigned char *dst_ssid, *src_ssid;
struct _adapter *adapter;
struct __queue *queue = NULL;
struct wlan_network *pnetwork = NULL;
struct wlan_network *pnetwork_max_rssi = NULL;
adapter = (struct _adapter *)pmlmepriv->nic_hdl;
queue = &pmlmepriv->scanned_queue;
phead = get_list_head(queue);
pmlmepriv->pscanned = get_next(phead);
while (1) {
if (end_of_queue_search(phead, pmlmepriv->pscanned) == true) {
if ((pmlmepriv->assoc_by_rssi == true) &&
(pnetwork_max_rssi != NULL)) {
pnetwork = pnetwork_max_rssi;
goto ask_for_joinbss;
}
return _FAIL;
}
pnetwork = LIST_CONTAINOR(pmlmepriv->pscanned,
struct wlan_network, list);
if (pnetwork == NULL)
return _FAIL;
pmlmepriv->pscanned = get_next(pmlmepriv->pscanned);
if (pmlmepriv->assoc_by_bssid == true) {
dst_ssid = pnetwork->network.MacAddress;
src_ssid = pmlmepriv->assoc_bssid;
if (!memcmp(dst_ssid, src_ssid, ETH_ALEN)) {
if (check_fwstate(pmlmepriv, _FW_LINKED)) {
if (is_same_network(&pmlmepriv->
cur_network.network,
&pnetwork->network)) {
_clr_fwstate_(pmlmepriv,
_FW_UNDER_LINKING);
/*r8712_indicate_connect again*/
r8712_indicate_connect(adapter);
return 2;
}
r8712_disassoc_cmd(adapter);
r8712_ind_disconnect(adapter);
r8712_free_assoc_resources(adapter);
}
goto ask_for_joinbss;
}
} else if (pmlmepriv->assoc_ssid.SsidLength == 0)
goto ask_for_joinbss;
dst_ssid = pnetwork->network.Ssid.Ssid;
src_ssid = pmlmepriv->assoc_ssid.Ssid;
if ((pnetwork->network.Ssid.SsidLength ==
pmlmepriv->assoc_ssid.SsidLength) &&
(!memcmp(dst_ssid, src_ssid,
pmlmepriv->assoc_ssid.SsidLength))) {
if (pmlmepriv->assoc_by_rssi == true) {
/* if the ssid is the same, select the bss
* which has the max rssi*/
if (pnetwork_max_rssi) {
if (pnetwork->network.Rssi >
pnetwork_max_rssi->network.Rssi)
pnetwork_max_rssi = pnetwork;
} else
pnetwork_max_rssi = pnetwork;
} else if (is_desired_network(adapter, pnetwork)) {
if (check_fwstate(pmlmepriv, _FW_LINKED)) {
r8712_disassoc_cmd(adapter);
r8712_free_assoc_resources(adapter);
}
goto ask_for_joinbss;
}
}
}
return _FAIL;
ask_for_joinbss:
return r8712_joinbss_cmd(adapter, pnetwork);
}
sint r8712_set_auth(struct _adapter *adapter,
struct security_priv *psecuritypriv)
{
struct cmd_priv *pcmdpriv = &adapter->cmdpriv;
struct cmd_obj *pcmd;
struct setauth_parm *psetauthparm;
sint ret = _SUCCESS;
pcmd = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (pcmd == NULL)
return _FAIL;
psetauthparm = (struct setauth_parm *)_malloc(
sizeof(struct setauth_parm));
if (psetauthparm == NULL) {
kfree((unsigned char *)pcmd);
return _FAIL;
}
memset(psetauthparm, 0, sizeof(struct setauth_parm));
psetauthparm->mode = (u8)psecuritypriv->AuthAlgrthm;
pcmd->cmdcode = _SetAuth_CMD_;
pcmd->parmbuf = (unsigned char *)psetauthparm;
pcmd->cmdsz = sizeof(struct setauth_parm);
pcmd->rsp = NULL;
pcmd->rspsz = 0;
_init_listhead(&pcmd->list);
r8712_enqueue_cmd(pcmdpriv, pcmd);
return ret;
}
sint r8712_set_key(struct _adapter *adapter,
struct security_priv *psecuritypriv,
sint keyid)
{
struct cmd_priv *pcmdpriv = &adapter->cmdpriv;
struct cmd_obj *pcmd;
struct setkey_parm *psetkeyparm;
u8 keylen;
pcmd = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (pcmd == NULL)
return _FAIL;
psetkeyparm = (struct setkey_parm *)_malloc(sizeof(struct setkey_parm));
if (psetkeyparm == NULL) {
kfree((unsigned char *)pcmd);
return _FAIL;
}
memset(psetkeyparm, 0, sizeof(struct setkey_parm));
if (psecuritypriv->AuthAlgrthm == 2) { /* 802.1X */
psetkeyparm->algorithm =
(u8)psecuritypriv->XGrpPrivacy;
} else { /* WEP */
psetkeyparm->algorithm =
(u8)psecuritypriv->PrivacyAlgrthm;
}
psetkeyparm->keyid = (u8)keyid;
switch (psetkeyparm->algorithm) {
case _WEP40_:
keylen = 5;
memcpy(psetkeyparm->key,
psecuritypriv->DefKey[keyid].skey, keylen);
break;
case _WEP104_:
keylen = 13;
memcpy(psetkeyparm->key,
psecuritypriv->DefKey[keyid].skey, keylen);
break;
case _TKIP_:
if (keyid < 1 || keyid > 2)
return _FAIL;
keylen = 16;
memcpy(psetkeyparm->key,
&psecuritypriv->XGrpKey[keyid - 1], keylen);
psetkeyparm->grpkey = 1;
break;
case _AES_:
if (keyid < 1 || keyid > 2)
return _FAIL;
keylen = 16;
memcpy(psetkeyparm->key,
&psecuritypriv->XGrpKey[keyid - 1], keylen);
psetkeyparm->grpkey = 1;
break;
default:
return _FAIL;
}
pcmd->cmdcode = _SetKey_CMD_;
pcmd->parmbuf = (u8 *)psetkeyparm;
pcmd->cmdsz = (sizeof(struct setkey_parm));
pcmd->rsp = NULL;
pcmd->rspsz = 0;
_init_listhead(&pcmd->list);
r8712_enqueue_cmd(pcmdpriv, pcmd);
return _SUCCESS;
}
/* adjust IEs for r8712_joinbss_cmd in WMM */
int r8712_restruct_wmm_ie(struct _adapter *adapter, u8 *in_ie, u8 *out_ie,
uint in_len, uint initial_out_len)
{
unsigned int ielength = 0;
unsigned int i, j;
i = 12; /* after the fixed IE */
while (i < in_len) {
ielength = initial_out_len;
if (in_ie[i] == 0xDD && in_ie[i + 2] == 0x00 &&
in_ie[i + 3] == 0x50 && in_ie[i + 4] == 0xF2 &&
in_ie[i + 5] == 0x02 && i + 5 < in_len) {
/*WMM element ID and OUI*/
for (j = i; j < i + 9; j++) {
out_ie[ielength] = in_ie[j];
ielength++;
}
out_ie[initial_out_len + 1] = 0x07;
out_ie[initial_out_len + 6] = 0x00;
out_ie[initial_out_len + 8] = 0x00;
break;
}
i += (in_ie[i + 1] + 2); /* to the next IE element */
}
return ielength;
}
/*
* Ported from 8185: IsInPreAuthKeyList().
*
* Search by BSSID,
* Return Value:
* -1 :if there is no pre-auth key in the table
* >=0 :if there is pre-auth key, and return the entry id
*/
static int SecIsInPMKIDList(struct _adapter *Adapter, u8 *bssid)
{
struct security_priv *psecuritypriv = &Adapter->securitypriv;
int i = 0;
do {
if (psecuritypriv->PMKIDList[i].bUsed &&
(!memcmp(psecuritypriv->PMKIDList[i].Bssid,
bssid, ETH_ALEN)))
break;
else
i++;
} while (i < NUM_PMKID_CACHE);
if (i == NUM_PMKID_CACHE) {
i = -1; /* Could not find. */
} else {
; /* There is one Pre-Authentication Key for the
* specific BSSID. */
}
return i;
}
sint r8712_restruct_sec_ie(struct _adapter *adapter, u8 *in_ie,
u8 *out_ie, uint in_len)
{
u8 authmode = 0, securitytype, match;
u8 sec_ie[255], uncst_oui[4], bkup_ie[255];
u8 wpa_oui[4] = {0x0, 0x50, 0xf2, 0x01};
uint ielength, cnt, remove_cnt;
int iEntry;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
struct security_priv *psecuritypriv = &adapter->securitypriv;
uint ndisauthmode = psecuritypriv->ndisauthtype;
uint ndissecuritytype = psecuritypriv->ndisencryptstatus;
if ((ndisauthmode == Ndis802_11AuthModeWPA) ||
(ndisauthmode == Ndis802_11AuthModeWPAPSK)) {
authmode = _WPA_IE_ID_;
uncst_oui[0] = 0x0;
uncst_oui[1] = 0x50;
uncst_oui[2] = 0xf2;
}
if ((ndisauthmode == Ndis802_11AuthModeWPA2) ||
(ndisauthmode == Ndis802_11AuthModeWPA2PSK)) {
authmode = _WPA2_IE_ID_;
uncst_oui[0] = 0x0;
uncst_oui[1] = 0x0f;
uncst_oui[2] = 0xac;
}
switch (ndissecuritytype) {
case Ndis802_11Encryption1Enabled:
case Ndis802_11Encryption1KeyAbsent:
securitytype = _WEP40_;
uncst_oui[3] = 0x1;
break;
case Ndis802_11Encryption2Enabled:
case Ndis802_11Encryption2KeyAbsent:
securitytype = _TKIP_;
uncst_oui[3] = 0x2;
break;
case Ndis802_11Encryption3Enabled:
case Ndis802_11Encryption3KeyAbsent:
securitytype = _AES_;
uncst_oui[3] = 0x4;
break;
default:
securitytype = _NO_PRIVACY_;
break;
}
/*Search required WPA or WPA2 IE and copy to sec_ie[] */
cnt = 12;
match = false;
while (cnt < in_len) {
if (in_ie[cnt] == authmode) {
if ((authmode == _WPA_IE_ID_) &&
(!memcmp(&in_ie[cnt+2], &wpa_oui[0], 4))) {
memcpy(&sec_ie[0], &in_ie[cnt],
in_ie[cnt + 1] + 2);
match = true;
break;
}
if (authmode == _WPA2_IE_ID_) {
memcpy(&sec_ie[0], &in_ie[cnt],
in_ie[cnt + 1] + 2);
match = true;
break;
}
if (((authmode == _WPA_IE_ID_) &&
(!memcmp(&in_ie[cnt + 2], &wpa_oui[0], 4))) ||
(authmode == _WPA2_IE_ID_))
memcpy(&bkup_ie[0], &in_ie[cnt],
in_ie[cnt + 1] + 2);
}
cnt += in_ie[cnt+1] + 2; /*get next*/
}
/*restruct WPA IE or WPA2 IE in sec_ie[] */
if (match == true) {
if (sec_ie[0] == _WPA_IE_ID_) {
/* parsing SSN IE to select required encryption
* algorithm, and set the bc/mc encryption algorithm */
while (true) {
/*check wpa_oui tag*/
if (memcmp(&sec_ie[2], &wpa_oui[0], 4)) {
match = false;
break;
}
if ((sec_ie[6] != 0x01) || (sec_ie[7] != 0x0)) {
/*IE Ver error*/
match = false;
break;
}
if (!memcmp(&sec_ie[8], &wpa_oui[0], 3)) {
/* get bc/mc encryption type (group
* key type)*/
switch (sec_ie[11]) {
case 0x0: /*none*/
psecuritypriv->XGrpPrivacy =
_NO_PRIVACY_;
break;
case 0x1: /*WEP_40*/
psecuritypriv->XGrpPrivacy =
_WEP40_;
break;
case 0x2: /*TKIP*/
psecuritypriv->XGrpPrivacy =
_TKIP_;
break;
case 0x3: /*AESCCMP*/
case 0x4:
psecuritypriv->XGrpPrivacy =
_AES_;
break;
case 0x5: /*WEP_104*/
psecuritypriv->XGrpPrivacy =
_WEP104_;
break;
}
} else {
match = false;
break;
}
if (sec_ie[12] == 0x01) {
/*check the unicast encryption type*/
if (memcmp(&sec_ie[14],
&uncst_oui[0], 4)) {
match = false;
break;
} /*else the uncst_oui is match*/
} else { /*mixed mode, unicast_enc_type > 1*/
/*select the uncst_oui and remove
* the other uncst_oui*/
cnt = sec_ie[12];
remove_cnt = (cnt-1) * 4;
sec_ie[12] = 0x01;
memcpy(&sec_ie[14], &uncst_oui[0], 4);
/*remove the other unicast suit*/
memcpy(&sec_ie[18],
&sec_ie[18 + remove_cnt],
sec_ie[1] - 18 + 2 -
remove_cnt);
sec_ie[1] = sec_ie[1] - remove_cnt;
}
break;
}
}
if (authmode == _WPA2_IE_ID_) {
/* parsing RSN IE to select required encryption
* algorithm, and set the bc/mc encryption algorithm */
while (true) {
if ((sec_ie[2] != 0x01) || (sec_ie[3] != 0x0)) {
/*IE Ver error*/
match = false;
break;
}
if (!memcmp(&sec_ie[4], &uncst_oui[0], 3)) {
/*get bc/mc encryption type*/
switch (sec_ie[7]) {
case 0x1: /*WEP_40*/
psecuritypriv->XGrpPrivacy =
_WEP40_;
break;
case 0x2: /*TKIP*/
psecuritypriv->XGrpPrivacy =
_TKIP_;
break;
case 0x4: /*AESWRAP*/
psecuritypriv->XGrpPrivacy =
_AES_;
break;
case 0x5: /*WEP_104*/
psecuritypriv->XGrpPrivacy =
_WEP104_;
break;
default: /*one*/
psecuritypriv->XGrpPrivacy =
_NO_PRIVACY_;
break;
}
} else {
match = false;
break;
}
if (sec_ie[8] == 0x01) {
/*check the unicast encryption type*/
if (memcmp(&sec_ie[10],
&uncst_oui[0], 4)) {
match = false;
break;
} /*else the uncst_oui is match*/
} else { /*mixed mode, unicast_enc_type > 1*/
/*select the uncst_oui and remove the
* other uncst_oui*/
cnt = sec_ie[8];
remove_cnt = (cnt-1)*4;
sec_ie[8] = 0x01;
memcpy(&sec_ie[10], &uncst_oui[0], 4);
/*remove the other unicast suit*/
memcpy(&sec_ie[14],
&sec_ie[14 + remove_cnt],
(sec_ie[1] - 14 + 2 -
remove_cnt));
sec_ie[1] = sec_ie[1]-remove_cnt;
}
break;
}
}
}
if ((authmode == _WPA_IE_ID_) || (authmode == _WPA2_IE_ID_)) {
/*copy fixed ie*/
memcpy(out_ie, in_ie, 12);
ielength = 12;
/*copy RSN or SSN*/
if (match == true) {
memcpy(&out_ie[ielength], &sec_ie[0], sec_ie[1]+2);
ielength += sec_ie[1] + 2;
if (authmode == _WPA2_IE_ID_) {
/*the Pre-Authentication bit should be zero*/
out_ie[ielength - 1] = 0;
out_ie[ielength - 2] = 0;
}
r8712_report_sec_ie(adapter, authmode, sec_ie);
}
} else {
/*copy fixed ie only*/
memcpy(out_ie, in_ie, 12);
ielength = 12;
if (psecuritypriv->wps_phase == true) {
memcpy(out_ie+ielength, psecuritypriv->wps_ie,
psecuritypriv->wps_ie_len);
ielength += psecuritypriv->wps_ie_len;
}
}
iEntry = SecIsInPMKIDList(adapter, pmlmepriv->assoc_bssid);
if (iEntry < 0)
return ielength;
else {
if (authmode == _WPA2_IE_ID_) {
out_ie[ielength] = 1;
ielength++;
out_ie[ielength] = 0; /*PMKID count = 0x0100*/
ielength++;
memcpy(&out_ie[ielength],
&psecuritypriv->PMKIDList[iEntry].PMKID, 16);
ielength += 16;
out_ie[13] += 18;/*PMKID length = 2+16*/
}
}
return ielength;
}
void r8712_init_registrypriv_dev_network(struct _adapter *adapter)
{
struct registry_priv *pregistrypriv = &adapter->registrypriv;
struct eeprom_priv *peepriv = &adapter->eeprompriv;
struct wlan_bssid_ex *pdev_network = &pregistrypriv->dev_network;
u8 *myhwaddr = myid(peepriv);
memcpy(pdev_network->MacAddress, myhwaddr, ETH_ALEN);
memcpy(&pdev_network->Ssid, &pregistrypriv->ssid,
sizeof(struct ndis_802_11_ssid));
pdev_network->Configuration.Length =
sizeof(struct NDIS_802_11_CONFIGURATION);
pdev_network->Configuration.BeaconPeriod = 100;
pdev_network->Configuration.FHConfig.Length = 0;
pdev_network->Configuration.FHConfig.HopPattern = 0;
pdev_network->Configuration.FHConfig.HopSet = 0;
pdev_network->Configuration.FHConfig.DwellTime = 0;
}
void r8712_update_registrypriv_dev_network(struct _adapter *adapter)
{
int sz = 0;
struct registry_priv *pregistrypriv = &adapter->registrypriv;
struct wlan_bssid_ex *pdev_network = &pregistrypriv->dev_network;
struct security_priv *psecuritypriv = &adapter->securitypriv;
struct wlan_network *cur_network = &adapter->mlmepriv.cur_network;
pdev_network->Privacy = cpu_to_le32(psecuritypriv->PrivacyAlgrthm
> 0 ? 1 : 0) ; /* adhoc no 802.1x */
pdev_network->Rssi = 0;
switch (pregistrypriv->wireless_mode) {
case WIRELESS_11B:
pdev_network->NetworkTypeInUse = cpu_to_le32(Ndis802_11DS);
break;
case WIRELESS_11G:
case WIRELESS_11BG:
pdev_network->NetworkTypeInUse = cpu_to_le32(Ndis802_11OFDM24);
break;
case WIRELESS_11A:
pdev_network->NetworkTypeInUse = cpu_to_le32(Ndis802_11OFDM5);
break;
default:
/* TODO */
break;
}
pdev_network->Configuration.DSConfig = cpu_to_le32(
pregistrypriv->channel);
if (cur_network->network.InfrastructureMode == Ndis802_11IBSS)
pdev_network->Configuration.ATIMWindow = cpu_to_le32(3);
pdev_network->InfrastructureMode = cpu_to_le32(
cur_network->network.InfrastructureMode);
/* 1. Supported rates
* 2. IE
*/
sz = r8712_generate_ie(pregistrypriv);
pdev_network->IELength = sz;
pdev_network->Length = r8712_get_ndis_wlan_bssid_ex_sz(
(struct ndis_wlan_bssid_ex *)pdev_network);
}
/*the function is at passive_level*/
void r8712_joinbss_reset(struct _adapter *padapter)
{
int i;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct ht_priv *phtpriv = &pmlmepriv->htpriv;
/* todo: if you want to do something io/reg/hw setting before join_bss,
* please add code here */
phtpriv->ampdu_enable = false;/*reset to disabled*/
for (i = 0; i < 16; i++)
phtpriv->baddbareq_issued[i] = false;/*reset it*/
if (phtpriv->ht_option) {
/* validate usb rx aggregation */
r8712_write8(padapter, 0x102500D9, 48);/*TH = 48 pages, 6k*/
} else {
/* invalidate usb rx aggregation */
/* TH=1 => means that invalidate usb rx aggregation */
r8712_write8(padapter, 0x102500D9, 1);
}
}
/*the function is >= passive_level*/
unsigned int r8712_restructure_ht_ie(struct _adapter *padapter, u8 *in_ie,
u8 *out_ie, uint in_len, uint *pout_len)
{
u32 ielen, out_len;
unsigned char *p, *pframe;
struct ieee80211_ht_cap ht_capie;
unsigned char WMM_IE[] = {0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00};
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct qos_priv *pqospriv = &pmlmepriv->qospriv;
struct ht_priv *phtpriv = &pmlmepriv->htpriv;
phtpriv->ht_option = 0;
p = r8712_get_ie(in_ie+12, _HT_CAPABILITY_IE_, &ielen, in_len-12);
if (p && (ielen > 0)) {
if (pqospriv->qos_option == 0) {
out_len = *pout_len;
pframe = r8712_set_ie(out_ie+out_len,
_VENDOR_SPECIFIC_IE_,
_WMM_IE_Length_,
WMM_IE, pout_len);
pqospriv->qos_option = 1;
}
out_len = *pout_len;
memset(&ht_capie, 0, sizeof(struct ieee80211_ht_cap));
ht_capie.cap_info = IEEE80211_HT_CAP_SUP_WIDTH |
IEEE80211_HT_CAP_SGI_20 |
IEEE80211_HT_CAP_SGI_40 |
IEEE80211_HT_CAP_TX_STBC |
IEEE80211_HT_CAP_MAX_AMSDU |
IEEE80211_HT_CAP_DSSSCCK40;
ht_capie.ampdu_params_info = (IEEE80211_HT_CAP_AMPDU_FACTOR &
0x03) | (IEEE80211_HT_CAP_AMPDU_DENSITY & 0x00);
pframe = r8712_set_ie(out_ie+out_len, _HT_CAPABILITY_IE_,
sizeof(struct ieee80211_ht_cap),
(unsigned char *)&ht_capie, pout_len);
phtpriv->ht_option = 1;
}
return phtpriv->ht_option;
}
/* the function is > passive_level (in critical_section) */
static void update_ht_cap(struct _adapter *padapter, u8 *pie, uint ie_len)
{
u8 *p, max_ampdu_sz;
int i, len;
struct sta_info *bmc_sta, *psta;
struct ieee80211_ht_cap *pht_capie;
struct ieee80211_ht_addt_info *pht_addtinfo;
struct recv_reorder_ctrl *preorder_ctrl;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct ht_priv *phtpriv = &pmlmepriv->htpriv;
struct registry_priv *pregistrypriv = &padapter->registrypriv;
struct wlan_network *pcur_network = &(pmlmepriv->cur_network);
if (!phtpriv->ht_option)
return;
/* maybe needs check if ap supports rx ampdu. */
if ((phtpriv->ampdu_enable == false) &&
(pregistrypriv->ampdu_enable == 1))
phtpriv->ampdu_enable = true;
/*check Max Rx A-MPDU Size*/
len = 0;
p = r8712_get_ie(pie + sizeof(struct NDIS_802_11_FIXED_IEs),
_HT_CAPABILITY_IE_,
&len, ie_len -
sizeof(struct NDIS_802_11_FIXED_IEs));
if (p && len > 0) {
pht_capie = (struct ieee80211_ht_cap *)(p+2);
max_ampdu_sz = (pht_capie->ampdu_params_info &
IEEE80211_HT_CAP_AMPDU_FACTOR);
/* max_ampdu_sz (kbytes); */
max_ampdu_sz = 1 << (max_ampdu_sz+3);
phtpriv->rx_ampdu_maxlen = max_ampdu_sz;
}
/* for A-MPDU Rx reordering buffer control for bmc_sta & sta_info
* if A-MPDU Rx is enabled, reseting rx_ordering_ctrl
* wstart_b(indicate_seq) to default value=0xffff
* todo: check if AP can send A-MPDU packets
*/
bmc_sta = r8712_get_bcmc_stainfo(padapter);
if (bmc_sta) {
for (i = 0; i < 16; i++) {
preorder_ctrl = &bmc_sta->recvreorder_ctrl[i];
preorder_ctrl->indicate_seq = 0xffff;
preorder_ctrl->wend_b = 0xffff;
}
}
psta = r8712_get_stainfo(&padapter->stapriv,
pcur_network->network.MacAddress);
if (psta) {
for (i = 0; i < 16 ; i++) {
preorder_ctrl = &psta->recvreorder_ctrl[i];
preorder_ctrl->indicate_seq = 0xffff;
preorder_ctrl->wend_b = 0xffff;
}
}
len = 0;
p = r8712_get_ie(pie + sizeof(struct NDIS_802_11_FIXED_IEs),
_HT_ADD_INFO_IE_, &len,
ie_len-sizeof(struct NDIS_802_11_FIXED_IEs));
if (p && len > 0)
pht_addtinfo = (struct ieee80211_ht_addt_info *)(p + 2);
}
void r8712_issue_addbareq_cmd(struct _adapter *padapter, int priority)
{
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct ht_priv *phtpriv = &pmlmepriv->htpriv;
if ((phtpriv->ht_option == 1) && (phtpriv->ampdu_enable == true)) {
if (phtpriv->baddbareq_issued[priority] == false) {
r8712_addbareq_cmd(padapter, (u8)priority);
phtpriv->baddbareq_issued[priority] = true;
}
}
}
| gpl-2.0 |
zarboz/M7_wls_43 | drivers/video/pxa3xx-gcu.c | 4896 | 17738 | /*
* pxa3xx-gcu.c - Linux kernel module for PXA3xx graphics controllers
*
* This driver needs a DirectFB counterpart in user space, communication
* is handled via mmap()ed memory areas and an ioctl.
*
* Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
* Copyright (c) 2009 Janine Kropp <nin@directfb.org>
* Copyright (c) 2009 Denis Oliver Kropp <dok@directfb.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.
*/
/*
* WARNING: This controller is attached to System Bus 2 of the PXA which
* needs its arbiter to be enabled explicitly (CKENB & 1<<9).
* There is currently no way to do this from Linux, so you need to teach
* your bootloader for now.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/miscdevice.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/ioctl.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/fs.h>
#include <linux/io.h>
#include "pxa3xx-gcu.h"
#define DRV_NAME "pxa3xx-gcu"
#define MISCDEV_MINOR 197
#define REG_GCCR 0x00
#define GCCR_SYNC_CLR (1 << 9)
#define GCCR_BP_RST (1 << 8)
#define GCCR_ABORT (1 << 6)
#define GCCR_STOP (1 << 4)
#define REG_GCISCR 0x04
#define REG_GCIECR 0x08
#define REG_GCRBBR 0x20
#define REG_GCRBLR 0x24
#define REG_GCRBHR 0x28
#define REG_GCRBTR 0x2C
#define REG_GCRBEXHR 0x30
#define IE_EOB (1 << 0)
#define IE_EEOB (1 << 5)
#define IE_ALL 0xff
#define SHARED_SIZE PAGE_ALIGN(sizeof(struct pxa3xx_gcu_shared))
/* #define PXA3XX_GCU_DEBUG */
/* #define PXA3XX_GCU_DEBUG_TIMER */
#ifdef PXA3XX_GCU_DEBUG
#define QDUMP(msg) \
do { \
QPRINT(priv, KERN_DEBUG, msg); \
} while (0)
#else
#define QDUMP(msg) do {} while (0)
#endif
#define QERROR(msg) \
do { \
QPRINT(priv, KERN_ERR, msg); \
} while (0)
struct pxa3xx_gcu_batch {
struct pxa3xx_gcu_batch *next;
u32 *ptr;
dma_addr_t phys;
unsigned long length;
};
struct pxa3xx_gcu_priv {
void __iomem *mmio_base;
struct clk *clk;
struct pxa3xx_gcu_shared *shared;
dma_addr_t shared_phys;
struct resource *resource_mem;
struct miscdevice misc_dev;
struct file_operations misc_fops;
wait_queue_head_t wait_idle;
wait_queue_head_t wait_free;
spinlock_t spinlock;
struct timeval base_time;
struct pxa3xx_gcu_batch *free;
struct pxa3xx_gcu_batch *ready;
struct pxa3xx_gcu_batch *ready_last;
struct pxa3xx_gcu_batch *running;
};
static inline unsigned long
gc_readl(struct pxa3xx_gcu_priv *priv, unsigned int off)
{
return __raw_readl(priv->mmio_base + off);
}
static inline void
gc_writel(struct pxa3xx_gcu_priv *priv, unsigned int off, unsigned long val)
{
__raw_writel(val, priv->mmio_base + off);
}
#define QPRINT(priv, level, msg) \
do { \
struct timeval tv; \
struct pxa3xx_gcu_shared *shared = priv->shared; \
u32 base = gc_readl(priv, REG_GCRBBR); \
\
do_gettimeofday(&tv); \
\
printk(level "%ld.%03ld.%03ld - %-17s: %-21s (%s, " \
"STATUS " \
"0x%02lx, B 0x%08lx [%ld], E %5ld, H %5ld, " \
"T %5ld)\n", \
tv.tv_sec - priv->base_time.tv_sec, \
tv.tv_usec / 1000, tv.tv_usec % 1000, \
__func__, msg, \
shared->hw_running ? "running" : " idle", \
gc_readl(priv, REG_GCISCR), \
gc_readl(priv, REG_GCRBBR), \
gc_readl(priv, REG_GCRBLR), \
(gc_readl(priv, REG_GCRBEXHR) - base) / 4, \
(gc_readl(priv, REG_GCRBHR) - base) / 4, \
(gc_readl(priv, REG_GCRBTR) - base) / 4); \
} while (0)
static void
pxa3xx_gcu_reset(struct pxa3xx_gcu_priv *priv)
{
QDUMP("RESET");
/* disable interrupts */
gc_writel(priv, REG_GCIECR, 0);
/* reset hardware */
gc_writel(priv, REG_GCCR, GCCR_ABORT);
gc_writel(priv, REG_GCCR, 0);
memset(priv->shared, 0, SHARED_SIZE);
priv->shared->buffer_phys = priv->shared_phys;
priv->shared->magic = PXA3XX_GCU_SHARED_MAGIC;
do_gettimeofday(&priv->base_time);
/* set up the ring buffer pointers */
gc_writel(priv, REG_GCRBLR, 0);
gc_writel(priv, REG_GCRBBR, priv->shared_phys);
gc_writel(priv, REG_GCRBTR, priv->shared_phys);
/* enable all IRQs except EOB */
gc_writel(priv, REG_GCIECR, IE_ALL & ~IE_EOB);
}
static void
dump_whole_state(struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_shared *sh = priv->shared;
u32 base = gc_readl(priv, REG_GCRBBR);
QDUMP("DUMP");
printk(KERN_DEBUG "== PXA3XX-GCU DUMP ==\n"
"%s, STATUS 0x%02lx, B 0x%08lx [%ld], E %5ld, H %5ld, T %5ld\n",
sh->hw_running ? "running" : "idle ",
gc_readl(priv, REG_GCISCR),
gc_readl(priv, REG_GCRBBR),
gc_readl(priv, REG_GCRBLR),
(gc_readl(priv, REG_GCRBEXHR) - base) / 4,
(gc_readl(priv, REG_GCRBHR) - base) / 4,
(gc_readl(priv, REG_GCRBTR) - base) / 4);
}
static void
flush_running(struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_batch *running = priv->running;
struct pxa3xx_gcu_batch *next;
while (running) {
next = running->next;
running->next = priv->free;
priv->free = running;
running = next;
}
priv->running = NULL;
}
static void
run_ready(struct pxa3xx_gcu_priv *priv)
{
unsigned int num = 0;
struct pxa3xx_gcu_shared *shared = priv->shared;
struct pxa3xx_gcu_batch *ready = priv->ready;
QDUMP("Start");
BUG_ON(!ready);
shared->buffer[num++] = 0x05000000;
while (ready) {
shared->buffer[num++] = 0x00000001;
shared->buffer[num++] = ready->phys;
ready = ready->next;
}
shared->buffer[num++] = 0x05000000;
priv->running = priv->ready;
priv->ready = priv->ready_last = NULL;
gc_writel(priv, REG_GCRBLR, 0);
shared->hw_running = 1;
/* ring base address */
gc_writel(priv, REG_GCRBBR, shared->buffer_phys);
/* ring tail address */
gc_writel(priv, REG_GCRBTR, shared->buffer_phys + num * 4);
/* ring length */
gc_writel(priv, REG_GCRBLR, ((num + 63) & ~63) * 4);
}
static irqreturn_t
pxa3xx_gcu_handle_irq(int irq, void *ctx)
{
struct pxa3xx_gcu_priv *priv = ctx;
struct pxa3xx_gcu_shared *shared = priv->shared;
u32 status = gc_readl(priv, REG_GCISCR) & IE_ALL;
QDUMP("-Interrupt");
if (!status)
return IRQ_NONE;
spin_lock(&priv->spinlock);
shared->num_interrupts++;
if (status & IE_EEOB) {
QDUMP(" [EEOB]");
flush_running(priv);
wake_up_all(&priv->wait_free);
if (priv->ready) {
run_ready(priv);
} else {
/* There is no more data prepared by the userspace.
* Set hw_running = 0 and wait for the next userspace
* kick-off */
shared->num_idle++;
shared->hw_running = 0;
QDUMP(" '-> Idle.");
/* set ring buffer length to zero */
gc_writel(priv, REG_GCRBLR, 0);
wake_up_all(&priv->wait_idle);
}
shared->num_done++;
} else {
QERROR(" [???]");
dump_whole_state(priv);
}
/* Clear the interrupt */
gc_writel(priv, REG_GCISCR, status);
spin_unlock(&priv->spinlock);
return IRQ_HANDLED;
}
static int
pxa3xx_gcu_wait_idle(struct pxa3xx_gcu_priv *priv)
{
int ret = 0;
QDUMP("Waiting for idle...");
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_wait_idle++;
while (priv->shared->hw_running) {
int num = priv->shared->num_interrupts;
u32 rbexhr = gc_readl(priv, REG_GCRBEXHR);
ret = wait_event_interruptible_timeout(priv->wait_idle,
!priv->shared->hw_running, HZ*4);
if (ret < 0)
break;
if (ret > 0)
continue;
if (gc_readl(priv, REG_GCRBEXHR) == rbexhr &&
priv->shared->num_interrupts == num) {
QERROR("TIMEOUT");
ret = -ETIMEDOUT;
break;
}
}
QDUMP("done");
return ret;
}
static int
pxa3xx_gcu_wait_free(struct pxa3xx_gcu_priv *priv)
{
int ret = 0;
QDUMP("Waiting for free...");
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_wait_free++;
while (!priv->free) {
u32 rbexhr = gc_readl(priv, REG_GCRBEXHR);
ret = wait_event_interruptible_timeout(priv->wait_free,
priv->free, HZ*4);
if (ret < 0)
break;
if (ret > 0)
continue;
if (gc_readl(priv, REG_GCRBEXHR) == rbexhr) {
QERROR("TIMEOUT");
ret = -ETIMEDOUT;
break;
}
}
QDUMP("done");
return ret;
}
/* Misc device layer */
static ssize_t
pxa3xx_gcu_misc_write(struct file *filp, const char *buff,
size_t count, loff_t *offp)
{
int ret;
unsigned long flags;
struct pxa3xx_gcu_batch *buffer;
struct pxa3xx_gcu_priv *priv =
container_of(filp->f_op, struct pxa3xx_gcu_priv, misc_fops);
int words = count / 4;
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_writes++;
priv->shared->num_words += words;
/* Last word reserved for batch buffer end command */
if (words >= PXA3XX_GCU_BATCH_WORDS)
return -E2BIG;
/* Wait for a free buffer */
if (!priv->free) {
ret = pxa3xx_gcu_wait_free(priv);
if (ret < 0)
return ret;
}
/*
* Get buffer from free list
*/
spin_lock_irqsave(&priv->spinlock, flags);
buffer = priv->free;
priv->free = buffer->next;
spin_unlock_irqrestore(&priv->spinlock, flags);
/* Copy data from user into buffer */
ret = copy_from_user(buffer->ptr, buff, words * 4);
if (ret) {
spin_lock_irqsave(&priv->spinlock, flags);
buffer->next = priv->free;
priv->free = buffer;
spin_unlock_irqrestore(&priv->spinlock, flags);
return -EFAULT;
}
buffer->length = words;
/* Append batch buffer end command */
buffer->ptr[words] = 0x01000000;
/*
* Add buffer to ready list
*/
spin_lock_irqsave(&priv->spinlock, flags);
buffer->next = NULL;
if (priv->ready) {
BUG_ON(priv->ready_last == NULL);
priv->ready_last->next = buffer;
} else
priv->ready = buffer;
priv->ready_last = buffer;
if (!priv->shared->hw_running)
run_ready(priv);
spin_unlock_irqrestore(&priv->spinlock, flags);
return words * 4;
}
static long
pxa3xx_gcu_misc_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned long flags;
struct pxa3xx_gcu_priv *priv =
container_of(filp->f_op, struct pxa3xx_gcu_priv, misc_fops);
switch (cmd) {
case PXA3XX_GCU_IOCTL_RESET:
spin_lock_irqsave(&priv->spinlock, flags);
pxa3xx_gcu_reset(priv);
spin_unlock_irqrestore(&priv->spinlock, flags);
return 0;
case PXA3XX_GCU_IOCTL_WAIT_IDLE:
return pxa3xx_gcu_wait_idle(priv);
}
return -ENOSYS;
}
static int
pxa3xx_gcu_misc_mmap(struct file *filp, struct vm_area_struct *vma)
{
unsigned int size = vma->vm_end - vma->vm_start;
struct pxa3xx_gcu_priv *priv =
container_of(filp->f_op, struct pxa3xx_gcu_priv, misc_fops);
switch (vma->vm_pgoff) {
case 0:
/* hand out the shared data area */
if (size != SHARED_SIZE)
return -EINVAL;
return dma_mmap_coherent(NULL, vma,
priv->shared, priv->shared_phys, size);
case SHARED_SIZE >> PAGE_SHIFT:
/* hand out the MMIO base for direct register access
* from userspace */
if (size != resource_size(priv->resource_mem))
return -EINVAL;
vma->vm_flags |= VM_IO;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return io_remap_pfn_range(vma, vma->vm_start,
priv->resource_mem->start >> PAGE_SHIFT,
size, vma->vm_page_prot);
}
return -EINVAL;
}
#ifdef PXA3XX_GCU_DEBUG_TIMER
static struct timer_list pxa3xx_gcu_debug_timer;
static void pxa3xx_gcu_debug_timedout(unsigned long ptr)
{
struct pxa3xx_gcu_priv *priv = (struct pxa3xx_gcu_priv *) ptr;
QERROR("Timer DUMP");
/* init the timer structure */
init_timer(&pxa3xx_gcu_debug_timer);
pxa3xx_gcu_debug_timer.function = pxa3xx_gcu_debug_timedout;
pxa3xx_gcu_debug_timer.data = ptr;
pxa3xx_gcu_debug_timer.expires = jiffies + 5*HZ; /* one second */
add_timer(&pxa3xx_gcu_debug_timer);
}
static void pxa3xx_gcu_init_debug_timer(void)
{
pxa3xx_gcu_debug_timedout((unsigned long) &pxa3xx_gcu_debug_timer);
}
#else
static inline void pxa3xx_gcu_init_debug_timer(void) {}
#endif
static int
add_buffer(struct platform_device *dev,
struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_batch *buffer;
buffer = kzalloc(sizeof(struct pxa3xx_gcu_batch), GFP_KERNEL);
if (!buffer)
return -ENOMEM;
buffer->ptr = dma_alloc_coherent(&dev->dev, PXA3XX_GCU_BATCH_WORDS * 4,
&buffer->phys, GFP_KERNEL);
if (!buffer->ptr) {
kfree(buffer);
return -ENOMEM;
}
buffer->next = priv->free;
priv->free = buffer;
return 0;
}
static void
free_buffers(struct platform_device *dev,
struct pxa3xx_gcu_priv *priv)
{
struct pxa3xx_gcu_batch *next, *buffer = priv->free;
while (buffer) {
next = buffer->next;
dma_free_coherent(&dev->dev, PXA3XX_GCU_BATCH_WORDS * 4,
buffer->ptr, buffer->phys);
kfree(buffer);
buffer = next;
}
priv->free = NULL;
}
static int __devinit
pxa3xx_gcu_probe(struct platform_device *dev)
{
int i, ret, irq;
struct resource *r;
struct pxa3xx_gcu_priv *priv;
priv = kzalloc(sizeof(struct pxa3xx_gcu_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
for (i = 0; i < 8; i++) {
ret = add_buffer(dev, priv);
if (ret) {
dev_err(&dev->dev, "failed to allocate DMA memory\n");
goto err_free_priv;
}
}
init_waitqueue_head(&priv->wait_idle);
init_waitqueue_head(&priv->wait_free);
spin_lock_init(&priv->spinlock);
/* we allocate the misc device structure as part of our own allocation,
* so we can get a pointer to our priv structure later on with
* container_of(). This isn't really necessary as we have a fixed minor
* number anyway, but this is to avoid statics. */
priv->misc_fops.owner = THIS_MODULE;
priv->misc_fops.write = pxa3xx_gcu_misc_write;
priv->misc_fops.unlocked_ioctl = pxa3xx_gcu_misc_ioctl;
priv->misc_fops.mmap = pxa3xx_gcu_misc_mmap;
priv->misc_dev.minor = MISCDEV_MINOR,
priv->misc_dev.name = DRV_NAME,
priv->misc_dev.fops = &priv->misc_fops,
/* register misc device */
ret = misc_register(&priv->misc_dev);
if (ret < 0) {
dev_err(&dev->dev, "misc_register() for minor %d failed\n",
MISCDEV_MINOR);
goto err_free_priv;
}
/* handle IO resources */
r = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (r == NULL) {
dev_err(&dev->dev, "no I/O memory resource defined\n");
ret = -ENODEV;
goto err_misc_deregister;
}
if (!request_mem_region(r->start, resource_size(r), dev->name)) {
dev_err(&dev->dev, "failed to request I/O memory\n");
ret = -EBUSY;
goto err_misc_deregister;
}
priv->mmio_base = ioremap_nocache(r->start, resource_size(r));
if (!priv->mmio_base) {
dev_err(&dev->dev, "failed to map I/O memory\n");
ret = -EBUSY;
goto err_free_mem_region;
}
/* allocate dma memory */
priv->shared = dma_alloc_coherent(&dev->dev, SHARED_SIZE,
&priv->shared_phys, GFP_KERNEL);
if (!priv->shared) {
dev_err(&dev->dev, "failed to allocate DMA memory\n");
ret = -ENOMEM;
goto err_free_io;
}
/* enable the clock */
priv->clk = clk_get(&dev->dev, NULL);
if (IS_ERR(priv->clk)) {
dev_err(&dev->dev, "failed to get clock\n");
ret = -ENODEV;
goto err_free_dma;
}
ret = clk_enable(priv->clk);
if (ret < 0) {
dev_err(&dev->dev, "failed to enable clock\n");
goto err_put_clk;
}
/* request the IRQ */
irq = platform_get_irq(dev, 0);
if (irq < 0) {
dev_err(&dev->dev, "no IRQ defined\n");
ret = -ENODEV;
goto err_put_clk;
}
ret = request_irq(irq, pxa3xx_gcu_handle_irq,
0, DRV_NAME, priv);
if (ret) {
dev_err(&dev->dev, "request_irq failed\n");
ret = -EBUSY;
goto err_put_clk;
}
platform_set_drvdata(dev, priv);
priv->resource_mem = r;
pxa3xx_gcu_reset(priv);
pxa3xx_gcu_init_debug_timer();
dev_info(&dev->dev, "registered @0x%p, DMA 0x%p (%d bytes), IRQ %d\n",
(void *) r->start, (void *) priv->shared_phys,
SHARED_SIZE, irq);
return 0;
err_put_clk:
clk_disable(priv->clk);
clk_put(priv->clk);
err_free_dma:
dma_free_coherent(&dev->dev, SHARED_SIZE,
priv->shared, priv->shared_phys);
err_free_io:
iounmap(priv->mmio_base);
err_free_mem_region:
release_mem_region(r->start, resource_size(r));
err_misc_deregister:
misc_deregister(&priv->misc_dev);
err_free_priv:
platform_set_drvdata(dev, NULL);
free_buffers(dev, priv);
kfree(priv);
return ret;
}
static int __devexit
pxa3xx_gcu_remove(struct platform_device *dev)
{
struct pxa3xx_gcu_priv *priv = platform_get_drvdata(dev);
struct resource *r = priv->resource_mem;
pxa3xx_gcu_wait_idle(priv);
misc_deregister(&priv->misc_dev);
dma_free_coherent(&dev->dev, SHARED_SIZE,
priv->shared, priv->shared_phys);
iounmap(priv->mmio_base);
release_mem_region(r->start, resource_size(r));
platform_set_drvdata(dev, NULL);
clk_disable(priv->clk);
free_buffers(dev, priv);
kfree(priv);
return 0;
}
static struct platform_driver pxa3xx_gcu_driver = {
.probe = pxa3xx_gcu_probe,
.remove = __devexit_p(pxa3xx_gcu_remove),
.driver = {
.owner = THIS_MODULE,
.name = DRV_NAME,
},
};
module_platform_driver(pxa3xx_gcu_driver);
MODULE_DESCRIPTION("PXA3xx graphics controller unit driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(MISCDEV_MINOR);
MODULE_AUTHOR("Janine Kropp <nin@directfb.org>, "
"Denis Oliver Kropp <dok@directfb.org>, "
"Daniel Mack <daniel@caiaq.de>");
| gpl-2.0 |
rutvik95/android_kernel_samsung_i9060 | drivers/media/rc/redrat3.c | 4896 | 34713 | /*
* USB RedRat3 IR Transceiver rc-core driver
*
* Copyright (c) 2011 by Jarod Wilson <jarod@redhat.com>
* based heavily on the work of Stephen Cox, with additional
* help from RedRat Ltd.
*
* This driver began life based an an old version of the first-generation
* lirc_mceusb driver from the lirc 0.7.2 distribution. It was then
* significantly rewritten by Stephen Cox with the aid of RedRat Ltd's
* Chris Dodge.
*
* The driver was then ported to rc-core and significantly rewritten again,
* by Jarod, using the in-kernel mceusb driver as a guide, after an initial
* port effort was started by Stephen.
*
* TODO LIST:
* - fix lirc not showing repeats properly
* --
*
* The RedRat3 is a USB transceiver with both send & receive,
* with 2 separate sensors available for receive to enable
* both good long range reception for general use, and good
* short range reception when required for learning a signal.
*
* http://www.redrat.co.uk/
*
* It uses its own little protocol to communicate, the required
* parts of which are embedded within this driver.
* --
*
* 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/device.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/input.h>
#include <media/rc-core.h>
/* Driver Information */
#define DRIVER_VERSION "0.70"
#define DRIVER_AUTHOR "Jarod Wilson <jarod@redhat.com>"
#define DRIVER_AUTHOR2 "The Dweller, Stephen Cox"
#define DRIVER_DESC "RedRat3 USB IR Transceiver Driver"
#define DRIVER_NAME "redrat3"
/* module parameters */
#ifdef CONFIG_USB_DEBUG
static int debug = 1;
#else
static int debug;
#endif
#define RR3_DEBUG_STANDARD 0x1
#define RR3_DEBUG_FUNCTION_TRACE 0x2
#define rr3_dbg(dev, fmt, ...) \
do { \
if (debug & RR3_DEBUG_STANDARD) \
dev_info(dev, fmt, ## __VA_ARGS__); \
} while (0)
#define rr3_ftr(dev, fmt, ...) \
do { \
if (debug & RR3_DEBUG_FUNCTION_TRACE) \
dev_info(dev, fmt, ## __VA_ARGS__); \
} while (0)
/* bulk data transfer types */
#define RR3_ERROR 0x01
#define RR3_MOD_SIGNAL_IN 0x20
#define RR3_MOD_SIGNAL_OUT 0x21
/* Get the RR firmware version */
#define RR3_FW_VERSION 0xb1
#define RR3_FW_VERSION_LEN 64
/* Send encoded signal bulk-sent earlier*/
#define RR3_TX_SEND_SIGNAL 0xb3
#define RR3_SET_IR_PARAM 0xb7
#define RR3_GET_IR_PARAM 0xb8
/* Blink the red LED on the device */
#define RR3_BLINK_LED 0xb9
/* Read serial number of device */
#define RR3_READ_SER_NO 0xba
#define RR3_SER_NO_LEN 4
/* Start capture with the RC receiver */
#define RR3_RC_DET_ENABLE 0xbb
/* Stop capture with the RC receiver */
#define RR3_RC_DET_DISABLE 0xbc
/* Return the status of RC detector capture */
#define RR3_RC_DET_STATUS 0xbd
/* Reset redrat */
#define RR3_RESET 0xa0
/* Max number of lengths in the signal. */
#define RR3_IR_IO_MAX_LENGTHS 0x01
/* Periods to measure mod. freq. */
#define RR3_IR_IO_PERIODS_MF 0x02
/* Size of memory for main signal data */
#define RR3_IR_IO_SIG_MEM_SIZE 0x03
/* Delta value when measuring lengths */
#define RR3_IR_IO_LENGTH_FUZZ 0x04
/* Timeout for end of signal detection */
#define RR3_IR_IO_SIG_TIMEOUT 0x05
/* Minumum value for pause recognition. */
#define RR3_IR_IO_MIN_PAUSE 0x06
/* Clock freq. of EZ-USB chip */
#define RR3_CLK 24000000
/* Clock periods per timer count */
#define RR3_CLK_PER_COUNT 12
/* (RR3_CLK / RR3_CLK_PER_COUNT) */
#define RR3_CLK_CONV_FACTOR 2000000
/* USB bulk-in IR data endpoint address */
#define RR3_BULK_IN_EP_ADDR 0x82
/* Raw Modulated signal data value offsets */
#define RR3_PAUSE_OFFSET 0
#define RR3_FREQ_COUNT_OFFSET 4
#define RR3_NUM_PERIOD_OFFSET 6
#define RR3_MAX_LENGTHS_OFFSET 8
#define RR3_NUM_LENGTHS_OFFSET 9
#define RR3_MAX_SIGS_OFFSET 10
#define RR3_NUM_SIGS_OFFSET 12
#define RR3_REPEATS_OFFSET 14
/* Size of the fixed-length portion of the signal */
#define RR3_HEADER_LENGTH 15
#define RR3_DRIVER_MAXLENS 128
#define RR3_MAX_SIG_SIZE 512
#define RR3_MAX_BUF_SIZE \
((2 * RR3_HEADER_LENGTH) + RR3_DRIVER_MAXLENS + RR3_MAX_SIG_SIZE)
#define RR3_TIME_UNIT 50
#define RR3_END_OF_SIGNAL 0x7f
#define RR3_TX_HEADER_OFFSET 4
#define RR3_TX_TRAILER_LEN 2
#define RR3_RX_MIN_TIMEOUT 5
#define RR3_RX_MAX_TIMEOUT 2000
/* The 8051's CPUCS Register address */
#define RR3_CPUCS_REG_ADDR 0x7f92
#define USB_RR3USB_VENDOR_ID 0x112a
#define USB_RR3USB_PRODUCT_ID 0x0001
#define USB_RR3IIUSB_PRODUCT_ID 0x0005
/* table of devices that work with this driver */
static struct usb_device_id redrat3_dev_table[] = {
/* Original version of the RedRat3 */
{USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3USB_PRODUCT_ID)},
/* Second Version/release of the RedRat3 - RetRat3-II */
{USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3IIUSB_PRODUCT_ID)},
{} /* Terminating entry */
};
/* Structure to hold all of our device specific stuff */
struct redrat3_dev {
/* core device bits */
struct rc_dev *rc;
struct device *dev;
/* save off the usb device pointer */
struct usb_device *udev;
/* the receive endpoint */
struct usb_endpoint_descriptor *ep_in;
/* the buffer to receive data */
unsigned char *bulk_in_buf;
/* urb used to read ir data */
struct urb *read_urb;
/* the send endpoint */
struct usb_endpoint_descriptor *ep_out;
/* the buffer to send data */
unsigned char *bulk_out_buf;
/* the urb used to send data */
struct urb *write_urb;
/* usb dma */
dma_addr_t dma_in;
dma_addr_t dma_out;
/* locks this structure */
struct mutex lock;
/* rx signal timeout timer */
struct timer_list rx_timeout;
u32 hw_timeout;
/* is the detector enabled*/
bool det_enabled;
/* Is the device currently transmitting?*/
bool transmitting;
/* store for current packet */
char pbuf[RR3_MAX_BUF_SIZE];
u16 pktlen;
u16 pkttype;
u16 bytes_read;
/* indicate whether we are going to reprocess
* the USB callback with a bigger buffer */
int buftoosmall;
char *datap;
u32 carrier;
char name[128];
char phys[64];
};
/* All incoming data buffers adhere to a very specific data format */
struct redrat3_signal_header {
u16 length; /* Length of data being transferred */
u16 transfer_type; /* Type of data transferred */
u32 pause; /* Pause between main and repeat signals */
u16 mod_freq_count; /* Value of timer on mod. freq. measurement */
u16 no_periods; /* No. of periods over which mod. freq. is measured */
u8 max_lengths; /* Max no. of lengths (i.e. size of array) */
u8 no_lengths; /* Actual no. of elements in lengths array */
u16 max_sig_size; /* Max no. of values in signal data array */
u16 sig_size; /* Acuto no. of values in signal data array */
u8 no_repeats; /* No. of repeats of repeat signal section */
/* Here forward is the lengths and signal data */
};
static void redrat3_dump_signal_header(struct redrat3_signal_header *header)
{
pr_info("%s:\n", __func__);
pr_info(" * length: %u, transfer_type: 0x%02x\n",
header->length, header->transfer_type);
pr_info(" * pause: %u, freq_count: %u, no_periods: %u\n",
header->pause, header->mod_freq_count, header->no_periods);
pr_info(" * lengths: %u (max: %u)\n",
header->no_lengths, header->max_lengths);
pr_info(" * sig_size: %u (max: %u)\n",
header->sig_size, header->max_sig_size);
pr_info(" * repeats: %u\n", header->no_repeats);
}
static void redrat3_dump_signal_data(char *buffer, u16 len)
{
int offset, i;
char *data_vals;
pr_info("%s:", __func__);
offset = RR3_TX_HEADER_OFFSET + RR3_HEADER_LENGTH
+ (RR3_DRIVER_MAXLENS * sizeof(u16));
/* read RR3_DRIVER_MAXLENS from ctrl msg */
data_vals = buffer + offset;
for (i = 0; i < len; i++) {
if (i % 10 == 0)
pr_cont("\n * ");
pr_cont("%02x ", *data_vals++);
}
pr_cont("\n");
}
/*
* redrat3_issue_async
*
* Issues an async read to the ir data in port..
* sets the callback to be redrat3_handle_async
*/
static void redrat3_issue_async(struct redrat3_dev *rr3)
{
int res;
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
memset(rr3->bulk_in_buf, 0, rr3->ep_in->wMaxPacketSize);
res = usb_submit_urb(rr3->read_urb, GFP_ATOMIC);
if (res)
rr3_dbg(rr3->dev, "%s: receive request FAILED! "
"(res %d, len %d)\n", __func__, res,
rr3->read_urb->transfer_buffer_length);
}
static void redrat3_dump_fw_error(struct redrat3_dev *rr3, int code)
{
if (!rr3->transmitting && (code != 0x40))
dev_info(rr3->dev, "fw error code 0x%02x: ", code);
switch (code) {
case 0x00:
pr_cont("No Error\n");
break;
/* Codes 0x20 through 0x2f are IR Firmware Errors */
case 0x20:
pr_cont("Initial signal pulse not long enough "
"to measure carrier frequency\n");
break;
case 0x21:
pr_cont("Not enough length values allocated for signal\n");
break;
case 0x22:
pr_cont("Not enough memory allocated for signal data\n");
break;
case 0x23:
pr_cont("Too many signal repeats\n");
break;
case 0x28:
pr_cont("Insufficient memory available for IR signal "
"data memory allocation\n");
break;
case 0x29:
pr_cont("Insufficient memory available "
"for IrDa signal data memory allocation\n");
break;
/* Codes 0x30 through 0x3f are USB Firmware Errors */
case 0x30:
pr_cont("Insufficient memory available for bulk "
"transfer structure\n");
break;
/*
* Other error codes... These are primarily errors that can occur in
* the control messages sent to the redrat
*/
case 0x40:
if (!rr3->transmitting)
pr_cont("Signal capture has been terminated\n");
break;
case 0x41:
pr_cont("Attempt to set/get and unknown signal I/O "
"algorithm parameter\n");
break;
case 0x42:
pr_cont("Signal capture already started\n");
break;
default:
pr_cont("Unknown Error\n");
break;
}
}
static u32 redrat3_val_to_mod_freq(struct redrat3_signal_header *ph)
{
u32 mod_freq = 0;
if (ph->mod_freq_count != 0)
mod_freq = (RR3_CLK * ph->no_periods) /
(ph->mod_freq_count * RR3_CLK_PER_COUNT);
return mod_freq;
}
/* this function scales down the figures for the same result... */
static u32 redrat3_len_to_us(u32 length)
{
u32 biglen = length * 1000;
u32 divisor = (RR3_CLK_CONV_FACTOR) / 1000;
u32 result = (u32) (biglen / divisor);
/* don't allow zero lengths to go back, breaks lirc */
return result ? result : 1;
}
/*
* convert us back into redrat3 lengths
*
* length * 1000 length * 1000000
* ------------- = ---------------- = micro
* rr3clk / 1000 rr3clk
* 6 * 2 4 * 3 micro * rr3clk micro * rr3clk / 1000
* ----- = 4 ----- = 6 -------------- = len ---------------------
* 3 2 1000000 1000
*/
static u32 redrat3_us_to_len(u32 microsec)
{
u32 result;
u32 divisor;
microsec &= IR_MAX_DURATION;
divisor = (RR3_CLK_CONV_FACTOR / 1000);
result = (u32)(microsec * divisor) / 1000;
/* don't allow zero lengths to go back, breaks lirc */
return result ? result : 1;
}
/* timer callback to send reset event */
static void redrat3_rx_timeout(unsigned long data)
{
struct redrat3_dev *rr3 = (struct redrat3_dev *)data;
rr3_dbg(rr3->dev, "calling ir_raw_event_reset\n");
ir_raw_event_reset(rr3->rc);
}
static void redrat3_process_ir_data(struct redrat3_dev *rr3)
{
DEFINE_IR_RAW_EVENT(rawir);
struct redrat3_signal_header header;
struct device *dev;
int i, trailer = 0;
unsigned long delay;
u32 mod_freq, single_len;
u16 *len_vals;
u8 *data_vals;
u32 tmp32;
u16 tmp16;
char *sig_data;
if (!rr3) {
pr_err("%s called with no context!\n", __func__);
return;
}
rr3_ftr(rr3->dev, "Entered %s\n", __func__);
dev = rr3->dev;
sig_data = rr3->pbuf;
header.length = rr3->pktlen;
header.transfer_type = rr3->pkttype;
/* Sanity check */
if (!(header.length >= RR3_HEADER_LENGTH))
dev_warn(dev, "read returned less than rr3 header len\n");
/* Make sure we reset the IR kfifo after a bit of inactivity */
delay = usecs_to_jiffies(rr3->hw_timeout);
mod_timer(&rr3->rx_timeout, jiffies + delay);
memcpy(&tmp32, sig_data + RR3_PAUSE_OFFSET, sizeof(tmp32));
header.pause = be32_to_cpu(tmp32);
memcpy(&tmp16, sig_data + RR3_FREQ_COUNT_OFFSET, sizeof(tmp16));
header.mod_freq_count = be16_to_cpu(tmp16);
memcpy(&tmp16, sig_data + RR3_NUM_PERIOD_OFFSET, sizeof(tmp16));
header.no_periods = be16_to_cpu(tmp16);
header.max_lengths = sig_data[RR3_MAX_LENGTHS_OFFSET];
header.no_lengths = sig_data[RR3_NUM_LENGTHS_OFFSET];
memcpy(&tmp16, sig_data + RR3_MAX_SIGS_OFFSET, sizeof(tmp16));
header.max_sig_size = be16_to_cpu(tmp16);
memcpy(&tmp16, sig_data + RR3_NUM_SIGS_OFFSET, sizeof(tmp16));
header.sig_size = be16_to_cpu(tmp16);
header.no_repeats= sig_data[RR3_REPEATS_OFFSET];
if (debug) {
redrat3_dump_signal_header(&header);
redrat3_dump_signal_data(sig_data, header.sig_size);
}
mod_freq = redrat3_val_to_mod_freq(&header);
rr3_dbg(dev, "Got mod_freq of %u\n", mod_freq);
/* Here we pull out the 'length' values from the signal */
len_vals = (u16 *)(sig_data + RR3_HEADER_LENGTH);
data_vals = sig_data + RR3_HEADER_LENGTH +
(header.max_lengths * sizeof(u16));
/* process each rr3 encoded byte into an int */
for (i = 0; i < header.sig_size; i++) {
u16 val = len_vals[data_vals[i]];
single_len = redrat3_len_to_us((u32)be16_to_cpu(val));
/* we should always get pulse/space/pulse/space samples */
if (i % 2)
rawir.pulse = false;
else
rawir.pulse = true;
rawir.duration = US_TO_NS(single_len);
/* Save initial pulse length to fudge trailer */
if (i == 0)
trailer = rawir.duration;
/* cap the value to IR_MAX_DURATION */
rawir.duration &= IR_MAX_DURATION;
rr3_dbg(dev, "storing %s with duration %d (i: %d)\n",
rawir.pulse ? "pulse" : "space", rawir.duration, i);
ir_raw_event_store_with_filter(rr3->rc, &rawir);
}
/* add a trailing space, if need be */
if (i % 2) {
rawir.pulse = false;
/* this duration is made up, and may not be ideal... */
if (trailer < US_TO_NS(1000))
rawir.duration = US_TO_NS(2800);
else
rawir.duration = trailer;
rr3_dbg(dev, "storing trailing space with duration %d\n",
rawir.duration);
ir_raw_event_store_with_filter(rr3->rc, &rawir);
}
rr3_dbg(dev, "calling ir_raw_event_handle\n");
ir_raw_event_handle(rr3->rc);
return;
}
/* Util fn to send rr3 cmds */
static u8 redrat3_send_cmd(int cmd, struct redrat3_dev *rr3)
{
struct usb_device *udev;
u8 *data;
int res;
data = kzalloc(sizeof(u8), GFP_KERNEL);
if (!data)
return -ENOMEM;
udev = rr3->udev;
res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), cmd,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x0000, 0x0000, data, sizeof(u8), HZ * 10);
if (res < 0) {
dev_err(rr3->dev, "%s: Error sending rr3 cmd res %d, data %d",
__func__, res, *data);
res = -EIO;
} else
res = (u8)data[0];
kfree(data);
return res;
}
/* Enables the long range detector and starts async receive */
static int redrat3_enable_detector(struct redrat3_dev *rr3)
{
struct device *dev = rr3->dev;
u8 ret;
rr3_ftr(dev, "Entering %s\n", __func__);
ret = redrat3_send_cmd(RR3_RC_DET_ENABLE, rr3);
if (ret != 0)
dev_dbg(dev, "%s: unexpected ret of %d\n",
__func__, ret);
ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
if (ret != 1) {
dev_err(dev, "%s: detector status: %d, should be 1\n",
__func__, ret);
return -EIO;
}
rr3->det_enabled = true;
redrat3_issue_async(rr3);
return 0;
}
/* Disables the rr3 long range detector */
static void redrat3_disable_detector(struct redrat3_dev *rr3)
{
struct device *dev = rr3->dev;
u8 ret;
rr3_ftr(dev, "Entering %s\n", __func__);
ret = redrat3_send_cmd(RR3_RC_DET_DISABLE, rr3);
if (ret != 0)
dev_err(dev, "%s: failure!\n", __func__);
ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
if (ret != 0)
dev_warn(dev, "%s: detector status: %d, should be 0\n",
__func__, ret);
rr3->det_enabled = false;
}
static inline void redrat3_delete(struct redrat3_dev *rr3,
struct usb_device *udev)
{
rr3_ftr(rr3->dev, "%s cleaning up\n", __func__);
usb_kill_urb(rr3->read_urb);
usb_kill_urb(rr3->write_urb);
usb_free_urb(rr3->read_urb);
usb_free_urb(rr3->write_urb);
usb_free_coherent(udev, rr3->ep_in->wMaxPacketSize,
rr3->bulk_in_buf, rr3->dma_in);
usb_free_coherent(udev, rr3->ep_out->wMaxPacketSize,
rr3->bulk_out_buf, rr3->dma_out);
kfree(rr3);
}
static u32 redrat3_get_timeout(struct redrat3_dev *rr3)
{
u32 *tmp;
u32 timeout = MS_TO_US(150); /* a sane default, if things go haywire */
int len, ret, pipe;
len = sizeof(*tmp);
tmp = kzalloc(len, GFP_KERNEL);
if (!tmp) {
dev_warn(rr3->dev, "Memory allocation faillure\n");
return timeout;
}
pipe = usb_rcvctrlpipe(rr3->udev, 0);
ret = usb_control_msg(rr3->udev, pipe, RR3_GET_IR_PARAM,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
RR3_IR_IO_SIG_TIMEOUT, 0, tmp, len, HZ * 5);
if (ret != len) {
dev_warn(rr3->dev, "Failed to read timeout from hardware\n");
return timeout;
}
timeout = redrat3_len_to_us(be32_to_cpu(*tmp));
rr3_dbg(rr3->dev, "Got timeout of %d ms\n", timeout / 1000);
return timeout;
}
static void redrat3_reset(struct redrat3_dev *rr3)
{
struct usb_device *udev = rr3->udev;
struct device *dev = rr3->dev;
int rc, rxpipe, txpipe;
u8 *val;
int len = sizeof(u8);
rr3_ftr(dev, "Entering %s\n", __func__);
rxpipe = usb_rcvctrlpipe(udev, 0);
txpipe = usb_sndctrlpipe(udev, 0);
val = kzalloc(len, GFP_KERNEL);
if (!val) {
dev_err(dev, "Memory allocation failure\n");
return;
}
*val = 0x01;
rc = usb_control_msg(udev, rxpipe, RR3_RESET,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
RR3_CPUCS_REG_ADDR, 0, val, len, HZ * 25);
rr3_dbg(dev, "reset returned 0x%02x\n", rc);
*val = 5;
rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
RR3_IR_IO_LENGTH_FUZZ, 0, val, len, HZ * 25);
rr3_dbg(dev, "set ir parm len fuzz %d rc 0x%02x\n", *val, rc);
*val = RR3_DRIVER_MAXLENS;
rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
RR3_IR_IO_MAX_LENGTHS, 0, val, len, HZ * 25);
rr3_dbg(dev, "set ir parm max lens %d rc 0x%02x\n", *val, rc);
kfree(val);
}
static void redrat3_get_firmware_rev(struct redrat3_dev *rr3)
{
int rc = 0;
char *buffer;
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
buffer = kzalloc(sizeof(char) * (RR3_FW_VERSION_LEN + 1), GFP_KERNEL);
if (!buffer) {
dev_err(rr3->dev, "Memory allocation failure\n");
return;
}
rc = usb_control_msg(rr3->udev, usb_rcvctrlpipe(rr3->udev, 0),
RR3_FW_VERSION,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0, 0, buffer, RR3_FW_VERSION_LEN, HZ * 5);
if (rc >= 0)
dev_info(rr3->dev, "Firmware rev: %s", buffer);
else
dev_err(rr3->dev, "Problem fetching firmware ID\n");
kfree(buffer);
rr3_ftr(rr3->dev, "Exiting %s\n", __func__);
}
static void redrat3_read_packet_start(struct redrat3_dev *rr3, int len)
{
u16 tx_error;
u16 hdrlen;
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
/* grab the Length and type of transfer */
memcpy(&(rr3->pktlen), (unsigned char *) rr3->bulk_in_buf,
sizeof(rr3->pktlen));
memcpy(&(rr3->pkttype), ((unsigned char *) rr3->bulk_in_buf +
sizeof(rr3->pktlen)),
sizeof(rr3->pkttype));
/*data needs conversion to know what its real values are*/
rr3->pktlen = be16_to_cpu(rr3->pktlen);
rr3->pkttype = be16_to_cpu(rr3->pkttype);
switch (rr3->pkttype) {
case RR3_ERROR:
memcpy(&tx_error, ((unsigned char *)rr3->bulk_in_buf
+ (sizeof(rr3->pktlen) + sizeof(rr3->pkttype))),
sizeof(tx_error));
tx_error = be16_to_cpu(tx_error);
redrat3_dump_fw_error(rr3, tx_error);
break;
case RR3_MOD_SIGNAL_IN:
hdrlen = sizeof(rr3->pktlen) + sizeof(rr3->pkttype);
rr3->bytes_read = len;
rr3->bytes_read -= hdrlen;
rr3->datap = &(rr3->pbuf[0]);
memcpy(rr3->datap, ((unsigned char *)rr3->bulk_in_buf + hdrlen),
rr3->bytes_read);
rr3->datap += rr3->bytes_read;
rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
rr3->bytes_read, rr3->pktlen);
break;
default:
rr3_dbg(rr3->dev, "ignoring packet with type 0x%02x, "
"len of %d, 0x%02x\n", rr3->pkttype, len, rr3->pktlen);
break;
}
}
static void redrat3_read_packet_continue(struct redrat3_dev *rr3, int len)
{
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
memcpy(rr3->datap, (unsigned char *)rr3->bulk_in_buf, len);
rr3->datap += len;
rr3->bytes_read += len;
rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
rr3->bytes_read, rr3->pktlen);
}
/* gather IR data from incoming urb, process it when we have enough */
static int redrat3_get_ir_data(struct redrat3_dev *rr3, int len)
{
struct device *dev = rr3->dev;
int ret = 0;
rr3_ftr(dev, "Entering %s\n", __func__);
if (rr3->pktlen > RR3_MAX_BUF_SIZE) {
dev_err(rr3->dev, "error: packet larger than buffer\n");
ret = -EINVAL;
goto out;
}
if ((rr3->bytes_read == 0) &&
(len >= (sizeof(rr3->pkttype) + sizeof(rr3->pktlen)))) {
redrat3_read_packet_start(rr3, len);
} else if (rr3->bytes_read != 0) {
redrat3_read_packet_continue(rr3, len);
} else if (rr3->bytes_read == 0) {
dev_err(dev, "error: no packet data read\n");
ret = -ENODATA;
goto out;
}
if (rr3->bytes_read > rr3->pktlen) {
dev_err(dev, "bytes_read (%d) greater than pktlen (%d)\n",
rr3->bytes_read, rr3->pktlen);
ret = -EINVAL;
goto out;
} else if (rr3->bytes_read < rr3->pktlen)
/* we're still accumulating data */
return 0;
/* if we get here, we've got IR data to decode */
if (rr3->pkttype == RR3_MOD_SIGNAL_IN)
redrat3_process_ir_data(rr3);
else
rr3_dbg(dev, "discarding non-signal data packet "
"(type 0x%02x)\n", rr3->pkttype);
out:
rr3->bytes_read = 0;
rr3->pktlen = 0;
rr3->pkttype = 0;
return ret;
}
/* callback function from USB when async USB request has completed */
static void redrat3_handle_async(struct urb *urb, struct pt_regs *regs)
{
struct redrat3_dev *rr3;
int ret;
if (!urb)
return;
rr3 = urb->context;
if (!rr3) {
pr_err("%s called with invalid context!\n", __func__);
usb_unlink_urb(urb);
return;
}
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
switch (urb->status) {
case 0:
ret = redrat3_get_ir_data(rr3, urb->actual_length);
if (!ret) {
/* no error, prepare to read more */
redrat3_issue_async(rr3);
}
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
usb_unlink_urb(urb);
return;
case -EPIPE:
default:
dev_warn(rr3->dev, "Error: urb status = %d\n", urb->status);
rr3->bytes_read = 0;
rr3->pktlen = 0;
rr3->pkttype = 0;
break;
}
}
static void redrat3_write_bulk_callback(struct urb *urb, struct pt_regs *regs)
{
struct redrat3_dev *rr3;
int len;
if (!urb)
return;
rr3 = urb->context;
if (rr3) {
len = urb->actual_length;
rr3_ftr(rr3->dev, "%s: called (status=%d len=%d)\n",
__func__, urb->status, len);
}
}
static u16 mod_freq_to_val(unsigned int mod_freq)
{
int mult = 6000000;
/* Clk used in mod. freq. generation is CLK24/4. */
return (u16)(65536 - (mult / mod_freq));
}
static int redrat3_set_tx_carrier(struct rc_dev *rcdev, u32 carrier)
{
struct redrat3_dev *rr3 = rcdev->priv;
struct device *dev = rr3->dev;
rr3_dbg(dev, "Setting modulation frequency to %u", carrier);
rr3->carrier = carrier;
return carrier;
}
static int redrat3_transmit_ir(struct rc_dev *rcdev, unsigned *txbuf,
unsigned count)
{
struct redrat3_dev *rr3 = rcdev->priv;
struct device *dev = rr3->dev;
struct redrat3_signal_header header;
int i, j, ret, ret_len, offset;
int lencheck, cur_sample_len, pipe;
char *buffer = NULL, *sigdata = NULL;
int *sample_lens = NULL;
u32 tmpi;
u16 tmps;
u8 *datap;
u8 curlencheck = 0;
u16 *lengths_ptr;
int sendbuf_len;
rr3_ftr(dev, "Entering %s\n", __func__);
if (rr3->transmitting) {
dev_warn(dev, "%s: transmitter already in use\n", __func__);
return -EAGAIN;
}
if (count > (RR3_DRIVER_MAXLENS * 2))
return -EINVAL;
/* rr3 will disable rc detector on transmit */
rr3->det_enabled = false;
rr3->transmitting = true;
sample_lens = kzalloc(sizeof(int) * RR3_DRIVER_MAXLENS, GFP_KERNEL);
if (!sample_lens) {
ret = -ENOMEM;
goto out;
}
for (i = 0; i < count; i++) {
for (lencheck = 0; lencheck < curlencheck; lencheck++) {
cur_sample_len = redrat3_us_to_len(txbuf[i]);
if (sample_lens[lencheck] == cur_sample_len)
break;
}
if (lencheck == curlencheck) {
cur_sample_len = redrat3_us_to_len(txbuf[i]);
rr3_dbg(dev, "txbuf[%d]=%u, pos %d, enc %u\n",
i, txbuf[i], curlencheck, cur_sample_len);
if (curlencheck < 255) {
/* now convert the value to a proper
* rr3 value.. */
sample_lens[curlencheck] = cur_sample_len;
curlencheck++;
} else {
dev_err(dev, "signal too long\n");
ret = -EINVAL;
goto out;
}
}
}
sigdata = kzalloc((count + RR3_TX_TRAILER_LEN), GFP_KERNEL);
if (!sigdata) {
ret = -ENOMEM;
goto out;
}
sigdata[count] = RR3_END_OF_SIGNAL;
sigdata[count + 1] = RR3_END_OF_SIGNAL;
for (i = 0; i < count; i++) {
for (j = 0; j < curlencheck; j++) {
if (sample_lens[j] == redrat3_us_to_len(txbuf[i]))
sigdata[i] = j;
}
}
offset = RR3_TX_HEADER_OFFSET;
sendbuf_len = RR3_HEADER_LENGTH + (sizeof(u16) * RR3_DRIVER_MAXLENS)
+ count + RR3_TX_TRAILER_LEN + offset;
buffer = kzalloc(sendbuf_len, GFP_KERNEL);
if (!buffer) {
ret = -ENOMEM;
goto out;
}
/* fill in our packet header */
header.length = sendbuf_len - offset;
header.transfer_type = RR3_MOD_SIGNAL_OUT;
header.pause = redrat3_len_to_us(100);
header.mod_freq_count = mod_freq_to_val(rr3->carrier);
header.no_periods = 0; /* n/a to transmit */
header.max_lengths = RR3_DRIVER_MAXLENS;
header.no_lengths = curlencheck;
header.max_sig_size = RR3_MAX_SIG_SIZE;
header.sig_size = count + RR3_TX_TRAILER_LEN;
/* we currently rely on repeat handling in the IR encoding source */
header.no_repeats = 0;
tmps = cpu_to_be16(header.length);
memcpy(buffer, &tmps, 2);
tmps = cpu_to_be16(header.transfer_type);
memcpy(buffer + 2, &tmps, 2);
tmpi = cpu_to_be32(header.pause);
memcpy(buffer + offset, &tmpi, sizeof(tmpi));
tmps = cpu_to_be16(header.mod_freq_count);
memcpy(buffer + offset + RR3_FREQ_COUNT_OFFSET, &tmps, 2);
buffer[offset + RR3_NUM_LENGTHS_OFFSET] = header.no_lengths;
tmps = cpu_to_be16(header.sig_size);
memcpy(buffer + offset + RR3_NUM_SIGS_OFFSET, &tmps, 2);
buffer[offset + RR3_REPEATS_OFFSET] = header.no_repeats;
lengths_ptr = (u16 *)(buffer + offset + RR3_HEADER_LENGTH);
for (i = 0; i < curlencheck; ++i)
lengths_ptr[i] = cpu_to_be16(sample_lens[i]);
datap = (u8 *)(buffer + offset + RR3_HEADER_LENGTH +
(sizeof(u16) * RR3_DRIVER_MAXLENS));
memcpy(datap, sigdata, (count + RR3_TX_TRAILER_LEN));
if (debug) {
redrat3_dump_signal_header(&header);
redrat3_dump_signal_data(buffer, header.sig_size);
}
pipe = usb_sndbulkpipe(rr3->udev, rr3->ep_out->bEndpointAddress);
tmps = usb_bulk_msg(rr3->udev, pipe, buffer,
sendbuf_len, &ret_len, 10 * HZ);
rr3_dbg(dev, "sent %d bytes, (ret %d)\n", ret_len, tmps);
/* now tell the hardware to transmit what we sent it */
pipe = usb_rcvctrlpipe(rr3->udev, 0);
ret = usb_control_msg(rr3->udev, pipe, RR3_TX_SEND_SIGNAL,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0, 0, buffer, 2, HZ * 10);
if (ret < 0)
dev_err(dev, "Error: control msg send failed, rc %d\n", ret);
else
ret = count;
out:
kfree(sample_lens);
kfree(buffer);
kfree(sigdata);
rr3->transmitting = false;
/* rr3 re-enables rc detector because it was enabled before */
rr3->det_enabled = true;
return ret;
}
static struct rc_dev *redrat3_init_rc_dev(struct redrat3_dev *rr3)
{
struct device *dev = rr3->dev;
struct rc_dev *rc;
int ret = -ENODEV;
u16 prod = le16_to_cpu(rr3->udev->descriptor.idProduct);
rc = rc_allocate_device();
if (!rc) {
dev_err(dev, "remote input dev allocation failed\n");
goto out;
}
snprintf(rr3->name, sizeof(rr3->name), "RedRat3%s "
"Infrared Remote Transceiver (%04x:%04x)",
prod == USB_RR3IIUSB_PRODUCT_ID ? "-II" : "",
le16_to_cpu(rr3->udev->descriptor.idVendor), prod);
usb_make_path(rr3->udev, rr3->phys, sizeof(rr3->phys));
rc->input_name = rr3->name;
rc->input_phys = rr3->phys;
usb_to_input_id(rr3->udev, &rc->input_id);
rc->dev.parent = dev;
rc->priv = rr3;
rc->driver_type = RC_DRIVER_IR_RAW;
rc->allowed_protos = RC_TYPE_ALL;
rc->timeout = US_TO_NS(2750);
rc->tx_ir = redrat3_transmit_ir;
rc->s_tx_carrier = redrat3_set_tx_carrier;
rc->driver_name = DRIVER_NAME;
rc->map_name = RC_MAP_HAUPPAUGE;
ret = rc_register_device(rc);
if (ret < 0) {
dev_err(dev, "remote dev registration failed\n");
goto out;
}
return rc;
out:
rc_free_device(rc);
return NULL;
}
static int __devinit redrat3_dev_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct device *dev = &intf->dev;
struct usb_host_interface *uhi;
struct redrat3_dev *rr3;
struct usb_endpoint_descriptor *ep;
struct usb_endpoint_descriptor *ep_in = NULL;
struct usb_endpoint_descriptor *ep_out = NULL;
u8 addr, attrs;
int pipe, i;
int retval = -ENOMEM;
rr3_ftr(dev, "%s called\n", __func__);
uhi = intf->cur_altsetting;
/* find our bulk-in and bulk-out endpoints */
for (i = 0; i < uhi->desc.bNumEndpoints; ++i) {
ep = &uhi->endpoint[i].desc;
addr = ep->bEndpointAddress;
attrs = ep->bmAttributes;
if ((ep_in == NULL) &&
((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) &&
((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_BULK)) {
rr3_dbg(dev, "found bulk-in endpoint at 0x%02x\n",
ep->bEndpointAddress);
/* data comes in on 0x82, 0x81 is for other data... */
if (ep->bEndpointAddress == RR3_BULK_IN_EP_ADDR)
ep_in = ep;
}
if ((ep_out == NULL) &&
((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) &&
((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_BULK)) {
rr3_dbg(dev, "found bulk-out endpoint at 0x%02x\n",
ep->bEndpointAddress);
ep_out = ep;
}
}
if (!ep_in || !ep_out) {
dev_err(dev, "Couldn't find both in and out endpoints\n");
retval = -ENODEV;
goto no_endpoints;
}
/* allocate memory for our device state and initialize it */
rr3 = kzalloc(sizeof(*rr3), GFP_KERNEL);
if (rr3 == NULL) {
dev_err(dev, "Memory allocation failure\n");
goto no_endpoints;
}
rr3->dev = &intf->dev;
/* set up bulk-in endpoint */
rr3->read_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rr3->read_urb) {
dev_err(dev, "Read urb allocation failure\n");
goto error;
}
rr3->ep_in = ep_in;
rr3->bulk_in_buf = usb_alloc_coherent(udev, ep_in->wMaxPacketSize,
GFP_ATOMIC, &rr3->dma_in);
if (!rr3->bulk_in_buf) {
dev_err(dev, "Read buffer allocation failure\n");
goto error;
}
pipe = usb_rcvbulkpipe(udev, ep_in->bEndpointAddress);
usb_fill_bulk_urb(rr3->read_urb, udev, pipe,
rr3->bulk_in_buf, ep_in->wMaxPacketSize,
(usb_complete_t)redrat3_handle_async, rr3);
/* set up bulk-out endpoint*/
rr3->write_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rr3->write_urb) {
dev_err(dev, "Write urb allocation failure\n");
goto error;
}
rr3->ep_out = ep_out;
rr3->bulk_out_buf = usb_alloc_coherent(udev, ep_out->wMaxPacketSize,
GFP_ATOMIC, &rr3->dma_out);
if (!rr3->bulk_out_buf) {
dev_err(dev, "Write buffer allocation failure\n");
goto error;
}
pipe = usb_sndbulkpipe(udev, ep_out->bEndpointAddress);
usb_fill_bulk_urb(rr3->write_urb, udev, pipe,
rr3->bulk_out_buf, ep_out->wMaxPacketSize,
(usb_complete_t)redrat3_write_bulk_callback, rr3);
mutex_init(&rr3->lock);
rr3->udev = udev;
redrat3_reset(rr3);
redrat3_get_firmware_rev(rr3);
/* might be all we need to do? */
retval = redrat3_enable_detector(rr3);
if (retval < 0)
goto error;
/* store current hardware timeout, in us, will use for kfifo resets */
rr3->hw_timeout = redrat3_get_timeout(rr3);
/* default.. will get overridden by any sends with a freq defined */
rr3->carrier = 38000;
rr3->rc = redrat3_init_rc_dev(rr3);
if (!rr3->rc)
goto error;
setup_timer(&rr3->rx_timeout, redrat3_rx_timeout, (unsigned long)rr3);
/* we can register the device now, as it is ready */
usb_set_intfdata(intf, rr3);
rr3_ftr(dev, "Exiting %s\n", __func__);
return 0;
error:
redrat3_delete(rr3, rr3->udev);
no_endpoints:
dev_err(dev, "%s: retval = %x", __func__, retval);
return retval;
}
static void __devexit redrat3_dev_disconnect(struct usb_interface *intf)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct redrat3_dev *rr3 = usb_get_intfdata(intf);
rr3_ftr(&intf->dev, "Entering %s\n", __func__);
if (!rr3)
return;
redrat3_disable_detector(rr3);
usb_set_intfdata(intf, NULL);
rc_unregister_device(rr3->rc);
del_timer_sync(&rr3->rx_timeout);
redrat3_delete(rr3, udev);
rr3_ftr(&intf->dev, "RedRat3 IR Transceiver now disconnected\n");
}
static int redrat3_dev_suspend(struct usb_interface *intf, pm_message_t message)
{
struct redrat3_dev *rr3 = usb_get_intfdata(intf);
rr3_ftr(rr3->dev, "suspend\n");
usb_kill_urb(rr3->read_urb);
return 0;
}
static int redrat3_dev_resume(struct usb_interface *intf)
{
struct redrat3_dev *rr3 = usb_get_intfdata(intf);
rr3_ftr(rr3->dev, "resume\n");
if (usb_submit_urb(rr3->read_urb, GFP_ATOMIC))
return -EIO;
return 0;
}
static struct usb_driver redrat3_dev_driver = {
.name = DRIVER_NAME,
.probe = redrat3_dev_probe,
.disconnect = redrat3_dev_disconnect,
.suspend = redrat3_dev_suspend,
.resume = redrat3_dev_resume,
.reset_resume = redrat3_dev_resume,
.id_table = redrat3_dev_table
};
module_usb_driver(redrat3_dev_driver);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_AUTHOR(DRIVER_AUTHOR2);
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(usb, redrat3_dev_table);
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Enable module debug spew. 0 = no debugging (default) "
"0x1 = standard debug messages, 0x2 = function tracing debug. "
"Flag bits are addative (i.e., 0x3 for both debug types).");
| gpl-2.0 |
AK-Kernel/AK-Mako | drivers/gpu/drm/ttm/ttm_agp_backend.c | 5408 | 4164 | /**************************************************************************
*
* Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
* 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, sub license, 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 NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS 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.
*
**************************************************************************/
/*
* Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
* Keith Packard.
*/
#define pr_fmt(fmt) "[TTM] " fmt
#include "ttm/ttm_module.h"
#include "ttm/ttm_bo_driver.h"
#include "ttm/ttm_page_alloc.h"
#ifdef TTM_HAS_AGP
#include "ttm/ttm_placement.h"
#include <linux/agp_backend.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <asm/agp.h>
struct ttm_agp_backend {
struct ttm_tt ttm;
struct agp_memory *mem;
struct agp_bridge_data *bridge;
};
static int ttm_agp_bind(struct ttm_tt *ttm, struct ttm_mem_reg *bo_mem)
{
struct ttm_agp_backend *agp_be = container_of(ttm, struct ttm_agp_backend, ttm);
struct drm_mm_node *node = bo_mem->mm_node;
struct agp_memory *mem;
int ret, cached = (bo_mem->placement & TTM_PL_FLAG_CACHED);
unsigned i;
mem = agp_allocate_memory(agp_be->bridge, ttm->num_pages, AGP_USER_MEMORY);
if (unlikely(mem == NULL))
return -ENOMEM;
mem->page_count = 0;
for (i = 0; i < ttm->num_pages; i++) {
struct page *page = ttm->pages[i];
if (!page)
page = ttm->dummy_read_page;
mem->pages[mem->page_count++] = page;
}
agp_be->mem = mem;
mem->is_flushed = 1;
mem->type = (cached) ? AGP_USER_CACHED_MEMORY : AGP_USER_MEMORY;
ret = agp_bind_memory(mem, node->start);
if (ret)
pr_err("AGP Bind memory failed\n");
return ret;
}
static int ttm_agp_unbind(struct ttm_tt *ttm)
{
struct ttm_agp_backend *agp_be = container_of(ttm, struct ttm_agp_backend, ttm);
if (agp_be->mem) {
if (agp_be->mem->is_bound)
return agp_unbind_memory(agp_be->mem);
agp_free_memory(agp_be->mem);
agp_be->mem = NULL;
}
return 0;
}
static void ttm_agp_destroy(struct ttm_tt *ttm)
{
struct ttm_agp_backend *agp_be = container_of(ttm, struct ttm_agp_backend, ttm);
if (agp_be->mem)
ttm_agp_unbind(ttm);
ttm_tt_fini(ttm);
kfree(agp_be);
}
static struct ttm_backend_func ttm_agp_func = {
.bind = ttm_agp_bind,
.unbind = ttm_agp_unbind,
.destroy = ttm_agp_destroy,
};
struct ttm_tt *ttm_agp_tt_create(struct ttm_bo_device *bdev,
struct agp_bridge_data *bridge,
unsigned long size, uint32_t page_flags,
struct page *dummy_read_page)
{
struct ttm_agp_backend *agp_be;
agp_be = kmalloc(sizeof(*agp_be), GFP_KERNEL);
if (!agp_be)
return NULL;
agp_be->mem = NULL;
agp_be->bridge = bridge;
agp_be->ttm.func = &ttm_agp_func;
if (ttm_tt_init(&agp_be->ttm, bdev, size, page_flags, dummy_read_page)) {
return NULL;
}
return &agp_be->ttm;
}
EXPORT_SYMBOL(ttm_agp_tt_create);
int ttm_agp_tt_populate(struct ttm_tt *ttm)
{
if (ttm->state != tt_unpopulated)
return 0;
return ttm_pool_populate(ttm);
}
EXPORT_SYMBOL(ttm_agp_tt_populate);
void ttm_agp_tt_unpopulate(struct ttm_tt *ttm)
{
ttm_pool_unpopulate(ttm);
}
EXPORT_SYMBOL(ttm_agp_tt_unpopulate);
#endif
| gpl-2.0 |
friedrich420/N4-AEL-KERNEL-LOLLIPOP | drivers/i2c/algos/i2c-algo-pcf.c | 7456 | 11674 | /*
* i2c-algo-pcf.c i2c driver algorithms for PCF8584 adapters
*
* Copyright (C) 1995-1997 Simon G. Vogl
* 1998-2000 Hans Berglund
*
* 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.
*
* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi> and
* Frodo Looijaard <frodol@dds.nl>, and also from Martin Bailey
* <mbailey@littlefeet-inc.com>
*
* Partially rewriten by Oleg I. Vdovikin <vdovikin@jscc.ru> to handle multiple
* messages, proper stop/repstart signaling during receive, added detect code
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-pcf.h>
#include "i2c-algo-pcf.h"
#define DEB2(x) if (i2c_debug >= 2) x
#define DEB3(x) if (i2c_debug >= 3) x /* print several statistical values */
#define DEBPROTO(x) if (i2c_debug >= 9) x;
/* debug the protocol by showing transferred bits */
#define DEF_TIMEOUT 16
/*
* module parameters:
*/
static int i2c_debug;
/* setting states on the bus with the right timing: */
#define set_pcf(adap, ctl, val) adap->setpcf(adap->data, ctl, val)
#define get_pcf(adap, ctl) adap->getpcf(adap->data, ctl)
#define get_own(adap) adap->getown(adap->data)
#define get_clock(adap) adap->getclock(adap->data)
#define i2c_outb(adap, val) adap->setpcf(adap->data, 0, val)
#define i2c_inb(adap) adap->getpcf(adap->data, 0)
/* other auxiliary functions */
static void i2c_start(struct i2c_algo_pcf_data *adap)
{
DEBPROTO(printk(KERN_DEBUG "S "));
set_pcf(adap, 1, I2C_PCF_START);
}
static void i2c_repstart(struct i2c_algo_pcf_data *adap)
{
DEBPROTO(printk(" Sr "));
set_pcf(adap, 1, I2C_PCF_REPSTART);
}
static void i2c_stop(struct i2c_algo_pcf_data *adap)
{
DEBPROTO(printk("P\n"));
set_pcf(adap, 1, I2C_PCF_STOP);
}
static void handle_lab(struct i2c_algo_pcf_data *adap, const int *status)
{
DEB2(printk(KERN_INFO
"i2c-algo-pcf.o: lost arbitration (CSR 0x%02x)\n",
*status));
/*
* Cleanup from LAB -- reset and enable ESO.
* This resets the PCF8584; since we've lost the bus, no
* further attempts should be made by callers to clean up
* (no i2c_stop() etc.)
*/
set_pcf(adap, 1, I2C_PCF_PIN);
set_pcf(adap, 1, I2C_PCF_ESO);
/*
* We pause for a time period sufficient for any running
* I2C transaction to complete -- the arbitration logic won't
* work properly until the next START is seen.
* It is assumed the bus driver or client has set a proper value.
*
* REVISIT: should probably use msleep instead of mdelay if we
* know we can sleep.
*/
if (adap->lab_mdelay)
mdelay(adap->lab_mdelay);
DEB2(printk(KERN_INFO
"i2c-algo-pcf.o: reset LAB condition (CSR 0x%02x)\n",
get_pcf(adap, 1)));
}
static int wait_for_bb(struct i2c_algo_pcf_data *adap)
{
int timeout = DEF_TIMEOUT;
int status;
status = get_pcf(adap, 1);
while (!(status & I2C_PCF_BB) && --timeout) {
udelay(100); /* wait for 100 us */
status = get_pcf(adap, 1);
}
if (timeout == 0) {
printk(KERN_ERR "Timeout waiting for Bus Busy\n");
return -ETIMEDOUT;
}
return 0;
}
static int wait_for_pin(struct i2c_algo_pcf_data *adap, int *status)
{
int timeout = DEF_TIMEOUT;
*status = get_pcf(adap, 1);
while ((*status & I2C_PCF_PIN) && --timeout) {
adap->waitforpin(adap->data);
*status = get_pcf(adap, 1);
}
if (*status & I2C_PCF_LAB) {
handle_lab(adap, status);
return -EINTR;
}
if (timeout == 0)
return -ETIMEDOUT;
return 0;
}
/*
* This should perform the 'PCF8584 initialization sequence' as described
* in the Philips IC12 data book (1995, Aug 29).
* There should be a 30 clock cycle wait after reset, I assume this
* has been fulfilled.
* There should be a delay at the end equal to the longest I2C message
* to synchronize the BB-bit (in multimaster systems). How long is
* this? I assume 1 second is always long enough.
*
* vdovikin: added detect code for PCF8584
*/
static int pcf_init_8584 (struct i2c_algo_pcf_data *adap)
{
unsigned char temp;
DEB3(printk(KERN_DEBUG "i2c-algo-pcf.o: PCF state 0x%02x\n",
get_pcf(adap, 1)));
/* S1=0x80: S0 selected, serial interface off */
set_pcf(adap, 1, I2C_PCF_PIN);
/*
* check to see S1 now used as R/W ctrl -
* PCF8584 does that when ESO is zero
*/
if (((temp = get_pcf(adap, 1)) & 0x7f) != (0)) {
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: PCF detection failed -- can't select S0 (0x%02x).\n", temp));
return -ENXIO; /* definitely not PCF8584 */
}
/* load own address in S0, effective address is (own << 1) */
i2c_outb(adap, get_own(adap));
/* check it's really written */
if ((temp = i2c_inb(adap)) != get_own(adap)) {
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: PCF detection failed -- can't set S0 (0x%02x).\n", temp));
return -ENXIO;
}
/* S1=0xA0, next byte in S2 */
set_pcf(adap, 1, I2C_PCF_PIN | I2C_PCF_ES1);
/* check to see S2 now selected */
if (((temp = get_pcf(adap, 1)) & 0x7f) != I2C_PCF_ES1) {
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: PCF detection failed -- can't select S2 (0x%02x).\n", temp));
return -ENXIO;
}
/* load clock register S2 */
i2c_outb(adap, get_clock(adap));
/* check it's really written, the only 5 lowest bits does matter */
if (((temp = i2c_inb(adap)) & 0x1f) != get_clock(adap)) {
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: PCF detection failed -- can't set S2 (0x%02x).\n", temp));
return -ENXIO;
}
/* Enable serial interface, idle, S0 selected */
set_pcf(adap, 1, I2C_PCF_IDLE);
/* check to see PCF is really idled and we can access status register */
if ((temp = get_pcf(adap, 1)) != (I2C_PCF_PIN | I2C_PCF_BB)) {
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: PCF detection failed -- can't select S1` (0x%02x).\n", temp));
return -ENXIO;
}
printk(KERN_DEBUG "i2c-algo-pcf.o: detected and initialized PCF8584.\n");
return 0;
}
static int pcf_sendbytes(struct i2c_adapter *i2c_adap, const char *buf,
int count, int last)
{
struct i2c_algo_pcf_data *adap = i2c_adap->algo_data;
int wrcount, status, timeout;
for (wrcount=0; wrcount<count; ++wrcount) {
DEB2(dev_dbg(&i2c_adap->dev, "i2c_write: writing %2.2X\n",
buf[wrcount] & 0xff));
i2c_outb(adap, buf[wrcount]);
timeout = wait_for_pin(adap, &status);
if (timeout) {
if (timeout == -EINTR)
return -EINTR; /* arbitration lost */
i2c_stop(adap);
dev_err(&i2c_adap->dev, "i2c_write: error - timeout.\n");
return -EREMOTEIO; /* got a better one ?? */
}
if (status & I2C_PCF_LRB) {
i2c_stop(adap);
dev_err(&i2c_adap->dev, "i2c_write: error - no ack.\n");
return -EREMOTEIO; /* got a better one ?? */
}
}
if (last)
i2c_stop(adap);
else
i2c_repstart(adap);
return wrcount;
}
static int pcf_readbytes(struct i2c_adapter *i2c_adap, char *buf,
int count, int last)
{
int i, status;
struct i2c_algo_pcf_data *adap = i2c_adap->algo_data;
int wfp;
/* increment number of bytes to read by one -- read dummy byte */
for (i = 0; i <= count; i++) {
if ((wfp = wait_for_pin(adap, &status))) {
if (wfp == -EINTR)
return -EINTR; /* arbitration lost */
i2c_stop(adap);
dev_err(&i2c_adap->dev, "pcf_readbytes timed out.\n");
return -1;
}
if ((status & I2C_PCF_LRB) && (i != count)) {
i2c_stop(adap);
dev_err(&i2c_adap->dev, "i2c_read: i2c_inb, No ack.\n");
return -1;
}
if (i == count - 1) {
set_pcf(adap, 1, I2C_PCF_ESO);
} else if (i == count) {
if (last)
i2c_stop(adap);
else
i2c_repstart(adap);
}
if (i)
buf[i - 1] = i2c_inb(adap);
else
i2c_inb(adap); /* dummy read */
}
return i - 1;
}
static int pcf_doAddress(struct i2c_algo_pcf_data *adap,
struct i2c_msg *msg)
{
unsigned short flags = msg->flags;
unsigned char addr;
addr = msg->addr << 1;
if (flags & I2C_M_RD)
addr |= 1;
if (flags & I2C_M_REV_DIR_ADDR)
addr ^= 1;
i2c_outb(adap, addr);
return 0;
}
static int pcf_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg *msgs,
int num)
{
struct i2c_algo_pcf_data *adap = i2c_adap->algo_data;
struct i2c_msg *pmsg;
int i;
int ret=0, timeout, status;
if (adap->xfer_begin)
adap->xfer_begin(adap->data);
/* Check for bus busy */
timeout = wait_for_bb(adap);
if (timeout) {
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: "
"Timeout waiting for BB in pcf_xfer\n");)
i = -EIO;
goto out;
}
for (i = 0;ret >= 0 && i < num; i++) {
pmsg = &msgs[i];
DEB2(printk(KERN_DEBUG "i2c-algo-pcf.o: Doing %s %d bytes to 0x%02x - %d of %d messages\n",
pmsg->flags & I2C_M_RD ? "read" : "write",
pmsg->len, pmsg->addr, i + 1, num);)
ret = pcf_doAddress(adap, pmsg);
/* Send START */
if (i == 0)
i2c_start(adap);
/* Wait for PIN (pending interrupt NOT) */
timeout = wait_for_pin(adap, &status);
if (timeout) {
if (timeout == -EINTR) {
/* arbitration lost */
i = -EINTR;
goto out;
}
i2c_stop(adap);
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: Timeout waiting "
"for PIN(1) in pcf_xfer\n");)
i = -EREMOTEIO;
goto out;
}
/* Check LRB (last rcvd bit - slave ack) */
if (status & I2C_PCF_LRB) {
i2c_stop(adap);
DEB2(printk(KERN_ERR "i2c-algo-pcf.o: No LRB(1) in pcf_xfer\n");)
i = -EREMOTEIO;
goto out;
}
DEB3(printk(KERN_DEBUG "i2c-algo-pcf.o: Msg %d, addr=0x%x, flags=0x%x, len=%d\n",
i, msgs[i].addr, msgs[i].flags, msgs[i].len);)
if (pmsg->flags & I2C_M_RD) {
ret = pcf_readbytes(i2c_adap, pmsg->buf, pmsg->len,
(i + 1 == num));
if (ret != pmsg->len) {
DEB2(printk(KERN_DEBUG "i2c-algo-pcf.o: fail: "
"only read %d bytes.\n",ret));
} else {
DEB2(printk(KERN_DEBUG "i2c-algo-pcf.o: read %d bytes.\n",ret));
}
} else {
ret = pcf_sendbytes(i2c_adap, pmsg->buf, pmsg->len,
(i + 1 == num));
if (ret != pmsg->len) {
DEB2(printk(KERN_DEBUG "i2c-algo-pcf.o: fail: "
"only wrote %d bytes.\n",ret));
} else {
DEB2(printk(KERN_DEBUG "i2c-algo-pcf.o: wrote %d bytes.\n",ret));
}
}
}
out:
if (adap->xfer_end)
adap->xfer_end(adap->data);
return i;
}
static u32 pcf_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
I2C_FUNC_PROTOCOL_MANGLING;
}
/* exported algorithm data: */
static const struct i2c_algorithm pcf_algo = {
.master_xfer = pcf_xfer,
.functionality = pcf_func,
};
/*
* registering functions to load algorithms at runtime
*/
int i2c_pcf_add_bus(struct i2c_adapter *adap)
{
struct i2c_algo_pcf_data *pcf_adap = adap->algo_data;
int rval;
DEB2(dev_dbg(&adap->dev, "hw routines registered.\n"));
/* register new adapter to i2c module... */
adap->algo = &pcf_algo;
if ((rval = pcf_init_8584(pcf_adap)))
return rval;
rval = i2c_add_adapter(adap);
return rval;
}
EXPORT_SYMBOL(i2c_pcf_add_bus);
MODULE_AUTHOR("Hans Berglund <hb@spacetec.no>");
MODULE_DESCRIPTION("I2C-Bus PCF8584 algorithm");
MODULE_LICENSE("GPL");
module_param(i2c_debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(i2c_debug,
"debug level - 0 off; 1 normal; 2,3 more verbose; 9 pcf-protocol");
| gpl-2.0 |
SatrioDwiPrabowo/Intuisy-3.4xx-Kernel-Nanhu | tools/perf/util/pstack.c | 9248 | 1435 | /*
* Simple pointer stack
*
* (c) 2010 Arnaldo Carvalho de Melo <acme@redhat.com>
*/
#include "util.h"
#include "pstack.h"
#include <linux/kernel.h>
#include <stdlib.h>
struct pstack {
unsigned short top;
unsigned short max_nr_entries;
void *entries[0];
};
struct pstack *pstack__new(unsigned short max_nr_entries)
{
struct pstack *self = zalloc((sizeof(*self) +
max_nr_entries * sizeof(void *)));
if (self != NULL)
self->max_nr_entries = max_nr_entries;
return self;
}
void pstack__delete(struct pstack *self)
{
free(self);
}
bool pstack__empty(const struct pstack *self)
{
return self->top == 0;
}
void pstack__remove(struct pstack *self, void *key)
{
unsigned short i = self->top, last_index = self->top - 1;
while (i-- != 0) {
if (self->entries[i] == key) {
if (i < last_index)
memmove(self->entries + i,
self->entries + i + 1,
(last_index - i) * sizeof(void *));
--self->top;
return;
}
}
pr_err("%s: %p not on the pstack!\n", __func__, key);
}
void pstack__push(struct pstack *self, void *key)
{
if (self->top == self->max_nr_entries) {
pr_err("%s: top=%d, overflow!\n", __func__, self->top);
return;
}
self->entries[self->top++] = key;
}
void *pstack__pop(struct pstack *self)
{
void *ret;
if (self->top == 0) {
pr_err("%s: underflow!\n", __func__);
return NULL;
}
ret = self->entries[--self->top];
self->entries[self->top] = NULL;
return ret;
}
| gpl-2.0 |
tobetter/board-config | arch/mips/pmc-sierra/msp71xx/msp_pci.c | 9504 | 1782 | /*
* The setup file for PCI related hardware on PMC-Sierra MSP processors.
*
* Copyright 2005-2006 PMC-Sierra, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <msp_prom.h>
#include <msp_regs.h>
extern void msp_pci_init(void);
static int __init msp_pci_setup(void)
{
#if 0 /* Linux 2.6 initialization code to be completed */
if (getdeviceid() & DEV_ID_SINGLE_PC) {
/* If single card mode */
slmRegs *sreg = (slmRegs *) SREG_BASE;
sreg->single_pc_enable = SINGLE_PCCARD;
}
#endif
msp_pci_init();
return 0;
}
subsys_initcall(msp_pci_setup);
| gpl-2.0 |
abhishekr700/Z00L_cmkernel | sound/isa/gus/gus_timer.c | 14880 | 5336 | /*
* Routines for Gravis UltraSound soundcards - Timers
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
* GUS have similar timers as AdLib (OPL2/OPL3 chips).
*
*
* 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/time.h>
#include <sound/core.h>
#include <sound/gus.h>
/*
* Timer 1 - 80us
*/
static int snd_gf1_timer1_start(struct snd_timer * timer)
{
unsigned long flags;
unsigned char tmp;
unsigned int ticks;
struct snd_gus_card *gus;
gus = snd_timer_chip(timer);
spin_lock_irqsave(&gus->reg_lock, flags);
ticks = timer->sticks;
tmp = (gus->gf1.timer_enabled |= 4);
snd_gf1_write8(gus, SNDRV_GF1_GB_ADLIB_TIMER_1, 256 - ticks); /* timer 1 count */
snd_gf1_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, tmp); /* enable timer 1 IRQ */
snd_gf1_adlib_write(gus, 0x04, tmp >> 2); /* timer 2 start */
spin_unlock_irqrestore(&gus->reg_lock, flags);
return 0;
}
static int snd_gf1_timer1_stop(struct snd_timer * timer)
{
unsigned long flags;
unsigned char tmp;
struct snd_gus_card *gus;
gus = snd_timer_chip(timer);
spin_lock_irqsave(&gus->reg_lock, flags);
tmp = (gus->gf1.timer_enabled &= ~4);
snd_gf1_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, tmp); /* disable timer #1 */
spin_unlock_irqrestore(&gus->reg_lock, flags);
return 0;
}
/*
* Timer 2 - 320us
*/
static int snd_gf1_timer2_start(struct snd_timer * timer)
{
unsigned long flags;
unsigned char tmp;
unsigned int ticks;
struct snd_gus_card *gus;
gus = snd_timer_chip(timer);
spin_lock_irqsave(&gus->reg_lock, flags);
ticks = timer->sticks;
tmp = (gus->gf1.timer_enabled |= 8);
snd_gf1_write8(gus, SNDRV_GF1_GB_ADLIB_TIMER_2, 256 - ticks); /* timer 2 count */
snd_gf1_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, tmp); /* enable timer 2 IRQ */
snd_gf1_adlib_write(gus, 0x04, tmp >> 2); /* timer 2 start */
spin_unlock_irqrestore(&gus->reg_lock, flags);
return 0;
}
static int snd_gf1_timer2_stop(struct snd_timer * timer)
{
unsigned long flags;
unsigned char tmp;
struct snd_gus_card *gus;
gus = snd_timer_chip(timer);
spin_lock_irqsave(&gus->reg_lock, flags);
tmp = (gus->gf1.timer_enabled &= ~8);
snd_gf1_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, tmp); /* disable timer #1 */
spin_unlock_irqrestore(&gus->reg_lock, flags);
return 0;
}
/*
*/
static void snd_gf1_interrupt_timer1(struct snd_gus_card * gus)
{
struct snd_timer *timer = gus->gf1.timer1;
if (timer == NULL)
return;
snd_timer_interrupt(timer, timer->sticks);
}
static void snd_gf1_interrupt_timer2(struct snd_gus_card * gus)
{
struct snd_timer *timer = gus->gf1.timer2;
if (timer == NULL)
return;
snd_timer_interrupt(timer, timer->sticks);
}
/*
*/
static struct snd_timer_hardware snd_gf1_timer1 =
{
.flags = SNDRV_TIMER_HW_STOP,
.resolution = 80000,
.ticks = 256,
.start = snd_gf1_timer1_start,
.stop = snd_gf1_timer1_stop,
};
static struct snd_timer_hardware snd_gf1_timer2 =
{
.flags = SNDRV_TIMER_HW_STOP,
.resolution = 320000,
.ticks = 256,
.start = snd_gf1_timer2_start,
.stop = snd_gf1_timer2_stop,
};
static void snd_gf1_timer1_free(struct snd_timer *timer)
{
struct snd_gus_card *gus = timer->private_data;
gus->gf1.timer1 = NULL;
}
static void snd_gf1_timer2_free(struct snd_timer *timer)
{
struct snd_gus_card *gus = timer->private_data;
gus->gf1.timer2 = NULL;
}
void snd_gf1_timers_init(struct snd_gus_card * gus)
{
struct snd_timer *timer;
struct snd_timer_id tid;
if (gus->gf1.timer1 != NULL || gus->gf1.timer2 != NULL)
return;
gus->gf1.interrupt_handler_timer1 = snd_gf1_interrupt_timer1;
gus->gf1.interrupt_handler_timer2 = snd_gf1_interrupt_timer2;
tid.dev_class = SNDRV_TIMER_CLASS_CARD;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = gus->card->number;
tid.device = gus->timer_dev;
tid.subdevice = 0;
if (snd_timer_new(gus->card, "GF1 timer", &tid, &timer) >= 0) {
strcpy(timer->name, "GF1 timer #1");
timer->private_data = gus;
timer->private_free = snd_gf1_timer1_free;
timer->hw = snd_gf1_timer1;
}
gus->gf1.timer1 = timer;
tid.device++;
if (snd_timer_new(gus->card, "GF1 timer", &tid, &timer) >= 0) {
strcpy(timer->name, "GF1 timer #2");
timer->private_data = gus;
timer->private_free = snd_gf1_timer2_free;
timer->hw = snd_gf1_timer2;
}
gus->gf1.timer2 = timer;
}
void snd_gf1_timers_done(struct snd_gus_card * gus)
{
snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_TIMER1 | SNDRV_GF1_HANDLER_TIMER2);
if (gus->gf1.timer1) {
snd_device_free(gus->card, gus->gf1.timer1);
gus->gf1.timer1 = NULL;
}
if (gus->gf1.timer2) {
snd_device_free(gus->card, gus->gf1.timer2);
gus->gf1.timer2 = NULL;
}
}
| gpl-2.0 |
Darge/libvirt | tests/commandhelper.c | 33 | 4252 | /*
* commandhelper.c: Auxiliary program for commandtest
*
* Copyright (C) 2010-2014 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include "internal.h"
#include "virutil.h"
#include "viralloc.h"
#include "virfile.h"
#include "testutils.h"
#include "virstring.h"
#ifndef WIN32
# define VIR_FROM_THIS VIR_FROM_NONE
static int envsort(const void *a, const void *b)
{
const char *const*astrptr = a;
const char *const*bstrptr = b;
const char *astr = *astrptr;
const char *bstr = *bstrptr;
char *aeq = strchr(astr, '=');
char *beq = strchr(bstr, '=');
char *akey;
char *bkey;
int ret;
ignore_value(VIR_STRNDUP_QUIET(akey, astr, aeq - astr));
ignore_value(VIR_STRNDUP_QUIET(bkey, bstr, beq - bstr));
ret = strcmp(akey, bkey);
VIR_FREE(akey);
VIR_FREE(bkey);
return ret;
}
int main(int argc, char **argv) {
size_t i, n;
int open_max;
char **origenv;
char **newenv = NULL;
char *cwd;
FILE *log = fopen(abs_builddir "/commandhelper.log", "w");
int ret = EXIT_FAILURE;
if (!log)
goto cleanup;
for (i = 1; i < argc; i++)
fprintf(log, "ARG:%s\n", argv[i]);
origenv = environ;
n = 0;
while (*origenv != NULL) {
n++;
origenv++;
}
if (VIR_ALLOC_N_QUIET(newenv, n) < 0)
goto cleanup;
origenv = environ;
n = i = 0;
while (*origenv != NULL) {
newenv[i++] = *origenv;
n++;
origenv++;
}
qsort(newenv, n, sizeof(newenv[0]), envsort);
for (i = 0; i < n; i++) {
/* Ignore the variables used to instruct the loader into
* behaving differently, as they could throw the tests off. */
if (!STRPREFIX(newenv[i], "LD_"))
fprintf(log, "ENV:%s\n", newenv[i]);
}
open_max = sysconf(_SC_OPEN_MAX);
if (open_max < 0)
goto cleanup;
for (i = 0; i < open_max; i++) {
int f;
int closed;
if (i == fileno(log))
continue;
closed = fcntl(i, F_GETFD, &f) == -1 &&
errno == EBADF;
if (!closed)
fprintf(log, "FD:%zu\n", i);
}
fprintf(log, "DAEMON:%s\n", getpgrp() == getsid(0) ? "yes" : "no");
if (!(cwd = getcwd(NULL, 0)))
goto cleanup;
if (strlen(cwd) > strlen(".../commanddata") &&
STREQ(cwd + strlen(cwd) - strlen("/commanddata"), "/commanddata"))
strcpy(cwd, ".../commanddata");
fprintf(log, "CWD:%s\n", cwd);
VIR_FREE(cwd);
fprintf(log, "UMASK:%04o\n", umask(0));
if (argc > 1 && STREQ(argv[1], "--close-stdin")) {
if (freopen("/dev/null", "r", stdin) != stdin)
goto cleanup;
usleep(100*1000);
}
char buf[1024];
ssize_t got;
fprintf(stdout, "BEGIN STDOUT\n");
fflush(stdout);
fprintf(stderr, "BEGIN STDERR\n");
fflush(stderr);
for (;;) {
got = read(STDIN_FILENO, buf, sizeof(buf));
if (got < 0)
goto cleanup;
if (got == 0)
break;
if (safewrite(STDOUT_FILENO, buf, got) != got)
goto cleanup;
if (safewrite(STDERR_FILENO, buf, got) != got)
goto cleanup;
}
fprintf(stdout, "END STDOUT\n");
fflush(stdout);
fprintf(stderr, "END STDERR\n");
fflush(stderr);
ret = EXIT_SUCCESS;
cleanup:
VIR_FORCE_FCLOSE(log);
VIR_FREE(newenv);
return ret;
}
#else
int
main(void)
{
return EXIT_AM_SKIP;
}
#endif
| gpl-2.0 |
BrandonSchaefer/xbmc | lib/addons/library.kodi.audioengine/libKODI_audioengine.cpp | 33 | 6983 | /*
* Copyright (C) 2013-2014 Team KODI
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KODI; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "addons/kodi-addon-dev-kit/include/kodi/libKODI_audioengine.h"
#include "addons/binary/interfaces/api1/AudioEngine/AddonCallbacksAudioEngine.h"
#ifdef _WIN32
#include <windows.h>
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
using namespace std;
using namespace V1::KodiAPI::AudioEngine;
#define LIBRARY_NAME "libKODI_audioengine"
extern "C"
{
DLLEXPORT void* AudioEngine_register_me(void *hdl)
{
CB_AudioEngineLib *cb = NULL;
if (!hdl)
fprintf(stderr, "%s-ERROR: AudioEngine_register_me is called with NULL handle !!!\n", LIBRARY_NAME);
else
{
cb = (CB_AudioEngineLib*)((AddonCB*)hdl)->AudioEngineLib_RegisterMe(((AddonCB*)hdl)->addonData);
if (!cb)
fprintf(stderr, "%s-ERROR: AudioEngine_register_me can't get callback table from KODI !!!\n", LIBRARY_NAME);
}
return cb;
}
DLLEXPORT void AudioEngine_unregister_me(void *hdl, void* cb)
{
if (hdl && cb)
((AddonCB*)hdl)->AudioEngineLib_UnRegisterMe(((AddonCB*)hdl)->addonData, (CB_AudioEngineLib*)cb);
}
// ---------------------------------------------
// CAddonAEStream implementations
// ---------------------------------------------
DLLEXPORT CAddonAEStream* AudioEngine_make_stream(void *hdl, void *cb, AudioEngineFormat& Format, unsigned int Options)
{
if (!hdl || !cb)
{
fprintf(stderr, "%s-ERROR: AudioEngine_register_me is called with NULL handle !!!\n", LIBRARY_NAME);
return NULL;
}
AEStreamHandle *streamHandle = ((CB_AudioEngineLib*)cb)->MakeStream(Format, Options);
if (!streamHandle)
{
fprintf(stderr, "%s-ERROR: AudioEngine_make_stream MakeStream failed!\n", LIBRARY_NAME);
return NULL;
}
return new CAddonAEStream(hdl, cb, streamHandle);
}
DLLEXPORT void AudioEngine_free_stream(CAddonAEStream *p)
{
if (p)
{
delete p;
}
}
DLLEXPORT bool AudioEngine_get_current_sink_Format(void *hdl, void *cb, AudioEngineFormat *SinkFormat)
{
if (!cb)
{
return false;
}
return ((CB_AudioEngineLib*)cb)->GetCurrentSinkFormat(((AddonCB*)hdl)->addonData, SinkFormat);
}
CAddonAEStream::CAddonAEStream(void *Addon, void *Callbacks, AEStreamHandle *StreamHandle)
{
m_AddonHandle = Addon;
m_Callbacks = Callbacks;
m_StreamHandle = StreamHandle;
}
CAddonAEStream::~CAddonAEStream()
{
if (m_StreamHandle)
{
((CB_AudioEngineLib*)m_Callbacks)->FreeStream(m_StreamHandle);
m_StreamHandle = NULL;
}
}
unsigned int CAddonAEStream::GetSpace()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetSpace(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
unsigned int CAddonAEStream::AddData(uint8_t* const *Data, unsigned int Offset, unsigned int Frames)
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_AddData(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle, Data, Offset, Frames);
}
double CAddonAEStream::GetDelay()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetDelay(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
bool CAddonAEStream::IsBuffering()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_IsBuffering(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
double CAddonAEStream::GetCacheTime()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetCacheTime(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
double CAddonAEStream::GetCacheTotal()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetCacheTotal(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::Pause()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_Pause(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::Resume()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_Resume(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::Drain(bool Wait)
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_Drain(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle, Wait);
}
bool CAddonAEStream::IsDraining()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_IsDraining(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
bool CAddonAEStream::IsDrained()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_IsDrained(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::Flush()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_Flush(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
float CAddonAEStream::GetVolume()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetVolume(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::SetVolume(float Volume)
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_SetVolume(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle, Volume);
}
float CAddonAEStream::GetAmplification()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetAmplification(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::SetAmplification(float Amplify)
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_SetAmplification(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle, Amplify);
}
const unsigned int CAddonAEStream::GetFrameSize() const
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetFrameSize(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
const unsigned int CAddonAEStream::GetChannelCount() const
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetChannelCount(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
const unsigned int CAddonAEStream::GetSampleRate() const
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetSampleRate(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
const AEDataFormat CAddonAEStream::GetDataFormat() const
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetDataFormat(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
double CAddonAEStream::GetResampleRatio()
{
return ((CB_AudioEngineLib*)m_Callbacks)->AEStream_GetResampleRatio(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle);
}
void CAddonAEStream::SetResampleRatio(double Ratio)
{
((CB_AudioEngineLib*)m_Callbacks)->AEStream_SetResampleRatio(((AddonCB*)m_AddonHandle)->addonData, m_StreamHandle, Ratio);
}
};
| gpl-2.0 |
ntrdma/ntrdma | net/ipv6/sit.c | 33 | 45122 | /*
* IPv6 over IPv4 tunnel device - Simple Internet Transition (SIT)
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Changes:
* Roger Venning <r.venning@telstra.com>: 6to4 support
* Nate Thompson <nate@thebog.net>: 6to4 support
* Fred Templin <fred.l.templin@boeing.com>: isatap support
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/icmp.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/netfilter_ipv4.h>
#include <linux/if_ether.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/transp_v6.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/ip.h>
#include <net/udp.h>
#include <net/icmp.h>
#include <net/ip_tunnels.h>
#include <net/inet_ecn.h>
#include <net/xfrm.h>
#include <net/dsfield.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
/*
This version of net/ipv6/sit.c is cloned of net/ipv4/ip_gre.c
For comments look at net/ipv4/ip_gre.c --ANK
*/
#define IP6_SIT_HASH_SIZE 16
#define HASH(addr) (((__force u32)addr^((__force u32)addr>>4))&0xF)
static bool log_ecn_error = true;
module_param(log_ecn_error, bool, 0644);
MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN");
static int ipip6_tunnel_init(struct net_device *dev);
static void ipip6_tunnel_setup(struct net_device *dev);
static void ipip6_dev_free(struct net_device *dev);
static bool check_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst,
__be32 *v4dst);
static struct rtnl_link_ops sit_link_ops __read_mostly;
static unsigned int sit_net_id __read_mostly;
struct sit_net {
struct ip_tunnel __rcu *tunnels_r_l[IP6_SIT_HASH_SIZE];
struct ip_tunnel __rcu *tunnels_r[IP6_SIT_HASH_SIZE];
struct ip_tunnel __rcu *tunnels_l[IP6_SIT_HASH_SIZE];
struct ip_tunnel __rcu *tunnels_wc[1];
struct ip_tunnel __rcu **tunnels[4];
struct net_device *fb_tunnel_dev;
};
/*
* Must be invoked with rcu_read_lock
*/
static struct ip_tunnel *ipip6_tunnel_lookup(struct net *net,
struct net_device *dev, __be32 remote, __be32 local)
{
unsigned int h0 = HASH(remote);
unsigned int h1 = HASH(local);
struct ip_tunnel *t;
struct sit_net *sitn = net_generic(net, sit_net_id);
for_each_ip_tunnel_rcu(t, sitn->tunnels_r_l[h0 ^ h1]) {
if (local == t->parms.iph.saddr &&
remote == t->parms.iph.daddr &&
(!dev || !t->parms.link || dev->ifindex == t->parms.link) &&
(t->dev->flags & IFF_UP))
return t;
}
for_each_ip_tunnel_rcu(t, sitn->tunnels_r[h0]) {
if (remote == t->parms.iph.daddr &&
(!dev || !t->parms.link || dev->ifindex == t->parms.link) &&
(t->dev->flags & IFF_UP))
return t;
}
for_each_ip_tunnel_rcu(t, sitn->tunnels_l[h1]) {
if (local == t->parms.iph.saddr &&
(!dev || !t->parms.link || dev->ifindex == t->parms.link) &&
(t->dev->flags & IFF_UP))
return t;
}
t = rcu_dereference(sitn->tunnels_wc[0]);
if (t && (t->dev->flags & IFF_UP))
return t;
return NULL;
}
static struct ip_tunnel __rcu **__ipip6_bucket(struct sit_net *sitn,
struct ip_tunnel_parm *parms)
{
__be32 remote = parms->iph.daddr;
__be32 local = parms->iph.saddr;
unsigned int h = 0;
int prio = 0;
if (remote) {
prio |= 2;
h ^= HASH(remote);
}
if (local) {
prio |= 1;
h ^= HASH(local);
}
return &sitn->tunnels[prio][h];
}
static inline struct ip_tunnel __rcu **ipip6_bucket(struct sit_net *sitn,
struct ip_tunnel *t)
{
return __ipip6_bucket(sitn, &t->parms);
}
static void ipip6_tunnel_unlink(struct sit_net *sitn, struct ip_tunnel *t)
{
struct ip_tunnel __rcu **tp;
struct ip_tunnel *iter;
for (tp = ipip6_bucket(sitn, t);
(iter = rtnl_dereference(*tp)) != NULL;
tp = &iter->next) {
if (t == iter) {
rcu_assign_pointer(*tp, t->next);
break;
}
}
}
static void ipip6_tunnel_link(struct sit_net *sitn, struct ip_tunnel *t)
{
struct ip_tunnel __rcu **tp = ipip6_bucket(sitn, t);
rcu_assign_pointer(t->next, rtnl_dereference(*tp));
rcu_assign_pointer(*tp, t);
}
static void ipip6_tunnel_clone_6rd(struct net_device *dev, struct sit_net *sitn)
{
#ifdef CONFIG_IPV6_SIT_6RD
struct ip_tunnel *t = netdev_priv(dev);
if (t->dev == sitn->fb_tunnel_dev) {
ipv6_addr_set(&t->ip6rd.prefix, htonl(0x20020000), 0, 0, 0);
t->ip6rd.relay_prefix = 0;
t->ip6rd.prefixlen = 16;
t->ip6rd.relay_prefixlen = 0;
} else {
struct ip_tunnel *t0 = netdev_priv(sitn->fb_tunnel_dev);
memcpy(&t->ip6rd, &t0->ip6rd, sizeof(t->ip6rd));
}
#endif
}
static int ipip6_tunnel_create(struct net_device *dev)
{
struct ip_tunnel *t = netdev_priv(dev);
struct net *net = dev_net(dev);
struct sit_net *sitn = net_generic(net, sit_net_id);
int err;
memcpy(dev->dev_addr, &t->parms.iph.saddr, 4);
memcpy(dev->broadcast, &t->parms.iph.daddr, 4);
if ((__force u16)t->parms.i_flags & SIT_ISATAP)
dev->priv_flags |= IFF_ISATAP;
dev->rtnl_link_ops = &sit_link_ops;
err = register_netdevice(dev);
if (err < 0)
goto out;
ipip6_tunnel_clone_6rd(dev, sitn);
dev_hold(dev);
ipip6_tunnel_link(sitn, t);
return 0;
out:
return err;
}
static struct ip_tunnel *ipip6_tunnel_locate(struct net *net,
struct ip_tunnel_parm *parms, int create)
{
__be32 remote = parms->iph.daddr;
__be32 local = parms->iph.saddr;
struct ip_tunnel *t, *nt;
struct ip_tunnel __rcu **tp;
struct net_device *dev;
char name[IFNAMSIZ];
struct sit_net *sitn = net_generic(net, sit_net_id);
for (tp = __ipip6_bucket(sitn, parms);
(t = rtnl_dereference(*tp)) != NULL;
tp = &t->next) {
if (local == t->parms.iph.saddr &&
remote == t->parms.iph.daddr &&
parms->link == t->parms.link) {
if (create)
return NULL;
else
return t;
}
}
if (!create)
goto failed;
if (parms->name[0])
strlcpy(name, parms->name, IFNAMSIZ);
else
strcpy(name, "sit%d");
dev = alloc_netdev(sizeof(*t), name, NET_NAME_UNKNOWN,
ipip6_tunnel_setup);
if (!dev)
return NULL;
dev_net_set(dev, net);
nt = netdev_priv(dev);
nt->parms = *parms;
if (ipip6_tunnel_create(dev) < 0)
goto failed_free;
return nt;
failed_free:
ipip6_dev_free(dev);
failed:
return NULL;
}
#define for_each_prl_rcu(start) \
for (prl = rcu_dereference(start); \
prl; \
prl = rcu_dereference(prl->next))
static struct ip_tunnel_prl_entry *
__ipip6_tunnel_locate_prl(struct ip_tunnel *t, __be32 addr)
{
struct ip_tunnel_prl_entry *prl;
for_each_prl_rcu(t->prl)
if (prl->addr == addr)
break;
return prl;
}
static int ipip6_tunnel_get_prl(struct ip_tunnel *t,
struct ip_tunnel_prl __user *a)
{
struct ip_tunnel_prl kprl, *kp;
struct ip_tunnel_prl_entry *prl;
unsigned int cmax, c = 0, ca, len;
int ret = 0;
if (copy_from_user(&kprl, a, sizeof(kprl)))
return -EFAULT;
cmax = kprl.datalen / sizeof(kprl);
if (cmax > 1 && kprl.addr != htonl(INADDR_ANY))
cmax = 1;
/* For simple GET or for root users,
* we try harder to allocate.
*/
kp = (cmax <= 1 || capable(CAP_NET_ADMIN)) ?
kcalloc(cmax, sizeof(*kp), GFP_KERNEL) :
NULL;
rcu_read_lock();
ca = t->prl_count < cmax ? t->prl_count : cmax;
if (!kp) {
/* We don't try hard to allocate much memory for
* non-root users.
* For root users, retry allocating enough memory for
* the answer.
*/
kp = kcalloc(ca, sizeof(*kp), GFP_ATOMIC);
if (!kp) {
ret = -ENOMEM;
goto out;
}
}
c = 0;
for_each_prl_rcu(t->prl) {
if (c >= cmax)
break;
if (kprl.addr != htonl(INADDR_ANY) && prl->addr != kprl.addr)
continue;
kp[c].addr = prl->addr;
kp[c].flags = prl->flags;
c++;
if (kprl.addr != htonl(INADDR_ANY))
break;
}
out:
rcu_read_unlock();
len = sizeof(*kp) * c;
ret = 0;
if ((len && copy_to_user(a + 1, kp, len)) || put_user(len, &a->datalen))
ret = -EFAULT;
kfree(kp);
return ret;
}
static int
ipip6_tunnel_add_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a, int chg)
{
struct ip_tunnel_prl_entry *p;
int err = 0;
if (a->addr == htonl(INADDR_ANY))
return -EINVAL;
ASSERT_RTNL();
for (p = rtnl_dereference(t->prl); p; p = rtnl_dereference(p->next)) {
if (p->addr == a->addr) {
if (chg) {
p->flags = a->flags;
goto out;
}
err = -EEXIST;
goto out;
}
}
if (chg) {
err = -ENXIO;
goto out;
}
p = kzalloc(sizeof(struct ip_tunnel_prl_entry), GFP_KERNEL);
if (!p) {
err = -ENOBUFS;
goto out;
}
p->next = t->prl;
p->addr = a->addr;
p->flags = a->flags;
t->prl_count++;
rcu_assign_pointer(t->prl, p);
out:
return err;
}
static void prl_list_destroy_rcu(struct rcu_head *head)
{
struct ip_tunnel_prl_entry *p, *n;
p = container_of(head, struct ip_tunnel_prl_entry, rcu_head);
do {
n = rcu_dereference_protected(p->next, 1);
kfree(p);
p = n;
} while (p);
}
static int
ipip6_tunnel_del_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a)
{
struct ip_tunnel_prl_entry *x;
struct ip_tunnel_prl_entry __rcu **p;
int err = 0;
ASSERT_RTNL();
if (a && a->addr != htonl(INADDR_ANY)) {
for (p = &t->prl;
(x = rtnl_dereference(*p)) != NULL;
p = &x->next) {
if (x->addr == a->addr) {
*p = x->next;
kfree_rcu(x, rcu_head);
t->prl_count--;
goto out;
}
}
err = -ENXIO;
} else {
x = rtnl_dereference(t->prl);
if (x) {
t->prl_count = 0;
call_rcu(&x->rcu_head, prl_list_destroy_rcu);
t->prl = NULL;
}
}
out:
return err;
}
static int
isatap_chksrc(struct sk_buff *skb, const struct iphdr *iph, struct ip_tunnel *t)
{
struct ip_tunnel_prl_entry *p;
int ok = 1;
rcu_read_lock();
p = __ipip6_tunnel_locate_prl(t, iph->saddr);
if (p) {
if (p->flags & PRL_DEFAULT)
skb->ndisc_nodetype = NDISC_NODETYPE_DEFAULT;
else
skb->ndisc_nodetype = NDISC_NODETYPE_NODEFAULT;
} else {
const struct in6_addr *addr6 = &ipv6_hdr(skb)->saddr;
if (ipv6_addr_is_isatap(addr6) &&
(addr6->s6_addr32[3] == iph->saddr) &&
ipv6_chk_prefix(addr6, t->dev))
skb->ndisc_nodetype = NDISC_NODETYPE_HOST;
else
ok = 0;
}
rcu_read_unlock();
return ok;
}
static void ipip6_tunnel_uninit(struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
struct sit_net *sitn = net_generic(tunnel->net, sit_net_id);
if (dev == sitn->fb_tunnel_dev) {
RCU_INIT_POINTER(sitn->tunnels_wc[0], NULL);
} else {
ipip6_tunnel_unlink(sitn, tunnel);
ipip6_tunnel_del_prl(tunnel, NULL);
}
dst_cache_reset(&tunnel->dst_cache);
dev_put(dev);
}
static int ipip6_err(struct sk_buff *skb, u32 info)
{
const struct iphdr *iph = (const struct iphdr *)skb->data;
const int type = icmp_hdr(skb)->type;
const int code = icmp_hdr(skb)->code;
unsigned int data_len = 0;
struct ip_tunnel *t;
int err;
switch (type) {
default:
case ICMP_PARAMETERPROB:
return 0;
case ICMP_DEST_UNREACH:
switch (code) {
case ICMP_SR_FAILED:
/* Impossible event. */
return 0;
default:
/* All others are translated to HOST_UNREACH.
rfc2003 contains "deep thoughts" about NET_UNREACH,
I believe they are just ether pollution. --ANK
*/
break;
}
break;
case ICMP_TIME_EXCEEDED:
if (code != ICMP_EXC_TTL)
return 0;
data_len = icmp_hdr(skb)->un.reserved[1] * 4; /* RFC 4884 4.1 */
break;
case ICMP_REDIRECT:
break;
}
err = -ENOENT;
t = ipip6_tunnel_lookup(dev_net(skb->dev),
skb->dev,
iph->daddr,
iph->saddr);
if (!t)
goto out;
if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED) {
ipv4_update_pmtu(skb, dev_net(skb->dev), info,
t->parms.link, 0, iph->protocol, 0);
err = 0;
goto out;
}
if (type == ICMP_REDIRECT) {
ipv4_redirect(skb, dev_net(skb->dev), t->parms.link, 0,
iph->protocol, 0);
err = 0;
goto out;
}
err = 0;
if (!ip6_err_gen_icmpv6_unreach(skb, iph->ihl * 4, type, data_len))
goto out;
if (t->parms.iph.daddr == 0)
goto out;
if (t->parms.iph.ttl == 0 && type == ICMP_TIME_EXCEEDED)
goto out;
if (time_before(jiffies, t->err_time + IPTUNNEL_ERR_TIMEO))
t->err_count++;
else
t->err_count = 1;
t->err_time = jiffies;
out:
return err;
}
static inline bool is_spoofed_6rd(struct ip_tunnel *tunnel, const __be32 v4addr,
const struct in6_addr *v6addr)
{
__be32 v4embed = 0;
if (check_6rd(tunnel, v6addr, &v4embed) && v4addr != v4embed)
return true;
return false;
}
/* Checks if an address matches an address on the tunnel interface.
* Used to detect the NAT of proto 41 packets and let them pass spoofing test.
* Long story:
* This function is called after we considered the packet as spoofed
* in is_spoofed_6rd.
* We may have a router that is doing NAT for proto 41 packets
* for an internal station. Destination a.a.a.a/PREFIX:bbbb:bbbb
* will be translated to n.n.n.n/PREFIX:bbbb:bbbb. And is_spoofed_6rd
* function will return true, dropping the packet.
* But, we can still check if is spoofed against the IP
* addresses associated with the interface.
*/
static bool only_dnatted(const struct ip_tunnel *tunnel,
const struct in6_addr *v6dst)
{
int prefix_len;
#ifdef CONFIG_IPV6_SIT_6RD
prefix_len = tunnel->ip6rd.prefixlen + 32
- tunnel->ip6rd.relay_prefixlen;
#else
prefix_len = 48;
#endif
return ipv6_chk_custom_prefix(v6dst, prefix_len, tunnel->dev);
}
/* Returns true if a packet is spoofed */
static bool packet_is_spoofed(struct sk_buff *skb,
const struct iphdr *iph,
struct ip_tunnel *tunnel)
{
const struct ipv6hdr *ipv6h;
if (tunnel->dev->priv_flags & IFF_ISATAP) {
if (!isatap_chksrc(skb, iph, tunnel))
return true;
return false;
}
if (tunnel->dev->flags & IFF_POINTOPOINT)
return false;
ipv6h = ipv6_hdr(skb);
if (unlikely(is_spoofed_6rd(tunnel, iph->saddr, &ipv6h->saddr))) {
net_warn_ratelimited("Src spoofed %pI4/%pI6c -> %pI4/%pI6c\n",
&iph->saddr, &ipv6h->saddr,
&iph->daddr, &ipv6h->daddr);
return true;
}
if (likely(!is_spoofed_6rd(tunnel, iph->daddr, &ipv6h->daddr)))
return false;
if (only_dnatted(tunnel, &ipv6h->daddr))
return false;
net_warn_ratelimited("Dst spoofed %pI4/%pI6c -> %pI4/%pI6c\n",
&iph->saddr, &ipv6h->saddr,
&iph->daddr, &ipv6h->daddr);
return true;
}
static int ipip6_rcv(struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct ip_tunnel *tunnel;
int err;
tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev,
iph->saddr, iph->daddr);
if (tunnel) {
struct pcpu_sw_netstats *tstats;
if (tunnel->parms.iph.protocol != IPPROTO_IPV6 &&
tunnel->parms.iph.protocol != 0)
goto out;
skb->mac_header = skb->network_header;
skb_reset_network_header(skb);
IPCB(skb)->flags = 0;
skb->dev = tunnel->dev;
if (packet_is_spoofed(skb, iph, tunnel)) {
tunnel->dev->stats.rx_errors++;
goto out;
}
if (iptunnel_pull_header(skb, 0, htons(ETH_P_IPV6),
!net_eq(tunnel->net, dev_net(tunnel->dev))))
goto out;
err = IP_ECN_decapsulate(iph, skb);
if (unlikely(err)) {
if (log_ecn_error)
net_info_ratelimited("non-ECT from %pI4 with TOS=%#x\n",
&iph->saddr, iph->tos);
if (err > 1) {
++tunnel->dev->stats.rx_frame_errors;
++tunnel->dev->stats.rx_errors;
goto out;
}
}
tstats = this_cpu_ptr(tunnel->dev->tstats);
u64_stats_update_begin(&tstats->syncp);
tstats->rx_packets++;
tstats->rx_bytes += skb->len;
u64_stats_update_end(&tstats->syncp);
netif_rx(skb);
return 0;
}
/* no tunnel matched, let upstream know, ipsec may handle it */
return 1;
out:
kfree_skb(skb);
return 0;
}
static const struct tnl_ptk_info ipip_tpi = {
/* no tunnel info required for ipip. */
.proto = htons(ETH_P_IP),
};
#if IS_ENABLED(CONFIG_MPLS)
static const struct tnl_ptk_info mplsip_tpi = {
/* no tunnel info required for mplsip. */
.proto = htons(ETH_P_MPLS_UC),
};
#endif
static int sit_tunnel_rcv(struct sk_buff *skb, u8 ipproto)
{
const struct iphdr *iph;
struct ip_tunnel *tunnel;
iph = ip_hdr(skb);
tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev,
iph->saddr, iph->daddr);
if (tunnel) {
const struct tnl_ptk_info *tpi;
if (tunnel->parms.iph.protocol != ipproto &&
tunnel->parms.iph.protocol != 0)
goto drop;
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto drop;
#if IS_ENABLED(CONFIG_MPLS)
if (ipproto == IPPROTO_MPLS)
tpi = &mplsip_tpi;
else
#endif
tpi = &ipip_tpi;
if (iptunnel_pull_header(skb, 0, tpi->proto, false))
goto drop;
return ip_tunnel_rcv(tunnel, skb, tpi, NULL, log_ecn_error);
}
return 1;
drop:
kfree_skb(skb);
return 0;
}
static int ipip_rcv(struct sk_buff *skb)
{
return sit_tunnel_rcv(skb, IPPROTO_IPIP);
}
#if IS_ENABLED(CONFIG_MPLS)
static int mplsip_rcv(struct sk_buff *skb)
{
return sit_tunnel_rcv(skb, IPPROTO_MPLS);
}
#endif
/*
* If the IPv6 address comes from 6rd / 6to4 (RFC 3056) addr space this function
* stores the embedded IPv4 address in v4dst and returns true.
*/
static bool check_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst,
__be32 *v4dst)
{
#ifdef CONFIG_IPV6_SIT_6RD
if (ipv6_prefix_equal(v6dst, &tunnel->ip6rd.prefix,
tunnel->ip6rd.prefixlen)) {
unsigned int pbw0, pbi0;
int pbi1;
u32 d;
pbw0 = tunnel->ip6rd.prefixlen >> 5;
pbi0 = tunnel->ip6rd.prefixlen & 0x1f;
d = (ntohl(v6dst->s6_addr32[pbw0]) << pbi0) >>
tunnel->ip6rd.relay_prefixlen;
pbi1 = pbi0 - tunnel->ip6rd.relay_prefixlen;
if (pbi1 > 0)
d |= ntohl(v6dst->s6_addr32[pbw0 + 1]) >>
(32 - pbi1);
*v4dst = tunnel->ip6rd.relay_prefix | htonl(d);
return true;
}
#else
if (v6dst->s6_addr16[0] == htons(0x2002)) {
/* 6to4 v6 addr has 16 bits prefix, 32 v4addr, 16 SLA, ... */
memcpy(v4dst, &v6dst->s6_addr16[1], 4);
return true;
}
#endif
return false;
}
static inline __be32 try_6rd(struct ip_tunnel *tunnel,
const struct in6_addr *v6dst)
{
__be32 dst = 0;
check_6rd(tunnel, v6dst, &dst);
return dst;
}
/*
* This function assumes it is being called from dev_queue_xmit()
* and that skb is filled properly by that function.
*/
static netdev_tx_t ipip6_tunnel_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
const struct iphdr *tiph = &tunnel->parms.iph;
const struct ipv6hdr *iph6 = ipv6_hdr(skb);
u8 tos = tunnel->parms.iph.tos;
__be16 df = tiph->frag_off;
struct rtable *rt; /* Route to the other host */
struct net_device *tdev; /* Device to other host */
unsigned int max_headroom; /* The extra header space needed */
__be32 dst = tiph->daddr;
struct flowi4 fl4;
int mtu;
const struct in6_addr *addr6;
int addr_type;
u8 ttl;
u8 protocol = IPPROTO_IPV6;
int t_hlen = tunnel->hlen + sizeof(struct iphdr);
if (tos == 1)
tos = ipv6_get_dsfield(iph6);
/* ISATAP (RFC4214) - must come before 6to4 */
if (dev->priv_flags & IFF_ISATAP) {
struct neighbour *neigh = NULL;
bool do_tx_error = false;
if (skb_dst(skb))
neigh = dst_neigh_lookup(skb_dst(skb), &iph6->daddr);
if (!neigh) {
net_dbg_ratelimited("nexthop == NULL\n");
goto tx_error;
}
addr6 = (const struct in6_addr *)&neigh->primary_key;
addr_type = ipv6_addr_type(addr6);
if ((addr_type & IPV6_ADDR_UNICAST) &&
ipv6_addr_is_isatap(addr6))
dst = addr6->s6_addr32[3];
else
do_tx_error = true;
neigh_release(neigh);
if (do_tx_error)
goto tx_error;
}
if (!dst)
dst = try_6rd(tunnel, &iph6->daddr);
if (!dst) {
struct neighbour *neigh = NULL;
bool do_tx_error = false;
if (skb_dst(skb))
neigh = dst_neigh_lookup(skb_dst(skb), &iph6->daddr);
if (!neigh) {
net_dbg_ratelimited("nexthop == NULL\n");
goto tx_error;
}
addr6 = (const struct in6_addr *)&neigh->primary_key;
addr_type = ipv6_addr_type(addr6);
if (addr_type == IPV6_ADDR_ANY) {
addr6 = &ipv6_hdr(skb)->daddr;
addr_type = ipv6_addr_type(addr6);
}
if ((addr_type & IPV6_ADDR_COMPATv4) != 0)
dst = addr6->s6_addr32[3];
else
do_tx_error = true;
neigh_release(neigh);
if (do_tx_error)
goto tx_error;
}
rt = ip_route_output_ports(tunnel->net, &fl4, NULL,
dst, tiph->saddr,
0, 0,
IPPROTO_IPV6, RT_TOS(tos),
tunnel->parms.link);
if (IS_ERR(rt)) {
dev->stats.tx_carrier_errors++;
goto tx_error_icmp;
}
if (rt->rt_type != RTN_UNICAST) {
ip_rt_put(rt);
dev->stats.tx_carrier_errors++;
goto tx_error_icmp;
}
tdev = rt->dst.dev;
if (tdev == dev) {
ip_rt_put(rt);
dev->stats.collisions++;
goto tx_error;
}
if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP4)) {
ip_rt_put(rt);
goto tx_error;
}
if (df) {
mtu = dst_mtu(&rt->dst) - t_hlen;
if (mtu < 68) {
dev->stats.collisions++;
ip_rt_put(rt);
goto tx_error;
}
if (mtu < IPV6_MIN_MTU) {
mtu = IPV6_MIN_MTU;
df = 0;
}
if (tunnel->parms.iph.daddr && skb_dst(skb))
skb_dst(skb)->ops->update_pmtu(skb_dst(skb), NULL, skb, mtu);
if (skb->len > mtu && !skb_is_gso(skb)) {
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
ip_rt_put(rt);
goto tx_error;
}
}
if (tunnel->err_count > 0) {
if (time_before(jiffies,
tunnel->err_time + IPTUNNEL_ERR_TIMEO)) {
tunnel->err_count--;
dst_link_failure(skb);
} else
tunnel->err_count = 0;
}
/*
* Okay, now see if we can stuff it in the buffer as-is.
*/
max_headroom = LL_RESERVED_SPACE(tdev) + t_hlen;
if (skb_headroom(skb) < max_headroom || skb_shared(skb) ||
(skb_cloned(skb) && !skb_clone_writable(skb, 0))) {
struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom);
if (!new_skb) {
ip_rt_put(rt);
dev->stats.tx_dropped++;
kfree_skb(skb);
return NETDEV_TX_OK;
}
if (skb->sk)
skb_set_owner_w(new_skb, skb->sk);
dev_kfree_skb(skb);
skb = new_skb;
iph6 = ipv6_hdr(skb);
}
ttl = tiph->ttl;
if (ttl == 0)
ttl = iph6->hop_limit;
tos = INET_ECN_encapsulate(tos, ipv6_get_dsfield(iph6));
if (ip_tunnel_encap(skb, tunnel, &protocol, &fl4) < 0) {
ip_rt_put(rt);
goto tx_error;
}
skb_set_inner_ipproto(skb, IPPROTO_IPV6);
iptunnel_xmit(NULL, rt, skb, fl4.saddr, fl4.daddr, protocol, tos, ttl,
df, !net_eq(tunnel->net, dev_net(dev)));
return NETDEV_TX_OK;
tx_error_icmp:
dst_link_failure(skb);
tx_error:
kfree_skb(skb);
dev->stats.tx_errors++;
return NETDEV_TX_OK;
}
static netdev_tx_t sit_tunnel_xmit__(struct sk_buff *skb,
struct net_device *dev, u8 ipproto)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
const struct iphdr *tiph = &tunnel->parms.iph;
if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP4))
goto tx_error;
skb_set_inner_ipproto(skb, ipproto);
ip_tunnel_xmit(skb, dev, tiph, ipproto);
return NETDEV_TX_OK;
tx_error:
kfree_skb(skb);
dev->stats.tx_errors++;
return NETDEV_TX_OK;
}
static netdev_tx_t sit_tunnel_xmit(struct sk_buff *skb,
struct net_device *dev)
{
switch (skb->protocol) {
case htons(ETH_P_IP):
sit_tunnel_xmit__(skb, dev, IPPROTO_IPIP);
break;
case htons(ETH_P_IPV6):
ipip6_tunnel_xmit(skb, dev);
break;
#if IS_ENABLED(CONFIG_MPLS)
case htons(ETH_P_MPLS_UC):
sit_tunnel_xmit__(skb, dev, IPPROTO_MPLS);
break;
#endif
default:
goto tx_err;
}
return NETDEV_TX_OK;
tx_err:
dev->stats.tx_errors++;
kfree_skb(skb);
return NETDEV_TX_OK;
}
static void ipip6_tunnel_bind_dev(struct net_device *dev)
{
struct net_device *tdev = NULL;
struct ip_tunnel *tunnel;
const struct iphdr *iph;
struct flowi4 fl4;
tunnel = netdev_priv(dev);
iph = &tunnel->parms.iph;
if (iph->daddr) {
struct rtable *rt = ip_route_output_ports(tunnel->net, &fl4,
NULL,
iph->daddr, iph->saddr,
0, 0,
IPPROTO_IPV6,
RT_TOS(iph->tos),
tunnel->parms.link);
if (!IS_ERR(rt)) {
tdev = rt->dst.dev;
ip_rt_put(rt);
}
dev->flags |= IFF_POINTOPOINT;
}
if (!tdev && tunnel->parms.link)
tdev = __dev_get_by_index(tunnel->net, tunnel->parms.link);
if (tdev) {
int t_hlen = tunnel->hlen + sizeof(struct iphdr);
dev->hard_header_len = tdev->hard_header_len + sizeof(struct iphdr);
dev->mtu = tdev->mtu - t_hlen;
if (dev->mtu < IPV6_MIN_MTU)
dev->mtu = IPV6_MIN_MTU;
}
}
static void ipip6_tunnel_update(struct ip_tunnel *t, struct ip_tunnel_parm *p)
{
struct net *net = t->net;
struct sit_net *sitn = net_generic(net, sit_net_id);
ipip6_tunnel_unlink(sitn, t);
synchronize_net();
t->parms.iph.saddr = p->iph.saddr;
t->parms.iph.daddr = p->iph.daddr;
memcpy(t->dev->dev_addr, &p->iph.saddr, 4);
memcpy(t->dev->broadcast, &p->iph.daddr, 4);
ipip6_tunnel_link(sitn, t);
t->parms.iph.ttl = p->iph.ttl;
t->parms.iph.tos = p->iph.tos;
if (t->parms.link != p->link) {
t->parms.link = p->link;
ipip6_tunnel_bind_dev(t->dev);
}
dst_cache_reset(&t->dst_cache);
netdev_state_change(t->dev);
}
#ifdef CONFIG_IPV6_SIT_6RD
static int ipip6_tunnel_update_6rd(struct ip_tunnel *t,
struct ip_tunnel_6rd *ip6rd)
{
struct in6_addr prefix;
__be32 relay_prefix;
if (ip6rd->relay_prefixlen > 32 ||
ip6rd->prefixlen + (32 - ip6rd->relay_prefixlen) > 64)
return -EINVAL;
ipv6_addr_prefix(&prefix, &ip6rd->prefix, ip6rd->prefixlen);
if (!ipv6_addr_equal(&prefix, &ip6rd->prefix))
return -EINVAL;
if (ip6rd->relay_prefixlen)
relay_prefix = ip6rd->relay_prefix &
htonl(0xffffffffUL <<
(32 - ip6rd->relay_prefixlen));
else
relay_prefix = 0;
if (relay_prefix != ip6rd->relay_prefix)
return -EINVAL;
t->ip6rd.prefix = prefix;
t->ip6rd.relay_prefix = relay_prefix;
t->ip6rd.prefixlen = ip6rd->prefixlen;
t->ip6rd.relay_prefixlen = ip6rd->relay_prefixlen;
dst_cache_reset(&t->dst_cache);
netdev_state_change(t->dev);
return 0;
}
#endif
static bool ipip6_valid_ip_proto(u8 ipproto)
{
return ipproto == IPPROTO_IPV6 ||
ipproto == IPPROTO_IPIP ||
#if IS_ENABLED(CONFIG_MPLS)
ipproto == IPPROTO_MPLS ||
#endif
ipproto == 0;
}
static int
ipip6_tunnel_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
int err = 0;
struct ip_tunnel_parm p;
struct ip_tunnel_prl prl;
struct ip_tunnel *t = netdev_priv(dev);
struct net *net = t->net;
struct sit_net *sitn = net_generic(net, sit_net_id);
#ifdef CONFIG_IPV6_SIT_6RD
struct ip_tunnel_6rd ip6rd;
#endif
switch (cmd) {
case SIOCGETTUNNEL:
#ifdef CONFIG_IPV6_SIT_6RD
case SIOCGET6RD:
#endif
if (dev == sitn->fb_tunnel_dev) {
if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) {
err = -EFAULT;
break;
}
t = ipip6_tunnel_locate(net, &p, 0);
if (!t)
t = netdev_priv(dev);
}
err = -EFAULT;
if (cmd == SIOCGETTUNNEL) {
memcpy(&p, &t->parms, sizeof(p));
if (copy_to_user(ifr->ifr_ifru.ifru_data, &p,
sizeof(p)))
goto done;
#ifdef CONFIG_IPV6_SIT_6RD
} else {
ip6rd.prefix = t->ip6rd.prefix;
ip6rd.relay_prefix = t->ip6rd.relay_prefix;
ip6rd.prefixlen = t->ip6rd.prefixlen;
ip6rd.relay_prefixlen = t->ip6rd.relay_prefixlen;
if (copy_to_user(ifr->ifr_ifru.ifru_data, &ip6rd,
sizeof(ip6rd)))
goto done;
#endif
}
err = 0;
break;
case SIOCADDTUNNEL:
case SIOCCHGTUNNEL:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
goto done;
err = -EFAULT;
if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p)))
goto done;
err = -EINVAL;
if (!ipip6_valid_ip_proto(p.iph.protocol))
goto done;
if (p.iph.version != 4 ||
p.iph.ihl != 5 || (p.iph.frag_off&htons(~IP_DF)))
goto done;
if (p.iph.ttl)
p.iph.frag_off |= htons(IP_DF);
t = ipip6_tunnel_locate(net, &p, cmd == SIOCADDTUNNEL);
if (dev != sitn->fb_tunnel_dev && cmd == SIOCCHGTUNNEL) {
if (t) {
if (t->dev != dev) {
err = -EEXIST;
break;
}
} else {
if (((dev->flags&IFF_POINTOPOINT) && !p.iph.daddr) ||
(!(dev->flags&IFF_POINTOPOINT) && p.iph.daddr)) {
err = -EINVAL;
break;
}
t = netdev_priv(dev);
}
ipip6_tunnel_update(t, &p);
}
if (t) {
err = 0;
if (copy_to_user(ifr->ifr_ifru.ifru_data, &t->parms, sizeof(p)))
err = -EFAULT;
} else
err = (cmd == SIOCADDTUNNEL ? -ENOBUFS : -ENOENT);
break;
case SIOCDELTUNNEL:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
goto done;
if (dev == sitn->fb_tunnel_dev) {
err = -EFAULT;
if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p)))
goto done;
err = -ENOENT;
t = ipip6_tunnel_locate(net, &p, 0);
if (!t)
goto done;
err = -EPERM;
if (t == netdev_priv(sitn->fb_tunnel_dev))
goto done;
dev = t->dev;
}
unregister_netdevice(dev);
err = 0;
break;
case SIOCGETPRL:
err = -EINVAL;
if (dev == sitn->fb_tunnel_dev)
goto done;
err = ipip6_tunnel_get_prl(t, ifr->ifr_ifru.ifru_data);
break;
case SIOCADDPRL:
case SIOCDELPRL:
case SIOCCHGPRL:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
goto done;
err = -EINVAL;
if (dev == sitn->fb_tunnel_dev)
goto done;
err = -EFAULT;
if (copy_from_user(&prl, ifr->ifr_ifru.ifru_data, sizeof(prl)))
goto done;
switch (cmd) {
case SIOCDELPRL:
err = ipip6_tunnel_del_prl(t, &prl);
break;
case SIOCADDPRL:
case SIOCCHGPRL:
err = ipip6_tunnel_add_prl(t, &prl, cmd == SIOCCHGPRL);
break;
}
dst_cache_reset(&t->dst_cache);
netdev_state_change(dev);
break;
#ifdef CONFIG_IPV6_SIT_6RD
case SIOCADD6RD:
case SIOCCHG6RD:
case SIOCDEL6RD:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
goto done;
err = -EFAULT;
if (copy_from_user(&ip6rd, ifr->ifr_ifru.ifru_data,
sizeof(ip6rd)))
goto done;
if (cmd != SIOCDEL6RD) {
err = ipip6_tunnel_update_6rd(t, &ip6rd);
if (err < 0)
goto done;
} else
ipip6_tunnel_clone_6rd(dev, sitn);
err = 0;
break;
#endif
default:
err = -EINVAL;
}
done:
return err;
}
static const struct net_device_ops ipip6_netdev_ops = {
.ndo_init = ipip6_tunnel_init,
.ndo_uninit = ipip6_tunnel_uninit,
.ndo_start_xmit = sit_tunnel_xmit,
.ndo_do_ioctl = ipip6_tunnel_ioctl,
.ndo_get_stats64 = ip_tunnel_get_stats64,
.ndo_get_iflink = ip_tunnel_get_iflink,
};
static void ipip6_dev_free(struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
dst_cache_destroy(&tunnel->dst_cache);
free_percpu(dev->tstats);
free_netdev(dev);
}
#define SIT_FEATURES (NETIF_F_SG | \
NETIF_F_FRAGLIST | \
NETIF_F_HIGHDMA | \
NETIF_F_GSO_SOFTWARE | \
NETIF_F_HW_CSUM)
static void ipip6_tunnel_setup(struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
int t_hlen = tunnel->hlen + sizeof(struct iphdr);
dev->netdev_ops = &ipip6_netdev_ops;
dev->destructor = ipip6_dev_free;
dev->type = ARPHRD_SIT;
dev->hard_header_len = LL_MAX_HEADER + t_hlen;
dev->mtu = ETH_DATA_LEN - t_hlen;
dev->min_mtu = IPV6_MIN_MTU;
dev->max_mtu = 0xFFF8 - t_hlen;
dev->flags = IFF_NOARP;
netif_keep_dst(dev);
dev->addr_len = 4;
dev->features |= NETIF_F_LLTX;
dev->features |= SIT_FEATURES;
dev->hw_features |= SIT_FEATURES;
}
static int ipip6_tunnel_init(struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
int err;
tunnel->dev = dev;
tunnel->net = dev_net(dev);
strcpy(tunnel->parms.name, dev->name);
ipip6_tunnel_bind_dev(dev);
dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
if (!dev->tstats)
return -ENOMEM;
err = dst_cache_init(&tunnel->dst_cache, GFP_KERNEL);
if (err) {
free_percpu(dev->tstats);
dev->tstats = NULL;
return err;
}
return 0;
}
static void __net_init ipip6_fb_tunnel_init(struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
struct iphdr *iph = &tunnel->parms.iph;
struct net *net = dev_net(dev);
struct sit_net *sitn = net_generic(net, sit_net_id);
iph->version = 4;
iph->protocol = IPPROTO_IPV6;
iph->ihl = 5;
iph->ttl = 64;
dev_hold(dev);
rcu_assign_pointer(sitn->tunnels_wc[0], tunnel);
}
static int ipip6_validate(struct nlattr *tb[], struct nlattr *data[])
{
u8 proto;
if (!data || !data[IFLA_IPTUN_PROTO])
return 0;
proto = nla_get_u8(data[IFLA_IPTUN_PROTO]);
if (!ipip6_valid_ip_proto(proto))
return -EINVAL;
return 0;
}
static void ipip6_netlink_parms(struct nlattr *data[],
struct ip_tunnel_parm *parms)
{
memset(parms, 0, sizeof(*parms));
parms->iph.version = 4;
parms->iph.protocol = IPPROTO_IPV6;
parms->iph.ihl = 5;
parms->iph.ttl = 64;
if (!data)
return;
if (data[IFLA_IPTUN_LINK])
parms->link = nla_get_u32(data[IFLA_IPTUN_LINK]);
if (data[IFLA_IPTUN_LOCAL])
parms->iph.saddr = nla_get_be32(data[IFLA_IPTUN_LOCAL]);
if (data[IFLA_IPTUN_REMOTE])
parms->iph.daddr = nla_get_be32(data[IFLA_IPTUN_REMOTE]);
if (data[IFLA_IPTUN_TTL]) {
parms->iph.ttl = nla_get_u8(data[IFLA_IPTUN_TTL]);
if (parms->iph.ttl)
parms->iph.frag_off = htons(IP_DF);
}
if (data[IFLA_IPTUN_TOS])
parms->iph.tos = nla_get_u8(data[IFLA_IPTUN_TOS]);
if (!data[IFLA_IPTUN_PMTUDISC] || nla_get_u8(data[IFLA_IPTUN_PMTUDISC]))
parms->iph.frag_off = htons(IP_DF);
if (data[IFLA_IPTUN_FLAGS])
parms->i_flags = nla_get_be16(data[IFLA_IPTUN_FLAGS]);
if (data[IFLA_IPTUN_PROTO])
parms->iph.protocol = nla_get_u8(data[IFLA_IPTUN_PROTO]);
}
/* This function returns true when ENCAP attributes are present in the nl msg */
static bool ipip6_netlink_encap_parms(struct nlattr *data[],
struct ip_tunnel_encap *ipencap)
{
bool ret = false;
memset(ipencap, 0, sizeof(*ipencap));
if (!data)
return ret;
if (data[IFLA_IPTUN_ENCAP_TYPE]) {
ret = true;
ipencap->type = nla_get_u16(data[IFLA_IPTUN_ENCAP_TYPE]);
}
if (data[IFLA_IPTUN_ENCAP_FLAGS]) {
ret = true;
ipencap->flags = nla_get_u16(data[IFLA_IPTUN_ENCAP_FLAGS]);
}
if (data[IFLA_IPTUN_ENCAP_SPORT]) {
ret = true;
ipencap->sport = nla_get_be16(data[IFLA_IPTUN_ENCAP_SPORT]);
}
if (data[IFLA_IPTUN_ENCAP_DPORT]) {
ret = true;
ipencap->dport = nla_get_be16(data[IFLA_IPTUN_ENCAP_DPORT]);
}
return ret;
}
#ifdef CONFIG_IPV6_SIT_6RD
/* This function returns true when 6RD attributes are present in the nl msg */
static bool ipip6_netlink_6rd_parms(struct nlattr *data[],
struct ip_tunnel_6rd *ip6rd)
{
bool ret = false;
memset(ip6rd, 0, sizeof(*ip6rd));
if (!data)
return ret;
if (data[IFLA_IPTUN_6RD_PREFIX]) {
ret = true;
ip6rd->prefix = nla_get_in6_addr(data[IFLA_IPTUN_6RD_PREFIX]);
}
if (data[IFLA_IPTUN_6RD_RELAY_PREFIX]) {
ret = true;
ip6rd->relay_prefix =
nla_get_be32(data[IFLA_IPTUN_6RD_RELAY_PREFIX]);
}
if (data[IFLA_IPTUN_6RD_PREFIXLEN]) {
ret = true;
ip6rd->prefixlen = nla_get_u16(data[IFLA_IPTUN_6RD_PREFIXLEN]);
}
if (data[IFLA_IPTUN_6RD_RELAY_PREFIXLEN]) {
ret = true;
ip6rd->relay_prefixlen =
nla_get_u16(data[IFLA_IPTUN_6RD_RELAY_PREFIXLEN]);
}
return ret;
}
#endif
static int ipip6_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[])
{
struct net *net = dev_net(dev);
struct ip_tunnel *nt;
struct ip_tunnel_encap ipencap;
#ifdef CONFIG_IPV6_SIT_6RD
struct ip_tunnel_6rd ip6rd;
#endif
int err;
nt = netdev_priv(dev);
if (ipip6_netlink_encap_parms(data, &ipencap)) {
err = ip_tunnel_encap_setup(nt, &ipencap);
if (err < 0)
return err;
}
ipip6_netlink_parms(data, &nt->parms);
if (ipip6_tunnel_locate(net, &nt->parms, 0))
return -EEXIST;
err = ipip6_tunnel_create(dev);
if (err < 0)
return err;
#ifdef CONFIG_IPV6_SIT_6RD
if (ipip6_netlink_6rd_parms(data, &ip6rd))
err = ipip6_tunnel_update_6rd(nt, &ip6rd);
#endif
return err;
}
static int ipip6_changelink(struct net_device *dev, struct nlattr *tb[],
struct nlattr *data[])
{
struct ip_tunnel *t = netdev_priv(dev);
struct ip_tunnel_parm p;
struct ip_tunnel_encap ipencap;
struct net *net = t->net;
struct sit_net *sitn = net_generic(net, sit_net_id);
#ifdef CONFIG_IPV6_SIT_6RD
struct ip_tunnel_6rd ip6rd;
#endif
int err;
if (dev == sitn->fb_tunnel_dev)
return -EINVAL;
if (ipip6_netlink_encap_parms(data, &ipencap)) {
err = ip_tunnel_encap_setup(t, &ipencap);
if (err < 0)
return err;
}
ipip6_netlink_parms(data, &p);
if (((dev->flags & IFF_POINTOPOINT) && !p.iph.daddr) ||
(!(dev->flags & IFF_POINTOPOINT) && p.iph.daddr))
return -EINVAL;
t = ipip6_tunnel_locate(net, &p, 0);
if (t) {
if (t->dev != dev)
return -EEXIST;
} else
t = netdev_priv(dev);
ipip6_tunnel_update(t, &p);
#ifdef CONFIG_IPV6_SIT_6RD
if (ipip6_netlink_6rd_parms(data, &ip6rd))
return ipip6_tunnel_update_6rd(t, &ip6rd);
#endif
return 0;
}
static size_t ipip6_get_size(const struct net_device *dev)
{
return
/* IFLA_IPTUN_LINK */
nla_total_size(4) +
/* IFLA_IPTUN_LOCAL */
nla_total_size(4) +
/* IFLA_IPTUN_REMOTE */
nla_total_size(4) +
/* IFLA_IPTUN_TTL */
nla_total_size(1) +
/* IFLA_IPTUN_TOS */
nla_total_size(1) +
/* IFLA_IPTUN_PMTUDISC */
nla_total_size(1) +
/* IFLA_IPTUN_FLAGS */
nla_total_size(2) +
/* IFLA_IPTUN_PROTO */
nla_total_size(1) +
#ifdef CONFIG_IPV6_SIT_6RD
/* IFLA_IPTUN_6RD_PREFIX */
nla_total_size(sizeof(struct in6_addr)) +
/* IFLA_IPTUN_6RD_RELAY_PREFIX */
nla_total_size(4) +
/* IFLA_IPTUN_6RD_PREFIXLEN */
nla_total_size(2) +
/* IFLA_IPTUN_6RD_RELAY_PREFIXLEN */
nla_total_size(2) +
#endif
/* IFLA_IPTUN_ENCAP_TYPE */
nla_total_size(2) +
/* IFLA_IPTUN_ENCAP_FLAGS */
nla_total_size(2) +
/* IFLA_IPTUN_ENCAP_SPORT */
nla_total_size(2) +
/* IFLA_IPTUN_ENCAP_DPORT */
nla_total_size(2) +
0;
}
static int ipip6_fill_info(struct sk_buff *skb, const struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
struct ip_tunnel_parm *parm = &tunnel->parms;
if (nla_put_u32(skb, IFLA_IPTUN_LINK, parm->link) ||
nla_put_in_addr(skb, IFLA_IPTUN_LOCAL, parm->iph.saddr) ||
nla_put_in_addr(skb, IFLA_IPTUN_REMOTE, parm->iph.daddr) ||
nla_put_u8(skb, IFLA_IPTUN_TTL, parm->iph.ttl) ||
nla_put_u8(skb, IFLA_IPTUN_TOS, parm->iph.tos) ||
nla_put_u8(skb, IFLA_IPTUN_PMTUDISC,
!!(parm->iph.frag_off & htons(IP_DF))) ||
nla_put_u8(skb, IFLA_IPTUN_PROTO, parm->iph.protocol) ||
nla_put_be16(skb, IFLA_IPTUN_FLAGS, parm->i_flags))
goto nla_put_failure;
#ifdef CONFIG_IPV6_SIT_6RD
if (nla_put_in6_addr(skb, IFLA_IPTUN_6RD_PREFIX,
&tunnel->ip6rd.prefix) ||
nla_put_in_addr(skb, IFLA_IPTUN_6RD_RELAY_PREFIX,
tunnel->ip6rd.relay_prefix) ||
nla_put_u16(skb, IFLA_IPTUN_6RD_PREFIXLEN,
tunnel->ip6rd.prefixlen) ||
nla_put_u16(skb, IFLA_IPTUN_6RD_RELAY_PREFIXLEN,
tunnel->ip6rd.relay_prefixlen))
goto nla_put_failure;
#endif
if (nla_put_u16(skb, IFLA_IPTUN_ENCAP_TYPE,
tunnel->encap.type) ||
nla_put_be16(skb, IFLA_IPTUN_ENCAP_SPORT,
tunnel->encap.sport) ||
nla_put_be16(skb, IFLA_IPTUN_ENCAP_DPORT,
tunnel->encap.dport) ||
nla_put_u16(skb, IFLA_IPTUN_ENCAP_FLAGS,
tunnel->encap.flags))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static const struct nla_policy ipip6_policy[IFLA_IPTUN_MAX + 1] = {
[IFLA_IPTUN_LINK] = { .type = NLA_U32 },
[IFLA_IPTUN_LOCAL] = { .type = NLA_U32 },
[IFLA_IPTUN_REMOTE] = { .type = NLA_U32 },
[IFLA_IPTUN_TTL] = { .type = NLA_U8 },
[IFLA_IPTUN_TOS] = { .type = NLA_U8 },
[IFLA_IPTUN_PMTUDISC] = { .type = NLA_U8 },
[IFLA_IPTUN_FLAGS] = { .type = NLA_U16 },
[IFLA_IPTUN_PROTO] = { .type = NLA_U8 },
#ifdef CONFIG_IPV6_SIT_6RD
[IFLA_IPTUN_6RD_PREFIX] = { .len = sizeof(struct in6_addr) },
[IFLA_IPTUN_6RD_RELAY_PREFIX] = { .type = NLA_U32 },
[IFLA_IPTUN_6RD_PREFIXLEN] = { .type = NLA_U16 },
[IFLA_IPTUN_6RD_RELAY_PREFIXLEN] = { .type = NLA_U16 },
#endif
[IFLA_IPTUN_ENCAP_TYPE] = { .type = NLA_U16 },
[IFLA_IPTUN_ENCAP_FLAGS] = { .type = NLA_U16 },
[IFLA_IPTUN_ENCAP_SPORT] = { .type = NLA_U16 },
[IFLA_IPTUN_ENCAP_DPORT] = { .type = NLA_U16 },
};
static void ipip6_dellink(struct net_device *dev, struct list_head *head)
{
struct net *net = dev_net(dev);
struct sit_net *sitn = net_generic(net, sit_net_id);
if (dev != sitn->fb_tunnel_dev)
unregister_netdevice_queue(dev, head);
}
static struct rtnl_link_ops sit_link_ops __read_mostly = {
.kind = "sit",
.maxtype = IFLA_IPTUN_MAX,
.policy = ipip6_policy,
.priv_size = sizeof(struct ip_tunnel),
.setup = ipip6_tunnel_setup,
.validate = ipip6_validate,
.newlink = ipip6_newlink,
.changelink = ipip6_changelink,
.get_size = ipip6_get_size,
.fill_info = ipip6_fill_info,
.dellink = ipip6_dellink,
.get_link_net = ip_tunnel_get_link_net,
};
static struct xfrm_tunnel sit_handler __read_mostly = {
.handler = ipip6_rcv,
.err_handler = ipip6_err,
.priority = 1,
};
static struct xfrm_tunnel ipip_handler __read_mostly = {
.handler = ipip_rcv,
.err_handler = ipip6_err,
.priority = 2,
};
#if IS_ENABLED(CONFIG_MPLS)
static struct xfrm_tunnel mplsip_handler __read_mostly = {
.handler = mplsip_rcv,
.err_handler = ipip6_err,
.priority = 2,
};
#endif
static void __net_exit sit_destroy_tunnels(struct net *net,
struct list_head *head)
{
struct sit_net *sitn = net_generic(net, sit_net_id);
struct net_device *dev, *aux;
int prio;
for_each_netdev_safe(net, dev, aux)
if (dev->rtnl_link_ops == &sit_link_ops)
unregister_netdevice_queue(dev, head);
for (prio = 1; prio < 4; prio++) {
int h;
for (h = 0; h < IP6_SIT_HASH_SIZE; h++) {
struct ip_tunnel *t;
t = rtnl_dereference(sitn->tunnels[prio][h]);
while (t) {
/* If dev is in the same netns, it has already
* been added to the list by the previous loop.
*/
if (!net_eq(dev_net(t->dev), net))
unregister_netdevice_queue(t->dev,
head);
t = rtnl_dereference(t->next);
}
}
}
}
static int __net_init sit_init_net(struct net *net)
{
struct sit_net *sitn = net_generic(net, sit_net_id);
struct ip_tunnel *t;
int err;
sitn->tunnels[0] = sitn->tunnels_wc;
sitn->tunnels[1] = sitn->tunnels_l;
sitn->tunnels[2] = sitn->tunnels_r;
sitn->tunnels[3] = sitn->tunnels_r_l;
sitn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "sit0",
NET_NAME_UNKNOWN,
ipip6_tunnel_setup);
if (!sitn->fb_tunnel_dev) {
err = -ENOMEM;
goto err_alloc_dev;
}
dev_net_set(sitn->fb_tunnel_dev, net);
sitn->fb_tunnel_dev->rtnl_link_ops = &sit_link_ops;
/* FB netdevice is special: we have one, and only one per netns.
* Allowing to move it to another netns is clearly unsafe.
*/
sitn->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL;
err = register_netdev(sitn->fb_tunnel_dev);
if (err)
goto err_reg_dev;
ipip6_tunnel_clone_6rd(sitn->fb_tunnel_dev, sitn);
ipip6_fb_tunnel_init(sitn->fb_tunnel_dev);
t = netdev_priv(sitn->fb_tunnel_dev);
strcpy(t->parms.name, sitn->fb_tunnel_dev->name);
return 0;
err_reg_dev:
ipip6_dev_free(sitn->fb_tunnel_dev);
err_alloc_dev:
return err;
}
static void __net_exit sit_exit_net(struct net *net)
{
LIST_HEAD(list);
rtnl_lock();
sit_destroy_tunnels(net, &list);
unregister_netdevice_many(&list);
rtnl_unlock();
}
static struct pernet_operations sit_net_ops = {
.init = sit_init_net,
.exit = sit_exit_net,
.id = &sit_net_id,
.size = sizeof(struct sit_net),
};
static void __exit sit_cleanup(void)
{
rtnl_link_unregister(&sit_link_ops);
xfrm4_tunnel_deregister(&sit_handler, AF_INET6);
xfrm4_tunnel_deregister(&ipip_handler, AF_INET);
#if IS_ENABLED(CONFIG_MPLS)
xfrm4_tunnel_deregister(&mplsip_handler, AF_MPLS);
#endif
unregister_pernet_device(&sit_net_ops);
rcu_barrier(); /* Wait for completion of call_rcu()'s */
}
static int __init sit_init(void)
{
int err;
pr_info("IPv6, IPv4 and MPLS over IPv4 tunneling driver\n");
err = register_pernet_device(&sit_net_ops);
if (err < 0)
return err;
err = xfrm4_tunnel_register(&sit_handler, AF_INET6);
if (err < 0) {
pr_info("%s: can't register ip6ip4\n", __func__);
goto xfrm_tunnel_failed;
}
err = xfrm4_tunnel_register(&ipip_handler, AF_INET);
if (err < 0) {
pr_info("%s: can't register ip4ip4\n", __func__);
goto xfrm_tunnel4_failed;
}
#if IS_ENABLED(CONFIG_MPLS)
err = xfrm4_tunnel_register(&mplsip_handler, AF_MPLS);
if (err < 0) {
pr_info("%s: can't register mplsip\n", __func__);
goto xfrm_tunnel_mpls_failed;
}
#endif
err = rtnl_link_register(&sit_link_ops);
if (err < 0)
goto rtnl_link_failed;
out:
return err;
rtnl_link_failed:
#if IS_ENABLED(CONFIG_MPLS)
xfrm4_tunnel_deregister(&mplsip_handler, AF_MPLS);
xfrm_tunnel_mpls_failed:
#endif
xfrm4_tunnel_deregister(&ipip_handler, AF_INET);
xfrm_tunnel4_failed:
xfrm4_tunnel_deregister(&sit_handler, AF_INET6);
xfrm_tunnel_failed:
unregister_pernet_device(&sit_net_ops);
goto out;
}
module_init(sit_init);
module_exit(sit_cleanup);
MODULE_LICENSE("GPL");
MODULE_ALIAS_RTNL_LINK("sit");
MODULE_ALIAS_NETDEV("sit0");
| gpl-2.0 |
fishbaoz/coreboot | src/vendorcode/amd/agesa/f16kb/Proc/Mem/Tech/mtthrcSeedTrain.c | 33 | 26288 | /* $NoKeywords:$ */
/**
* @file
*
* mtthrcSt.c
*
* Phy assisted DQS receiver enable seedless training
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: (Mem/Tech)
* @e \$Revision: 84150 $ @e \$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $
*
**/
/*****************************************************************************
*
* Copyright (c) 2008 - 2013, Advanced Micro Devices, 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:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ***************************************************************************
*
*/
/*
*----------------------------------------------------------------------------
* MODULES USED
*
*----------------------------------------------------------------------------
*/
#include "AGESA.h"
#include "amdlib.h"
#include "Ids.h"
#include "mm.h"
#include "mn.h"
#include "mt.h"
#include "mttEdgeDetect.h"
#include "Filecode.h"
CODE_GROUP (G1_PEICC)
RDATA_GROUP (G1_PEICC)
#define FILECODE PROC_MEM_TECH_MTTHRCSEEDTRAIN_FILECODE
/*----------------------------------------------------------------------------
3 * DEFINITIONS AND MACROS
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* TYPEDEFS AND STRUCTURES
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* PROTOTYPES OF LOCAL FUNCTIONS
*
*----------------------------------------------------------------------------
*/
VOID
STATIC
MemTRdPosRxEnSeedSetDly3 (
IN OUT MEM_TECH_BLOCK *TechPtr,
IN OUT UINT16 RcvEnDly,
IN OUT UINT8 ByteLane
);
VOID
STATIC
MemTRdPosRxEnSeedCheckRxEndly3 (
IN OUT MEM_TECH_BLOCK *TechPtr
);
/*----------------------------------------------------------------------------
* EXPORTED FUNCTIONS
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
* LOCAL FUNCTIONS
*
*----------------------------------------------------------------------------
*/
/*-----------------------------------------------------------------------------
*
*
* This function checks each bytelane for no window error.
*
*
* @param[in,out] *TechPtr - Pointer to the MEM_TECH_BLOCK
* @param[in,out] OptParam - Optional parameter
*
* @return TRUE
* ----------------------------------------------------------------------------
*/
BOOLEAN
MemTTrackRxEnSeedlessRdWrNoWindBLError (
IN OUT MEM_TECH_BLOCK *TechPtr,
IN OUT VOID *OptParam
)
{
UINT8 i;
SWEEP_INFO SweepData;
SweepData = *(SWEEP_INFO*)OptParam;
for (i = 0; i < ((TechPtr->NBPtr->MCTPtr->Status[SbEccDimms] && TechPtr->NBPtr->IsSupported[EccByteTraining]) ? 9 : 8) ; i++) {
//
/// Skip Bytelanes that have already reached the desired result
//
if ((SweepData.ResultFound & ((UINT16)1 << i)) == 0) {
if (SweepData.TrnDelays[i] == SweepData.EndDelay) {
if ((SweepData.EndResult & ((UINT16) (1 << i))) != 0) {
TechPtr->ByteLaneError[i] = TRUE;
} else {
TechPtr->ByteLaneError[i] = FALSE;
}
}
}
}
return TRUE;
}
/*-----------------------------------------------------------------------------
*
*
* This function checks each bytelane for small window error.
*
*
* @param[in,out] *TechPtr - Pointer to the MEM_TECH_BLOCK
* @param[in,out] OptParam - Optional parameter(Unused)
*
* @return TRUE
* ----------------------------------------------------------------------------
*/
BOOLEAN
MemTTrackRxEnSeedlessRdWrSmallWindBLError (
IN OUT MEM_TECH_BLOCK *TechPtr,
IN OUT VOID *OptParam
)
{
TechPtr->ByteLaneError[TechPtr->Bytelane] = TRUE;
return TRUE;
}
/* -----------------------------------------------------------------------------*/
/**
*
* This function sets the RxEn delay
*
* @param[in,out] *TechPtr - Pointer to the MEM_TECH_BLOCK
* @param[in,out] *RcvEnDly - Receiver Enable Delay
* @param[in,out] *ByteLane - Bytelane
*
*/
VOID
STATIC
MemTRdPosRxEnSeedSetDly3 (
IN OUT MEM_TECH_BLOCK *TechPtr,
IN OUT UINT16 RcvEnDly,
IN OUT UINT8 ByteLane
)
{
TechPtr->NBPtr->ChannelPtr->RcvEnDlys[(TechPtr->ChipSel / TechPtr->NBPtr->CsPerDelay) * TechPtr->DlyTableWidth () + ByteLane] = RcvEnDly;
TechPtr->NBPtr->SetTrainDly (TechPtr->NBPtr, AccessRcvEnDly, DIMM_BYTE_ACCESS ((TechPtr->ChipSel / TechPtr->NBPtr->CsPerDelay), ByteLane), RcvEnDly);
TechPtr->NBPtr->FamilySpecificHook[ResetRxFifoPtr] (TechPtr->NBPtr, TechPtr->NBPtr);
}
/* -----------------------------------------------------------------------------*/
/**
*
* This function determines if the currert RxEn delay settings have failed
*
* @param[in,out] *TechPtr - Pointer to the MEM_TECH_BLOCK
*
*/
VOID
STATIC
MemTRdPosRxEnSeedCheckRxEndly3 (
IN OUT MEM_TECH_BLOCK *TechPtr
)
{
UINT8 MaxDlyDimm;
TechPtr->FindMaxDlyForMaxRdLat (TechPtr, &MaxDlyDimm);
TechPtr->NBPtr->SetMaxLatency (TechPtr->NBPtr, TechPtr->MaxDlyForMaxRdLat);
TechPtr->DqsRdWrPosSaved = 0;
MemTTrainDQSEdgeDetect (TechPtr);
}
/* -----------------------------------------------------------------------------*/
/**
*
* This function executes RdDQS training and if fails adjusts the RxEn Gross results for
* each bytelane
*
* @param[in,out] *TechPtr - Pointer to the MEM_TECH_BLOCK
*
* @return TRUE - All bytelanes pass
* @return FALSE - Some bytelanes fail
*/
BOOLEAN
MemTRdPosWithRxEnDlySeeds3 (
IN OUT MEM_TECH_BLOCK *TechPtr
)
{
UINT8 ByteLane;
UINT16 PassTestRxEnDly[MAX_BYTELANES_PER_CHANNEL + 1];
UINT16 FailTestRxEnDly[MAX_BYTELANES_PER_CHANNEL + 1];
UINT16 FinalRxEnCycle[MAX_BYTELANES_PER_CHANNEL + 1];
UINT16 RxOrig[MAX_BYTELANES_PER_CHANNEL];
UINT8 i;
UINT8 j;
UINT8 NumBLWithTargetFound;
UINT8 MaxByteLanes;
INT16 RxEn;
BOOLEAN status;
BOOLEAN EsbNoDqsPosSave;
BOOLEAN OutOfRange[MAX_BYTELANES_PER_CHANNEL];
BOOLEAN ByteLanePass[MAX_BYTELANES_PER_CHANNEL];
BOOLEAN ByteLaneFail[MAX_BYTELANES_PER_CHANNEL];
BOOLEAN RxEnMemClkTested[MAX_BYTELANES_PER_CHANNEL][MAX_POS_RX_EN_SEED_GROSS_RANGE];
BOOLEAN RxEnMemClkSt[MAX_BYTELANES_PER_CHANNEL][MAX_POS_RX_EN_SEED_GROSS_RANGE];
BOOLEAN RxEnDlyTargetFound[MAX_BYTELANES_PER_CHANNEL];
BOOLEAN DlyWrittenToReg[MAX_BYTELANES_PER_CHANNEL];
UINT16 RxEnDlyTargetValue[MAX_BYTELANES_PER_CHANNEL];
UINT8 AllByteLanesOutOfRange;
UINT8 AllByteLanesSaved;
UINT8 TotalByteLanesCheckedForSaved;
UINT8 MemClkCycle;
MEM_NB_BLOCK *NBPtr;
CH_DEF_STRUCT *ChannelPtr;
NBPtr = TechPtr->NBPtr;
ChannelPtr = TechPtr->NBPtr->ChannelPtr;
NumBLWithTargetFound = 0;
status = FALSE;
EsbNoDqsPosSave = TechPtr->NBPtr->MCTPtr->ErrStatus[EsbNoDqsPos];
NBPtr->RdDqsDlyRetrnStat = RDDQSDLY_RTN_SUSPEND;
IDS_HDT_CONSOLE (MEM_FLOW, "\n\nStart HW RxEn Seedless training\n\n");
// 1. Program D18F2x9C_x0D0F_0[F,8:0]30_dct[1:0][BlockRxDqsLock] = 1.
NBPtr->SetBitField (NBPtr, BFBlockRxDqsLock, 0x0100);
IDS_HDT_CONSOLE (MEM_FLOW, "\tChip Select: %02x \n", TechPtr->ChipSel);
IDS_HDT_CONSOLE (MEM_FLOW, "\t\t\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t\t\t\tRxEn Orig: ");
//
// Start sweep loops for RxEn Seedless Training
//
MaxByteLanes = (TechPtr->NBPtr->MCTPtr->Status[SbEccDimms] && TechPtr->NBPtr->IsSupported[EccByteTraining]) ? 9 : 8; //dmach
//
//Initialialize BL variables
//
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
OutOfRange[ByteLane] = FALSE;
ByteLanePass[ByteLane] = FALSE;
ByteLaneFail[ByteLane] = FALSE;
// 2. RxEnOrig = D18F2x9C_x0000_00[2A:10]_dct[1:0][DqsRcvEnGrossDelay, DqsRcvEnFineDelay] result
// from 2.10.6.8.2 [Phy Assisted DQS Receiver Enable Training]
RxOrig[ByteLane] = TechPtr->RxOrig[ByteLane]; // Original RxEn Dly based on PRE results
RxEnDlyTargetFound[ByteLane] = FALSE;
RxEnDlyTargetValue[ByteLane] = 0;
IDS_HDT_CONSOLE (MEM_FLOW, "%03x ", RxOrig[ByteLane]);
for (i = 0; i < MAX_POS_RX_EN_SEED_GROSS_RANGE; i++) {
RxEnMemClkTested[ByteLane][i] = FALSE;
}
}
// Start MemClk delay sweep
for (i = 0; i < MAX_POS_RX_EN_SEED_GROSS_RANGE; i++) {
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\ti: %02x\n", i);
// Start direction sweep (0, - Positive, 1 - negative)
for (j = 0; j < MAX_POS_RX_EN_SEED_GROSS_DIR; j++) {
// Edge detect may run twice to see Pass to fail transition
// It is not run if the value are already saved
// Fail test is only done if pass is found
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\tj: %02x\n", j);
// Reset Bytelane Flags for next sweep
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
ByteLaneFail[ByteLane] = FALSE;
ByteLanePass[ByteLane] = FALSE;
OutOfRange[ByteLane] = FALSE;
}
if (i == 0 && j == 1) {
continue; // Since i & j are the same skip
}
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t Target BL Found: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", ((RxEnDlyTargetFound[ByteLane] == TRUE) ? 'Y' : 'N'));
}
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t Target BL Value: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, "%03x ", RxEnDlyTargetValue[ByteLane]);
}
);
//
// Find the RxEn Delay for the Pass condition in the Pass to Fail transition
// "PassTestRxEnDly"
//
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\t Setting PassTestRxEnDly\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t PassTestRxEnDly: ");
PassTestRxEnDly[ByteLane] = RxOrig[ByteLane];
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
// Calculate "PassTestRxEnDly" from current "RxEnDly"
// 3. RxEnOffset = MOD(RxEnOrig + 0x10, 0x40)
RxEn = (j == 0) ? ((INT16)RxOrig[ByteLane] + 0x10 + (0x40*i)) : ((INT16)RxOrig[ByteLane] + 0x10 - (0x40*i));
// Check if RxEnDly is in a valid range
if ((RxEn >= NBPtr->MinRxEnSeedGross) && (RxEn <= NBPtr->MaxRxEnSeedTotal)) {
PassTestRxEnDly[ByteLane] = (UINT16)RxEn;
// 4. For each DqsRcvEn value beginning from RxEnOffset incrementing by 1 MEMCLK:
// A. Program D18F2x9C_x0000_00[2A:10]_dct[1:0][DqsRcvEnGrossDelay, DqsRcvEnFineDelay] with
// the current value.
MemTRdPosRxEnSeedSetDly3 (TechPtr, PassTestRxEnDly[ByteLane], ByteLane);
OutOfRange[ByteLane] = FALSE;
} else {
OutOfRange[ByteLane] = TRUE;
}
} else {
PassTestRxEnDly[ByteLane] = RxEnDlyTargetValue[ByteLane];
}
IDS_HDT_CONSOLE (MEM_FLOW, "%03x ", PassTestRxEnDly[ByteLane]);
}
// Check if all BLs out of Range at "PassTestRxEnDly"
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t OutOfRange: ");
AllByteLanesOutOfRange = 0;
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (OutOfRange[ByteLane]) {
AllByteLanesOutOfRange++;
}
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (OutOfRange[ByteLane] == TRUE) ? 'Y' : 'N');
}
if (AllByteLanesOutOfRange == MaxByteLanes) {
continue; // All BLs out of range, so skip
}
// Check if all BLs saved Results at "PassTestRxEnDly"
AllByteLanesSaved = 0;
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
MemClkCycle = (UINT8) (PassTestRxEnDly[ByteLane] >> 5);
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
if (!RxEnMemClkTested[ByteLane][MemClkCycle]) {
AllByteLanesSaved++;
}
}
}
// Check if "RxEnDlyValueForPassCond" passed
if (AllByteLanesSaved != 0) {
// At least one BL has not been saved, so check if "PassTestRxEnDly" passed
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\t Checking if PassTestRxEnDly Passes?\n\n");
// 4B. Perform 2.10.6.8.5 [DQS Position Training].
// Record the result for the current DqsRcvEn setting as a pass or fail depending if a data eye is found.
MemTRdPosRxEnSeedCheckRxEndly3 (TechPtr);
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t\t Err Status: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (TechPtr->ByteLaneError[ByteLane] == TRUE) ? 'F' : 'P');
}
);
} else {
// All BLs saved, so use saved results for "PassTestRxEnDly"
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\tAll BLs Saved at PassTestRxEnDly\n");
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t Save Err Stat: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
MemClkCycle = (UINT8) (PassTestRxEnDly[ByteLane] >> 5);
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", ((RxEnMemClkSt[ByteLane][MemClkCycle] == TRUE) ? 'F' : 'P'));
}
);
}
// Update Saved values for "PassTestRxEnDly"
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
if (OutOfRange[ByteLane] == FALSE) {
MemClkCycle = (UINT8) (PassTestRxEnDly[ByteLane] >> 5);
if (!RxEnMemClkTested[ByteLane][MemClkCycle]) {
RxEnMemClkTested[ByteLane][MemClkCycle] = TRUE;
RxEnMemClkSt[ByteLane][MemClkCycle] = TechPtr->ByteLaneError[ByteLane];
}
}
}
}
//
// Find the RxEn Delay for the Fail condition in the Pass to Fail transition
// "FailTestRxEnDly"
//
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
DlyWrittenToReg[ByteLane] = FALSE;
}
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
FailTestRxEnDly[ByteLane] = PassTestRxEnDly[ByteLane] + 0x40;
}
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t FailTestRxEnDly: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, "%03x ", FailTestRxEnDly[ByteLane]);
}
);
// Check if all BLs Saved Results at FailTestRxEnDly
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\tSetting FailTestRxEnDly");
AllByteLanesSaved = 0;
TotalByteLanesCheckedForSaved = 0;
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
MemClkCycle = (UINT8) (FailTestRxEnDly[ByteLane] >> 5);
// Check if RxEnDly + 40 is valid
if ((FailTestRxEnDly[ByteLane] >= NBPtr->MinRxEnSeedGross) && (FailTestRxEnDly[ByteLane] <= NBPtr->MaxRxEnSeedTotal)) {
if (RxEnMemClkTested[ByteLane][MemClkCycle]) {
AllByteLanesSaved++;
}
OutOfRange[ByteLane] = FALSE;
} else {
OutOfRange[ByteLane] = TRUE;
}
TotalByteLanesCheckedForSaved++;
}
}
// Check if all BLs out of Range condition at FailTestRxEnDly
AllByteLanesOutOfRange = 0;
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t OutOfRange: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (OutOfRange[ByteLane]) {
AllByteLanesOutOfRange++;
}
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (OutOfRange[ByteLane] == TRUE) ? 'Y' : 'N');
}
if (AllByteLanesOutOfRange == MaxByteLanes) {
continue; // All BLs out of range, so skip
}
// Setting FailTestRxEnDly for any BL that was not saved
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t FailTestRxEnDly: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
MemClkCycle = (UINT8) (PassTestRxEnDly[ByteLane] >> 5);
// Check if New RxEnDly has Passed
if ((RxEnMemClkTested[ByteLane][MemClkCycle] ? RxEnMemClkSt[ByteLane][MemClkCycle] : TechPtr->ByteLaneError[ByteLane]) == FALSE) {
if (OutOfRange[ByteLane] == FALSE) {
// BL has passed at "New RxEnDly", so check if "New RxEnDly" + 0x40 fails
MemClkCycle = (UINT8) (FailTestRxEnDly[ByteLane] >> 5);
if (!RxEnMemClkTested[ByteLane][MemClkCycle]) {
// Only Set Delays for ByteLanes that have not been already tested
MemTRdPosRxEnSeedSetDly3 (TechPtr, FailTestRxEnDly[ByteLane], ByteLane);
DlyWrittenToReg[ByteLane] = TRUE;
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'Y');
} else {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'N');
}
ByteLanePass[ByteLane] = TRUE;
} else {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'O');
}
} else {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'F');
}
} else {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'N');
}
}
// Check if BLs that passed at PassTestRxEnDly fail at FailTestRxEnDly
if (AllByteLanesSaved != TotalByteLanesCheckedForSaved) {
// At least one BL has not been saved, so check if FailTestRxEnDly passed
IDS_HDT_CONSOLE (MEM_FLOW, "\n\n\t\t Checking if FailTestRxEnDly Fails?\n");
MemTRdPosRxEnSeedCheckRxEndly3 (TechPtr);
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t Err Status: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (TechPtr->ByteLaneError[ByteLane] == TRUE) ? 'F' : 'P');
}
);
} else {
// All BLs saved, so use saved results for FailTestRxEnDly
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\tAll BLs Saved at PassTestRxEnDly\n");
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\t Byte: 00 01 02 03 04 05 06 07 ECC\n");
IDS_HDT_CONSOLE (MEM_FLOW, "\t Save Err Stat: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
MemClkCycle = (UINT8) (FailTestRxEnDly[ByteLane] >> 5);
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (RxEnMemClkSt[ByteLane][MemClkCycle] == TRUE) ? 'F' : 'P');
}
);
}
//
// If BL failes at "FailTestRxEnDly" set FinalRxEnCycle
//
// Setting FinalRxEnCycle for any BL that Failed at FailTestRxEnDly
IDS_HDT_CONSOLE (MEM_FLOW, "\n Set FinalRxEnCycle: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
MemClkCycle = (UINT8) (FailTestRxEnDly[ByteLane] >> 5);
if (RxEnMemClkTested[ByteLane][MemClkCycle] ? RxEnMemClkSt[ByteLane][MemClkCycle] == TRUE : (TechPtr->ByteLaneError[ByteLane] && DlyWrittenToReg[ByteLane])) {
FinalRxEnCycle[ByteLane] = PassTestRxEnDly[ByteLane] - 0x10;
if (((UINT16) FinalRxEnCycle[ByteLane] >= NBPtr->MinRxEnSeedGross) && ((UINT16) FinalRxEnCycle[ByteLane] <= NBPtr->MaxRxEnSeedTotal)) {
// Since FailTestRxEnDly, we can set FinalRxEnCycle
MemTRdPosRxEnSeedSetDly3 (TechPtr, (UINT16) FinalRxEnCycle[ByteLane], ByteLane);
ByteLaneFail[ByteLane] = TRUE;
OutOfRange[ByteLane] = FALSE;
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'Y');
} else {
OutOfRange[ByteLane] = TRUE;
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'N');
}
} else {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'F');
OutOfRange[ByteLane] = FALSE;
}
} else {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", 'Y');
}
}
// Update Saved values for FailTestRxEnDly
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
if (OutOfRange[ByteLane] == FALSE) {
MemClkCycle = (UINT8) (FailTestRxEnDly[ByteLane] >> 5);
if (!RxEnMemClkTested[ByteLane][MemClkCycle] && DlyWrittenToReg[ByteLane]) {
RxEnMemClkTested[ByteLane][MemClkCycle] = TRUE;
RxEnMemClkSt[ByteLane][MemClkCycle] = TechPtr->ByteLaneError[ByteLane];
}
}
}
}
// Check for out of Range condition
AllByteLanesOutOfRange = 0;
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t OutOfRange: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (OutOfRange[ByteLane]) {
AllByteLanesOutOfRange++;
}
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (OutOfRange[ByteLane] == TRUE) ? 'Y' : 'N');
}
if (AllByteLanesOutOfRange == MaxByteLanes) {
continue; // All BLs out of range so skip
}
IDS_HDT_CONSOLE_DEBUG_CODE (
IDS_HDT_CONSOLE (MEM_FLOW, "\n FinalRxEnCycle: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, "%03x ", (UINT16) FinalRxEnCycle[ByteLane]);
}
IDS_HDT_CONSOLE (MEM_FLOW, "\n ByteLaneFail: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (ByteLaneFail[ByteLane] == TRUE) ? 'Y' : 'N');
}
IDS_HDT_CONSOLE (MEM_FLOW, "\n ByteLanePass: ");
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
IDS_HDT_CONSOLE (MEM_FLOW, " %c ", (ByteLanePass[ByteLane] == TRUE) ? 'Y' : 'N');
}
);
//
// Check for exit condition
// PassTestRxEnDly = Pass and FailTestRxEnDly[ByteLane] = Fail
// If found, use "FinalRxEnCycle" as final RxEnDly value
//
// 5. Process the array of results and determine a pass-to-fail transition.
NumBLWithTargetFound = 0;
for (ByteLane = 0; ByteLane < MaxByteLanes; ByteLane++) {
if (RxEnDlyTargetFound[ByteLane] == FALSE) {
// Check if the current BL has found its target
if (ByteLanePass[ByteLane] == TRUE && ByteLaneFail[ByteLane] == TRUE) {
RxEnDlyTargetFound[ByteLane] = TRUE;
NumBLWithTargetFound++;
RxEnDlyTargetValue[ByteLane] = FinalRxEnCycle[ByteLane];
} else {
RxEnDlyTargetFound[ByteLane] = FALSE;
}
} else {
// BL has already failed and passed, so increment both flags
NumBLWithTargetFound++;
}
}
IDS_HDT_CONSOLE (MEM_FLOW, "\n");
// Check for exit condition
if (NumBLWithTargetFound == MaxByteLanes) {
// Exit condition found, so setting new RDQS based on RxEn-0x10 \n\n
IDS_HDT_CONSOLE (MEM_FLOW, "\n\t\t\t Setting new RDQS based on FinalRxEnCycle \n\n");
// 5 A. DqsRcvEnCycle = the total delay value of the pass result.
// B. Program D18F2x9C_x0000_00[2A:10]_dct[1:0][DqsRcvEnGrossDelay, DqsRcvEnFineDelay] =
// DqsRcvEnCycle - 0x10.
NBPtr->RdDqsDlyRetrnStat = RDDQSDLY_RTN_NEEDED;
MemTRdPosRxEnSeedCheckRxEndly3 (TechPtr);
IDS_HDT_CONSOLE (MEM_FLOW, "\n");
status = TRUE;
break;
} else {
status = FALSE;
}
}
// Check for exit condition
if (NumBLWithTargetFound == MaxByteLanes) {
status = TRUE;
break;
} else {
status = FALSE;
}
IDS_HDT_CONSOLE (MEM_FLOW, "\n");
}
TechPtr->NBPtr->MCTPtr->ErrStatus[EsbNoDqsPos] = EsbNoDqsPosSave;
if (i == MAX_POS_RX_EN_SEED_GROSS_RANGE) {
TechPtr->NBPtr->MCTPtr->ErrStatus[EsbNoDqsPos] = TRUE;
}
// 6. Program D18F2x9C_x0D0F_0[F,8:0]30_dct[1:0][BlockRxDqsLock] = 0.
NBPtr->SetBitField (NBPtr, BFBlockRxDqsLock, 0);
IDS_HDT_CONSOLE (MEM_FLOW, "\nEnd HW RxEn Seedless training\n\n");
return status;
}
| gpl-2.0 |
Antonio-Zhou/Linux-2.6.11 | drivers/scsi/qla2xxx/qla_gs.c | 33 | 31172 | /*
* QLOGIC LINUX SOFTWARE
*
* QLogic ISP2x00 device driver for Linux 2.6.x
* Copyright (C) 2003-2004 QLogic Corporation
* (www.qlogic.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
*/
#include "qla_def.h"
static inline ms_iocb_entry_t *
qla2x00_prep_ms_iocb(scsi_qla_host_t *, uint32_t, uint32_t);
static inline struct ct_sns_req *
qla2x00_prep_ct_req(struct ct_sns_req *, uint16_t, uint16_t);
static inline struct sns_cmd_pkt *
qla2x00_prep_sns_cmd(scsi_qla_host_t *, uint16_t, uint16_t, uint16_t);
static int qla2x00_sns_ga_nxt(scsi_qla_host_t *, fc_port_t *);
static int qla2x00_sns_gid_pt(scsi_qla_host_t *, sw_info_t *);
static int qla2x00_sns_gpn_id(scsi_qla_host_t *, sw_info_t *);
static int qla2x00_sns_gnn_id(scsi_qla_host_t *, sw_info_t *);
static int qla2x00_sns_rft_id(scsi_qla_host_t *);
static int qla2x00_sns_rnn_id(scsi_qla_host_t *);
/**
* qla2x00_prep_ms_iocb() - Prepare common MS IOCB fields for SNS CT query.
* @ha: HA context
* @req_size: request size in bytes
* @rsp_size: response size in bytes
*
* Returns a pointer to the @ha's ms_iocb.
*/
static inline ms_iocb_entry_t *
qla2x00_prep_ms_iocb(scsi_qla_host_t *ha, uint32_t req_size, uint32_t rsp_size)
{
ms_iocb_entry_t *ms_pkt;
ms_pkt = ha->ms_iocb;
memset(ms_pkt, 0, sizeof(ms_iocb_entry_t));
ms_pkt->entry_type = MS_IOCB_TYPE;
ms_pkt->entry_count = 1;
SET_TARGET_ID(ha, ms_pkt->loop_id, SIMPLE_NAME_SERVER);
ms_pkt->control_flags = __constant_cpu_to_le16(CF_READ | CF_HEAD_TAG);
ms_pkt->timeout = __constant_cpu_to_le16(25);
ms_pkt->cmd_dsd_count = __constant_cpu_to_le16(1);
ms_pkt->total_dsd_count = __constant_cpu_to_le16(2);
ms_pkt->rsp_bytecount = cpu_to_le32(rsp_size);
ms_pkt->req_bytecount = cpu_to_le32(req_size);
ms_pkt->dseg_req_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ms_pkt->dseg_req_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ms_pkt->dseg_req_length = ms_pkt->req_bytecount;
ms_pkt->dseg_rsp_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ms_pkt->dseg_rsp_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ms_pkt->dseg_rsp_length = ms_pkt->rsp_bytecount;
return (ms_pkt);
}
/**
* qla2x00_prep_ct_req() - Prepare common CT request fields for SNS query.
* @ct_req: CT request buffer
* @cmd: GS command
* @rsp_size: response size in bytes
*
* Returns a pointer to the intitialized @ct_req.
*/
static inline struct ct_sns_req *
qla2x00_prep_ct_req(struct ct_sns_req *ct_req, uint16_t cmd, uint16_t rsp_size)
{
memset(ct_req, 0, sizeof(struct ct_sns_pkt));
ct_req->header.revision = 0x01;
ct_req->header.gs_type = 0xFC;
ct_req->header.gs_subtype = 0x02;
ct_req->command = cpu_to_be16(cmd);
ct_req->max_rsp_size = cpu_to_be16((rsp_size - 16) / 4);
return (ct_req);
}
/**
* qla2x00_ga_nxt() - SNS scan for fabric devices via GA_NXT command.
* @ha: HA context
* @fcport: fcport entry to updated
*
* Returns 0 on success.
*/
int
qla2x00_ga_nxt(scsi_qla_host_t *ha, fc_port_t *fcport)
{
int rval;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
return (qla2x00_sns_ga_nxt(ha, fcport));
}
/* Issue GA_NXT */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, GA_NXT_REQ_SIZE, GA_NXT_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, GA_NXT_CMD,
GA_NXT_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = fcport->d_id.b.domain;
ct_req->req.port_id.port_id[1] = fcport->d_id.b.area;
ct_req->req.port_id.port_id[2] = fcport->d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GA_NXT issue IOCB failed (%d).\n",
ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): GA_NXT failed, rejected request, "
"ga_nxt_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
/* Populate fc_port_t entry. */
fcport->d_id.b.domain = ct_rsp->rsp.ga_nxt.port_id[0];
fcport->d_id.b.area = ct_rsp->rsp.ga_nxt.port_id[1];
fcport->d_id.b.al_pa = ct_rsp->rsp.ga_nxt.port_id[2];
memcpy(fcport->node_name, ct_rsp->rsp.ga_nxt.node_name,
WWN_SIZE);
memcpy(fcport->port_name, ct_rsp->rsp.ga_nxt.port_name,
WWN_SIZE);
if (ct_rsp->rsp.ga_nxt.port_type != NS_N_PORT_TYPE &&
ct_rsp->rsp.ga_nxt.port_type != NS_NL_PORT_TYPE)
fcport->d_id.b.domain = 0xf0;
DEBUG2_3(printk("scsi(%ld): GA_NXT entry - "
"nn %02x%02x%02x%02x%02x%02x%02x%02x "
"pn %02x%02x%02x%02x%02x%02x%02x%02x "
"portid=%02x%02x%02x.\n",
ha->host_no,
fcport->node_name[0], fcport->node_name[1],
fcport->node_name[2], fcport->node_name[3],
fcport->node_name[4], fcport->node_name[5],
fcport->node_name[6], fcport->node_name[7],
fcport->port_name[0], fcport->port_name[1],
fcport->port_name[2], fcport->port_name[3],
fcport->port_name[4], fcport->port_name[5],
fcport->port_name[6], fcport->port_name[7],
fcport->d_id.b.domain, fcport->d_id.b.area,
fcport->d_id.b.al_pa));
}
return (rval);
}
/**
* qla2x00_gid_pt() - SNS scan for fabric devices via GID_PT command.
* @ha: HA context
* @list: switch info entries to populate
*
* NOTE: Non-Nx_Ports are not requested.
*
* Returns 0 on success.
*/
int
qla2x00_gid_pt(scsi_qla_host_t *ha, sw_info_t *list)
{
int rval;
uint16_t i;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
struct ct_sns_gid_pt_data *gid_data;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
return (qla2x00_sns_gid_pt(ha, list));
}
gid_data = NULL;
/* Issue GID_PT */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, GID_PT_REQ_SIZE, GID_PT_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, GID_PT_CMD,
GID_PT_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_type */
ct_req->req.gid_pt.port_type = NS_NX_PORT_TYPE;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GID_PT issue IOCB failed (%d).\n",
ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): GID_PT failed, rejected request, "
"gid_pt_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
/* Set port IDs in switch info list. */
for (i = 0; i < MAX_FIBRE_DEVICES; i++) {
gid_data = &ct_rsp->rsp.gid_pt.entries[i];
list[i].d_id.b.domain = gid_data->port_id[0];
list[i].d_id.b.area = gid_data->port_id[1];
list[i].d_id.b.al_pa = gid_data->port_id[2];
/* Last one exit. */
if (gid_data->control_byte & BIT_7) {
list[i].d_id.b.rsvd_1 = gid_data->control_byte;
break;
}
}
/*
* If we've used all available slots, then the switch is
* reporting back more devices than we can handle with this
* single call. Return a failed status, and let GA_NXT handle
* the overload.
*/
if (i == MAX_FIBRE_DEVICES)
rval = QLA_FUNCTION_FAILED;
}
return (rval);
}
/**
* qla2x00_gpn_id() - SNS Get Port Name (GPN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* Returns 0 on success.
*/
int
qla2x00_gpn_id(scsi_qla_host_t *ha, sw_info_t *list)
{
int rval;
uint16_t i;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
return (qla2x00_sns_gpn_id(ha, list));
}
for (i = 0; i < MAX_FIBRE_DEVICES; i++) {
/* Issue GPN_ID */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, GPN_ID_REQ_SIZE,
GPN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, GPN_ID_CMD,
GPN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = list[i].d_id.b.domain;
ct_req->req.port_id.port_id[1] = list[i].d_id.b.area;
ct_req->req.port_id.port_id[2] = list[i].d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GPN_ID issue IOCB failed "
"(%d).\n", ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): GPN_ID failed, rejected "
"request, gpn_id_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
/* Save portname */
memcpy(list[i].port_name,
ct_rsp->rsp.gpn_id.port_name, WWN_SIZE);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_gnn_id() - SNS Get Node Name (GNN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* Returns 0 on success.
*/
int
qla2x00_gnn_id(scsi_qla_host_t *ha, sw_info_t *list)
{
int rval;
uint16_t i;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
return (qla2x00_sns_gnn_id(ha, list));
}
for (i = 0; i < MAX_FIBRE_DEVICES; i++) {
/* Issue GNN_ID */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, GNN_ID_REQ_SIZE,
GNN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, GNN_ID_CMD,
GNN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = list[i].d_id.b.domain;
ct_req->req.port_id.port_id[1] = list[i].d_id.b.area;
ct_req->req.port_id.port_id[2] = list[i].d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GNN_ID issue IOCB failed "
"(%d).\n", ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): GNN_ID failed, rejected "
"request, gnn_id_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
/* Save nodename */
memcpy(list[i].node_name,
ct_rsp->rsp.gnn_id.node_name, WWN_SIZE);
DEBUG2_3(printk("scsi(%ld): GID_PT entry - "
"nn %02x%02x%02x%02x%02x%02x%02x%02x "
"pn %02x%02x%02x%02x%02x%02x%02x%02x "
"portid=%02x%02x%02x.\n",
ha->host_no,
list[i].node_name[0], list[i].node_name[1],
list[i].node_name[2], list[i].node_name[3],
list[i].node_name[4], list[i].node_name[5],
list[i].node_name[6], list[i].node_name[7],
list[i].port_name[0], list[i].port_name[1],
list[i].port_name[2], list[i].port_name[3],
list[i].port_name[4], list[i].port_name[5],
list[i].port_name[6], list[i].port_name[7],
list[i].d_id.b.domain, list[i].d_id.b.area,
list[i].d_id.b.al_pa));
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_rft_id() - SNS Register FC-4 TYPEs (RFT_ID) supported by the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rft_id(scsi_qla_host_t *ha)
{
int rval;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
return (qla2x00_sns_rft_id(ha));
}
/* Issue RFT_ID */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, RFT_ID_REQ_SIZE, RFT_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, RFT_ID_CMD,
RFT_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id, FC-4 types */
ct_req->req.rft_id.port_id[0] = ha->d_id.b.domain;
ct_req->req.rft_id.port_id[1] = ha->d_id.b.area;
ct_req->req.rft_id.port_id[2] = ha->d_id.b.al_pa;
ct_req->req.rft_id.fc4_types[2] = 0x01; /* FCP-3 */
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): RFT_ID issue IOCB failed (%d).\n",
ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): RFT_ID failed, rejected "
"request, rft_id_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("scsi(%ld): RFT_ID exiting normally.\n",
ha->host_no));
}
return (rval);
}
/**
* qla2x00_rff_id() - SNS Register FC-4 Features (RFF_ID) supported by the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rff_id(scsi_qla_host_t *ha)
{
int rval;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
DEBUG2(printk("scsi(%ld): RFF_ID call unsupported on "
"ISP2100/ISP2200.\n", ha->host_no));
return (QLA_SUCCESS);
}
/* Issue RFF_ID */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, RFF_ID_REQ_SIZE, RFF_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, RFF_ID_CMD,
RFF_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id, FC-4 feature, FC-4 type */
ct_req->req.rff_id.port_id[0] = ha->d_id.b.domain;
ct_req->req.rff_id.port_id[1] = ha->d_id.b.area;
ct_req->req.rff_id.port_id[2] = ha->d_id.b.al_pa;
ct_req->req.rff_id.fc4_type = 0x08; /* SCSI - FCP */
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): RFF_ID issue IOCB failed (%d).\n",
ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): RFF_ID failed, rejected "
"request, rff_id_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("scsi(%ld): RFF_ID exiting normally.\n",
ha->host_no));
}
return (rval);
}
/**
* qla2x00_rnn_id() - SNS Register Node Name (RNN_ID) of the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rnn_id(scsi_qla_host_t *ha)
{
int rval;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
return (qla2x00_sns_rnn_id(ha));
}
/* Issue RNN_ID */
/* Prepare common MS IOCB */
ms_pkt = qla2x00_prep_ms_iocb(ha, RNN_ID_REQ_SIZE, RNN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, RNN_ID_CMD,
RNN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id, node_name */
ct_req->req.rnn_id.port_id[0] = ha->d_id.b.domain;
ct_req->req.rnn_id.port_id[1] = ha->d_id.b.area;
ct_req->req.rnn_id.port_id[2] = ha->d_id.b.al_pa;
memcpy(ct_req->req.rnn_id.node_name, ha->init_cb->node_name, WWN_SIZE);
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): RNN_ID issue IOCB failed (%d).\n",
ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): RNN_ID failed, rejected "
"request, rnn_id_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("scsi(%ld): RNN_ID exiting normally.\n",
ha->host_no));
}
return (rval);
}
/**
* qla2x00_rsnn_nn() - SNS Register Symbolic Node Name (RSNN_NN) of the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rsnn_nn(scsi_qla_host_t *ha)
{
int rval;
uint8_t *snn;
uint8_t version[20];
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
DEBUG2(printk("scsi(%ld): RSNN_ID call unsupported on "
"ISP2100/ISP2200.\n", ha->host_no));
return (QLA_SUCCESS);
}
/* Issue RSNN_NN */
/* Prepare common MS IOCB */
/* Request size adjusted after CT preparation */
ms_pkt = qla2x00_prep_ms_iocb(ha, 0, RSNN_NN_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(&ha->ct_sns->p.req, RSNN_NN_CMD,
RSNN_NN_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- node_name, symbolic node_name, size */
memcpy(ct_req->req.rsnn_nn.node_name, ha->init_cb->node_name, WWN_SIZE);
/* Prepare the Symbolic Node Name */
/* Board type */
snn = ct_req->req.rsnn_nn.sym_node_name;
strcpy(snn, ha->model_number);
/* Firmware version */
strcat(snn, " FW:v");
sprintf(version, "%d.%02d.%02d", ha->fw_major_version,
ha->fw_minor_version, ha->fw_subminor_version);
strcat(snn, version);
/* Driver version */
strcat(snn, " DVR:v");
strcat(snn, qla2x00_version_str);
/* Calculate SNN length */
ct_req->req.rsnn_nn.name_len = (uint8_t)strlen(snn);
/* Update MS IOCB request */
ms_pkt->req_bytecount =
cpu_to_le32(24 + 1 + ct_req->req.rsnn_nn.name_len);
ms_pkt->dseg_req_length = ms_pkt->req_bytecount;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(ha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): RSNN_NN issue IOCB failed (%d).\n",
ha->host_no, rval));
} else if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
DEBUG2_3(printk("scsi(%ld): RSNN_NN failed, rejected "
"request, rsnn_id_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer((uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr)));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("scsi(%ld): RSNN_NN exiting normally.\n",
ha->host_no));
}
return (rval);
}
/**
* qla2x00_prep_sns_cmd() - Prepare common SNS command request fields for query.
* @ha: HA context
* @cmd: GS command
* @scmd_len: Subcommand length
* @data_size: response size in bytes
*
* Returns a pointer to the @ha's sns_cmd.
*/
static inline struct sns_cmd_pkt *
qla2x00_prep_sns_cmd(scsi_qla_host_t *ha, uint16_t cmd, uint16_t scmd_len,
uint16_t data_size)
{
uint16_t wc;
struct sns_cmd_pkt *sns_cmd;
sns_cmd = ha->sns_cmd;
memset(sns_cmd, 0, sizeof(struct sns_cmd_pkt));
wc = data_size / 2; /* Size in 16bit words. */
sns_cmd->p.cmd.buffer_length = cpu_to_le16(wc);
sns_cmd->p.cmd.buffer_address[0] = cpu_to_le32(LSD(ha->sns_cmd_dma));
sns_cmd->p.cmd.buffer_address[1] = cpu_to_le32(MSD(ha->sns_cmd_dma));
sns_cmd->p.cmd.subcommand_length = cpu_to_le16(scmd_len);
sns_cmd->p.cmd.subcommand = cpu_to_le16(cmd);
wc = (data_size - 16) / 4; /* Size in 32bit words. */
sns_cmd->p.cmd.size = cpu_to_le16(wc);
return (sns_cmd);
}
/**
* qla2x00_sns_ga_nxt() - SNS scan for fabric devices via GA_NXT command.
* @ha: HA context
* @fcport: fcport entry to updated
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_ga_nxt(scsi_qla_host_t *ha, fc_port_t *fcport)
{
int rval;
struct sns_cmd_pkt *sns_cmd;
/* Issue GA_NXT. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(ha, GA_NXT_CMD, GA_NXT_SNS_SCMD_LEN,
GA_NXT_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id. */
sns_cmd->p.cmd.param[0] = fcport->d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = fcport->d_id.b.area;
sns_cmd->p.cmd.param[2] = fcport->d_id.b.domain;
/* Execute SNS command. */
rval = qla2x00_send_sns(ha, ha->sns_cmd_dma, GA_NXT_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GA_NXT Send SNS failed (%d).\n",
ha->host_no, rval));
} else if (sns_cmd->p.gan_data[8] != 0x80 ||
sns_cmd->p.gan_data[9] != 0x02) {
DEBUG2_3(printk("scsi(%ld): GA_NXT failed, rejected request, "
"ga_nxt_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer(sns_cmd->p.gan_data, 16));
rval = QLA_FUNCTION_FAILED;
} else {
/* Populate fc_port_t entry. */
fcport->d_id.b.domain = sns_cmd->p.gan_data[17];
fcport->d_id.b.area = sns_cmd->p.gan_data[18];
fcport->d_id.b.al_pa = sns_cmd->p.gan_data[19];
memcpy(fcport->node_name, &sns_cmd->p.gan_data[284], WWN_SIZE);
memcpy(fcport->port_name, &sns_cmd->p.gan_data[20], WWN_SIZE);
if (sns_cmd->p.gan_data[16] != NS_N_PORT_TYPE &&
sns_cmd->p.gan_data[16] != NS_NL_PORT_TYPE)
fcport->d_id.b.domain = 0xf0;
DEBUG2_3(printk("scsi(%ld): GA_NXT entry - "
"nn %02x%02x%02x%02x%02x%02x%02x%02x "
"pn %02x%02x%02x%02x%02x%02x%02x%02x "
"portid=%02x%02x%02x.\n",
ha->host_no,
fcport->node_name[0], fcport->node_name[1],
fcport->node_name[2], fcport->node_name[3],
fcport->node_name[4], fcport->node_name[5],
fcport->node_name[6], fcport->node_name[7],
fcport->port_name[0], fcport->port_name[1],
fcport->port_name[2], fcport->port_name[3],
fcport->port_name[4], fcport->port_name[5],
fcport->port_name[6], fcport->port_name[7],
fcport->d_id.b.domain, fcport->d_id.b.area,
fcport->d_id.b.al_pa));
}
return (rval);
}
/**
* qla2x00_sns_gid_pt() - SNS scan for fabric devices via GID_PT command.
* @ha: HA context
* @list: switch info entries to populate
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* NOTE: Non-Nx_Ports are not requested.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_gid_pt(scsi_qla_host_t *ha, sw_info_t *list)
{
int rval;
uint16_t i;
uint8_t *entry;
struct sns_cmd_pkt *sns_cmd;
/* Issue GID_PT. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(ha, GID_PT_CMD, GID_PT_SNS_SCMD_LEN,
GID_PT_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_type. */
sns_cmd->p.cmd.param[0] = NS_NX_PORT_TYPE;
/* Execute SNS command. */
rval = qla2x00_send_sns(ha, ha->sns_cmd_dma, GID_PT_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GID_PT Send SNS failed (%d).\n",
ha->host_no, rval));
} else if (sns_cmd->p.gid_data[8] != 0x80 ||
sns_cmd->p.gid_data[9] != 0x02) {
DEBUG2_3(printk("scsi(%ld): GID_PT failed, rejected request, "
"gid_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer(sns_cmd->p.gid_data, 16));
rval = QLA_FUNCTION_FAILED;
} else {
/* Set port IDs in switch info list. */
for (i = 0; i < MAX_FIBRE_DEVICES; i++) {
entry = &sns_cmd->p.gid_data[(i * 4) + 16];
list[i].d_id.b.domain = entry[1];
list[i].d_id.b.area = entry[2];
list[i].d_id.b.al_pa = entry[3];
/* Last one exit. */
if (entry[0] & BIT_7) {
list[i].d_id.b.rsvd_1 = entry[0];
break;
}
}
/*
* If we've used all available slots, then the switch is
* reporting back more devices that we can handle with this
* single call. Return a failed status, and let GA_NXT handle
* the overload.
*/
if (i == MAX_FIBRE_DEVICES)
rval = QLA_FUNCTION_FAILED;
}
return (rval);
}
/**
* qla2x00_sns_gpn_id() - SNS Get Port Name (GPN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_gpn_id(scsi_qla_host_t *ha, sw_info_t *list)
{
int rval;
uint16_t i;
struct sns_cmd_pkt *sns_cmd;
for (i = 0; i < MAX_FIBRE_DEVICES; i++) {
/* Issue GPN_ID */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(ha, GPN_ID_CMD,
GPN_ID_SNS_SCMD_LEN, GPN_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id. */
sns_cmd->p.cmd.param[0] = list[i].d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = list[i].d_id.b.area;
sns_cmd->p.cmd.param[2] = list[i].d_id.b.domain;
/* Execute SNS command. */
rval = qla2x00_send_sns(ha, ha->sns_cmd_dma,
GPN_ID_SNS_CMD_SIZE / 2, sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GPN_ID Send SNS failed "
"(%d).\n", ha->host_no, rval));
} else if (sns_cmd->p.gpn_data[8] != 0x80 ||
sns_cmd->p.gpn_data[9] != 0x02) {
DEBUG2_3(printk("scsi(%ld): GPN_ID failed, rejected "
"request, gpn_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer(sns_cmd->p.gpn_data, 16));
rval = QLA_FUNCTION_FAILED;
} else {
/* Save portname */
memcpy(list[i].port_name, &sns_cmd->p.gpn_data[16],
WWN_SIZE);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_sns_gnn_id() - SNS Get Node Name (GNN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_gnn_id(scsi_qla_host_t *ha, sw_info_t *list)
{
int rval;
uint16_t i;
struct sns_cmd_pkt *sns_cmd;
for (i = 0; i < MAX_FIBRE_DEVICES; i++) {
/* Issue GNN_ID */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(ha, GNN_ID_CMD,
GNN_ID_SNS_SCMD_LEN, GNN_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id. */
sns_cmd->p.cmd.param[0] = list[i].d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = list[i].d_id.b.area;
sns_cmd->p.cmd.param[2] = list[i].d_id.b.domain;
/* Execute SNS command. */
rval = qla2x00_send_sns(ha, ha->sns_cmd_dma,
GNN_ID_SNS_CMD_SIZE / 2, sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): GNN_ID Send SNS failed "
"(%d).\n", ha->host_no, rval));
} else if (sns_cmd->p.gnn_data[8] != 0x80 ||
sns_cmd->p.gnn_data[9] != 0x02) {
DEBUG2_3(printk("scsi(%ld): GNN_ID failed, rejected "
"request, gnn_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer(sns_cmd->p.gnn_data, 16));
rval = QLA_FUNCTION_FAILED;
} else {
/* Save nodename */
memcpy(list[i].node_name, &sns_cmd->p.gnn_data[16],
WWN_SIZE);
DEBUG2_3(printk("scsi(%ld): GID_PT entry - "
"nn %02x%02x%02x%02x%02x%02x%02x%02x "
"pn %02x%02x%02x%02x%02x%02x%02x%02x "
"portid=%02x%02x%02x.\n",
ha->host_no,
list[i].node_name[0], list[i].node_name[1],
list[i].node_name[2], list[i].node_name[3],
list[i].node_name[4], list[i].node_name[5],
list[i].node_name[6], list[i].node_name[7],
list[i].port_name[0], list[i].port_name[1],
list[i].port_name[2], list[i].port_name[3],
list[i].port_name[4], list[i].port_name[5],
list[i].port_name[6], list[i].port_name[7],
list[i].d_id.b.domain, list[i].d_id.b.area,
list[i].d_id.b.al_pa));
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_snd_rft_id() - SNS Register FC-4 TYPEs (RFT_ID) supported by the HBA.
* @ha: HA context
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_rft_id(scsi_qla_host_t *ha)
{
int rval;
struct sns_cmd_pkt *sns_cmd;
/* Issue RFT_ID. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(ha, RFT_ID_CMD, RFT_ID_SNS_SCMD_LEN,
RFT_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id, FC-4 types */
sns_cmd->p.cmd.param[0] = ha->d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = ha->d_id.b.area;
sns_cmd->p.cmd.param[2] = ha->d_id.b.domain;
sns_cmd->p.cmd.param[5] = 0x01; /* FCP-3 */
/* Execute SNS command. */
rval = qla2x00_send_sns(ha, ha->sns_cmd_dma, RFT_ID_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): RFT_ID Send SNS failed (%d).\n",
ha->host_no, rval));
} else if (sns_cmd->p.rft_data[8] != 0x80 ||
sns_cmd->p.rft_data[9] != 0x02) {
DEBUG2_3(printk("scsi(%ld): RFT_ID failed, rejected request, "
"rft_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer(sns_cmd->p.rft_data, 16));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("scsi(%ld): RFT_ID exiting normally.\n",
ha->host_no));
}
return (rval);
}
/**
* qla2x00_sns_rnn_id() - SNS Register Node Name (RNN_ID) of the HBA.
* HBA.
* @ha: HA context
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_rnn_id(scsi_qla_host_t *ha)
{
int rval;
struct sns_cmd_pkt *sns_cmd;
/* Issue RNN_ID. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(ha, RNN_ID_CMD, RNN_ID_SNS_SCMD_LEN,
RNN_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id, nodename. */
sns_cmd->p.cmd.param[0] = ha->d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = ha->d_id.b.area;
sns_cmd->p.cmd.param[2] = ha->d_id.b.domain;
sns_cmd->p.cmd.param[4] = ha->init_cb->node_name[7];
sns_cmd->p.cmd.param[5] = ha->init_cb->node_name[6];
sns_cmd->p.cmd.param[6] = ha->init_cb->node_name[5];
sns_cmd->p.cmd.param[7] = ha->init_cb->node_name[4];
sns_cmd->p.cmd.param[8] = ha->init_cb->node_name[3];
sns_cmd->p.cmd.param[9] = ha->init_cb->node_name[2];
sns_cmd->p.cmd.param[10] = ha->init_cb->node_name[1];
sns_cmd->p.cmd.param[11] = ha->init_cb->node_name[0];
/* Execute SNS command. */
rval = qla2x00_send_sns(ha, ha->sns_cmd_dma, RNN_ID_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3(printk("scsi(%ld): RNN_ID Send SNS failed (%d).\n",
ha->host_no, rval));
} else if (sns_cmd->p.rnn_data[8] != 0x80 ||
sns_cmd->p.rnn_data[9] != 0x02) {
DEBUG2_3(printk("scsi(%ld): RNN_ID failed, rejected request, "
"rnn_rsp:\n", ha->host_no));
DEBUG2_3(qla2x00_dump_buffer(sns_cmd->p.rnn_data, 16));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("scsi(%ld): RNN_ID exiting normally.\n",
ha->host_no));
}
return (rval);
}
| gpl-2.0 |
novic/AniDroid-JB-N7000-Kernel | arch/arm/mach-exynos/cpu-exynos4.c | 289 | 12028 | /* linux/arch/arm/mach-exynos/cpu.c
*
* Copyright (c) 2010-2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/sched.h>
#include <linux/sysdev.h>
#include <linux/delay.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/proc-fns.h>
#include <asm/hardware/cache-l2x0.h>
#include <asm/hardware/gic.h>
#include <asm/cacheflush.h>
#include <plat/cpu.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/fb-core.h>
#include <plat/exynos4.h>
#include <plat/sdhci.h>
#include <plat/mshci.h>
#include <plat/fimc-core.h>
#include <plat/adc-core.h>
#include <plat/pm.h>
#include <plat/iic-core.h>
#include <plat/ace-core.h>
#include <plat/reset.h>
#include <plat/audio.h>
#include <plat/tv-core.h>
#include <plat/rtc-core.h>
#include <mach/regs-irq.h>
#include <mach/regs-pmu.h>
#include <mach/smc.h>
unsigned int gic_bank_offset __read_mostly;
extern int combiner_init(unsigned int combiner_nr, void __iomem *base,
unsigned int irq_start);
extern void combiner_cascade_irq(unsigned int combiner_nr, unsigned int irq);
/* Initial IO mappings */
static struct map_desc exynos4_iodesc[] __initdata = {
{
.virtual = (unsigned long)S5P_VA_SYSTIMER,
.pfn = __phys_to_pfn(EXYNOS4_PA_SYSTIMER),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_CMU,
.pfn = __phys_to_pfn(EXYNOS4_PA_CMU),
.length = SZ_128K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_PMU,
.pfn = __phys_to_pfn(EXYNOS4_PA_PMU),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_COMBINER_BASE,
.pfn = __phys_to_pfn(EXYNOS4_PA_COMBINER),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_COREPERI_BASE,
.pfn = __phys_to_pfn(EXYNOS4_PA_COREPERI),
.length = SZ_8K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_L2CC,
.pfn = __phys_to_pfn(EXYNOS4_PA_L2CC),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GPIO1,
.pfn = __phys_to_pfn(EXYNOS4_PA_GPIO1),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GPIO2,
.pfn = __phys_to_pfn(EXYNOS4_PA_GPIO2),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GPIO3,
.pfn = __phys_to_pfn(EXYNOS4_PA_GPIO3),
.length = SZ_256,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GPIO4,
.pfn = __phys_to_pfn(EXYNOS4_PA_GPIO4),
.length = SZ_256,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_UART,
.pfn = __phys_to_pfn(S3C_PA_UART),
.length = SZ_512K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_SROMC,
.pfn = __phys_to_pfn(EXYNOS4_PA_SROMC),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_USB_HSPHY,
.pfn = __phys_to_pfn(EXYNOS4_PA_HSPHY),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GIC_CPU,
.pfn = __phys_to_pfn(EXYNOS4_PA_GIC_CPU),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GIC_DIST,
.pfn = __phys_to_pfn(EXYNOS4_PA_GIC_DIST),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_AUDSS,
.pfn = __phys_to_pfn(EXYNOS4_PA_AUDSS),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_PPMU_CPU,
.pfn = __phys_to_pfn(EXYNOS4_PA_PPMU_CPU),
.length = SZ_8K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_PPMU_DMC0,
.pfn = __phys_to_pfn(EXYNOS4_PA_PPMU_DMC0),
.length = SZ_8K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_PPMU_DMC1,
.pfn = __phys_to_pfn(EXYNOS4_PA_PPMU_DMC1),
.length = SZ_8K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GDL,
.pfn = __phys_to_pfn(EXYNOS4_PA_GDL),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GDR,
.pfn = __phys_to_pfn(EXYNOS4_PA_GDR),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
static struct map_desc exynos4210_iodesc[] __initdata = {
{
.virtual = (unsigned long)S5P_VA_DMC0,
.pfn = __phys_to_pfn(EXYNOS4_PA_DMC0),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_DMC1,
.pfn = __phys_to_pfn(EXYNOS4_PA_DMC1),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_SYSRAM_NS,
.pfn = __phys_to_pfn(EXYNOS4_PA_SYSRAM_NS),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
static struct map_desc exynos4210_iodesc_rev_0[] __initdata = {
{
.virtual = (unsigned long)S5P_VA_SYSRAM,
.pfn = __phys_to_pfn(EXYNOS4_PA_SYSRAM0),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
static struct map_desc exynos4210_iodesc_rev_1[] __initdata = {
{
.virtual = (unsigned long)S5P_VA_SYSRAM,
.pfn = __phys_to_pfn(EXYNOS4_PA_SYSRAM1),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
static struct map_desc exynos4212_iodesc[] __initdata = {
{
.virtual = (unsigned long)S5P_VA_DMC0,
.pfn = __phys_to_pfn(EXYNOS4_PA_DMC0_4212),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_DMC1,
.pfn = __phys_to_pfn(EXYNOS4_PA_DMC1_4212),
.length = SZ_64K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_SYSRAM,
.pfn = __phys_to_pfn(EXYNOS4_PA_SYSRAM1),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_SYSRAM_NS,
.pfn = __phys_to_pfn(EXYNOS4_PA_SYSRAM_NS_4212),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
static void exynos4_idle(void)
{
if (!need_resched())
cpu_do_idle();
local_irq_enable();
}
/*
* exynos4_map_io
*
* register the standard cpu IO areas
*/
void __init exynos4_map_io(void)
{
iotable_init(exynos4_iodesc, ARRAY_SIZE(exynos4_iodesc));
if (soc_is_exynos4210()) {
iotable_init(exynos4210_iodesc, ARRAY_SIZE(exynos4210_iodesc));
if (samsung_rev() == EXYNOS4210_REV_0)
iotable_init(exynos4210_iodesc_rev_0,
ARRAY_SIZE(exynos4210_iodesc_rev_0));
else
iotable_init(exynos4210_iodesc_rev_1,
ARRAY_SIZE(exynos4210_iodesc_rev_1));
} else {
iotable_init(exynos4212_iodesc, ARRAY_SIZE(exynos4212_iodesc));
}
#ifdef CONFIG_S3C_DEV_HSMMC
exynos4_default_sdhci0();
#endif
#ifdef CONFIG_S3C_DEV_HSMMC1
exynos4_default_sdhci1();
#endif
#ifdef CONFIG_S3C_DEV_HSMMC2
exynos4_default_sdhci2();
#endif
#ifdef CONFIG_S3C_DEV_HSMMC3
exynos4_default_sdhci3();
#endif
#ifdef CONFIG_EXYNOS4_DEV_MSHC
exynos4_default_mshci();
#endif
exynos4_i2sv3_setup_resource();
s3c_fimc_setname(0, "exynos4-fimc");
s3c_fimc_setname(1, "exynos4-fimc");
s3c_fimc_setname(2, "exynos4-fimc");
s3c_fimc_setname(3, "exynos4-fimc");
#ifdef CONFIG_S3C_DEV_RTC
s3c_rtc_setname("exynos-rtc");
#endif
#ifdef CONFIG_FB_S3C
s5p_fb_setname(0, "exynos4-fb"); /* FIMD0 */
#endif
if (soc_is_exynos4210())
s3c_adc_setname("samsung-adc-v3");
else
s3c_adc_setname("samsung-adc-v4");
s5p_hdmi_setname("exynos4-hdmi");
/* The I2C bus controllers are directly compatible with s3c2440 */
s3c_i2c0_setname("s3c2440-i2c");
s3c_i2c1_setname("s3c2440-i2c");
s3c_i2c2_setname("s3c2440-i2c");
#ifdef CONFIG_S5P_DEV_ACE
s5p_ace_setname("exynos-ace");
#endif
}
void __init exynos4_init_clocks(int xtal)
{
printk(KERN_DEBUG "%s: initializing clocks\n", __func__);
s3c24xx_register_baseclocks(xtal);
if (soc_is_exynos4210())
exynos4210_register_clocks();
else
exynos4212_register_clocks();
s5p_register_clocks(xtal);
exynos4_register_clocks();
exynos4_setup_clocks();
}
#define COMBINER_MAP(x) ((x < 16) ? IRQ_SPI(x) : \
(x == 16) ? IRQ_SPI(107) : \
(x == 17) ? IRQ_SPI(108) : \
(x == 18) ? IRQ_SPI(48) : \
(x == 19) ? IRQ_SPI(49) : 0)
void __init exynos4_init_irq(void)
{
int irq;
gic_bank_offset = soc_is_exynos4412() ? 0x4000 : 0x8000;
gic_init(0, IRQ_PPI_MCT_L, S5P_VA_GIC_DIST, S5P_VA_GIC_CPU);
gic_arch_extn.irq_set_wake = s3c_irq_wake;
for (irq = 0; irq < COMMON_COMBINER_NR; irq++) {
combiner_init(irq, (void __iomem *)S5P_VA_COMBINER(irq),
COMBINER_IRQ(irq, 0));
combiner_cascade_irq(irq, COMBINER_MAP(irq));
}
if (soc_is_exynos4412() && (samsung_rev() >= EXYNOS4412_REV_1_0)) {
for (irq = COMMON_COMBINER_NR; irq < MAX_COMBINER_NR; irq++) {
combiner_init(irq, (void __iomem *)S5P_VA_COMBINER(irq),
COMBINER_IRQ(irq, 0));
combiner_cascade_irq(irq, COMBINER_MAP(irq));
}
}
/* The parameters of s5p_init_irq() are for VIC init.
* Theses parameters should be NULL and 0 because EXYNOS4
* uses GIC instead of VIC.
*/
s5p_init_irq(NULL, 0);
}
struct sysdev_class exynos4_sysclass = {
.name = "exynos4-core",
};
static struct sys_device exynos4_sysdev = {
.cls = &exynos4_sysclass,
};
static int __init exynos4_core_init(void)
{
return sysdev_class_register(&exynos4_sysclass);
}
core_initcall(exynos4_core_init);
#ifdef CONFIG_CACHE_L2X0
#ifdef CONFIG_ARM_TRUSTZONE
#if defined(CONFIG_PL310_ERRATA_588369) || defined(CONFIG_PL310_ERRATA_727915)
static void exynos4_l2x0_set_debug(unsigned long val)
{
exynos_smc(SMC_CMD_L2X0DEBUG, val, 0, 0);
}
#endif
#endif
static int __init exynos4_l2x0_cache_init(void)
{
u32 tag_latency = 0x110;
u32 data_latency = soc_is_exynos4210() ? 0x110 : 0x120;
u32 prefetch = (soc_is_exynos4412() &&
samsung_rev() >= EXYNOS4412_REV_1_0) ?
0x71000007 : 0x30000007;
u32 aux_val = 0x7C470001;
u32 aux_mask = 0xC200FFFF;
#ifdef CONFIG_ARM_TRUSTZONE
exynos_smc(SMC_CMD_L2X0SETUP1, tag_latency, data_latency, prefetch);
exynos_smc(SMC_CMD_L2X0SETUP2,
L2X0_DYNAMIC_CLK_GATING_EN | L2X0_STNDBY_MODE_EN,
aux_val, aux_mask);
exynos_smc(SMC_CMD_L2X0INVALL, 0, 0, 0);
exynos_smc(SMC_CMD_L2X0CTRL, 1, 0, 0);
#else
__raw_writel(tag_latency, S5P_VA_L2CC + L2X0_TAG_LATENCY_CTRL);
__raw_writel(data_latency, S5P_VA_L2CC + L2X0_DATA_LATENCY_CTRL);
__raw_writel(prefetch, S5P_VA_L2CC + L2X0_PREFETCH_CTRL);
__raw_writel(L2X0_DYNAMIC_CLK_GATING_EN | L2X0_STNDBY_MODE_EN,
S5P_VA_L2CC + L2X0_POWER_CTRL);
#endif
l2x0_init(S5P_VA_L2CC, aux_val, aux_mask);
#ifdef CONFIG_ARM_TRUSTZONE
#if defined(CONFIG_PL310_ERRATA_588369) || defined(CONFIG_PL310_ERRATA_727915)
outer_cache.set_debug = exynos4_l2x0_set_debug;
#endif
#endif
/* Enable the full line of zero */
enable_cache_foz();
return 0;
}
//early_initcall(exynos4_l2x0_cache_init);
early_initcall(exynos4_l2x0_cache_init);
#endif
static void exynos4_sw_reset(void)
{
int count = 3;
while (count--) {
__raw_writel(0x1, S5P_SWRESET);
mdelay(500);
}
}
static void __iomem *exynos4_pmu_init_zero[] = {
S5P_CMU_RESET_ISP_SYS,
S5P_CMU_SYSCLK_ISP_SYS,
};
int __init exynos4_init(void)
{
unsigned int value;
unsigned int tmp;
unsigned int i;
printk(KERN_INFO "EXYNOS4: Initializing architecture\n");
/* set idle function */
pm_idle = exynos4_idle;
/*
* on exynos4x12, CMU reset system power register should to be set 0x0
*/
if (!soc_is_exynos4210()) {
for (i = 0; i < ARRAY_SIZE(exynos4_pmu_init_zero); i++)
__raw_writel(0x0, exynos4_pmu_init_zero[i]);
}
/* set sw_reset function */
s5p_reset_hook = exynos4_sw_reset;
/* Disable auto wakeup from power off mode */
for (i = 0; i < num_possible_cpus(); i++) {
tmp = __raw_readl(S5P_ARM_CORE_OPTION(i));
tmp &= ~S5P_CORE_OPTION_DIS;
__raw_writel(tmp, S5P_ARM_CORE_OPTION(i));
}
if (soc_is_exynos4212() || soc_is_exynos4412()) {
value = __raw_readl(S5P_AUTOMATIC_WDT_RESET_DISABLE);
value &= ~S5P_SYS_WDTRESET;
__raw_writel(value, S5P_AUTOMATIC_WDT_RESET_DISABLE);
value = __raw_readl(S5P_MASK_WDT_RESET_REQUEST);
value &= ~S5P_SYS_WDTRESET;
__raw_writel(value, S5P_MASK_WDT_RESET_REQUEST);
}
return sysdev_register(&exynos4_sysdev);
}
| gpl-2.0 |
junmuzi/linux | tools/testing/selftests/vm/userfaultfd.c | 545 | 17529 | /*
* Stress userfaultfd syscall.
*
* Copyright (C) 2015 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
* This test allocates two virtual areas and bounces the physical
* memory across the two virtual areas (from area_src to area_dst)
* using userfaultfd.
*
* There are three threads running per CPU:
*
* 1) one per-CPU thread takes a per-page pthread_mutex in a random
* page of the area_dst (while the physical page may still be in
* area_src), and increments a per-page counter in the same page,
* and checks its value against a verification region.
*
* 2) another per-CPU thread handles the userfaults generated by
* thread 1 above. userfaultfd blocking reads or poll() modes are
* exercised interleaved.
*
* 3) one last per-CPU thread transfers the memory in the background
* at maximum bandwidth (if not already transferred by thread
* 2). Each cpu thread takes cares of transferring a portion of the
* area.
*
* When all threads of type 3 completed the transfer, one bounce is
* complete. area_src and area_dst are then swapped. All threads are
* respawned and so the bounce is immediately restarted in the
* opposite direction.
*
* per-CPU threads 1 by triggering userfaults inside
* pthread_mutex_lock will also verify the atomicity of the memory
* transfer (UFFDIO_COPY).
*
* The program takes two parameters: the amounts of physical memory in
* megabytes (MiB) of the area and the number of bounces to execute.
*
* # 100MiB 99999 bounces
* ./userfaultfd 100 99999
*
* # 1GiB 99 bounces
* ./userfaultfd 1000 99
*
* # 10MiB-~6GiB 999 bounces, continue forever unless an error triggers
* while ./userfaultfd $[RANDOM % 6000 + 10] 999; do true; done
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <poll.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <linux/userfaultfd.h>
#ifdef __NR_userfaultfd
static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size;
#define BOUNCE_RANDOM (1<<0)
#define BOUNCE_RACINGFAULTS (1<<1)
#define BOUNCE_VERIFY (1<<2)
#define BOUNCE_POLL (1<<3)
static int bounces;
static unsigned long long *count_verify;
static int uffd, finished, *pipefd;
static char *area_src, *area_dst;
static char *zeropage;
pthread_attr_t attr;
/* pthread_mutex_t starts at page offset 0 */
#define area_mutex(___area, ___nr) \
((pthread_mutex_t *) ((___area) + (___nr)*page_size))
/*
* count is placed in the page after pthread_mutex_t naturally aligned
* to avoid non alignment faults on non-x86 archs.
*/
#define area_count(___area, ___nr) \
((volatile unsigned long long *) ((unsigned long) \
((___area) + (___nr)*page_size + \
sizeof(pthread_mutex_t) + \
sizeof(unsigned long long) - 1) & \
~(unsigned long)(sizeof(unsigned long long) \
- 1)))
static int my_bcmp(char *str1, char *str2, size_t n)
{
unsigned long i;
for (i = 0; i < n; i++)
if (str1[i] != str2[i])
return 1;
return 0;
}
static void *locking_thread(void *arg)
{
unsigned long cpu = (unsigned long) arg;
struct random_data rand;
unsigned long page_nr = *(&(page_nr)); /* uninitialized warning */
int32_t rand_nr;
unsigned long long count;
char randstate[64];
unsigned int seed;
time_t start;
if (bounces & BOUNCE_RANDOM) {
seed = (unsigned int) time(NULL) - bounces;
if (!(bounces & BOUNCE_RACINGFAULTS))
seed += cpu;
bzero(&rand, sizeof(rand));
bzero(&randstate, sizeof(randstate));
if (initstate_r(seed, randstate, sizeof(randstate), &rand))
fprintf(stderr, "srandom_r error\n"), exit(1);
} else {
page_nr = -bounces;
if (!(bounces & BOUNCE_RACINGFAULTS))
page_nr += cpu * nr_pages_per_cpu;
}
while (!finished) {
if (bounces & BOUNCE_RANDOM) {
if (random_r(&rand, &rand_nr))
fprintf(stderr, "random_r 1 error\n"), exit(1);
page_nr = rand_nr;
if (sizeof(page_nr) > sizeof(rand_nr)) {
if (random_r(&rand, &rand_nr))
fprintf(stderr, "random_r 2 error\n"), exit(1);
page_nr |= (((unsigned long) rand_nr) << 16) <<
16;
}
} else
page_nr += 1;
page_nr %= nr_pages;
start = time(NULL);
if (bounces & BOUNCE_VERIFY) {
count = *area_count(area_dst, page_nr);
if (!count)
fprintf(stderr,
"page_nr %lu wrong count %Lu %Lu\n",
page_nr, count,
count_verify[page_nr]), exit(1);
/*
* We can't use bcmp (or memcmp) because that
* returns 0 erroneously if the memory is
* changing under it (even if the end of the
* page is never changing and always
* different).
*/
#if 1
if (!my_bcmp(area_dst + page_nr * page_size, zeropage,
page_size))
fprintf(stderr,
"my_bcmp page_nr %lu wrong count %Lu %Lu\n",
page_nr, count,
count_verify[page_nr]), exit(1);
#else
unsigned long loops;
loops = 0;
/* uncomment the below line to test with mutex */
/* pthread_mutex_lock(area_mutex(area_dst, page_nr)); */
while (!bcmp(area_dst + page_nr * page_size, zeropage,
page_size)) {
loops += 1;
if (loops > 10)
break;
}
/* uncomment below line to test with mutex */
/* pthread_mutex_unlock(area_mutex(area_dst, page_nr)); */
if (loops) {
fprintf(stderr,
"page_nr %lu all zero thread %lu %p %lu\n",
page_nr, cpu, area_dst + page_nr * page_size,
loops);
if (loops > 10)
exit(1);
}
#endif
}
pthread_mutex_lock(area_mutex(area_dst, page_nr));
count = *area_count(area_dst, page_nr);
if (count != count_verify[page_nr]) {
fprintf(stderr,
"page_nr %lu memory corruption %Lu %Lu\n",
page_nr, count,
count_verify[page_nr]), exit(1);
}
count++;
*area_count(area_dst, page_nr) = count_verify[page_nr] = count;
pthread_mutex_unlock(area_mutex(area_dst, page_nr));
if (time(NULL) - start > 1)
fprintf(stderr,
"userfault too slow %ld "
"possible false positive with overcommit\n",
time(NULL) - start);
}
return NULL;
}
static int copy_page(unsigned long offset)
{
struct uffdio_copy uffdio_copy;
if (offset >= nr_pages * page_size)
fprintf(stderr, "unexpected offset %lu\n",
offset), exit(1);
uffdio_copy.dst = (unsigned long) area_dst + offset;
uffdio_copy.src = (unsigned long) area_src + offset;
uffdio_copy.len = page_size;
uffdio_copy.mode = 0;
uffdio_copy.copy = 0;
if (ioctl(uffd, UFFDIO_COPY, &uffdio_copy)) {
/* real retval in ufdio_copy.copy */
if (uffdio_copy.copy != -EEXIST)
fprintf(stderr, "UFFDIO_COPY error %Ld\n",
uffdio_copy.copy), exit(1);
} else if (uffdio_copy.copy != page_size) {
fprintf(stderr, "UFFDIO_COPY unexpected copy %Ld\n",
uffdio_copy.copy), exit(1);
} else
return 1;
return 0;
}
static void *uffd_poll_thread(void *arg)
{
unsigned long cpu = (unsigned long) arg;
struct pollfd pollfd[2];
struct uffd_msg msg;
int ret;
unsigned long offset;
char tmp_chr;
unsigned long userfaults = 0;
pollfd[0].fd = uffd;
pollfd[0].events = POLLIN;
pollfd[1].fd = pipefd[cpu*2];
pollfd[1].events = POLLIN;
for (;;) {
ret = poll(pollfd, 2, -1);
if (!ret)
fprintf(stderr, "poll error %d\n", ret), exit(1);
if (ret < 0)
perror("poll"), exit(1);
if (pollfd[1].revents & POLLIN) {
if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
fprintf(stderr, "read pipefd error\n"),
exit(1);
break;
}
if (!(pollfd[0].revents & POLLIN))
fprintf(stderr, "pollfd[0].revents %d\n",
pollfd[0].revents), exit(1);
ret = read(uffd, &msg, sizeof(msg));
if (ret < 0) {
if (errno == EAGAIN)
continue;
perror("nonblocking read error"), exit(1);
}
if (msg.event != UFFD_EVENT_PAGEFAULT)
fprintf(stderr, "unexpected msg event %u\n",
msg.event), exit(1);
if (msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
fprintf(stderr, "unexpected write fault\n"), exit(1);
offset = (char *)(unsigned long)msg.arg.pagefault.address -
area_dst;
offset &= ~(page_size-1);
if (copy_page(offset))
userfaults++;
}
return (void *)userfaults;
}
pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
static void *uffd_read_thread(void *arg)
{
unsigned long *this_cpu_userfaults;
struct uffd_msg msg;
unsigned long offset;
int ret;
this_cpu_userfaults = (unsigned long *) arg;
*this_cpu_userfaults = 0;
pthread_mutex_unlock(&uffd_read_mutex);
/* from here cancellation is ok */
for (;;) {
ret = read(uffd, &msg, sizeof(msg));
if (ret != sizeof(msg)) {
if (ret < 0)
perror("blocking read error"), exit(1);
else
fprintf(stderr, "short read\n"), exit(1);
}
if (msg.event != UFFD_EVENT_PAGEFAULT)
fprintf(stderr, "unexpected msg event %u\n",
msg.event), exit(1);
if (bounces & BOUNCE_VERIFY &&
msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
fprintf(stderr, "unexpected write fault\n"), exit(1);
offset = (char *)(unsigned long)msg.arg.pagefault.address -
area_dst;
offset &= ~(page_size-1);
if (copy_page(offset))
(*this_cpu_userfaults)++;
}
return (void *)NULL;
}
static void *background_thread(void *arg)
{
unsigned long cpu = (unsigned long) arg;
unsigned long page_nr;
for (page_nr = cpu * nr_pages_per_cpu;
page_nr < (cpu+1) * nr_pages_per_cpu;
page_nr++)
copy_page(page_nr * page_size);
return NULL;
}
static int stress(unsigned long *userfaults)
{
unsigned long cpu;
pthread_t locking_threads[nr_cpus];
pthread_t uffd_threads[nr_cpus];
pthread_t background_threads[nr_cpus];
void **_userfaults = (void **) userfaults;
finished = 0;
for (cpu = 0; cpu < nr_cpus; cpu++) {
if (pthread_create(&locking_threads[cpu], &attr,
locking_thread, (void *)cpu))
return 1;
if (bounces & BOUNCE_POLL) {
if (pthread_create(&uffd_threads[cpu], &attr,
uffd_poll_thread, (void *)cpu))
return 1;
} else {
if (pthread_create(&uffd_threads[cpu], &attr,
uffd_read_thread,
&_userfaults[cpu]))
return 1;
pthread_mutex_lock(&uffd_read_mutex);
}
if (pthread_create(&background_threads[cpu], &attr,
background_thread, (void *)cpu))
return 1;
}
for (cpu = 0; cpu < nr_cpus; cpu++)
if (pthread_join(background_threads[cpu], NULL))
return 1;
/*
* Be strict and immediately zap area_src, the whole area has
* been transferred already by the background treads. The
* area_src could then be faulted in in a racy way by still
* running uffdio_threads reading zeropages after we zapped
* area_src (but they're guaranteed to get -EEXIST from
* UFFDIO_COPY without writing zero pages into area_dst
* because the background threads already completed).
*/
if (madvise(area_src, nr_pages * page_size, MADV_DONTNEED)) {
perror("madvise");
return 1;
}
for (cpu = 0; cpu < nr_cpus; cpu++) {
char c;
if (bounces & BOUNCE_POLL) {
if (write(pipefd[cpu*2+1], &c, 1) != 1) {
fprintf(stderr, "pipefd write error\n");
return 1;
}
if (pthread_join(uffd_threads[cpu], &_userfaults[cpu]))
return 1;
} else {
if (pthread_cancel(uffd_threads[cpu]))
return 1;
if (pthread_join(uffd_threads[cpu], NULL))
return 1;
}
}
finished = 1;
for (cpu = 0; cpu < nr_cpus; cpu++)
if (pthread_join(locking_threads[cpu], NULL))
return 1;
return 0;
}
static int userfaultfd_stress(void)
{
void *area;
char *tmp_area;
unsigned long nr;
struct uffdio_register uffdio_register;
struct uffdio_api uffdio_api;
unsigned long cpu;
int uffd_flags, err;
unsigned long userfaults[nr_cpus];
if (posix_memalign(&area, page_size, nr_pages * page_size)) {
fprintf(stderr, "out of memory\n");
return 1;
}
area_src = area;
if (posix_memalign(&area, page_size, nr_pages * page_size)) {
fprintf(stderr, "out of memory\n");
return 1;
}
area_dst = area;
uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
if (uffd < 0) {
fprintf(stderr,
"userfaultfd syscall not available in this kernel\n");
return 1;
}
uffd_flags = fcntl(uffd, F_GETFD, NULL);
uffdio_api.api = UFFD_API;
uffdio_api.features = 0;
if (ioctl(uffd, UFFDIO_API, &uffdio_api)) {
fprintf(stderr, "UFFDIO_API\n");
return 1;
}
if (uffdio_api.api != UFFD_API) {
fprintf(stderr, "UFFDIO_API error %Lu\n", uffdio_api.api);
return 1;
}
count_verify = malloc(nr_pages * sizeof(unsigned long long));
if (!count_verify) {
perror("count_verify");
return 1;
}
for (nr = 0; nr < nr_pages; nr++) {
*area_mutex(area_src, nr) = (pthread_mutex_t)
PTHREAD_MUTEX_INITIALIZER;
count_verify[nr] = *area_count(area_src, nr) = 1;
/*
* In the transition between 255 to 256, powerpc will
* read out of order in my_bcmp and see both bytes as
* zero, so leave a placeholder below always non-zero
* after the count, to avoid my_bcmp to trigger false
* positives.
*/
*(area_count(area_src, nr) + 1) = 1;
}
pipefd = malloc(sizeof(int) * nr_cpus * 2);
if (!pipefd) {
perror("pipefd");
return 1;
}
for (cpu = 0; cpu < nr_cpus; cpu++) {
if (pipe2(&pipefd[cpu*2], O_CLOEXEC | O_NONBLOCK)) {
perror("pipe");
return 1;
}
}
if (posix_memalign(&area, page_size, page_size)) {
fprintf(stderr, "out of memory\n");
return 1;
}
zeropage = area;
bzero(zeropage, page_size);
pthread_mutex_lock(&uffd_read_mutex);
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 16*1024*1024);
err = 0;
while (bounces--) {
unsigned long expected_ioctls;
printf("bounces: %d, mode:", bounces);
if (bounces & BOUNCE_RANDOM)
printf(" rnd");
if (bounces & BOUNCE_RACINGFAULTS)
printf(" racing");
if (bounces & BOUNCE_VERIFY)
printf(" ver");
if (bounces & BOUNCE_POLL)
printf(" poll");
printf(", ");
fflush(stdout);
if (bounces & BOUNCE_POLL)
fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
else
fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
/* register */
uffdio_register.range.start = (unsigned long) area_dst;
uffdio_register.range.len = nr_pages * page_size;
uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
fprintf(stderr, "register failure\n");
return 1;
}
expected_ioctls = (1 << _UFFDIO_WAKE) |
(1 << _UFFDIO_COPY) |
(1 << _UFFDIO_ZEROPAGE);
if ((uffdio_register.ioctls & expected_ioctls) !=
expected_ioctls) {
fprintf(stderr,
"unexpected missing ioctl for anon memory\n");
return 1;
}
/*
* The madvise done previously isn't enough: some
* uffd_thread could have read userfaults (one of
* those already resolved by the background thread)
* and it may be in the process of calling
* UFFDIO_COPY. UFFDIO_COPY will read the zapped
* area_src and it would map a zero page in it (of
* course such a UFFDIO_COPY is perfectly safe as it'd
* return -EEXIST). The problem comes at the next
* bounce though: that racing UFFDIO_COPY would
* generate zeropages in the area_src, so invalidating
* the previous MADV_DONTNEED. Without this additional
* MADV_DONTNEED those zeropages leftovers in the
* area_src would lead to -EEXIST failure during the
* next bounce, effectively leaving a zeropage in the
* area_dst.
*
* Try to comment this out madvise to see the memory
* corruption being caught pretty quick.
*
* khugepaged is also inhibited to collapse THP after
* MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
* required to MADV_DONTNEED here.
*/
if (madvise(area_dst, nr_pages * page_size, MADV_DONTNEED)) {
perror("madvise 2");
return 1;
}
/* bounce pass */
if (stress(userfaults))
return 1;
/* unregister */
if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range)) {
fprintf(stderr, "register failure\n");
return 1;
}
/* verification */
if (bounces & BOUNCE_VERIFY) {
for (nr = 0; nr < nr_pages; nr++) {
if (*area_count(area_dst, nr) != count_verify[nr]) {
fprintf(stderr,
"error area_count %Lu %Lu %lu\n",
*area_count(area_src, nr),
count_verify[nr],
nr);
err = 1;
bounces = 0;
}
}
}
/* prepare next bounce */
tmp_area = area_src;
area_src = area_dst;
area_dst = tmp_area;
printf("userfaults:");
for (cpu = 0; cpu < nr_cpus; cpu++)
printf(" %lu", userfaults[cpu]);
printf("\n");
}
return err;
}
int main(int argc, char **argv)
{
if (argc < 3)
fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
page_size = sysconf(_SC_PAGE_SIZE);
if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
> page_size)
fprintf(stderr, "Impossible to run this test\n"), exit(2);
nr_pages_per_cpu = atol(argv[1]) * 1024*1024 / page_size /
nr_cpus;
if (!nr_pages_per_cpu) {
fprintf(stderr, "invalid MiB\n");
fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
}
bounces = atoi(argv[2]);
if (bounces <= 0) {
fprintf(stderr, "invalid bounces\n");
fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
}
nr_pages = nr_pages_per_cpu * nr_cpus;
printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
nr_pages, nr_pages_per_cpu);
return userfaultfd_stress();
}
#else /* __NR_userfaultfd */
#warning "missing __NR_userfaultfd definition"
int main(void)
{
printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
return 0;
}
#endif /* __NR_userfaultfd */
| gpl-2.0 |
ztemt/Z5S_NX503A_KitKat_kernel | net/wireless/reg.c | 545 | 65064 | /*
* Copyright 2002-2005, Instant802 Networks, Inc.
* Copyright 2005-2006, Devicescape Software, Inc.
* Copyright 2007 Johannes Berg <johannes@sipsolutions.net>
* Copyright 2008-2011 Luis R. Rodriguez <mcgrof@qca.qualcomm.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* 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/export.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 <linux/moduleparam.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...) \
printk(KERN_DEBUG pr_fmt(format), ##args)
#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. No HT40
* channel fits here. */
REG_RULE(2467-10, 2472+10, 20, 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 bool is_cfg80211_regdom_intersected(void)
{
return is_intersected_alpha2(cfg80211_regdomain->alpha2);
}
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);
}
#else
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 @ %d KHz), (%s mBi, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
freq_range->max_bandwidth_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;
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
request_wiphy && request_wiphy == wiphy &&
request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
REG_DBG_PRINT("Disabling freq %d MHz for good\n",
chan->center_freq);
chan->orig_flags |= IEEE80211_CHAN_DISABLED;
chan->flags = chan->orig_flags;
} else {
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));
chan->max_reg_power = (int) MBM_TO_DBM(power_rule->max_eirp);
if (chan->orig_mpwr) {
/*
* Devices that use NL80211_COUNTRY_IE_FOLLOW_POWER will always
* follow the passed country IE power settings.
*/
if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
wiphy->country_ie_pref & NL80211_COUNTRY_IE_FOLLOW_POWER)
chan->max_power = chan->max_reg_power;
else
chan->max_power = min(chan->orig_mpwr,
chan->max_reg_power);
} else
chan->max_power = chan->max_reg_power;
}
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\n",
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 regulatory "
"domain to be set first\n",
reg_initiator_name(initiator));
return true;
}
return false;
}
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);
}
}
static void wiphy_update_regulatory(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
enum ieee80211_band band;
assert_reg_lock();
if (ignore_reg_update(wiphy, initiator))
return;
last_request->dfs_region = cfg80211_regdomain->dfs_region;
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);
}
void regulatory_update(struct wiphy *wiphy,
enum nl80211_reg_initiator setby)
{
mutex_lock(®_mutex);
if (last_request)
wiphy_update_regulatory(wiphy, last_request->initiator);
else
wiphy_update_regulatory(wiphy, setby);
mutex_unlock(®_mutex);
}
static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)
{
struct cfg80211_registered_device *rdev;
struct wiphy *wiphy;
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
wiphy = &rdev->wiphy;
wiphy_update_regulatory(wiphy, initiator);
/*
* Regulatory updates set by CORE are ignored for custom
* regulatory cards. Let us notify the changes to the driver,
* as some drivers used this to restore its orig_* reg domain.
*/
if (initiator == NL80211_REGDOM_SET_BY_CORE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY &&
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->orig_flags |= IEEE80211_CHAN_DISABLED;
chan->flags = chan->orig_flags;
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:
if (wiphy->country_ie_pref & NL80211_COUNTRY_IE_IGNORE_CORE)
return -EALREADY;
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 (last_request->intersect) {
if (!is_cfg80211_regdom_intersected())
return -EAGAIN;
} else 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_sync(®_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,
enum nl80211_reg_initiator reg_initiator)
{
int r = 0;
struct wiphy *wiphy = NULL;
BUG_ON(!reg_request->alpha2);
if (wiphy_idx_valid(reg_request->wiphy_idx))
wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx);
if ((reg_initiator == NL80211_REGDOM_SET_BY_DRIVER ||
reg_initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) && !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, reg_initiator);
return;
}
/*
* We only time out user hints, given that they should be the only
* source of bogus requests.
*/
if (r != -EALREADY &&
reg_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...\n");
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, reg_request->initiator);
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;
}
EXPORT_SYMBOL(regulatory_hint_user);
/* 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");
}
static void restore_custom_reg_settings(struct wiphy *wiphy)
{
struct ieee80211_supported_band *sband;
enum ieee80211_band band;
struct ieee80211_channel *chan;
int i;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
sband = wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_channels; i++) {
chan = &sband->channels[i];
chan->flags = chan->orig_flags;
chan->max_antenna_gain = chan->orig_mag;
chan->max_power = chan->orig_mpwr;
}
}
}
/*
* 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);
struct cfg80211_registered_device *rdev;
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];
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
if (rdev->wiphy.flags & WIPHY_FLAG_CUSTOM_REGULATORY)
restore_custom_reg_settings(&rdev->wiphy);
}
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);
}
}
bool reg_supported_dfs_region(u8 dfs_region)
{
switch (dfs_region) {
case NL80211_DFS_UNSET:
case NL80211_DFS_FCC:
case NL80211_DFS_ETSI:
case NL80211_DFS_JP:
return true;
default:
REG_DBG_PRINT("Ignoring uknown DFS master region: %d\n",
dfs_region);
return false;
}
}
static void print_dfs_region(u8 dfs_region)
{
if (!dfs_region)
return;
switch (dfs_region) {
case NL80211_DFS_FCC:
pr_info(" DFS Master region FCC");
break;
case NL80211_DFS_ETSI:
pr_info(" DFS Master region ETSI");
break;
case NL80211_DFS_JP:
pr_info(" DFS Master region JP");
break;
default:
pr_info(" DFS Master region Uknown");
break;
}
}
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_dfs_region(rd->dfs_region);
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 -EALREADY;
}
/*
* 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) {
const struct ieee80211_regdomain *tmp;
tmp = request_wiphy->regd;
request_wiphy->regd = rd;
kfree(tmp);
} 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) {
if (r == -EALREADY)
reg_set_request_processed();
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\n");
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);
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 |
chenyu105/linux | tools/perf/bench/futex-wake.c | 545 | 5384 | /*
* Copyright (C) 2013 Davidlohr Bueso <davidlohr@hp.com>
*
* futex-wake: Block a bunch of threads on a futex and wake'em up, N at a time.
*
* This program is particularly useful to measure the latency of nthread wakeups
* in non-error situations: all waiters are queued and all wake calls wakeup
* one or more tasks, and thus the waitqueue is never empty.
*/
#include "../perf.h"
#include "../util/util.h"
#include "../util/stat.h"
#include "../util/parse-options.h"
#include "../util/header.h"
#include "bench.h"
#include "futex.h"
#include <err.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
/* all threads will block on the same futex */
static u_int32_t futex1 = 0;
/*
* How many wakeups to do at a time.
* Default to 1 in order to make the kernel work more.
*/
static unsigned int nwakes = 1;
pthread_t *worker;
static bool done = false, silent = false, fshared = false;
static pthread_mutex_t thread_lock;
static pthread_cond_t thread_parent, thread_worker;
static struct stats waketime_stats, wakeup_stats;
static unsigned int ncpus, threads_starting, nthreads = 0;
static int futex_flag = 0;
static const struct option options[] = {
OPT_UINTEGER('t', "threads", &nthreads, "Specify amount of threads"),
OPT_UINTEGER('w', "nwakes", &nwakes, "Specify amount of threads to wake at once"),
OPT_BOOLEAN( 's', "silent", &silent, "Silent mode: do not display data/details"),
OPT_BOOLEAN( 'S', "shared", &fshared, "Use shared futexes instead of private ones"),
OPT_END()
};
static const char * const bench_futex_wake_usage[] = {
"perf bench futex wake <options>",
NULL
};
static void *workerfn(void *arg __maybe_unused)
{
pthread_mutex_lock(&thread_lock);
threads_starting--;
if (!threads_starting)
pthread_cond_signal(&thread_parent);
pthread_cond_wait(&thread_worker, &thread_lock);
pthread_mutex_unlock(&thread_lock);
while (1) {
if (futex_wait(&futex1, 0, NULL, futex_flag) != EINTR)
break;
}
pthread_exit(NULL);
return NULL;
}
static void print_summary(void)
{
double waketime_avg = avg_stats(&waketime_stats);
double waketime_stddev = stddev_stats(&waketime_stats);
unsigned int wakeup_avg = avg_stats(&wakeup_stats);
printf("Wokeup %d of %d threads in %.4f ms (+-%.2f%%)\n",
wakeup_avg,
nthreads,
waketime_avg/1e3,
rel_stddev_stats(waketime_stddev, waketime_avg));
}
static void block_threads(pthread_t *w,
pthread_attr_t thread_attr)
{
cpu_set_t cpu;
unsigned int i;
threads_starting = nthreads;
/* create and block all threads */
for (i = 0; i < nthreads; i++) {
CPU_ZERO(&cpu);
CPU_SET(i % ncpus, &cpu);
if (pthread_attr_setaffinity_np(&thread_attr, sizeof(cpu_set_t), &cpu))
err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
if (pthread_create(&w[i], &thread_attr, workerfn, NULL))
err(EXIT_FAILURE, "pthread_create");
}
}
static void toggle_done(int sig __maybe_unused,
siginfo_t *info __maybe_unused,
void *uc __maybe_unused)
{
done = true;
}
int bench_futex_wake(int argc, const char **argv,
const char *prefix __maybe_unused)
{
int ret = 0;
unsigned int i, j;
struct sigaction act;
pthread_attr_t thread_attr;
argc = parse_options(argc, argv, options, bench_futex_wake_usage, 0);
if (argc) {
usage_with_options(bench_futex_wake_usage, options);
exit(EXIT_FAILURE);
}
ncpus = sysconf(_SC_NPROCESSORS_ONLN);
sigfillset(&act.sa_mask);
act.sa_sigaction = toggle_done;
sigaction(SIGINT, &act, NULL);
if (!nthreads)
nthreads = ncpus;
worker = calloc(nthreads, sizeof(*worker));
if (!worker)
err(EXIT_FAILURE, "calloc");
if (!fshared)
futex_flag = FUTEX_PRIVATE_FLAG;
printf("Run summary [PID %d]: blocking on %d threads (at [%s] futex %p), "
"waking up %d at a time.\n\n",
getpid(), nthreads, fshared ? "shared":"private", &futex1, nwakes);
init_stats(&wakeup_stats);
init_stats(&waketime_stats);
pthread_attr_init(&thread_attr);
pthread_mutex_init(&thread_lock, NULL);
pthread_cond_init(&thread_parent, NULL);
pthread_cond_init(&thread_worker, NULL);
for (j = 0; j < bench_repeat && !done; j++) {
unsigned int nwoken = 0;
struct timeval start, end, runtime;
/* create, launch & block all threads */
block_threads(worker, thread_attr);
/* make sure all threads are already blocked */
pthread_mutex_lock(&thread_lock);
while (threads_starting)
pthread_cond_wait(&thread_parent, &thread_lock);
pthread_cond_broadcast(&thread_worker);
pthread_mutex_unlock(&thread_lock);
usleep(100000);
/* Ok, all threads are patiently blocked, start waking folks up */
gettimeofday(&start, NULL);
while (nwoken != nthreads)
nwoken += futex_wake(&futex1, nwakes, futex_flag);
gettimeofday(&end, NULL);
timersub(&end, &start, &runtime);
update_stats(&wakeup_stats, nwoken);
update_stats(&waketime_stats, runtime.tv_usec);
if (!silent) {
printf("[Run %d]: Wokeup %d of %d threads in %.4f ms\n",
j + 1, nwoken, nthreads, runtime.tv_usec/1e3);
}
for (i = 0; i < nthreads; i++) {
ret = pthread_join(worker[i], NULL);
if (ret)
err(EXIT_FAILURE, "pthread_join");
}
}
/* cleanup & report results */
pthread_cond_destroy(&thread_parent);
pthread_cond_destroy(&thread_worker);
pthread_mutex_destroy(&thread_lock);
pthread_attr_destroy(&thread_attr);
print_summary();
free(worker);
return ret;
}
| gpl-2.0 |
samno1607/NO-IDEA | drivers/mtd/nand/nomadik_nand.c | 1057 | 6099 | /*
* drivers/mtd/nand/nomadik_nand.c
*
* Overview:
* Driver for on-board NAND flash on Nomadik Platforms
*
* Copyright © 2007 STMicroelectronics Pvt. Ltd.
* Author: Sachin Verma <sachin.verma@st.com>
*
* Copyright © 2009 Alessandro Rubini
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/platform_device.h>
#include <linux/mtd/partitions.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <mach/nand.h>
#include <mach/fsmc.h>
#include <mtd/mtd-abi.h>
struct nomadik_nand_host {
struct mtd_info mtd;
struct nand_chip nand;
void __iomem *data_va;
void __iomem *cmd_va;
void __iomem *addr_va;
struct nand_bbt_descr *bbt_desc;
};
static struct nand_ecclayout nomadik_ecc_layout = {
.eccbytes = 3 * 4,
.eccpos = { /* each subpage has 16 bytes: pos 2,3,4 hosts ECC */
0x02, 0x03, 0x04,
0x12, 0x13, 0x14,
0x22, 0x23, 0x24,
0x32, 0x33, 0x34},
/* let's keep bytes 5,6,7 for us, just in case we change ECC algo */
.oobfree = { {0x08, 0x08}, {0x18, 0x08}, {0x28, 0x08}, {0x38, 0x08} },
};
static void nomadik_ecc_control(struct mtd_info *mtd, int mode)
{
/* No need to enable hw ecc, it's on by default */
}
static void nomadik_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl)
{
struct nand_chip *nand = mtd->priv;
struct nomadik_nand_host *host = nand->priv;
if (cmd == NAND_CMD_NONE)
return;
if (ctrl & NAND_CLE)
writeb(cmd, host->cmd_va);
else
writeb(cmd, host->addr_va);
}
static int nomadik_nand_probe(struct platform_device *pdev)
{
struct nomadik_nand_platform_data *pdata = pdev->dev.platform_data;
struct nomadik_nand_host *host;
struct mtd_info *mtd;
struct nand_chip *nand;
struct resource *res;
int ret = 0;
/* Allocate memory for the device structure (and zero it) */
host = kzalloc(sizeof(struct nomadik_nand_host), GFP_KERNEL);
if (!host) {
dev_err(&pdev->dev, "Failed to allocate device structure.\n");
return -ENOMEM;
}
/* Call the client's init function, if any */
if (pdata->init)
ret = pdata->init();
if (ret < 0) {
dev_err(&pdev->dev, "Init function failed\n");
goto err;
}
/* ioremap three regions */
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand_addr");
if (!res) {
ret = -EIO;
goto err_unmap;
}
host->addr_va = ioremap(res->start, resource_size(res));
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand_data");
if (!res) {
ret = -EIO;
goto err_unmap;
}
host->data_va = ioremap(res->start, resource_size(res));
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "nand_cmd");
if (!res) {
ret = -EIO;
goto err_unmap;
}
host->cmd_va = ioremap(res->start, resource_size(res));
if (!host->addr_va || !host->data_va || !host->cmd_va) {
ret = -ENOMEM;
goto err_unmap;
}
/* Link all private pointers */
mtd = &host->mtd;
nand = &host->nand;
mtd->priv = nand;
nand->priv = host;
host->mtd.owner = THIS_MODULE;
nand->IO_ADDR_R = host->data_va;
nand->IO_ADDR_W = host->data_va;
nand->cmd_ctrl = nomadik_cmd_ctrl;
/*
* This stanza declares ECC_HW but uses soft routines. It's because
* HW claims to make the calculation but not the correction. However,
* I haven't managed to get the desired data out of it until now.
*/
nand->ecc.mode = NAND_ECC_SOFT;
nand->ecc.layout = &nomadik_ecc_layout;
nand->ecc.hwctl = nomadik_ecc_control;
nand->ecc.size = 512;
nand->ecc.bytes = 3;
nand->options = pdata->options;
/*
* Scan to find existance of the device
*/
if (nand_scan(&host->mtd, 1)) {
ret = -ENXIO;
goto err_unmap;
}
#ifdef CONFIG_MTD_PARTITIONS
add_mtd_partitions(&host->mtd, pdata->parts, pdata->nparts);
#else
pr_info("Registering %s as whole device\n", mtd->name);
add_mtd_device(mtd);
#endif
platform_set_drvdata(pdev, host);
return 0;
err_unmap:
if (host->cmd_va)
iounmap(host->cmd_va);
if (host->data_va)
iounmap(host->data_va);
if (host->addr_va)
iounmap(host->addr_va);
err:
kfree(host);
return ret;
}
/*
* Clean up routine
*/
static int nomadik_nand_remove(struct platform_device *pdev)
{
struct nomadik_nand_host *host = platform_get_drvdata(pdev);
struct nomadik_nand_platform_data *pdata = pdev->dev.platform_data;
if (pdata->exit)
pdata->exit();
if (host) {
iounmap(host->cmd_va);
iounmap(host->data_va);
iounmap(host->addr_va);
kfree(host);
}
return 0;
}
static int nomadik_nand_suspend(struct device *dev)
{
struct nomadik_nand_host *host = dev_get_drvdata(dev);
int ret = 0;
if (host)
ret = host->mtd.suspend(&host->mtd);
return ret;
}
static int nomadik_nand_resume(struct device *dev)
{
struct nomadik_nand_host *host = dev_get_drvdata(dev);
if (host)
host->mtd.resume(&host->mtd);
return 0;
}
static const struct dev_pm_ops nomadik_nand_pm_ops = {
.suspend = nomadik_nand_suspend,
.resume = nomadik_nand_resume,
};
static struct platform_driver nomadik_nand_driver = {
.probe = nomadik_nand_probe,
.remove = nomadik_nand_remove,
.driver = {
.owner = THIS_MODULE,
.name = "nomadik_nand",
.pm = &nomadik_nand_pm_ops,
},
};
static int __init nand_nomadik_init(void)
{
pr_info("Nomadik NAND driver\n");
return platform_driver_register(&nomadik_nand_driver);
}
static void __exit nand_nomadik_exit(void)
{
platform_driver_unregister(&nomadik_nand_driver);
}
module_init(nand_nomadik_init);
module_exit(nand_nomadik_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("ST Microelectronics (sachin.verma@st.com)");
MODULE_DESCRIPTION("NAND driver for Nomadik Platform");
| gpl-2.0 |
bigzz/linaro-aarch64 | drivers/rtc/rtc-stmp3xxx.c | 2081 | 9672 | /*
* Freescale STMP37XX/STMP378X Real Time Clock driver
*
* Copyright (c) 2007 Sigmatel, Inc.
* Peter Hartley, <peter.hartley@sigmatel.com>
*
* Copyright 2008 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved.
* Copyright 2011 Wolfram Sang, Pengutronix e.K.
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#include <linux/of_device.h>
#include <linux/of.h>
#include <linux/stmp_device.h>
#include <linux/stmp3xxx_rtc_wdt.h>
#define STMP3XXX_RTC_CTRL 0x0
#define STMP3XXX_RTC_CTRL_SET 0x4
#define STMP3XXX_RTC_CTRL_CLR 0x8
#define STMP3XXX_RTC_CTRL_ALARM_IRQ_EN 0x00000001
#define STMP3XXX_RTC_CTRL_ONEMSEC_IRQ_EN 0x00000002
#define STMP3XXX_RTC_CTRL_ALARM_IRQ 0x00000004
#define STMP3XXX_RTC_CTRL_WATCHDOGEN 0x00000010
#define STMP3XXX_RTC_STAT 0x10
#define STMP3XXX_RTC_STAT_STALE_SHIFT 16
#define STMP3XXX_RTC_STAT_RTC_PRESENT 0x80000000
#define STMP3XXX_RTC_SECONDS 0x30
#define STMP3XXX_RTC_ALARM 0x40
#define STMP3XXX_RTC_WATCHDOG 0x50
#define STMP3XXX_RTC_PERSISTENT0 0x60
#define STMP3XXX_RTC_PERSISTENT0_SET 0x64
#define STMP3XXX_RTC_PERSISTENT0_CLR 0x68
#define STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE_EN 0x00000002
#define STMP3XXX_RTC_PERSISTENT0_ALARM_EN 0x00000004
#define STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE 0x00000080
#define STMP3XXX_RTC_PERSISTENT1 0x70
/* missing bitmask in headers */
#define STMP3XXX_RTC_PERSISTENT1_FORCE_UPDATER 0x80000000
struct stmp3xxx_rtc_data {
struct rtc_device *rtc;
void __iomem *io;
int irq_alarm;
};
#if IS_ENABLED(CONFIG_STMP3XXX_RTC_WATCHDOG)
/**
* stmp3xxx_wdt_set_timeout - configure the watchdog inside the STMP3xxx RTC
* @dev: the parent device of the watchdog (= the RTC)
* @timeout: the desired value for the timeout register of the watchdog.
* 0 disables the watchdog
*
* The watchdog needs one register and two bits which are in the RTC domain.
* To handle the resource conflict, the RTC driver will create another
* platform_device for the watchdog driver as a child of the RTC device.
* The watchdog driver is passed the below accessor function via platform_data
* to configure the watchdog. Locking is not needed because accessing SET/CLR
* registers is atomic.
*/
static void stmp3xxx_wdt_set_timeout(struct device *dev, u32 timeout)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
if (timeout) {
writel(timeout, rtc_data->io + STMP3XXX_RTC_WATCHDOG);
writel(STMP3XXX_RTC_CTRL_WATCHDOGEN,
rtc_data->io + STMP3XXX_RTC_CTRL + STMP_OFFSET_REG_SET);
writel(STMP3XXX_RTC_PERSISTENT1_FORCE_UPDATER,
rtc_data->io + STMP3XXX_RTC_PERSISTENT1 + STMP_OFFSET_REG_SET);
} else {
writel(STMP3XXX_RTC_CTRL_WATCHDOGEN,
rtc_data->io + STMP3XXX_RTC_CTRL + STMP_OFFSET_REG_CLR);
writel(STMP3XXX_RTC_PERSISTENT1_FORCE_UPDATER,
rtc_data->io + STMP3XXX_RTC_PERSISTENT1 + STMP_OFFSET_REG_CLR);
}
}
static struct stmp3xxx_wdt_pdata wdt_pdata = {
.wdt_set_timeout = stmp3xxx_wdt_set_timeout,
};
static void stmp3xxx_wdt_register(struct platform_device *rtc_pdev)
{
struct platform_device *wdt_pdev =
platform_device_alloc("stmp3xxx_rtc_wdt", rtc_pdev->id);
if (wdt_pdev) {
wdt_pdev->dev.parent = &rtc_pdev->dev;
wdt_pdev->dev.platform_data = &wdt_pdata;
platform_device_add(wdt_pdev);
}
}
#else
static void stmp3xxx_wdt_register(struct platform_device *rtc_pdev)
{
}
#endif /* CONFIG_STMP3XXX_RTC_WATCHDOG */
static void stmp3xxx_wait_time(struct stmp3xxx_rtc_data *rtc_data)
{
/*
* The datasheet doesn't say which way round the
* NEW_REGS/STALE_REGS bitfields go. In fact it's 0x1=P0,
* 0x2=P1, .., 0x20=P5, 0x40=ALARM, 0x80=SECONDS
*/
while (readl(rtc_data->io + STMP3XXX_RTC_STAT) &
(0x80 << STMP3XXX_RTC_STAT_STALE_SHIFT))
cpu_relax();
}
/* Time read/write */
static int stmp3xxx_rtc_gettime(struct device *dev, struct rtc_time *rtc_tm)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
stmp3xxx_wait_time(rtc_data);
rtc_time_to_tm(readl(rtc_data->io + STMP3XXX_RTC_SECONDS), rtc_tm);
return 0;
}
static int stmp3xxx_rtc_set_mmss(struct device *dev, unsigned long t)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
writel(t, rtc_data->io + STMP3XXX_RTC_SECONDS);
stmp3xxx_wait_time(rtc_data);
return 0;
}
/* interrupt(s) handler */
static irqreturn_t stmp3xxx_rtc_interrupt(int irq, void *dev_id)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev_id);
u32 status = readl(rtc_data->io + STMP3XXX_RTC_CTRL);
if (status & STMP3XXX_RTC_CTRL_ALARM_IRQ) {
writel(STMP3XXX_RTC_CTRL_ALARM_IRQ,
rtc_data->io + STMP3XXX_RTC_CTRL_CLR);
rtc_update_irq(rtc_data->rtc, 1, RTC_AF | RTC_IRQF);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static int stmp3xxx_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
if (enabled) {
writel(STMP3XXX_RTC_PERSISTENT0_ALARM_EN |
STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE_EN,
rtc_data->io + STMP3XXX_RTC_PERSISTENT0_SET);
writel(STMP3XXX_RTC_CTRL_ALARM_IRQ_EN,
rtc_data->io + STMP3XXX_RTC_CTRL_SET);
} else {
writel(STMP3XXX_RTC_PERSISTENT0_ALARM_EN |
STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE_EN,
rtc_data->io + STMP3XXX_RTC_PERSISTENT0_CLR);
writel(STMP3XXX_RTC_CTRL_ALARM_IRQ_EN,
rtc_data->io + STMP3XXX_RTC_CTRL_CLR);
}
return 0;
}
static int stmp3xxx_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
rtc_time_to_tm(readl(rtc_data->io + STMP3XXX_RTC_ALARM), &alm->time);
return 0;
}
static int stmp3xxx_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
{
unsigned long t;
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
rtc_tm_to_time(&alm->time, &t);
writel(t, rtc_data->io + STMP3XXX_RTC_ALARM);
stmp3xxx_alarm_irq_enable(dev, alm->enabled);
return 0;
}
static struct rtc_class_ops stmp3xxx_rtc_ops = {
.alarm_irq_enable =
stmp3xxx_alarm_irq_enable,
.read_time = stmp3xxx_rtc_gettime,
.set_mmss = stmp3xxx_rtc_set_mmss,
.read_alarm = stmp3xxx_rtc_read_alarm,
.set_alarm = stmp3xxx_rtc_set_alarm,
};
static int stmp3xxx_rtc_remove(struct platform_device *pdev)
{
struct stmp3xxx_rtc_data *rtc_data = platform_get_drvdata(pdev);
if (!rtc_data)
return 0;
writel(STMP3XXX_RTC_CTRL_ALARM_IRQ_EN,
rtc_data->io + STMP3XXX_RTC_CTRL_CLR);
platform_set_drvdata(pdev, NULL);
return 0;
}
static int stmp3xxx_rtc_probe(struct platform_device *pdev)
{
struct stmp3xxx_rtc_data *rtc_data;
struct resource *r;
int err;
rtc_data = devm_kzalloc(&pdev->dev, sizeof(*rtc_data), GFP_KERNEL);
if (!rtc_data)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
dev_err(&pdev->dev, "failed to get resource\n");
return -ENXIO;
}
rtc_data->io = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!rtc_data->io) {
dev_err(&pdev->dev, "ioremap failed\n");
return -EIO;
}
rtc_data->irq_alarm = platform_get_irq(pdev, 0);
if (!(readl(STMP3XXX_RTC_STAT + rtc_data->io) &
STMP3XXX_RTC_STAT_RTC_PRESENT)) {
dev_err(&pdev->dev, "no device onboard\n");
return -ENODEV;
}
platform_set_drvdata(pdev, rtc_data);
stmp_reset_block(rtc_data->io);
writel(STMP3XXX_RTC_PERSISTENT0_ALARM_EN |
STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE_EN |
STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE,
rtc_data->io + STMP3XXX_RTC_PERSISTENT0_CLR);
writel(STMP3XXX_RTC_CTRL_ONEMSEC_IRQ_EN |
STMP3XXX_RTC_CTRL_ALARM_IRQ_EN,
rtc_data->io + STMP3XXX_RTC_CTRL_CLR);
rtc_data->rtc = devm_rtc_device_register(&pdev->dev, pdev->name,
&stmp3xxx_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc_data->rtc)) {
err = PTR_ERR(rtc_data->rtc);
goto out;
}
err = devm_request_irq(&pdev->dev, rtc_data->irq_alarm,
stmp3xxx_rtc_interrupt, 0, "RTC alarm", &pdev->dev);
if (err) {
dev_err(&pdev->dev, "Cannot claim IRQ%d\n",
rtc_data->irq_alarm);
goto out;
}
stmp3xxx_wdt_register(pdev);
return 0;
out:
platform_set_drvdata(pdev, NULL);
return err;
}
#ifdef CONFIG_PM_SLEEP
static int stmp3xxx_rtc_suspend(struct device *dev)
{
return 0;
}
static int stmp3xxx_rtc_resume(struct device *dev)
{
struct stmp3xxx_rtc_data *rtc_data = dev_get_drvdata(dev);
stmp_reset_block(rtc_data->io);
writel(STMP3XXX_RTC_PERSISTENT0_ALARM_EN |
STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE_EN |
STMP3XXX_RTC_PERSISTENT0_ALARM_WAKE,
rtc_data->io + STMP3XXX_RTC_PERSISTENT0_CLR);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(stmp3xxx_rtc_pm_ops, stmp3xxx_rtc_suspend,
stmp3xxx_rtc_resume);
static const struct of_device_id rtc_dt_ids[] = {
{ .compatible = "fsl,stmp3xxx-rtc", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, rtc_dt_ids);
static struct platform_driver stmp3xxx_rtcdrv = {
.probe = stmp3xxx_rtc_probe,
.remove = stmp3xxx_rtc_remove,
.driver = {
.name = "stmp3xxx-rtc",
.owner = THIS_MODULE,
.pm = &stmp3xxx_rtc_pm_ops,
.of_match_table = of_match_ptr(rtc_dt_ids),
},
};
module_platform_driver(stmp3xxx_rtcdrv);
MODULE_DESCRIPTION("STMP3xxx RTC Driver");
MODULE_AUTHOR("dmitry pervushin <dpervushin@embeddedalley.com> and "
"Wolfram Sang <w.sang@pengutronix.de>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
gototem/kernel | net/openvswitch/flow.c | 2081 | 36109 | /*
* Copyright (c) 2007-2011 Nicira, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*/
#include "flow.h"
#include "datapath.h"
#include <linux/uaccess.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <net/llc_pdu.h>
#include <linux/kernel.h>
#include <linux/jhash.h>
#include <linux/jiffies.h>
#include <linux/llc.h>
#include <linux/module.h>
#include <linux/in.h>
#include <linux/rcupdate.h>
#include <linux/if_arp.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/icmpv6.h>
#include <linux/rculist.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
static struct kmem_cache *flow_cache;
static int check_header(struct sk_buff *skb, int len)
{
if (unlikely(skb->len < len))
return -EINVAL;
if (unlikely(!pskb_may_pull(skb, len)))
return -ENOMEM;
return 0;
}
static bool arphdr_ok(struct sk_buff *skb)
{
return pskb_may_pull(skb, skb_network_offset(skb) +
sizeof(struct arp_eth_header));
}
static int check_iphdr(struct sk_buff *skb)
{
unsigned int nh_ofs = skb_network_offset(skb);
unsigned int ip_len;
int err;
err = check_header(skb, nh_ofs + sizeof(struct iphdr));
if (unlikely(err))
return err;
ip_len = ip_hdrlen(skb);
if (unlikely(ip_len < sizeof(struct iphdr) ||
skb->len < nh_ofs + ip_len))
return -EINVAL;
skb_set_transport_header(skb, nh_ofs + ip_len);
return 0;
}
static bool tcphdr_ok(struct sk_buff *skb)
{
int th_ofs = skb_transport_offset(skb);
int tcp_len;
if (unlikely(!pskb_may_pull(skb, th_ofs + sizeof(struct tcphdr))))
return false;
tcp_len = tcp_hdrlen(skb);
if (unlikely(tcp_len < sizeof(struct tcphdr) ||
skb->len < th_ofs + tcp_len))
return false;
return true;
}
static bool udphdr_ok(struct sk_buff *skb)
{
return pskb_may_pull(skb, skb_transport_offset(skb) +
sizeof(struct udphdr));
}
static bool icmphdr_ok(struct sk_buff *skb)
{
return pskb_may_pull(skb, skb_transport_offset(skb) +
sizeof(struct icmphdr));
}
u64 ovs_flow_used_time(unsigned long flow_jiffies)
{
struct timespec cur_ts;
u64 cur_ms, idle_ms;
ktime_get_ts(&cur_ts);
idle_ms = jiffies_to_msecs(jiffies - flow_jiffies);
cur_ms = (u64)cur_ts.tv_sec * MSEC_PER_SEC +
cur_ts.tv_nsec / NSEC_PER_MSEC;
return cur_ms - idle_ms;
}
#define SW_FLOW_KEY_OFFSET(field) \
(offsetof(struct sw_flow_key, field) + \
FIELD_SIZEOF(struct sw_flow_key, field))
static int parse_ipv6hdr(struct sk_buff *skb, struct sw_flow_key *key,
int *key_lenp)
{
unsigned int nh_ofs = skb_network_offset(skb);
unsigned int nh_len;
int payload_ofs;
struct ipv6hdr *nh;
uint8_t nexthdr;
__be16 frag_off;
int err;
*key_lenp = SW_FLOW_KEY_OFFSET(ipv6.label);
err = check_header(skb, nh_ofs + sizeof(*nh));
if (unlikely(err))
return err;
nh = ipv6_hdr(skb);
nexthdr = nh->nexthdr;
payload_ofs = (u8 *)(nh + 1) - skb->data;
key->ip.proto = NEXTHDR_NONE;
key->ip.tos = ipv6_get_dsfield(nh);
key->ip.ttl = nh->hop_limit;
key->ipv6.label = *(__be32 *)nh & htonl(IPV6_FLOWINFO_FLOWLABEL);
key->ipv6.addr.src = nh->saddr;
key->ipv6.addr.dst = nh->daddr;
payload_ofs = ipv6_skip_exthdr(skb, payload_ofs, &nexthdr, &frag_off);
if (unlikely(payload_ofs < 0))
return -EINVAL;
if (frag_off) {
if (frag_off & htons(~0x7))
key->ip.frag = OVS_FRAG_TYPE_LATER;
else
key->ip.frag = OVS_FRAG_TYPE_FIRST;
}
nh_len = payload_ofs - nh_ofs;
skb_set_transport_header(skb, nh_ofs + nh_len);
key->ip.proto = nexthdr;
return nh_len;
}
static bool icmp6hdr_ok(struct sk_buff *skb)
{
return pskb_may_pull(skb, skb_transport_offset(skb) +
sizeof(struct icmp6hdr));
}
#define TCP_FLAGS_OFFSET 13
#define TCP_FLAG_MASK 0x3f
void ovs_flow_used(struct sw_flow *flow, struct sk_buff *skb)
{
u8 tcp_flags = 0;
if ((flow->key.eth.type == htons(ETH_P_IP) ||
flow->key.eth.type == htons(ETH_P_IPV6)) &&
flow->key.ip.proto == IPPROTO_TCP &&
likely(skb->len >= skb_transport_offset(skb) + sizeof(struct tcphdr))) {
u8 *tcp = (u8 *)tcp_hdr(skb);
tcp_flags = *(tcp + TCP_FLAGS_OFFSET) & TCP_FLAG_MASK;
}
spin_lock(&flow->lock);
flow->used = jiffies;
flow->packet_count++;
flow->byte_count += skb->len;
flow->tcp_flags |= tcp_flags;
spin_unlock(&flow->lock);
}
struct sw_flow_actions *ovs_flow_actions_alloc(const struct nlattr *actions)
{
int actions_len = nla_len(actions);
struct sw_flow_actions *sfa;
if (actions_len > MAX_ACTIONS_BUFSIZE)
return ERR_PTR(-EINVAL);
sfa = kmalloc(sizeof(*sfa) + actions_len, GFP_KERNEL);
if (!sfa)
return ERR_PTR(-ENOMEM);
sfa->actions_len = actions_len;
nla_memcpy(sfa->actions, actions, actions_len);
return sfa;
}
struct sw_flow *ovs_flow_alloc(void)
{
struct sw_flow *flow;
flow = kmem_cache_alloc(flow_cache, GFP_KERNEL);
if (!flow)
return ERR_PTR(-ENOMEM);
spin_lock_init(&flow->lock);
flow->sf_acts = NULL;
return flow;
}
static struct hlist_head *find_bucket(struct flow_table *table, u32 hash)
{
hash = jhash_1word(hash, table->hash_seed);
return flex_array_get(table->buckets,
(hash & (table->n_buckets - 1)));
}
static struct flex_array *alloc_buckets(unsigned int n_buckets)
{
struct flex_array *buckets;
int i, err;
buckets = flex_array_alloc(sizeof(struct hlist_head *),
n_buckets, GFP_KERNEL);
if (!buckets)
return NULL;
err = flex_array_prealloc(buckets, 0, n_buckets, GFP_KERNEL);
if (err) {
flex_array_free(buckets);
return NULL;
}
for (i = 0; i < n_buckets; i++)
INIT_HLIST_HEAD((struct hlist_head *)
flex_array_get(buckets, i));
return buckets;
}
static void free_buckets(struct flex_array *buckets)
{
flex_array_free(buckets);
}
struct flow_table *ovs_flow_tbl_alloc(int new_size)
{
struct flow_table *table = kmalloc(sizeof(*table), GFP_KERNEL);
if (!table)
return NULL;
table->buckets = alloc_buckets(new_size);
if (!table->buckets) {
kfree(table);
return NULL;
}
table->n_buckets = new_size;
table->count = 0;
table->node_ver = 0;
table->keep_flows = false;
get_random_bytes(&table->hash_seed, sizeof(u32));
return table;
}
void ovs_flow_tbl_destroy(struct flow_table *table)
{
int i;
if (!table)
return;
if (table->keep_flows)
goto skip_flows;
for (i = 0; i < table->n_buckets; i++) {
struct sw_flow *flow;
struct hlist_head *head = flex_array_get(table->buckets, i);
struct hlist_node *n;
int ver = table->node_ver;
hlist_for_each_entry_safe(flow, n, head, hash_node[ver]) {
hlist_del_rcu(&flow->hash_node[ver]);
ovs_flow_free(flow);
}
}
skip_flows:
free_buckets(table->buckets);
kfree(table);
}
static void flow_tbl_destroy_rcu_cb(struct rcu_head *rcu)
{
struct flow_table *table = container_of(rcu, struct flow_table, rcu);
ovs_flow_tbl_destroy(table);
}
void ovs_flow_tbl_deferred_destroy(struct flow_table *table)
{
if (!table)
return;
call_rcu(&table->rcu, flow_tbl_destroy_rcu_cb);
}
struct sw_flow *ovs_flow_tbl_next(struct flow_table *table, u32 *bucket, u32 *last)
{
struct sw_flow *flow;
struct hlist_head *head;
int ver;
int i;
ver = table->node_ver;
while (*bucket < table->n_buckets) {
i = 0;
head = flex_array_get(table->buckets, *bucket);
hlist_for_each_entry_rcu(flow, head, hash_node[ver]) {
if (i < *last) {
i++;
continue;
}
*last = i + 1;
return flow;
}
(*bucket)++;
*last = 0;
}
return NULL;
}
static void flow_table_copy_flows(struct flow_table *old, struct flow_table *new)
{
int old_ver;
int i;
old_ver = old->node_ver;
new->node_ver = !old_ver;
/* Insert in new table. */
for (i = 0; i < old->n_buckets; i++) {
struct sw_flow *flow;
struct hlist_head *head;
head = flex_array_get(old->buckets, i);
hlist_for_each_entry(flow, head, hash_node[old_ver])
ovs_flow_tbl_insert(new, flow);
}
old->keep_flows = true;
}
static struct flow_table *__flow_tbl_rehash(struct flow_table *table, int n_buckets)
{
struct flow_table *new_table;
new_table = ovs_flow_tbl_alloc(n_buckets);
if (!new_table)
return ERR_PTR(-ENOMEM);
flow_table_copy_flows(table, new_table);
return new_table;
}
struct flow_table *ovs_flow_tbl_rehash(struct flow_table *table)
{
return __flow_tbl_rehash(table, table->n_buckets);
}
struct flow_table *ovs_flow_tbl_expand(struct flow_table *table)
{
return __flow_tbl_rehash(table, table->n_buckets * 2);
}
void ovs_flow_free(struct sw_flow *flow)
{
if (unlikely(!flow))
return;
kfree((struct sf_flow_acts __force *)flow->sf_acts);
kmem_cache_free(flow_cache, flow);
}
/* RCU callback used by ovs_flow_deferred_free. */
static void rcu_free_flow_callback(struct rcu_head *rcu)
{
struct sw_flow *flow = container_of(rcu, struct sw_flow, rcu);
ovs_flow_free(flow);
}
/* Schedules 'flow' to be freed after the next RCU grace period.
* The caller must hold rcu_read_lock for this to be sensible. */
void ovs_flow_deferred_free(struct sw_flow *flow)
{
call_rcu(&flow->rcu, rcu_free_flow_callback);
}
/* Schedules 'sf_acts' to be freed after the next RCU grace period.
* The caller must hold rcu_read_lock for this to be sensible. */
void ovs_flow_deferred_free_acts(struct sw_flow_actions *sf_acts)
{
kfree_rcu(sf_acts, rcu);
}
static int parse_vlan(struct sk_buff *skb, struct sw_flow_key *key)
{
struct qtag_prefix {
__be16 eth_type; /* ETH_P_8021Q */
__be16 tci;
};
struct qtag_prefix *qp;
if (unlikely(skb->len < sizeof(struct qtag_prefix) + sizeof(__be16)))
return 0;
if (unlikely(!pskb_may_pull(skb, sizeof(struct qtag_prefix) +
sizeof(__be16))))
return -ENOMEM;
qp = (struct qtag_prefix *) skb->data;
key->eth.tci = qp->tci | htons(VLAN_TAG_PRESENT);
__skb_pull(skb, sizeof(struct qtag_prefix));
return 0;
}
static __be16 parse_ethertype(struct sk_buff *skb)
{
struct llc_snap_hdr {
u8 dsap; /* Always 0xAA */
u8 ssap; /* Always 0xAA */
u8 ctrl;
u8 oui[3];
__be16 ethertype;
};
struct llc_snap_hdr *llc;
__be16 proto;
proto = *(__be16 *) skb->data;
__skb_pull(skb, sizeof(__be16));
if (ntohs(proto) >= ETH_P_802_3_MIN)
return proto;
if (skb->len < sizeof(struct llc_snap_hdr))
return htons(ETH_P_802_2);
if (unlikely(!pskb_may_pull(skb, sizeof(struct llc_snap_hdr))))
return htons(0);
llc = (struct llc_snap_hdr *) skb->data;
if (llc->dsap != LLC_SAP_SNAP ||
llc->ssap != LLC_SAP_SNAP ||
(llc->oui[0] | llc->oui[1] | llc->oui[2]) != 0)
return htons(ETH_P_802_2);
__skb_pull(skb, sizeof(struct llc_snap_hdr));
if (ntohs(llc->ethertype) >= ETH_P_802_3_MIN)
return llc->ethertype;
return htons(ETH_P_802_2);
}
static int parse_icmpv6(struct sk_buff *skb, struct sw_flow_key *key,
int *key_lenp, int nh_len)
{
struct icmp6hdr *icmp = icmp6_hdr(skb);
int error = 0;
int key_len;
/* The ICMPv6 type and code fields use the 16-bit transport port
* fields, so we need to store them in 16-bit network byte order.
*/
key->ipv6.tp.src = htons(icmp->icmp6_type);
key->ipv6.tp.dst = htons(icmp->icmp6_code);
key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
if (icmp->icmp6_code == 0 &&
(icmp->icmp6_type == NDISC_NEIGHBOUR_SOLICITATION ||
icmp->icmp6_type == NDISC_NEIGHBOUR_ADVERTISEMENT)) {
int icmp_len = skb->len - skb_transport_offset(skb);
struct nd_msg *nd;
int offset;
key_len = SW_FLOW_KEY_OFFSET(ipv6.nd);
/* In order to process neighbor discovery options, we need the
* entire packet.
*/
if (unlikely(icmp_len < sizeof(*nd)))
goto out;
if (unlikely(skb_linearize(skb))) {
error = -ENOMEM;
goto out;
}
nd = (struct nd_msg *)skb_transport_header(skb);
key->ipv6.nd.target = nd->target;
key_len = SW_FLOW_KEY_OFFSET(ipv6.nd);
icmp_len -= sizeof(*nd);
offset = 0;
while (icmp_len >= 8) {
struct nd_opt_hdr *nd_opt =
(struct nd_opt_hdr *)(nd->opt + offset);
int opt_len = nd_opt->nd_opt_len * 8;
if (unlikely(!opt_len || opt_len > icmp_len))
goto invalid;
/* Store the link layer address if the appropriate
* option is provided. It is considered an error if
* the same link layer option is specified twice.
*/
if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LL_ADDR
&& opt_len == 8) {
if (unlikely(!is_zero_ether_addr(key->ipv6.nd.sll)))
goto invalid;
memcpy(key->ipv6.nd.sll,
&nd->opt[offset+sizeof(*nd_opt)], ETH_ALEN);
} else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LL_ADDR
&& opt_len == 8) {
if (unlikely(!is_zero_ether_addr(key->ipv6.nd.tll)))
goto invalid;
memcpy(key->ipv6.nd.tll,
&nd->opt[offset+sizeof(*nd_opt)], ETH_ALEN);
}
icmp_len -= opt_len;
offset += opt_len;
}
}
goto out;
invalid:
memset(&key->ipv6.nd.target, 0, sizeof(key->ipv6.nd.target));
memset(key->ipv6.nd.sll, 0, sizeof(key->ipv6.nd.sll));
memset(key->ipv6.nd.tll, 0, sizeof(key->ipv6.nd.tll));
out:
*key_lenp = key_len;
return error;
}
/**
* ovs_flow_extract - extracts a flow key from an Ethernet frame.
* @skb: sk_buff that contains the frame, with skb->data pointing to the
* Ethernet header
* @in_port: port number on which @skb was received.
* @key: output flow key
* @key_lenp: length of output flow key
*
* The caller must ensure that skb->len >= ETH_HLEN.
*
* Returns 0 if successful, otherwise a negative errno value.
*
* Initializes @skb header pointers as follows:
*
* - skb->mac_header: the Ethernet header.
*
* - skb->network_header: just past the Ethernet header, or just past the
* VLAN header, to the first byte of the Ethernet payload.
*
* - skb->transport_header: If key->dl_type is ETH_P_IP or ETH_P_IPV6
* on output, then just past the IP header, if one is present and
* of a correct length, otherwise the same as skb->network_header.
* For other key->dl_type values it is left untouched.
*/
int ovs_flow_extract(struct sk_buff *skb, u16 in_port, struct sw_flow_key *key,
int *key_lenp)
{
int error = 0;
int key_len = SW_FLOW_KEY_OFFSET(eth);
struct ethhdr *eth;
memset(key, 0, sizeof(*key));
key->phy.priority = skb->priority;
key->phy.in_port = in_port;
key->phy.skb_mark = skb->mark;
skb_reset_mac_header(skb);
/* Link layer. We are guaranteed to have at least the 14 byte Ethernet
* header in the linear data area.
*/
eth = eth_hdr(skb);
memcpy(key->eth.src, eth->h_source, ETH_ALEN);
memcpy(key->eth.dst, eth->h_dest, ETH_ALEN);
__skb_pull(skb, 2 * ETH_ALEN);
if (vlan_tx_tag_present(skb))
key->eth.tci = htons(skb->vlan_tci);
else if (eth->h_proto == htons(ETH_P_8021Q))
if (unlikely(parse_vlan(skb, key)))
return -ENOMEM;
key->eth.type = parse_ethertype(skb);
if (unlikely(key->eth.type == htons(0)))
return -ENOMEM;
skb_reset_network_header(skb);
__skb_push(skb, skb->data - skb_mac_header(skb));
/* Network layer. */
if (key->eth.type == htons(ETH_P_IP)) {
struct iphdr *nh;
__be16 offset;
key_len = SW_FLOW_KEY_OFFSET(ipv4.addr);
error = check_iphdr(skb);
if (unlikely(error)) {
if (error == -EINVAL) {
skb->transport_header = skb->network_header;
error = 0;
}
goto out;
}
nh = ip_hdr(skb);
key->ipv4.addr.src = nh->saddr;
key->ipv4.addr.dst = nh->daddr;
key->ip.proto = nh->protocol;
key->ip.tos = nh->tos;
key->ip.ttl = nh->ttl;
offset = nh->frag_off & htons(IP_OFFSET);
if (offset) {
key->ip.frag = OVS_FRAG_TYPE_LATER;
goto out;
}
if (nh->frag_off & htons(IP_MF) ||
skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
key->ip.frag = OVS_FRAG_TYPE_FIRST;
/* Transport layer. */
if (key->ip.proto == IPPROTO_TCP) {
key_len = SW_FLOW_KEY_OFFSET(ipv4.tp);
if (tcphdr_ok(skb)) {
struct tcphdr *tcp = tcp_hdr(skb);
key->ipv4.tp.src = tcp->source;
key->ipv4.tp.dst = tcp->dest;
}
} else if (key->ip.proto == IPPROTO_UDP) {
key_len = SW_FLOW_KEY_OFFSET(ipv4.tp);
if (udphdr_ok(skb)) {
struct udphdr *udp = udp_hdr(skb);
key->ipv4.tp.src = udp->source;
key->ipv4.tp.dst = udp->dest;
}
} else if (key->ip.proto == IPPROTO_ICMP) {
key_len = SW_FLOW_KEY_OFFSET(ipv4.tp);
if (icmphdr_ok(skb)) {
struct icmphdr *icmp = icmp_hdr(skb);
/* The ICMP type and code fields use the 16-bit
* transport port fields, so we need to store
* them in 16-bit network byte order. */
key->ipv4.tp.src = htons(icmp->type);
key->ipv4.tp.dst = htons(icmp->code);
}
}
} else if ((key->eth.type == htons(ETH_P_ARP) ||
key->eth.type == htons(ETH_P_RARP)) && arphdr_ok(skb)) {
struct arp_eth_header *arp;
arp = (struct arp_eth_header *)skb_network_header(skb);
if (arp->ar_hrd == htons(ARPHRD_ETHER)
&& arp->ar_pro == htons(ETH_P_IP)
&& arp->ar_hln == ETH_ALEN
&& arp->ar_pln == 4) {
/* We only match on the lower 8 bits of the opcode. */
if (ntohs(arp->ar_op) <= 0xff)
key->ip.proto = ntohs(arp->ar_op);
memcpy(&key->ipv4.addr.src, arp->ar_sip, sizeof(key->ipv4.addr.src));
memcpy(&key->ipv4.addr.dst, arp->ar_tip, sizeof(key->ipv4.addr.dst));
memcpy(key->ipv4.arp.sha, arp->ar_sha, ETH_ALEN);
memcpy(key->ipv4.arp.tha, arp->ar_tha, ETH_ALEN);
key_len = SW_FLOW_KEY_OFFSET(ipv4.arp);
}
} else if (key->eth.type == htons(ETH_P_IPV6)) {
int nh_len; /* IPv6 Header + Extensions */
nh_len = parse_ipv6hdr(skb, key, &key_len);
if (unlikely(nh_len < 0)) {
if (nh_len == -EINVAL)
skb->transport_header = skb->network_header;
else
error = nh_len;
goto out;
}
if (key->ip.frag == OVS_FRAG_TYPE_LATER)
goto out;
if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
key->ip.frag = OVS_FRAG_TYPE_FIRST;
/* Transport layer. */
if (key->ip.proto == NEXTHDR_TCP) {
key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
if (tcphdr_ok(skb)) {
struct tcphdr *tcp = tcp_hdr(skb);
key->ipv6.tp.src = tcp->source;
key->ipv6.tp.dst = tcp->dest;
}
} else if (key->ip.proto == NEXTHDR_UDP) {
key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
if (udphdr_ok(skb)) {
struct udphdr *udp = udp_hdr(skb);
key->ipv6.tp.src = udp->source;
key->ipv6.tp.dst = udp->dest;
}
} else if (key->ip.proto == NEXTHDR_ICMP) {
key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
if (icmp6hdr_ok(skb)) {
error = parse_icmpv6(skb, key, &key_len, nh_len);
if (error < 0)
goto out;
}
}
}
out:
*key_lenp = key_len;
return error;
}
u32 ovs_flow_hash(const struct sw_flow_key *key, int key_len)
{
return jhash2((u32 *)key, DIV_ROUND_UP(key_len, sizeof(u32)), 0);
}
struct sw_flow *ovs_flow_tbl_lookup(struct flow_table *table,
struct sw_flow_key *key, int key_len)
{
struct sw_flow *flow;
struct hlist_head *head;
u32 hash;
hash = ovs_flow_hash(key, key_len);
head = find_bucket(table, hash);
hlist_for_each_entry_rcu(flow, head, hash_node[table->node_ver]) {
if (flow->hash == hash &&
!memcmp(&flow->key, key, key_len)) {
return flow;
}
}
return NULL;
}
void ovs_flow_tbl_insert(struct flow_table *table, struct sw_flow *flow)
{
struct hlist_head *head;
head = find_bucket(table, flow->hash);
hlist_add_head_rcu(&flow->hash_node[table->node_ver], head);
table->count++;
}
void ovs_flow_tbl_remove(struct flow_table *table, struct sw_flow *flow)
{
BUG_ON(table->count == 0);
hlist_del_rcu(&flow->hash_node[table->node_ver]);
table->count--;
}
/* The size of the argument for each %OVS_KEY_ATTR_* Netlink attribute. */
const int ovs_key_lens[OVS_KEY_ATTR_MAX + 1] = {
[OVS_KEY_ATTR_ENCAP] = -1,
[OVS_KEY_ATTR_PRIORITY] = sizeof(u32),
[OVS_KEY_ATTR_IN_PORT] = sizeof(u32),
[OVS_KEY_ATTR_SKB_MARK] = sizeof(u32),
[OVS_KEY_ATTR_ETHERNET] = sizeof(struct ovs_key_ethernet),
[OVS_KEY_ATTR_VLAN] = sizeof(__be16),
[OVS_KEY_ATTR_ETHERTYPE] = sizeof(__be16),
[OVS_KEY_ATTR_IPV4] = sizeof(struct ovs_key_ipv4),
[OVS_KEY_ATTR_IPV6] = sizeof(struct ovs_key_ipv6),
[OVS_KEY_ATTR_TCP] = sizeof(struct ovs_key_tcp),
[OVS_KEY_ATTR_UDP] = sizeof(struct ovs_key_udp),
[OVS_KEY_ATTR_ICMP] = sizeof(struct ovs_key_icmp),
[OVS_KEY_ATTR_ICMPV6] = sizeof(struct ovs_key_icmpv6),
[OVS_KEY_ATTR_ARP] = sizeof(struct ovs_key_arp),
[OVS_KEY_ATTR_ND] = sizeof(struct ovs_key_nd),
};
static int ipv4_flow_from_nlattrs(struct sw_flow_key *swkey, int *key_len,
const struct nlattr *a[], u32 *attrs)
{
const struct ovs_key_icmp *icmp_key;
const struct ovs_key_tcp *tcp_key;
const struct ovs_key_udp *udp_key;
switch (swkey->ip.proto) {
case IPPROTO_TCP:
if (!(*attrs & (1 << OVS_KEY_ATTR_TCP)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_TCP);
*key_len = SW_FLOW_KEY_OFFSET(ipv4.tp);
tcp_key = nla_data(a[OVS_KEY_ATTR_TCP]);
swkey->ipv4.tp.src = tcp_key->tcp_src;
swkey->ipv4.tp.dst = tcp_key->tcp_dst;
break;
case IPPROTO_UDP:
if (!(*attrs & (1 << OVS_KEY_ATTR_UDP)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_UDP);
*key_len = SW_FLOW_KEY_OFFSET(ipv4.tp);
udp_key = nla_data(a[OVS_KEY_ATTR_UDP]);
swkey->ipv4.tp.src = udp_key->udp_src;
swkey->ipv4.tp.dst = udp_key->udp_dst;
break;
case IPPROTO_ICMP:
if (!(*attrs & (1 << OVS_KEY_ATTR_ICMP)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_ICMP);
*key_len = SW_FLOW_KEY_OFFSET(ipv4.tp);
icmp_key = nla_data(a[OVS_KEY_ATTR_ICMP]);
swkey->ipv4.tp.src = htons(icmp_key->icmp_type);
swkey->ipv4.tp.dst = htons(icmp_key->icmp_code);
break;
}
return 0;
}
static int ipv6_flow_from_nlattrs(struct sw_flow_key *swkey, int *key_len,
const struct nlattr *a[], u32 *attrs)
{
const struct ovs_key_icmpv6 *icmpv6_key;
const struct ovs_key_tcp *tcp_key;
const struct ovs_key_udp *udp_key;
switch (swkey->ip.proto) {
case IPPROTO_TCP:
if (!(*attrs & (1 << OVS_KEY_ATTR_TCP)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_TCP);
*key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
tcp_key = nla_data(a[OVS_KEY_ATTR_TCP]);
swkey->ipv6.tp.src = tcp_key->tcp_src;
swkey->ipv6.tp.dst = tcp_key->tcp_dst;
break;
case IPPROTO_UDP:
if (!(*attrs & (1 << OVS_KEY_ATTR_UDP)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_UDP);
*key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
udp_key = nla_data(a[OVS_KEY_ATTR_UDP]);
swkey->ipv6.tp.src = udp_key->udp_src;
swkey->ipv6.tp.dst = udp_key->udp_dst;
break;
case IPPROTO_ICMPV6:
if (!(*attrs & (1 << OVS_KEY_ATTR_ICMPV6)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_ICMPV6);
*key_len = SW_FLOW_KEY_OFFSET(ipv6.tp);
icmpv6_key = nla_data(a[OVS_KEY_ATTR_ICMPV6]);
swkey->ipv6.tp.src = htons(icmpv6_key->icmpv6_type);
swkey->ipv6.tp.dst = htons(icmpv6_key->icmpv6_code);
if (swkey->ipv6.tp.src == htons(NDISC_NEIGHBOUR_SOLICITATION) ||
swkey->ipv6.tp.src == htons(NDISC_NEIGHBOUR_ADVERTISEMENT)) {
const struct ovs_key_nd *nd_key;
if (!(*attrs & (1 << OVS_KEY_ATTR_ND)))
return -EINVAL;
*attrs &= ~(1 << OVS_KEY_ATTR_ND);
*key_len = SW_FLOW_KEY_OFFSET(ipv6.nd);
nd_key = nla_data(a[OVS_KEY_ATTR_ND]);
memcpy(&swkey->ipv6.nd.target, nd_key->nd_target,
sizeof(swkey->ipv6.nd.target));
memcpy(swkey->ipv6.nd.sll, nd_key->nd_sll, ETH_ALEN);
memcpy(swkey->ipv6.nd.tll, nd_key->nd_tll, ETH_ALEN);
}
break;
}
return 0;
}
static int parse_flow_nlattrs(const struct nlattr *attr,
const struct nlattr *a[], u32 *attrsp)
{
const struct nlattr *nla;
u32 attrs;
int rem;
attrs = 0;
nla_for_each_nested(nla, attr, rem) {
u16 type = nla_type(nla);
int expected_len;
if (type > OVS_KEY_ATTR_MAX || attrs & (1 << type))
return -EINVAL;
expected_len = ovs_key_lens[type];
if (nla_len(nla) != expected_len && expected_len != -1)
return -EINVAL;
attrs |= 1 << type;
a[type] = nla;
}
if (rem)
return -EINVAL;
*attrsp = attrs;
return 0;
}
/**
* ovs_flow_from_nlattrs - parses Netlink attributes into a flow key.
* @swkey: receives the extracted flow key.
* @key_lenp: number of bytes used in @swkey.
* @attr: Netlink attribute holding nested %OVS_KEY_ATTR_* Netlink attribute
* sequence.
*/
int ovs_flow_from_nlattrs(struct sw_flow_key *swkey, int *key_lenp,
const struct nlattr *attr)
{
const struct nlattr *a[OVS_KEY_ATTR_MAX + 1];
const struct ovs_key_ethernet *eth_key;
int key_len;
u32 attrs;
int err;
memset(swkey, 0, sizeof(struct sw_flow_key));
key_len = SW_FLOW_KEY_OFFSET(eth);
err = parse_flow_nlattrs(attr, a, &attrs);
if (err)
return err;
/* Metadata attributes. */
if (attrs & (1 << OVS_KEY_ATTR_PRIORITY)) {
swkey->phy.priority = nla_get_u32(a[OVS_KEY_ATTR_PRIORITY]);
attrs &= ~(1 << OVS_KEY_ATTR_PRIORITY);
}
if (attrs & (1 << OVS_KEY_ATTR_IN_PORT)) {
u32 in_port = nla_get_u32(a[OVS_KEY_ATTR_IN_PORT]);
if (in_port >= DP_MAX_PORTS)
return -EINVAL;
swkey->phy.in_port = in_port;
attrs &= ~(1 << OVS_KEY_ATTR_IN_PORT);
} else {
swkey->phy.in_port = DP_MAX_PORTS;
}
if (attrs & (1 << OVS_KEY_ATTR_SKB_MARK)) {
swkey->phy.skb_mark = nla_get_u32(a[OVS_KEY_ATTR_SKB_MARK]);
attrs &= ~(1 << OVS_KEY_ATTR_SKB_MARK);
}
/* Data attributes. */
if (!(attrs & (1 << OVS_KEY_ATTR_ETHERNET)))
return -EINVAL;
attrs &= ~(1 << OVS_KEY_ATTR_ETHERNET);
eth_key = nla_data(a[OVS_KEY_ATTR_ETHERNET]);
memcpy(swkey->eth.src, eth_key->eth_src, ETH_ALEN);
memcpy(swkey->eth.dst, eth_key->eth_dst, ETH_ALEN);
if (attrs & (1u << OVS_KEY_ATTR_ETHERTYPE) &&
nla_get_be16(a[OVS_KEY_ATTR_ETHERTYPE]) == htons(ETH_P_8021Q)) {
const struct nlattr *encap;
__be16 tci;
if (attrs != ((1 << OVS_KEY_ATTR_VLAN) |
(1 << OVS_KEY_ATTR_ETHERTYPE) |
(1 << OVS_KEY_ATTR_ENCAP)))
return -EINVAL;
encap = a[OVS_KEY_ATTR_ENCAP];
tci = nla_get_be16(a[OVS_KEY_ATTR_VLAN]);
if (tci & htons(VLAN_TAG_PRESENT)) {
swkey->eth.tci = tci;
err = parse_flow_nlattrs(encap, a, &attrs);
if (err)
return err;
} else if (!tci) {
/* Corner case for truncated 802.1Q header. */
if (nla_len(encap))
return -EINVAL;
swkey->eth.type = htons(ETH_P_8021Q);
*key_lenp = key_len;
return 0;
} else {
return -EINVAL;
}
}
if (attrs & (1 << OVS_KEY_ATTR_ETHERTYPE)) {
swkey->eth.type = nla_get_be16(a[OVS_KEY_ATTR_ETHERTYPE]);
if (ntohs(swkey->eth.type) < ETH_P_802_3_MIN)
return -EINVAL;
attrs &= ~(1 << OVS_KEY_ATTR_ETHERTYPE);
} else {
swkey->eth.type = htons(ETH_P_802_2);
}
if (swkey->eth.type == htons(ETH_P_IP)) {
const struct ovs_key_ipv4 *ipv4_key;
if (!(attrs & (1 << OVS_KEY_ATTR_IPV4)))
return -EINVAL;
attrs &= ~(1 << OVS_KEY_ATTR_IPV4);
key_len = SW_FLOW_KEY_OFFSET(ipv4.addr);
ipv4_key = nla_data(a[OVS_KEY_ATTR_IPV4]);
if (ipv4_key->ipv4_frag > OVS_FRAG_TYPE_MAX)
return -EINVAL;
swkey->ip.proto = ipv4_key->ipv4_proto;
swkey->ip.tos = ipv4_key->ipv4_tos;
swkey->ip.ttl = ipv4_key->ipv4_ttl;
swkey->ip.frag = ipv4_key->ipv4_frag;
swkey->ipv4.addr.src = ipv4_key->ipv4_src;
swkey->ipv4.addr.dst = ipv4_key->ipv4_dst;
if (swkey->ip.frag != OVS_FRAG_TYPE_LATER) {
err = ipv4_flow_from_nlattrs(swkey, &key_len, a, &attrs);
if (err)
return err;
}
} else if (swkey->eth.type == htons(ETH_P_IPV6)) {
const struct ovs_key_ipv6 *ipv6_key;
if (!(attrs & (1 << OVS_KEY_ATTR_IPV6)))
return -EINVAL;
attrs &= ~(1 << OVS_KEY_ATTR_IPV6);
key_len = SW_FLOW_KEY_OFFSET(ipv6.label);
ipv6_key = nla_data(a[OVS_KEY_ATTR_IPV6]);
if (ipv6_key->ipv6_frag > OVS_FRAG_TYPE_MAX)
return -EINVAL;
swkey->ipv6.label = ipv6_key->ipv6_label;
swkey->ip.proto = ipv6_key->ipv6_proto;
swkey->ip.tos = ipv6_key->ipv6_tclass;
swkey->ip.ttl = ipv6_key->ipv6_hlimit;
swkey->ip.frag = ipv6_key->ipv6_frag;
memcpy(&swkey->ipv6.addr.src, ipv6_key->ipv6_src,
sizeof(swkey->ipv6.addr.src));
memcpy(&swkey->ipv6.addr.dst, ipv6_key->ipv6_dst,
sizeof(swkey->ipv6.addr.dst));
if (swkey->ip.frag != OVS_FRAG_TYPE_LATER) {
err = ipv6_flow_from_nlattrs(swkey, &key_len, a, &attrs);
if (err)
return err;
}
} else if (swkey->eth.type == htons(ETH_P_ARP) ||
swkey->eth.type == htons(ETH_P_RARP)) {
const struct ovs_key_arp *arp_key;
if (!(attrs & (1 << OVS_KEY_ATTR_ARP)))
return -EINVAL;
attrs &= ~(1 << OVS_KEY_ATTR_ARP);
key_len = SW_FLOW_KEY_OFFSET(ipv4.arp);
arp_key = nla_data(a[OVS_KEY_ATTR_ARP]);
swkey->ipv4.addr.src = arp_key->arp_sip;
swkey->ipv4.addr.dst = arp_key->arp_tip;
if (arp_key->arp_op & htons(0xff00))
return -EINVAL;
swkey->ip.proto = ntohs(arp_key->arp_op);
memcpy(swkey->ipv4.arp.sha, arp_key->arp_sha, ETH_ALEN);
memcpy(swkey->ipv4.arp.tha, arp_key->arp_tha, ETH_ALEN);
}
if (attrs)
return -EINVAL;
*key_lenp = key_len;
return 0;
}
/**
* ovs_flow_metadata_from_nlattrs - parses Netlink attributes into a flow key.
* @priority: receives the skb priority
* @mark: receives the skb mark
* @in_port: receives the extracted input port.
* @key: Netlink attribute holding nested %OVS_KEY_ATTR_* Netlink attribute
* sequence.
*
* This parses a series of Netlink attributes that form a flow key, which must
* take the same form accepted by flow_from_nlattrs(), but only enough of it to
* get the metadata, that is, the parts of the flow key that cannot be
* extracted from the packet itself.
*/
int ovs_flow_metadata_from_nlattrs(u32 *priority, u32 *mark, u16 *in_port,
const struct nlattr *attr)
{
const struct nlattr *nla;
int rem;
*in_port = DP_MAX_PORTS;
*priority = 0;
*mark = 0;
nla_for_each_nested(nla, attr, rem) {
int type = nla_type(nla);
if (type <= OVS_KEY_ATTR_MAX && ovs_key_lens[type] > 0) {
if (nla_len(nla) != ovs_key_lens[type])
return -EINVAL;
switch (type) {
case OVS_KEY_ATTR_PRIORITY:
*priority = nla_get_u32(nla);
break;
case OVS_KEY_ATTR_IN_PORT:
if (nla_get_u32(nla) >= DP_MAX_PORTS)
return -EINVAL;
*in_port = nla_get_u32(nla);
break;
case OVS_KEY_ATTR_SKB_MARK:
*mark = nla_get_u32(nla);
break;
}
}
}
if (rem)
return -EINVAL;
return 0;
}
int ovs_flow_to_nlattrs(const struct sw_flow_key *swkey, struct sk_buff *skb)
{
struct ovs_key_ethernet *eth_key;
struct nlattr *nla, *encap;
if (swkey->phy.priority &&
nla_put_u32(skb, OVS_KEY_ATTR_PRIORITY, swkey->phy.priority))
goto nla_put_failure;
if (swkey->phy.in_port != DP_MAX_PORTS &&
nla_put_u32(skb, OVS_KEY_ATTR_IN_PORT, swkey->phy.in_port))
goto nla_put_failure;
if (swkey->phy.skb_mark &&
nla_put_u32(skb, OVS_KEY_ATTR_SKB_MARK, swkey->phy.skb_mark))
goto nla_put_failure;
nla = nla_reserve(skb, OVS_KEY_ATTR_ETHERNET, sizeof(*eth_key));
if (!nla)
goto nla_put_failure;
eth_key = nla_data(nla);
memcpy(eth_key->eth_src, swkey->eth.src, ETH_ALEN);
memcpy(eth_key->eth_dst, swkey->eth.dst, ETH_ALEN);
if (swkey->eth.tci || swkey->eth.type == htons(ETH_P_8021Q)) {
if (nla_put_be16(skb, OVS_KEY_ATTR_ETHERTYPE, htons(ETH_P_8021Q)) ||
nla_put_be16(skb, OVS_KEY_ATTR_VLAN, swkey->eth.tci))
goto nla_put_failure;
encap = nla_nest_start(skb, OVS_KEY_ATTR_ENCAP);
if (!swkey->eth.tci)
goto unencap;
} else {
encap = NULL;
}
if (swkey->eth.type == htons(ETH_P_802_2))
goto unencap;
if (nla_put_be16(skb, OVS_KEY_ATTR_ETHERTYPE, swkey->eth.type))
goto nla_put_failure;
if (swkey->eth.type == htons(ETH_P_IP)) {
struct ovs_key_ipv4 *ipv4_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_IPV4, sizeof(*ipv4_key));
if (!nla)
goto nla_put_failure;
ipv4_key = nla_data(nla);
ipv4_key->ipv4_src = swkey->ipv4.addr.src;
ipv4_key->ipv4_dst = swkey->ipv4.addr.dst;
ipv4_key->ipv4_proto = swkey->ip.proto;
ipv4_key->ipv4_tos = swkey->ip.tos;
ipv4_key->ipv4_ttl = swkey->ip.ttl;
ipv4_key->ipv4_frag = swkey->ip.frag;
} else if (swkey->eth.type == htons(ETH_P_IPV6)) {
struct ovs_key_ipv6 *ipv6_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_IPV6, sizeof(*ipv6_key));
if (!nla)
goto nla_put_failure;
ipv6_key = nla_data(nla);
memcpy(ipv6_key->ipv6_src, &swkey->ipv6.addr.src,
sizeof(ipv6_key->ipv6_src));
memcpy(ipv6_key->ipv6_dst, &swkey->ipv6.addr.dst,
sizeof(ipv6_key->ipv6_dst));
ipv6_key->ipv6_label = swkey->ipv6.label;
ipv6_key->ipv6_proto = swkey->ip.proto;
ipv6_key->ipv6_tclass = swkey->ip.tos;
ipv6_key->ipv6_hlimit = swkey->ip.ttl;
ipv6_key->ipv6_frag = swkey->ip.frag;
} else if (swkey->eth.type == htons(ETH_P_ARP) ||
swkey->eth.type == htons(ETH_P_RARP)) {
struct ovs_key_arp *arp_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_ARP, sizeof(*arp_key));
if (!nla)
goto nla_put_failure;
arp_key = nla_data(nla);
memset(arp_key, 0, sizeof(struct ovs_key_arp));
arp_key->arp_sip = swkey->ipv4.addr.src;
arp_key->arp_tip = swkey->ipv4.addr.dst;
arp_key->arp_op = htons(swkey->ip.proto);
memcpy(arp_key->arp_sha, swkey->ipv4.arp.sha, ETH_ALEN);
memcpy(arp_key->arp_tha, swkey->ipv4.arp.tha, ETH_ALEN);
}
if ((swkey->eth.type == htons(ETH_P_IP) ||
swkey->eth.type == htons(ETH_P_IPV6)) &&
swkey->ip.frag != OVS_FRAG_TYPE_LATER) {
if (swkey->ip.proto == IPPROTO_TCP) {
struct ovs_key_tcp *tcp_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_TCP, sizeof(*tcp_key));
if (!nla)
goto nla_put_failure;
tcp_key = nla_data(nla);
if (swkey->eth.type == htons(ETH_P_IP)) {
tcp_key->tcp_src = swkey->ipv4.tp.src;
tcp_key->tcp_dst = swkey->ipv4.tp.dst;
} else if (swkey->eth.type == htons(ETH_P_IPV6)) {
tcp_key->tcp_src = swkey->ipv6.tp.src;
tcp_key->tcp_dst = swkey->ipv6.tp.dst;
}
} else if (swkey->ip.proto == IPPROTO_UDP) {
struct ovs_key_udp *udp_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_UDP, sizeof(*udp_key));
if (!nla)
goto nla_put_failure;
udp_key = nla_data(nla);
if (swkey->eth.type == htons(ETH_P_IP)) {
udp_key->udp_src = swkey->ipv4.tp.src;
udp_key->udp_dst = swkey->ipv4.tp.dst;
} else if (swkey->eth.type == htons(ETH_P_IPV6)) {
udp_key->udp_src = swkey->ipv6.tp.src;
udp_key->udp_dst = swkey->ipv6.tp.dst;
}
} else if (swkey->eth.type == htons(ETH_P_IP) &&
swkey->ip.proto == IPPROTO_ICMP) {
struct ovs_key_icmp *icmp_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_ICMP, sizeof(*icmp_key));
if (!nla)
goto nla_put_failure;
icmp_key = nla_data(nla);
icmp_key->icmp_type = ntohs(swkey->ipv4.tp.src);
icmp_key->icmp_code = ntohs(swkey->ipv4.tp.dst);
} else if (swkey->eth.type == htons(ETH_P_IPV6) &&
swkey->ip.proto == IPPROTO_ICMPV6) {
struct ovs_key_icmpv6 *icmpv6_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_ICMPV6,
sizeof(*icmpv6_key));
if (!nla)
goto nla_put_failure;
icmpv6_key = nla_data(nla);
icmpv6_key->icmpv6_type = ntohs(swkey->ipv6.tp.src);
icmpv6_key->icmpv6_code = ntohs(swkey->ipv6.tp.dst);
if (icmpv6_key->icmpv6_type == NDISC_NEIGHBOUR_SOLICITATION ||
icmpv6_key->icmpv6_type == NDISC_NEIGHBOUR_ADVERTISEMENT) {
struct ovs_key_nd *nd_key;
nla = nla_reserve(skb, OVS_KEY_ATTR_ND, sizeof(*nd_key));
if (!nla)
goto nla_put_failure;
nd_key = nla_data(nla);
memcpy(nd_key->nd_target, &swkey->ipv6.nd.target,
sizeof(nd_key->nd_target));
memcpy(nd_key->nd_sll, swkey->ipv6.nd.sll, ETH_ALEN);
memcpy(nd_key->nd_tll, swkey->ipv6.nd.tll, ETH_ALEN);
}
}
}
unencap:
if (encap)
nla_nest_end(skb, encap);
return 0;
nla_put_failure:
return -EMSGSIZE;
}
/* Initializes the flow module.
* Returns zero if successful or a negative error code. */
int ovs_flow_init(void)
{
flow_cache = kmem_cache_create("sw_flow", sizeof(struct sw_flow), 0,
0, NULL);
if (flow_cache == NULL)
return -ENOMEM;
return 0;
}
/* Uninitializes the flow module. */
void ovs_flow_exit(void)
{
kmem_cache_destroy(flow_cache);
}
| gpl-2.0 |
keiranFTW/android_kernel_sony_msm8660 | arch/sh/kernel/cpu/sh4a/setup-sh7786.c | 2337 | 26693 | /*
* SH7786 Setup
*
* Copyright (C) 2009 - 2010 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
* Paul Mundt <paul.mundt@renesas.com>
*
* Based on SH7785 Setup
*
* Copyright (C) 2007 Paul Mundt
*
* 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/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <linux/dma-mapping.h>
#include <linux/sh_timer.h>
#include <linux/sh_dma.h>
#include <linux/sh_intc.h>
#include <cpu/dma-register.h>
#include <asm/mmzone.h>
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xffea0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = { 40, 41, 43, 42 },
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
/*
* The rest of these all have multiplexed IRQs
*/
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xffeb0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = { 44, 44, 44, 44 },
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
static struct plat_sci_port scif2_platform_data = {
.mapbase = 0xffec0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = { 50, 50, 50, 50 },
};
static struct platform_device scif2_device = {
.name = "sh-sci",
.id = 2,
.dev = {
.platform_data = &scif2_platform_data,
},
};
static struct plat_sci_port scif3_platform_data = {
.mapbase = 0xffed0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = { 51, 51, 51, 51 },
};
static struct platform_device scif3_device = {
.name = "sh-sci",
.id = 3,
.dev = {
.platform_data = &scif3_platform_data,
},
};
static struct plat_sci_port scif4_platform_data = {
.mapbase = 0xffee0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = { 52, 52, 52, 52 },
};
static struct platform_device scif4_device = {
.name = "sh-sci",
.id = 4,
.dev = {
.platform_data = &scif4_platform_data,
},
};
static struct plat_sci_port scif5_platform_data = {
.mapbase = 0xffef0000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = { 53, 53, 53, 53 },
};
static struct platform_device scif5_device = {
.name = "sh-sci",
.id = 5,
.dev = {
.platform_data = &scif5_platform_data,
},
};
static struct sh_timer_config tmu0_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
.clockevent_rating = 200,
};
static struct resource tmu0_resources[] = {
[0] = {
.start = 0xffd80008,
.end = 0xffd80013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 16,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu0_device = {
.name = "sh_tmu",
.id = 0,
.dev = {
.platform_data = &tmu0_platform_data,
},
.resource = tmu0_resources,
.num_resources = ARRAY_SIZE(tmu0_resources),
};
static struct sh_timer_config tmu1_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
.clocksource_rating = 200,
};
static struct resource tmu1_resources[] = {
[0] = {
.start = 0xffd80014,
.end = 0xffd8001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 17,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu1_device = {
.name = "sh_tmu",
.id = 1,
.dev = {
.platform_data = &tmu1_platform_data,
},
.resource = tmu1_resources,
.num_resources = ARRAY_SIZE(tmu1_resources),
};
static struct sh_timer_config tmu2_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu2_resources[] = {
[0] = {
.start = 0xffd80020,
.end = 0xffd8002f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 18,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu2_device = {
.name = "sh_tmu",
.id = 2,
.dev = {
.platform_data = &tmu2_platform_data,
},
.resource = tmu2_resources,
.num_resources = ARRAY_SIZE(tmu2_resources),
};
static struct sh_timer_config tmu3_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
};
static struct resource tmu3_resources[] = {
[0] = {
.start = 0xffda0008,
.end = 0xffda0013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 20,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu3_device = {
.name = "sh_tmu",
.id = 3,
.dev = {
.platform_data = &tmu3_platform_data,
},
.resource = tmu3_resources,
.num_resources = ARRAY_SIZE(tmu3_resources),
};
static struct sh_timer_config tmu4_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
};
static struct resource tmu4_resources[] = {
[0] = {
.start = 0xffda0014,
.end = 0xffda001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 21,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu4_device = {
.name = "sh_tmu",
.id = 4,
.dev = {
.platform_data = &tmu4_platform_data,
},
.resource = tmu4_resources,
.num_resources = ARRAY_SIZE(tmu4_resources),
};
static struct sh_timer_config tmu5_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu5_resources[] = {
[0] = {
.start = 0xffda0020,
.end = 0xffda002b,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 22,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu5_device = {
.name = "sh_tmu",
.id = 5,
.dev = {
.platform_data = &tmu5_platform_data,
},
.resource = tmu5_resources,
.num_resources = ARRAY_SIZE(tmu5_resources),
};
static struct sh_timer_config tmu6_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
};
static struct resource tmu6_resources[] = {
[0] = {
.start = 0xffdc0008,
.end = 0xffdc0013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 45,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu6_device = {
.name = "sh_tmu",
.id = 6,
.dev = {
.platform_data = &tmu6_platform_data,
},
.resource = tmu6_resources,
.num_resources = ARRAY_SIZE(tmu6_resources),
};
static struct sh_timer_config tmu7_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
};
static struct resource tmu7_resources[] = {
[0] = {
.start = 0xffdc0014,
.end = 0xffdc001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 45,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu7_device = {
.name = "sh_tmu",
.id = 7,
.dev = {
.platform_data = &tmu7_platform_data,
},
.resource = tmu7_resources,
.num_resources = ARRAY_SIZE(tmu7_resources),
};
static struct sh_timer_config tmu8_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu8_resources[] = {
[0] = {
.start = 0xffdc0020,
.end = 0xffdc002b,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 45,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu8_device = {
.name = "sh_tmu",
.id = 8,
.dev = {
.platform_data = &tmu8_platform_data,
},
.resource = tmu8_resources,
.num_resources = ARRAY_SIZE(tmu8_resources),
};
static struct sh_timer_config tmu9_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
};
static struct resource tmu9_resources[] = {
[0] = {
.start = 0xffde0008,
.end = 0xffde0013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 46,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu9_device = {
.name = "sh_tmu",
.id = 9,
.dev = {
.platform_data = &tmu9_platform_data,
},
.resource = tmu9_resources,
.num_resources = ARRAY_SIZE(tmu9_resources),
};
static struct sh_timer_config tmu10_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
};
static struct resource tmu10_resources[] = {
[0] = {
.start = 0xffde0014,
.end = 0xffde001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 46,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu10_device = {
.name = "sh_tmu",
.id = 10,
.dev = {
.platform_data = &tmu10_platform_data,
},
.resource = tmu10_resources,
.num_resources = ARRAY_SIZE(tmu10_resources),
};
static struct sh_timer_config tmu11_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu11_resources[] = {
[0] = {
.start = 0xffde0020,
.end = 0xffde002b,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 46,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu11_device = {
.name = "sh_tmu",
.id = 11,
.dev = {
.platform_data = &tmu11_platform_data,
},
.resource = tmu11_resources,
.num_resources = ARRAY_SIZE(tmu11_resources),
};
static const struct sh_dmae_channel dmac0_channels[] = {
{
.offset = 0,
.dmars = 0,
.dmars_bit = 0,
}, {
.offset = 0x10,
.dmars = 0,
.dmars_bit = 8,
}, {
.offset = 0x20,
.dmars = 4,
.dmars_bit = 0,
}, {
.offset = 0x30,
.dmars = 4,
.dmars_bit = 8,
}, {
.offset = 0x50,
.dmars = 8,
.dmars_bit = 0,
}, {
.offset = 0x60,
.dmars = 8,
.dmars_bit = 8,
}
};
static const unsigned int ts_shift[] = TS_SHIFT;
static struct sh_dmae_pdata dma0_platform_data = {
.channel = dmac0_channels,
.channel_num = ARRAY_SIZE(dmac0_channels),
.ts_low_shift = CHCR_TS_LOW_SHIFT,
.ts_low_mask = CHCR_TS_LOW_MASK,
.ts_high_shift = CHCR_TS_HIGH_SHIFT,
.ts_high_mask = CHCR_TS_HIGH_MASK,
.ts_shift = ts_shift,
.ts_shift_num = ARRAY_SIZE(ts_shift),
.dmaor_init = DMAOR_INIT,
};
/* Resource order important! */
static struct resource dmac0_resources[] = {
{
/* Channel registers and DMAOR */
.start = 0xfe008020,
.end = 0xfe00808f,
.flags = IORESOURCE_MEM,
}, {
/* DMARSx */
.start = 0xfe009000,
.end = 0xfe00900b,
.flags = IORESOURCE_MEM,
}, {
/* DMA error IRQ */
.start = evt2irq(0x5c0),
.end = evt2irq(0x5c0),
.flags = IORESOURCE_IRQ,
}, {
/* IRQ for channels 0-5 */
.start = evt2irq(0x500),
.end = evt2irq(0x5a0),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dma0_device = {
.name = "sh-dma-engine",
.id = 0,
.resource = dmac0_resources,
.num_resources = ARRAY_SIZE(dmac0_resources),
.dev = {
.platform_data = &dma0_platform_data,
},
};
#define USB_EHCI_START 0xffe70000
#define USB_OHCI_START 0xffe70400
static struct resource usb_ehci_resources[] = {
[0] = {
.start = USB_EHCI_START,
.end = USB_EHCI_START + 0x3ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 77,
.end = 77,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device usb_ehci_device = {
.name = "sh_ehci",
.id = -1,
.dev = {
.dma_mask = &usb_ehci_device.dev.coherent_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.num_resources = ARRAY_SIZE(usb_ehci_resources),
.resource = usb_ehci_resources,
};
static struct resource usb_ohci_resources[] = {
[0] = {
.start = USB_OHCI_START,
.end = USB_OHCI_START + 0x3ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 77,
.end = 77,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device usb_ohci_device = {
.name = "sh_ohci",
.id = -1,
.dev = {
.dma_mask = &usb_ohci_device.dev.coherent_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.num_resources = ARRAY_SIZE(usb_ohci_resources),
.resource = usb_ohci_resources,
};
static struct platform_device *sh7786_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&scif2_device,
&scif3_device,
&scif4_device,
&scif5_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
&tmu3_device,
&tmu4_device,
&tmu5_device,
&tmu6_device,
&tmu7_device,
&tmu8_device,
&tmu9_device,
&tmu10_device,
&tmu11_device,
};
static struct platform_device *sh7786_devices[] __initdata = {
&dma0_device,
&usb_ehci_device,
&usb_ohci_device,
};
/*
* Please call this function if your platform board
* use external clock for USB
* */
#define USBCTL0 0xffe70858
#define CLOCK_MODE_MASK 0xffffff7f
#define EXT_CLOCK_MODE 0x00000080
void __init sh7786_usb_use_exclock(void)
{
u32 val = __raw_readl(USBCTL0) & CLOCK_MODE_MASK;
__raw_writel(val | EXT_CLOCK_MODE, USBCTL0);
}
#define USBINITREG1 0xffe70094
#define USBINITREG2 0xffe7009c
#define USBINITVAL1 0x00ff0040
#define USBINITVAL2 0x00000001
#define USBPCTL1 0xffe70804
#define USBST 0xffe70808
#define PHY_ENB 0x00000001
#define PLL_ENB 0x00000002
#define PHY_RST 0x00000004
#define ACT_PLL_STATUS 0xc0000000
static void __init sh7786_usb_setup(void)
{
int i = 1000000;
/*
* USB initial settings
*
* The following settings are necessary
* for using the USB modules.
*
* see "USB Initial Settings" for detail
*/
__raw_writel(USBINITVAL1, USBINITREG1);
__raw_writel(USBINITVAL2, USBINITREG2);
/*
* Set the PHY and PLL enable bit
*/
__raw_writel(PHY_ENB | PLL_ENB, USBPCTL1);
while (i--) {
if (ACT_PLL_STATUS == (__raw_readl(USBST) & ACT_PLL_STATUS)) {
/* Set the PHY RST bit */
__raw_writel(PHY_ENB | PLL_ENB | PHY_RST, USBPCTL1);
printk(KERN_INFO "sh7786 usb setup done\n");
break;
}
cpu_relax();
}
}
enum {
UNUSED = 0,
/* interrupt sources */
IRL0_LLLL, IRL0_LLLH, IRL0_LLHL, IRL0_LLHH,
IRL0_LHLL, IRL0_LHLH, IRL0_LHHL, IRL0_LHHH,
IRL0_HLLL, IRL0_HLLH, IRL0_HLHL, IRL0_HLHH,
IRL0_HHLL, IRL0_HHLH, IRL0_HHHL,
IRL4_LLLL, IRL4_LLLH, IRL4_LLHL, IRL4_LLHH,
IRL4_LHLL, IRL4_LHLH, IRL4_LHHL, IRL4_LHHH,
IRL4_HLLL, IRL4_HLLH, IRL4_HLHL, IRL4_HLHH,
IRL4_HHLL, IRL4_HHLH, IRL4_HHHL,
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7,
WDT,
TMU0_0, TMU0_1, TMU0_2, TMU0_3,
TMU1_0, TMU1_1, TMU1_2,
DMAC0_0, DMAC0_1, DMAC0_2, DMAC0_3, DMAC0_4, DMAC0_5, DMAC0_6,
HUDI1, HUDI0,
DMAC1_0, DMAC1_1, DMAC1_2, DMAC1_3,
HPB_0, HPB_1, HPB_2,
SCIF0_0, SCIF0_1, SCIF0_2, SCIF0_3,
SCIF1,
TMU2, TMU3,
SCIF2, SCIF3, SCIF4, SCIF5,
Eth_0, Eth_1,
PCIeC0_0, PCIeC0_1, PCIeC0_2,
PCIeC1_0, PCIeC1_1, PCIeC1_2,
USB,
I2C0, I2C1,
DU,
SSI0, SSI1, SSI2, SSI3,
PCIeC2_0, PCIeC2_1, PCIeC2_2,
HAC0, HAC1,
FLCTL,
HSPI,
GPIO0, GPIO1,
Thermal,
INTICI0, INTICI1, INTICI2, INTICI3,
INTICI4, INTICI5, INTICI6, INTICI7,
/* Muxed sub-events */
TXI1, BRI1, RXI1, ERI1,
};
static struct intc_vect sh7786_vectors[] __initdata = {
INTC_VECT(WDT, 0x3e0),
INTC_VECT(TMU0_0, 0x400), INTC_VECT(TMU0_1, 0x420),
INTC_VECT(TMU0_2, 0x440), INTC_VECT(TMU0_3, 0x460),
INTC_VECT(TMU1_0, 0x480), INTC_VECT(TMU1_1, 0x4a0),
INTC_VECT(TMU1_2, 0x4c0),
INTC_VECT(DMAC0_0, 0x500), INTC_VECT(DMAC0_1, 0x520),
INTC_VECT(DMAC0_2, 0x540), INTC_VECT(DMAC0_3, 0x560),
INTC_VECT(DMAC0_4, 0x580), INTC_VECT(DMAC0_5, 0x5a0),
INTC_VECT(DMAC0_6, 0x5c0),
INTC_VECT(HUDI1, 0x5e0), INTC_VECT(HUDI0, 0x600),
INTC_VECT(DMAC1_0, 0x620), INTC_VECT(DMAC1_1, 0x640),
INTC_VECT(DMAC1_2, 0x660), INTC_VECT(DMAC1_3, 0x680),
INTC_VECT(HPB_0, 0x6a0), INTC_VECT(HPB_1, 0x6c0),
INTC_VECT(HPB_2, 0x6e0),
INTC_VECT(SCIF0_0, 0x700), INTC_VECT(SCIF0_1, 0x720),
INTC_VECT(SCIF0_2, 0x740), INTC_VECT(SCIF0_3, 0x760),
INTC_VECT(SCIF1, 0x780),
INTC_VECT(TMU2, 0x7a0), INTC_VECT(TMU3, 0x7c0),
INTC_VECT(SCIF2, 0x840), INTC_VECT(SCIF3, 0x860),
INTC_VECT(SCIF4, 0x880), INTC_VECT(SCIF5, 0x8a0),
INTC_VECT(Eth_0, 0x8c0), INTC_VECT(Eth_1, 0x8e0),
INTC_VECT(PCIeC0_0, 0xae0), INTC_VECT(PCIeC0_1, 0xb00),
INTC_VECT(PCIeC0_2, 0xb20),
INTC_VECT(PCIeC1_0, 0xb40), INTC_VECT(PCIeC1_1, 0xb60),
INTC_VECT(PCIeC1_2, 0xb80),
INTC_VECT(USB, 0xba0),
INTC_VECT(I2C0, 0xcc0), INTC_VECT(I2C1, 0xce0),
INTC_VECT(DU, 0xd00),
INTC_VECT(SSI0, 0xd20), INTC_VECT(SSI1, 0xd40),
INTC_VECT(SSI2, 0xd60), INTC_VECT(SSI3, 0xd80),
INTC_VECT(PCIeC2_0, 0xda0), INTC_VECT(PCIeC2_1, 0xdc0),
INTC_VECT(PCIeC2_2, 0xde0),
INTC_VECT(HAC0, 0xe00), INTC_VECT(HAC1, 0xe20),
INTC_VECT(FLCTL, 0xe40),
INTC_VECT(HSPI, 0xe80),
INTC_VECT(GPIO0, 0xea0), INTC_VECT(GPIO1, 0xec0),
INTC_VECT(Thermal, 0xee0),
INTC_VECT(INTICI0, 0xf00), INTC_VECT(INTICI1, 0xf20),
INTC_VECT(INTICI2, 0xf40), INTC_VECT(INTICI3, 0xf60),
INTC_VECT(INTICI4, 0xf80), INTC_VECT(INTICI5, 0xfa0),
INTC_VECT(INTICI6, 0xfc0), INTC_VECT(INTICI7, 0xfe0),
};
#define CnINTMSK0 0xfe410030
#define CnINTMSK1 0xfe410040
#define CnINTMSKCLR0 0xfe410050
#define CnINTMSKCLR1 0xfe410060
#define CnINT2MSKR0 0xfe410a20
#define CnINT2MSKR1 0xfe410a24
#define CnINT2MSKR2 0xfe410a28
#define CnINT2MSKR3 0xfe410a2c
#define CnINT2MSKCR0 0xfe410a30
#define CnINT2MSKCR1 0xfe410a34
#define CnINT2MSKCR2 0xfe410a38
#define CnINT2MSKCR3 0xfe410a3c
#define INTMSK2 0xfe410068
#define INTMSKCLR2 0xfe41006c
#define INTDISTCR0 0xfe4100b0
#define INTDISTCR1 0xfe4100b4
#define INT2DISTCR0 0xfe410900
#define INT2DISTCR1 0xfe410904
#define INT2DISTCR2 0xfe410908
#define INT2DISTCR3 0xfe41090c
static struct intc_mask_reg sh7786_mask_registers[] __initdata = {
{ CnINTMSK0, CnINTMSKCLR0, 32,
{ IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7 },
INTC_SMP_BALANCING(INTDISTCR0) },
{ INTMSK2, INTMSKCLR2, 32,
{ IRL0_LLLL, IRL0_LLLH, IRL0_LLHL, IRL0_LLHH,
IRL0_LHLL, IRL0_LHLH, IRL0_LHHL, IRL0_LHHH,
IRL0_HLLL, IRL0_HLLH, IRL0_HLHL, IRL0_HLHH,
IRL0_HHLL, IRL0_HHLH, IRL0_HHHL, 0,
IRL4_LLLL, IRL4_LLLH, IRL4_LLHL, IRL4_LLHH,
IRL4_LHLL, IRL4_LHLH, IRL4_LHHL, IRL4_LHHH,
IRL4_HLLL, IRL4_HLLH, IRL4_HLHL, IRL4_HLHH,
IRL4_HHLL, IRL4_HHLH, IRL4_HHHL, 0, } },
{ CnINT2MSKR0, CnINT2MSKCR0 , 32,
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, WDT },
INTC_SMP_BALANCING(INT2DISTCR0) },
{ CnINT2MSKR1, CnINT2MSKCR1, 32,
{ TMU0_0, TMU0_1, TMU0_2, TMU0_3, TMU1_0, TMU1_1, TMU1_2, 0,
DMAC0_0, DMAC0_1, DMAC0_2, DMAC0_3, DMAC0_4, DMAC0_5, DMAC0_6,
HUDI1, HUDI0,
DMAC1_0, DMAC1_1, DMAC1_2, DMAC1_3,
HPB_0, HPB_1, HPB_2,
SCIF0_0, SCIF0_1, SCIF0_2, SCIF0_3,
SCIF1,
TMU2, TMU3, 0, }, INTC_SMP_BALANCING(INT2DISTCR1) },
{ CnINT2MSKR2, CnINT2MSKCR2, 32,
{ 0, 0, SCIF2, SCIF3, SCIF4, SCIF5,
Eth_0, Eth_1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
PCIeC0_0, PCIeC0_1, PCIeC0_2,
PCIeC1_0, PCIeC1_1, PCIeC1_2,
USB, 0, 0 }, INTC_SMP_BALANCING(INT2DISTCR2) },
{ CnINT2MSKR3, CnINT2MSKCR3, 32,
{ 0, 0, 0, 0, 0, 0,
I2C0, I2C1,
DU, SSI0, SSI1, SSI2, SSI3,
PCIeC2_0, PCIeC2_1, PCIeC2_2,
HAC0, HAC1,
FLCTL, 0,
HSPI, GPIO0, GPIO1, Thermal,
0, 0, 0, 0, 0, 0, 0, 0 }, INTC_SMP_BALANCING(INT2DISTCR3) },
};
static struct intc_prio_reg sh7786_prio_registers[] __initdata = {
{ 0xfe410010, 0, 32, 4, /* INTPRI */ { IRQ0, IRQ1, IRQ2, IRQ3,
IRQ4, IRQ5, IRQ6, IRQ7 } },
{ 0xfe410800, 0, 32, 8, /* INT2PRI0 */ { 0, 0, 0, WDT } },
{ 0xfe410804, 0, 32, 8, /* INT2PRI1 */ { TMU0_0, TMU0_1,
TMU0_2, TMU0_3 } },
{ 0xfe410808, 0, 32, 8, /* INT2PRI2 */ { TMU1_0, TMU1_1,
TMU1_2, 0 } },
{ 0xfe41080c, 0, 32, 8, /* INT2PRI3 */ { DMAC0_0, DMAC0_1,
DMAC0_2, DMAC0_3 } },
{ 0xfe410810, 0, 32, 8, /* INT2PRI4 */ { DMAC0_4, DMAC0_5,
DMAC0_6, HUDI1 } },
{ 0xfe410814, 0, 32, 8, /* INT2PRI5 */ { HUDI0, DMAC1_0,
DMAC1_1, DMAC1_2 } },
{ 0xfe410818, 0, 32, 8, /* INT2PRI6 */ { DMAC1_3, HPB_0,
HPB_1, HPB_2 } },
{ 0xfe41081c, 0, 32, 8, /* INT2PRI7 */ { SCIF0_0, SCIF0_1,
SCIF0_2, SCIF0_3 } },
{ 0xfe410820, 0, 32, 8, /* INT2PRI8 */ { SCIF1, TMU2, TMU3, 0 } },
{ 0xfe410824, 0, 32, 8, /* INT2PRI9 */ { 0, 0, SCIF2, SCIF3 } },
{ 0xfe410828, 0, 32, 8, /* INT2PRI10 */ { SCIF4, SCIF5,
Eth_0, Eth_1 } },
{ 0xfe41082c, 0, 32, 8, /* INT2PRI11 */ { 0, 0, 0, 0 } },
{ 0xfe410830, 0, 32, 8, /* INT2PRI12 */ { 0, 0, 0, 0 } },
{ 0xfe410834, 0, 32, 8, /* INT2PRI13 */ { 0, 0, 0, 0 } },
{ 0xfe410838, 0, 32, 8, /* INT2PRI14 */ { 0, 0, 0, PCIeC0_0 } },
{ 0xfe41083c, 0, 32, 8, /* INT2PRI15 */ { PCIeC0_1, PCIeC0_2,
PCIeC1_0, PCIeC1_1 } },
{ 0xfe410840, 0, 32, 8, /* INT2PRI16 */ { PCIeC1_2, USB, 0, 0 } },
{ 0xfe410844, 0, 32, 8, /* INT2PRI17 */ { 0, 0, 0, 0 } },
{ 0xfe410848, 0, 32, 8, /* INT2PRI18 */ { 0, 0, I2C0, I2C1 } },
{ 0xfe41084c, 0, 32, 8, /* INT2PRI19 */ { DU, SSI0, SSI1, SSI2 } },
{ 0xfe410850, 0, 32, 8, /* INT2PRI20 */ { SSI3, PCIeC2_0,
PCIeC2_1, PCIeC2_2 } },
{ 0xfe410854, 0, 32, 8, /* INT2PRI21 */ { HAC0, HAC1, FLCTL, 0 } },
{ 0xfe410858, 0, 32, 8, /* INT2PRI22 */ { HSPI, GPIO0,
GPIO1, Thermal } },
{ 0xfe41085c, 0, 32, 8, /* INT2PRI23 */ { 0, 0, 0, 0 } },
{ 0xfe410860, 0, 32, 8, /* INT2PRI24 */ { 0, 0, 0, 0 } },
{ 0xfe410090, 0xfe4100a0, 32, 4, /* CnICIPRI / CnICIPRICLR */
{ INTICI7, INTICI6, INTICI5, INTICI4,
INTICI3, INTICI2, INTICI1, INTICI0 }, INTC_SMP(4, 2) },
};
static struct intc_subgroup sh7786_subgroups[] __initdata = {
{ 0xfe410c20, 32, SCIF1,
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TXI1, BRI1, RXI1, ERI1 } },
};
static struct intc_desc sh7786_intc_desc __initdata = {
.name = "sh7786",
.hw = {
.vectors = sh7786_vectors,
.nr_vectors = ARRAY_SIZE(sh7786_vectors),
.mask_regs = sh7786_mask_registers,
.nr_mask_regs = ARRAY_SIZE(sh7786_mask_registers),
.subgroups = sh7786_subgroups,
.nr_subgroups = ARRAY_SIZE(sh7786_subgroups),
.prio_regs = sh7786_prio_registers,
.nr_prio_regs = ARRAY_SIZE(sh7786_prio_registers),
},
};
/* Support for external interrupt pins in IRQ mode */
static struct intc_vect vectors_irq0123[] __initdata = {
INTC_VECT(IRQ0, 0x200), INTC_VECT(IRQ1, 0x240),
INTC_VECT(IRQ2, 0x280), INTC_VECT(IRQ3, 0x2c0),
};
static struct intc_vect vectors_irq4567[] __initdata = {
INTC_VECT(IRQ4, 0x300), INTC_VECT(IRQ5, 0x340),
INTC_VECT(IRQ6, 0x380), INTC_VECT(IRQ7, 0x3c0),
};
static struct intc_sense_reg sh7786_sense_registers[] __initdata = {
{ 0xfe41001c, 32, 2, /* ICR1 */ { IRQ0, IRQ1, IRQ2, IRQ3,
IRQ4, IRQ5, IRQ6, IRQ7 } },
};
static struct intc_mask_reg sh7786_ack_registers[] __initdata = {
{ 0xfe410024, 0, 32, /* INTREQ */
{ IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7 } },
};
static DECLARE_INTC_DESC_ACK(intc_desc_irq0123, "sh7786-irq0123",
vectors_irq0123, NULL, sh7786_mask_registers,
sh7786_prio_registers, sh7786_sense_registers,
sh7786_ack_registers);
static DECLARE_INTC_DESC_ACK(intc_desc_irq4567, "sh7786-irq4567",
vectors_irq4567, NULL, sh7786_mask_registers,
sh7786_prio_registers, sh7786_sense_registers,
sh7786_ack_registers);
/* External interrupt pins in IRL mode */
static struct intc_vect vectors_irl0123[] __initdata = {
INTC_VECT(IRL0_LLLL, 0x200), INTC_VECT(IRL0_LLLH, 0x220),
INTC_VECT(IRL0_LLHL, 0x240), INTC_VECT(IRL0_LLHH, 0x260),
INTC_VECT(IRL0_LHLL, 0x280), INTC_VECT(IRL0_LHLH, 0x2a0),
INTC_VECT(IRL0_LHHL, 0x2c0), INTC_VECT(IRL0_LHHH, 0x2e0),
INTC_VECT(IRL0_HLLL, 0x300), INTC_VECT(IRL0_HLLH, 0x320),
INTC_VECT(IRL0_HLHL, 0x340), INTC_VECT(IRL0_HLHH, 0x360),
INTC_VECT(IRL0_HHLL, 0x380), INTC_VECT(IRL0_HHLH, 0x3a0),
INTC_VECT(IRL0_HHHL, 0x3c0),
};
static struct intc_vect vectors_irl4567[] __initdata = {
INTC_VECT(IRL4_LLLL, 0x900), INTC_VECT(IRL4_LLLH, 0x920),
INTC_VECT(IRL4_LLHL, 0x940), INTC_VECT(IRL4_LLHH, 0x960),
INTC_VECT(IRL4_LHLL, 0x980), INTC_VECT(IRL4_LHLH, 0x9a0),
INTC_VECT(IRL4_LHHL, 0x9c0), INTC_VECT(IRL4_LHHH, 0x9e0),
INTC_VECT(IRL4_HLLL, 0xa00), INTC_VECT(IRL4_HLLH, 0xa20),
INTC_VECT(IRL4_HLHL, 0xa40), INTC_VECT(IRL4_HLHH, 0xa60),
INTC_VECT(IRL4_HHLL, 0xa80), INTC_VECT(IRL4_HHLH, 0xaa0),
INTC_VECT(IRL4_HHHL, 0xac0),
};
static DECLARE_INTC_DESC(intc_desc_irl0123, "sh7786-irl0123", vectors_irl0123,
NULL, sh7786_mask_registers, NULL, NULL);
static DECLARE_INTC_DESC(intc_desc_irl4567, "sh7786-irl4567", vectors_irl4567,
NULL, sh7786_mask_registers, NULL, NULL);
#define INTC_ICR0 0xfe410000
#define INTC_INTMSK0 CnINTMSK0
#define INTC_INTMSK1 CnINTMSK1
#define INTC_INTMSK2 INTMSK2
#define INTC_INTMSKCLR1 CnINTMSKCLR1
#define INTC_INTMSKCLR2 INTMSKCLR2
void __init plat_irq_setup(void)
{
/* disable IRQ3-0 + IRQ7-4 */
__raw_writel(0xff000000, INTC_INTMSK0);
/* disable IRL3-0 + IRL7-4 */
__raw_writel(0xc0000000, INTC_INTMSK1);
__raw_writel(0xfffefffe, INTC_INTMSK2);
/* select IRL mode for IRL3-0 + IRL7-4 */
__raw_writel(__raw_readl(INTC_ICR0) & ~0x00c00000, INTC_ICR0);
register_intc_controller(&sh7786_intc_desc);
}
void __init plat_irq_setup_pins(int mode)
{
switch (mode) {
case IRQ_MODE_IRQ7654:
/* select IRQ mode for IRL7-4 */
__raw_writel(__raw_readl(INTC_ICR0) | 0x00400000, INTC_ICR0);
register_intc_controller(&intc_desc_irq4567);
break;
case IRQ_MODE_IRQ3210:
/* select IRQ mode for IRL3-0 */
__raw_writel(__raw_readl(INTC_ICR0) | 0x00800000, INTC_ICR0);
register_intc_controller(&intc_desc_irq0123);
break;
case IRQ_MODE_IRL7654:
/* enable IRL7-4 but don't provide any masking */
__raw_writel(0x40000000, INTC_INTMSKCLR1);
__raw_writel(0x0000fffe, INTC_INTMSKCLR2);
break;
case IRQ_MODE_IRL3210:
/* enable IRL0-3 but don't provide any masking */
__raw_writel(0x80000000, INTC_INTMSKCLR1);
__raw_writel(0xfffe0000, INTC_INTMSKCLR2);
break;
case IRQ_MODE_IRL7654_MASK:
/* enable IRL7-4 and mask using cpu intc controller */
__raw_writel(0x40000000, INTC_INTMSKCLR1);
register_intc_controller(&intc_desc_irl4567);
break;
case IRQ_MODE_IRL3210_MASK:
/* enable IRL0-3 and mask using cpu intc controller */
__raw_writel(0x80000000, INTC_INTMSKCLR1);
register_intc_controller(&intc_desc_irl0123);
break;
default:
BUG();
}
}
void __init plat_mem_setup(void)
{
}
static int __init sh7786_devices_setup(void)
{
int ret, irq;
sh7786_usb_setup();
/*
* De-mux SCIF1 IRQs if possible
*/
irq = intc_irq_lookup(sh7786_intc_desc.name, TXI1);
if (irq > 0) {
scif1_platform_data.irqs[SCIx_TXI_IRQ] = irq;
scif1_platform_data.irqs[SCIx_ERI_IRQ] =
intc_irq_lookup(sh7786_intc_desc.name, ERI1);
scif1_platform_data.irqs[SCIx_BRI_IRQ] =
intc_irq_lookup(sh7786_intc_desc.name, BRI1);
scif1_platform_data.irqs[SCIx_RXI_IRQ] =
intc_irq_lookup(sh7786_intc_desc.name, RXI1);
}
ret = platform_add_devices(sh7786_early_devices,
ARRAY_SIZE(sh7786_early_devices));
if (unlikely(ret != 0))
return ret;
return platform_add_devices(sh7786_devices,
ARRAY_SIZE(sh7786_devices));
}
arch_initcall(sh7786_devices_setup);
void __init plat_early_device_setup(void)
{
early_platform_add_devices(sh7786_early_devices,
ARRAY_SIZE(sh7786_early_devices));
}
| gpl-2.0 |
MotoG3/android_kernel_motorola_msm8916 | fs/hfsplus/ioctl.c | 3361 | 3729 | /*
* linux/fs/hfsplus/ioctl.c
*
* Copyright (C) 2003
* Ethan Benson <erbenson@alaska.net>
* partially derived from linux/fs/ext2/ioctl.c
* Copyright (C) 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* hfsplus ioctls
*/
#include <linux/capability.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include "hfsplus_fs.h"
/*
* "Blessing" an HFS+ filesystem writes metadata to the superblock informing
* the platform firmware which file to boot from
*/
static int hfsplus_ioctl_bless(struct file *file, int __user *user_flags)
{
struct dentry *dentry = file->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct hfsplus_sb_info *sbi = HFSPLUS_SB(inode->i_sb);
struct hfsplus_vh *vh = sbi->s_vhdr;
struct hfsplus_vh *bvh = sbi->s_backup_vhdr;
u32 cnid = (unsigned long)dentry->d_fsdata;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&sbi->vh_mutex);
/* Directory containing the bootable system */
vh->finder_info[0] = bvh->finder_info[0] =
cpu_to_be32(parent_ino(dentry));
/*
* Bootloader. Just using the inode here breaks in the case of
* hard links - the firmware wants the ID of the hard link file,
* but the inode points at the indirect inode
*/
vh->finder_info[1] = bvh->finder_info[1] = cpu_to_be32(cnid);
/* Per spec, the OS X system folder - same as finder_info[0] here */
vh->finder_info[5] = bvh->finder_info[5] =
cpu_to_be32(parent_ino(dentry));
mutex_unlock(&sbi->vh_mutex);
return 0;
}
static int hfsplus_ioctl_getflags(struct file *file, int __user *user_flags)
{
struct inode *inode = file_inode(file);
struct hfsplus_inode_info *hip = HFSPLUS_I(inode);
unsigned int flags = 0;
if (inode->i_flags & S_IMMUTABLE)
flags |= FS_IMMUTABLE_FL;
if (inode->i_flags & S_APPEND)
flags |= FS_APPEND_FL;
if (hip->userflags & HFSPLUS_FLG_NODUMP)
flags |= FS_NODUMP_FL;
return put_user(flags, user_flags);
}
static int hfsplus_ioctl_setflags(struct file *file, int __user *user_flags)
{
struct inode *inode = file_inode(file);
struct hfsplus_inode_info *hip = HFSPLUS_I(inode);
unsigned int flags;
int err = 0;
err = mnt_want_write_file(file);
if (err)
goto out;
if (!inode_owner_or_capable(inode)) {
err = -EACCES;
goto out_drop_write;
}
if (get_user(flags, user_flags)) {
err = -EFAULT;
goto out_drop_write;
}
mutex_lock(&inode->i_mutex);
if ((flags & (FS_IMMUTABLE_FL|FS_APPEND_FL)) ||
inode->i_flags & (S_IMMUTABLE|S_APPEND)) {
if (!capable(CAP_LINUX_IMMUTABLE)) {
err = -EPERM;
goto out_unlock_inode;
}
}
/* don't silently ignore unsupported ext2 flags */
if (flags & ~(FS_IMMUTABLE_FL|FS_APPEND_FL|FS_NODUMP_FL)) {
err = -EOPNOTSUPP;
goto out_unlock_inode;
}
if (flags & FS_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
else
inode->i_flags &= ~S_IMMUTABLE;
if (flags & FS_APPEND_FL)
inode->i_flags |= S_APPEND;
else
inode->i_flags &= ~S_APPEND;
if (flags & FS_NODUMP_FL)
hip->userflags |= HFSPLUS_FLG_NODUMP;
else
hip->userflags &= ~HFSPLUS_FLG_NODUMP;
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
out_unlock_inode:
mutex_unlock(&inode->i_mutex);
out_drop_write:
mnt_drop_write_file(file);
out:
return err;
}
long hfsplus_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
switch (cmd) {
case HFSPLUS_IOC_EXT2_GETFLAGS:
return hfsplus_ioctl_getflags(file, argp);
case HFSPLUS_IOC_EXT2_SETFLAGS:
return hfsplus_ioctl_setflags(file, argp);
case HFSPLUS_IOC_BLESS:
return hfsplus_ioctl_bless(file, argp);
default:
return -ENOTTY;
}
}
| gpl-2.0 |
longsleep/ubuntu-odroidc | drivers/input/mouse/sentelic.c | 3873 | 26464 | /*-
* Finger Sensing Pad PS/2 mouse driver.
*
* Copyright (C) 2005-2007 Asia Vital Components Co., Ltd.
* Copyright (C) 2005-2012 Tai-hwa Liang, Sentelic 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/ctype.h>
#include <linux/libps2.h>
#include <linux/serio.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include "psmouse.h"
#include "sentelic.h"
/*
* Timeout for FSP PS/2 command only (in milliseconds).
*/
#define FSP_CMD_TIMEOUT 200
#define FSP_CMD_TIMEOUT2 30
#define GET_ABS_X(packet) ((packet[1] << 2) | ((packet[3] >> 2) & 0x03))
#define GET_ABS_Y(packet) ((packet[2] << 2) | (packet[3] & 0x03))
/** Driver version. */
static const char fsp_drv_ver[] = "1.1.0-K";
/*
* Make sure that the value being sent to FSP will not conflict with
* possible sample rate values.
*/
static unsigned char fsp_test_swap_cmd(unsigned char reg_val)
{
switch (reg_val) {
case 10: case 20: case 40: case 60: case 80: case 100: case 200:
/*
* The requested value being sent to FSP matched to possible
* sample rates, swap the given value such that the hardware
* wouldn't get confused.
*/
return (reg_val >> 4) | (reg_val << 4);
default:
return reg_val; /* swap isn't necessary */
}
}
/*
* Make sure that the value being sent to FSP will not conflict with certain
* commands.
*/
static unsigned char fsp_test_invert_cmd(unsigned char reg_val)
{
switch (reg_val) {
case 0xe9: case 0xee: case 0xf2: case 0xff:
/*
* The requested value being sent to FSP matched to certain
* commands, inverse the given value such that the hardware
* wouldn't get confused.
*/
return ~reg_val;
default:
return reg_val; /* inversion isn't necessary */
}
}
static int fsp_reg_read(struct psmouse *psmouse, int reg_addr, int *reg_val)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
unsigned char addr;
int rc = -1;
/*
* We need to shut off the device and switch it into command
* mode so we don't confuse our protocol handler. We don't need
* to do that for writes because sysfs set helper does this for
* us.
*/
psmouse_deactivate(psmouse);
ps2_begin_command(ps2dev);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
/* should return 0xfe(request for resending) */
ps2_sendbyte(ps2dev, 0x66, FSP_CMD_TIMEOUT2);
/* should return 0xfc(failed) */
ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
if ((addr = fsp_test_invert_cmd(reg_addr)) != reg_addr) {
ps2_sendbyte(ps2dev, 0x68, FSP_CMD_TIMEOUT2);
} else if ((addr = fsp_test_swap_cmd(reg_addr)) != reg_addr) {
/* swapping is required */
ps2_sendbyte(ps2dev, 0xcc, FSP_CMD_TIMEOUT2);
/* expect 0xfe */
} else {
/* swapping isn't necessary */
ps2_sendbyte(ps2dev, 0x66, FSP_CMD_TIMEOUT2);
/* expect 0xfe */
}
/* should return 0xfc(failed) */
ps2_sendbyte(ps2dev, addr, FSP_CMD_TIMEOUT);
if (__ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO) < 0)
goto out;
*reg_val = param[2];
rc = 0;
out:
ps2_end_command(ps2dev);
psmouse_activate(psmouse);
psmouse_dbg(psmouse,
"READ REG: 0x%02x is 0x%02x (rc = %d)\n",
reg_addr, *reg_val, rc);
return rc;
}
static int fsp_reg_write(struct psmouse *psmouse, int reg_addr, int reg_val)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char v;
int rc = -1;
ps2_begin_command(ps2dev);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
if ((v = fsp_test_invert_cmd(reg_addr)) != reg_addr) {
/* inversion is required */
ps2_sendbyte(ps2dev, 0x74, FSP_CMD_TIMEOUT2);
} else {
if ((v = fsp_test_swap_cmd(reg_addr)) != reg_addr) {
/* swapping is required */
ps2_sendbyte(ps2dev, 0x77, FSP_CMD_TIMEOUT2);
} else {
/* swapping isn't necessary */
ps2_sendbyte(ps2dev, 0x55, FSP_CMD_TIMEOUT2);
}
}
/* write the register address in correct order */
ps2_sendbyte(ps2dev, v, FSP_CMD_TIMEOUT2);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
if ((v = fsp_test_invert_cmd(reg_val)) != reg_val) {
/* inversion is required */
ps2_sendbyte(ps2dev, 0x47, FSP_CMD_TIMEOUT2);
} else if ((v = fsp_test_swap_cmd(reg_val)) != reg_val) {
/* swapping is required */
ps2_sendbyte(ps2dev, 0x44, FSP_CMD_TIMEOUT2);
} else {
/* swapping isn't necessary */
ps2_sendbyte(ps2dev, 0x33, FSP_CMD_TIMEOUT2);
}
/* write the register value in correct order */
ps2_sendbyte(ps2dev, v, FSP_CMD_TIMEOUT2);
rc = 0;
out:
ps2_end_command(ps2dev);
psmouse_dbg(psmouse,
"WRITE REG: 0x%02x to 0x%02x (rc = %d)\n",
reg_addr, reg_val, rc);
return rc;
}
/* Enable register clock gating for writing certain registers */
static int fsp_reg_write_enable(struct psmouse *psmouse, bool enable)
{
int v, nv;
if (fsp_reg_read(psmouse, FSP_REG_SYSCTL1, &v) == -1)
return -1;
if (enable)
nv = v | FSP_BIT_EN_REG_CLK;
else
nv = v & ~FSP_BIT_EN_REG_CLK;
/* only write if necessary */
if (nv != v)
if (fsp_reg_write(psmouse, FSP_REG_SYSCTL1, nv) == -1)
return -1;
return 0;
}
static int fsp_page_reg_read(struct psmouse *psmouse, int *reg_val)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
int rc = -1;
psmouse_deactivate(psmouse);
ps2_begin_command(ps2dev);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
ps2_sendbyte(ps2dev, 0x66, FSP_CMD_TIMEOUT2);
ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
ps2_sendbyte(ps2dev, 0x83, FSP_CMD_TIMEOUT2);
ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2);
/* get the returned result */
if (__ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO))
goto out;
*reg_val = param[2];
rc = 0;
out:
ps2_end_command(ps2dev);
psmouse_activate(psmouse);
psmouse_dbg(psmouse,
"READ PAGE REG: 0x%02x (rc = %d)\n",
*reg_val, rc);
return rc;
}
static int fsp_page_reg_write(struct psmouse *psmouse, int reg_val)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char v;
int rc = -1;
ps2_begin_command(ps2dev);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
ps2_sendbyte(ps2dev, 0x38, FSP_CMD_TIMEOUT2);
ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2);
if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0)
goto out;
if ((v = fsp_test_invert_cmd(reg_val)) != reg_val) {
ps2_sendbyte(ps2dev, 0x47, FSP_CMD_TIMEOUT2);
} else if ((v = fsp_test_swap_cmd(reg_val)) != reg_val) {
/* swapping is required */
ps2_sendbyte(ps2dev, 0x44, FSP_CMD_TIMEOUT2);
} else {
/* swapping isn't necessary */
ps2_sendbyte(ps2dev, 0x33, FSP_CMD_TIMEOUT2);
}
ps2_sendbyte(ps2dev, v, FSP_CMD_TIMEOUT2);
rc = 0;
out:
ps2_end_command(ps2dev);
psmouse_dbg(psmouse,
"WRITE PAGE REG: to 0x%02x (rc = %d)\n",
reg_val, rc);
return rc;
}
static int fsp_get_version(struct psmouse *psmouse, int *version)
{
if (fsp_reg_read(psmouse, FSP_REG_VERSION, version))
return -EIO;
return 0;
}
static int fsp_get_revision(struct psmouse *psmouse, int *rev)
{
if (fsp_reg_read(psmouse, FSP_REG_REVISION, rev))
return -EIO;
return 0;
}
static int fsp_get_sn(struct psmouse *psmouse, int *sn)
{
int v0, v1, v2;
int rc = -EIO;
/* production number since Cx is available at: 0x0b40 ~ 0x0b42 */
if (fsp_page_reg_write(psmouse, FSP_PAGE_0B))
goto out;
if (fsp_reg_read(psmouse, FSP_REG_SN0, &v0))
goto out;
if (fsp_reg_read(psmouse, FSP_REG_SN1, &v1))
goto out;
if (fsp_reg_read(psmouse, FSP_REG_SN2, &v2))
goto out;
*sn = (v0 << 16) | (v1 << 8) | v2;
rc = 0;
out:
fsp_page_reg_write(psmouse, FSP_PAGE_DEFAULT);
return rc;
}
static int fsp_get_buttons(struct psmouse *psmouse, int *btn)
{
static const int buttons[] = {
0x16, /* Left/Middle/Right/Forward/Backward & Scroll Up/Down */
0x06, /* Left/Middle/Right & Scroll Up/Down/Right/Left */
0x04, /* Left/Middle/Right & Scroll Up/Down */
0x02, /* Left/Middle/Right */
};
int val;
if (fsp_reg_read(psmouse, FSP_REG_TMOD_STATUS, &val) == -1)
return -EIO;
*btn = buttons[(val & 0x30) >> 4];
return 0;
}
/* Enable on-pad command tag output */
static int fsp_opc_tag_enable(struct psmouse *psmouse, bool enable)
{
int v, nv;
int res = 0;
if (fsp_reg_read(psmouse, FSP_REG_OPC_QDOWN, &v) == -1) {
psmouse_err(psmouse, "Unable get OPC state.\n");
return -EIO;
}
if (enable)
nv = v | FSP_BIT_EN_OPC_TAG;
else
nv = v & ~FSP_BIT_EN_OPC_TAG;
/* only write if necessary */
if (nv != v) {
fsp_reg_write_enable(psmouse, true);
res = fsp_reg_write(psmouse, FSP_REG_OPC_QDOWN, nv);
fsp_reg_write_enable(psmouse, false);
}
if (res != 0) {
psmouse_err(psmouse, "Unable to enable OPC tag.\n");
res = -EIO;
}
return res;
}
static int fsp_onpad_vscr(struct psmouse *psmouse, bool enable)
{
struct fsp_data *pad = psmouse->private;
int val;
if (fsp_reg_read(psmouse, FSP_REG_ONPAD_CTL, &val))
return -EIO;
pad->vscroll = enable;
if (enable)
val |= (FSP_BIT_FIX_VSCR | FSP_BIT_ONPAD_ENABLE);
else
val &= ~FSP_BIT_FIX_VSCR;
if (fsp_reg_write(psmouse, FSP_REG_ONPAD_CTL, val))
return -EIO;
return 0;
}
static int fsp_onpad_hscr(struct psmouse *psmouse, bool enable)
{
struct fsp_data *pad = psmouse->private;
int val, v2;
if (fsp_reg_read(psmouse, FSP_REG_ONPAD_CTL, &val))
return -EIO;
if (fsp_reg_read(psmouse, FSP_REG_SYSCTL5, &v2))
return -EIO;
pad->hscroll = enable;
if (enable) {
val |= (FSP_BIT_FIX_HSCR | FSP_BIT_ONPAD_ENABLE);
v2 |= FSP_BIT_EN_MSID6;
} else {
val &= ~FSP_BIT_FIX_HSCR;
v2 &= ~(FSP_BIT_EN_MSID6 | FSP_BIT_EN_MSID7 | FSP_BIT_EN_MSID8);
}
if (fsp_reg_write(psmouse, FSP_REG_ONPAD_CTL, val))
return -EIO;
/* reconfigure horizontal scrolling packet output */
if (fsp_reg_write(psmouse, FSP_REG_SYSCTL5, v2))
return -EIO;
return 0;
}
/*
* Write device specific initial parameters.
*
* ex: 0xab 0xcd - write oxcd into register 0xab
*/
static ssize_t fsp_attr_set_setreg(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
int reg, val;
char *rest;
ssize_t retval;
reg = simple_strtoul(buf, &rest, 16);
if (rest == buf || *rest != ' ' || reg > 0xff)
return -EINVAL;
retval = kstrtoint(rest + 1, 16, &val);
if (retval)
return retval;
if (val > 0xff)
return -EINVAL;
if (fsp_reg_write_enable(psmouse, true))
return -EIO;
retval = fsp_reg_write(psmouse, reg, val) < 0 ? -EIO : count;
fsp_reg_write_enable(psmouse, false);
return count;
}
PSMOUSE_DEFINE_WO_ATTR(setreg, S_IWUSR, NULL, fsp_attr_set_setreg);
static ssize_t fsp_attr_show_getreg(struct psmouse *psmouse,
void *data, char *buf)
{
struct fsp_data *pad = psmouse->private;
return sprintf(buf, "%02x%02x\n", pad->last_reg, pad->last_val);
}
/*
* Read a register from device.
*
* ex: 0xab -- read content from register 0xab
*/
static ssize_t fsp_attr_set_getreg(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct fsp_data *pad = psmouse->private;
int reg, val, err;
err = kstrtoint(buf, 16, ®);
if (err)
return err;
if (reg > 0xff)
return -EINVAL;
if (fsp_reg_read(psmouse, reg, &val))
return -EIO;
pad->last_reg = reg;
pad->last_val = val;
return count;
}
PSMOUSE_DEFINE_ATTR(getreg, S_IWUSR | S_IRUGO, NULL,
fsp_attr_show_getreg, fsp_attr_set_getreg);
static ssize_t fsp_attr_show_pagereg(struct psmouse *psmouse,
void *data, char *buf)
{
int val = 0;
if (fsp_page_reg_read(psmouse, &val))
return -EIO;
return sprintf(buf, "%02x\n", val);
}
static ssize_t fsp_attr_set_pagereg(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
int val, err;
err = kstrtoint(buf, 16, &val);
if (err)
return err;
if (val > 0xff)
return -EINVAL;
if (fsp_page_reg_write(psmouse, val))
return -EIO;
return count;
}
PSMOUSE_DEFINE_ATTR(page, S_IWUSR | S_IRUGO, NULL,
fsp_attr_show_pagereg, fsp_attr_set_pagereg);
static ssize_t fsp_attr_show_vscroll(struct psmouse *psmouse,
void *data, char *buf)
{
struct fsp_data *pad = psmouse->private;
return sprintf(buf, "%d\n", pad->vscroll);
}
static ssize_t fsp_attr_set_vscroll(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
unsigned int val;
int err;
err = kstrtouint(buf, 10, &val);
if (err)
return err;
if (val > 1)
return -EINVAL;
fsp_onpad_vscr(psmouse, val);
return count;
}
PSMOUSE_DEFINE_ATTR(vscroll, S_IWUSR | S_IRUGO, NULL,
fsp_attr_show_vscroll, fsp_attr_set_vscroll);
static ssize_t fsp_attr_show_hscroll(struct psmouse *psmouse,
void *data, char *buf)
{
struct fsp_data *pad = psmouse->private;
return sprintf(buf, "%d\n", pad->hscroll);
}
static ssize_t fsp_attr_set_hscroll(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
unsigned int val;
int err;
err = kstrtouint(buf, 10, &val);
if (err)
return err;
if (val > 1)
return -EINVAL;
fsp_onpad_hscr(psmouse, val);
return count;
}
PSMOUSE_DEFINE_ATTR(hscroll, S_IWUSR | S_IRUGO, NULL,
fsp_attr_show_hscroll, fsp_attr_set_hscroll);
static ssize_t fsp_attr_show_flags(struct psmouse *psmouse,
void *data, char *buf)
{
struct fsp_data *pad = psmouse->private;
return sprintf(buf, "%c\n",
pad->flags & FSPDRV_FLAG_EN_OPC ? 'C' : 'c');
}
static ssize_t fsp_attr_set_flags(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct fsp_data *pad = psmouse->private;
size_t i;
for (i = 0; i < count; i++) {
switch (buf[i]) {
case 'C':
pad->flags |= FSPDRV_FLAG_EN_OPC;
break;
case 'c':
pad->flags &= ~FSPDRV_FLAG_EN_OPC;
break;
default:
return -EINVAL;
}
}
return count;
}
PSMOUSE_DEFINE_ATTR(flags, S_IWUSR | S_IRUGO, NULL,
fsp_attr_show_flags, fsp_attr_set_flags);
static ssize_t fsp_attr_show_ver(struct psmouse *psmouse,
void *data, char *buf)
{
return sprintf(buf, "Sentelic FSP kernel module %s\n", fsp_drv_ver);
}
PSMOUSE_DEFINE_RO_ATTR(ver, S_IRUGO, NULL, fsp_attr_show_ver);
static struct attribute *fsp_attributes[] = {
&psmouse_attr_setreg.dattr.attr,
&psmouse_attr_getreg.dattr.attr,
&psmouse_attr_page.dattr.attr,
&psmouse_attr_vscroll.dattr.attr,
&psmouse_attr_hscroll.dattr.attr,
&psmouse_attr_flags.dattr.attr,
&psmouse_attr_ver.dattr.attr,
NULL
};
static struct attribute_group fsp_attribute_group = {
.attrs = fsp_attributes,
};
#ifdef FSP_DEBUG
static void fsp_packet_debug(struct psmouse *psmouse, unsigned char packet[])
{
static unsigned int ps2_packet_cnt;
static unsigned int ps2_last_second;
unsigned int jiffies_msec;
const char *packet_type = "UNKNOWN";
unsigned short abs_x = 0, abs_y = 0;
/* Interpret & dump the packet data. */
switch (packet[0] >> FSP_PKT_TYPE_SHIFT) {
case FSP_PKT_TYPE_ABS:
packet_type = "Absolute";
abs_x = GET_ABS_X(packet);
abs_y = GET_ABS_Y(packet);
break;
case FSP_PKT_TYPE_NORMAL:
packet_type = "Normal";
break;
case FSP_PKT_TYPE_NOTIFY:
packet_type = "Notify";
break;
case FSP_PKT_TYPE_NORMAL_OPC:
packet_type = "Normal-OPC";
break;
}
ps2_packet_cnt++;
jiffies_msec = jiffies_to_msecs(jiffies);
psmouse_dbg(psmouse,
"%08dms %s packets: %02x, %02x, %02x, %02x; "
"abs_x: %d, abs_y: %d\n",
jiffies_msec, packet_type,
packet[0], packet[1], packet[2], packet[3], abs_x, abs_y);
if (jiffies_msec - ps2_last_second > 1000) {
psmouse_dbg(psmouse, "PS/2 packets/sec = %d\n", ps2_packet_cnt);
ps2_packet_cnt = 0;
ps2_last_second = jiffies_msec;
}
}
#else
static void fsp_packet_debug(struct psmouse *psmouse, unsigned char packet[])
{
}
#endif
static void fsp_set_slot(struct input_dev *dev, int slot, bool active,
unsigned int x, unsigned int y)
{
input_mt_slot(dev, slot);
input_mt_report_slot_state(dev, MT_TOOL_FINGER, active);
if (active) {
input_report_abs(dev, ABS_MT_POSITION_X, x);
input_report_abs(dev, ABS_MT_POSITION_Y, y);
}
}
static psmouse_ret_t fsp_process_byte(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct fsp_data *ad = psmouse->private;
unsigned char *packet = psmouse->packet;
unsigned char button_status = 0, lscroll = 0, rscroll = 0;
unsigned short abs_x, abs_y, fgrs = 0;
int rel_x, rel_y;
if (psmouse->pktcnt < 4)
return PSMOUSE_GOOD_DATA;
/*
* Full packet accumulated, process it
*/
fsp_packet_debug(psmouse, packet);
switch (psmouse->packet[0] >> FSP_PKT_TYPE_SHIFT) {
case FSP_PKT_TYPE_ABS:
if ((packet[0] == 0x48 || packet[0] == 0x49) &&
packet[1] == 0 && packet[2] == 0) {
/*
* Ignore coordinate noise when finger leaving the
* surface, otherwise cursor may jump to upper-left
* corner.
*/
packet[3] &= 0xf0;
}
abs_x = GET_ABS_X(packet);
abs_y = GET_ABS_Y(packet);
if (packet[0] & FSP_PB0_MFMC) {
/*
* MFMC packet: assume that there are two fingers on
* pad
*/
fgrs = 2;
/* MFMC packet */
if (packet[0] & FSP_PB0_MFMC_FGR2) {
/* 2nd finger */
if (ad->last_mt_fgr == 2) {
/*
* workaround for buggy firmware
* which doesn't clear MFMC bit if
* the 1st finger is up
*/
fgrs = 1;
fsp_set_slot(dev, 0, false, 0, 0);
}
ad->last_mt_fgr = 2;
fsp_set_slot(dev, 1, fgrs == 2, abs_x, abs_y);
} else {
/* 1st finger */
if (ad->last_mt_fgr == 1) {
/*
* workaround for buggy firmware
* which doesn't clear MFMC bit if
* the 2nd finger is up
*/
fgrs = 1;
fsp_set_slot(dev, 1, false, 0, 0);
}
ad->last_mt_fgr = 1;
fsp_set_slot(dev, 0, fgrs != 0, abs_x, abs_y);
}
} else {
/* SFAC packet */
if ((packet[0] & (FSP_PB0_LBTN|FSP_PB0_PHY_BTN)) ==
FSP_PB0_LBTN) {
/* On-pad click in SFAC mode should be handled
* by userspace. On-pad clicks in MFMC mode
* are real clickpad clicks, and not ignored.
*/
packet[0] &= ~FSP_PB0_LBTN;
}
/* no multi-finger information */
ad->last_mt_fgr = 0;
if (abs_x != 0 && abs_y != 0)
fgrs = 1;
fsp_set_slot(dev, 0, fgrs > 0, abs_x, abs_y);
fsp_set_slot(dev, 1, false, 0, 0);
}
if (fgrs == 1 || (fgrs == 2 && !(packet[0] & FSP_PB0_MFMC_FGR2))) {
input_report_abs(dev, ABS_X, abs_x);
input_report_abs(dev, ABS_Y, abs_y);
}
input_report_key(dev, BTN_LEFT, packet[0] & 0x01);
input_report_key(dev, BTN_RIGHT, packet[0] & 0x02);
input_report_key(dev, BTN_TOUCH, fgrs);
input_report_key(dev, BTN_TOOL_FINGER, fgrs == 1);
input_report_key(dev, BTN_TOOL_DOUBLETAP, fgrs == 2);
break;
case FSP_PKT_TYPE_NORMAL_OPC:
/* on-pad click, filter it if necessary */
if ((ad->flags & FSPDRV_FLAG_EN_OPC) != FSPDRV_FLAG_EN_OPC)
packet[0] &= ~FSP_PB0_LBTN;
/* fall through */
case FSP_PKT_TYPE_NORMAL:
/* normal packet */
/* special packet data translation from on-pad packets */
if (packet[3] != 0) {
if (packet[3] & BIT(0))
button_status |= 0x01; /* wheel down */
if (packet[3] & BIT(1))
button_status |= 0x0f; /* wheel up */
if (packet[3] & BIT(2))
button_status |= BIT(4);/* horizontal left */
if (packet[3] & BIT(3))
button_status |= BIT(5);/* horizontal right */
/* push back to packet queue */
if (button_status != 0)
packet[3] = button_status;
rscroll = (packet[3] >> 4) & 1;
lscroll = (packet[3] >> 5) & 1;
}
/*
* Processing wheel up/down and extra button events
*/
input_report_rel(dev, REL_WHEEL,
(int)(packet[3] & 8) - (int)(packet[3] & 7));
input_report_rel(dev, REL_HWHEEL, lscroll - rscroll);
input_report_key(dev, BTN_BACK, lscroll);
input_report_key(dev, BTN_FORWARD, rscroll);
/*
* Standard PS/2 Mouse
*/
input_report_key(dev, BTN_LEFT, packet[0] & 1);
input_report_key(dev, BTN_MIDDLE, (packet[0] >> 2) & 1);
input_report_key(dev, BTN_RIGHT, (packet[0] >> 1) & 1);
rel_x = packet[1] ? (int)packet[1] - (int)((packet[0] << 4) & 0x100) : 0;
rel_y = packet[2] ? (int)((packet[0] << 3) & 0x100) - (int)packet[2] : 0;
input_report_rel(dev, REL_X, rel_x);
input_report_rel(dev, REL_Y, rel_y);
break;
}
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
static int fsp_activate_protocol(struct psmouse *psmouse)
{
struct fsp_data *pad = psmouse->private;
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[2];
int val;
/*
* Standard procedure to enter FSP Intellimouse mode
* (scrolling wheel, 4th and 5th buttons)
*/
param[0] = 200;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE);
param[0] = 200;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE);
param[0] = 80;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE);
ps2_command(ps2dev, param, PSMOUSE_CMD_GETID);
if (param[0] != 0x04) {
psmouse_err(psmouse,
"Unable to enable 4 bytes packet format.\n");
return -EIO;
}
if (pad->ver < FSP_VER_STL3888_C0) {
/* Preparing relative coordinates output for older hardware */
if (fsp_reg_read(psmouse, FSP_REG_SYSCTL5, &val)) {
psmouse_err(psmouse,
"Unable to read SYSCTL5 register.\n");
return -EIO;
}
if (fsp_get_buttons(psmouse, &pad->buttons)) {
psmouse_err(psmouse,
"Unable to retrieve number of buttons.\n");
return -EIO;
}
val &= ~(FSP_BIT_EN_MSID7 | FSP_BIT_EN_MSID8 | FSP_BIT_EN_AUTO_MSID8);
/* Ensure we are not in absolute mode */
val &= ~FSP_BIT_EN_PKT_G0;
if (pad->buttons == 0x06) {
/* Left/Middle/Right & Scroll Up/Down/Right/Left */
val |= FSP_BIT_EN_MSID6;
}
if (fsp_reg_write(psmouse, FSP_REG_SYSCTL5, val)) {
psmouse_err(psmouse,
"Unable to set up required mode bits.\n");
return -EIO;
}
/*
* Enable OPC tags such that driver can tell the difference
* between on-pad and real button click
*/
if (fsp_opc_tag_enable(psmouse, true))
psmouse_warn(psmouse,
"Failed to enable OPC tag mode.\n");
/* enable on-pad click by default */
pad->flags |= FSPDRV_FLAG_EN_OPC;
/* Enable on-pad vertical and horizontal scrolling */
fsp_onpad_vscr(psmouse, true);
fsp_onpad_hscr(psmouse, true);
} else {
/* Enable absolute coordinates output for Cx/Dx hardware */
if (fsp_reg_write(psmouse, FSP_REG_SWC1,
FSP_BIT_SWC1_EN_ABS_1F |
FSP_BIT_SWC1_EN_ABS_2F |
FSP_BIT_SWC1_EN_FUP_OUT |
FSP_BIT_SWC1_EN_ABS_CON)) {
psmouse_err(psmouse,
"Unable to enable absolute coordinates output.\n");
return -EIO;
}
}
return 0;
}
static int fsp_set_input_params(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct fsp_data *pad = psmouse->private;
if (pad->ver < FSP_VER_STL3888_C0) {
__set_bit(BTN_MIDDLE, dev->keybit);
__set_bit(BTN_BACK, dev->keybit);
__set_bit(BTN_FORWARD, dev->keybit);
__set_bit(REL_WHEEL, dev->relbit);
__set_bit(REL_HWHEEL, dev->relbit);
} else {
/*
* Hardware prior to Cx performs much better in relative mode;
* hence, only enable absolute coordinates output as well as
* multi-touch output for the newer hardware.
*
* Maximum coordinates can be computed as:
*
* number of scanlines * 64 - 57
*
* where number of X/Y scanline lines are 16/12.
*/
int abs_x = 967, abs_y = 711;
__set_bit(EV_ABS, dev->evbit);
__clear_bit(EV_REL, dev->evbit);
__set_bit(BTN_TOUCH, dev->keybit);
__set_bit(BTN_TOOL_FINGER, dev->keybit);
__set_bit(BTN_TOOL_DOUBLETAP, dev->keybit);
__set_bit(INPUT_PROP_SEMI_MT, dev->propbit);
input_set_abs_params(dev, ABS_X, 0, abs_x, 0, 0);
input_set_abs_params(dev, ABS_Y, 0, abs_y, 0, 0);
input_mt_init_slots(dev, 2, 0);
input_set_abs_params(dev, ABS_MT_POSITION_X, 0, abs_x, 0, 0);
input_set_abs_params(dev, ABS_MT_POSITION_Y, 0, abs_y, 0, 0);
}
return 0;
}
int fsp_detect(struct psmouse *psmouse, bool set_properties)
{
int id;
if (fsp_reg_read(psmouse, FSP_REG_DEVICE_ID, &id))
return -EIO;
if (id != 0x01)
return -ENODEV;
if (set_properties) {
psmouse->vendor = "Sentelic";
psmouse->name = "FingerSensingPad";
}
return 0;
}
static void fsp_reset(struct psmouse *psmouse)
{
fsp_opc_tag_enable(psmouse, false);
fsp_onpad_vscr(psmouse, false);
fsp_onpad_hscr(psmouse, false);
}
static void fsp_disconnect(struct psmouse *psmouse)
{
sysfs_remove_group(&psmouse->ps2dev.serio->dev.kobj,
&fsp_attribute_group);
fsp_reset(psmouse);
kfree(psmouse->private);
}
static int fsp_reconnect(struct psmouse *psmouse)
{
int version;
if (fsp_detect(psmouse, 0))
return -ENODEV;
if (fsp_get_version(psmouse, &version))
return -ENODEV;
if (fsp_activate_protocol(psmouse))
return -EIO;
return 0;
}
int fsp_init(struct psmouse *psmouse)
{
struct fsp_data *priv;
int ver, rev, sn = 0;
int error;
if (fsp_get_version(psmouse, &ver) ||
fsp_get_revision(psmouse, &rev)) {
return -ENODEV;
}
if (ver >= FSP_VER_STL3888_C0) {
/* firmware information is only available since C0 */
fsp_get_sn(psmouse, &sn);
}
psmouse_info(psmouse,
"Finger Sensing Pad, hw: %d.%d.%d, sn: %x, sw: %s\n",
ver >> 4, ver & 0x0F, rev, sn, fsp_drv_ver);
psmouse->private = priv = kzalloc(sizeof(struct fsp_data), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->ver = ver;
priv->rev = rev;
psmouse->protocol_handler = fsp_process_byte;
psmouse->disconnect = fsp_disconnect;
psmouse->reconnect = fsp_reconnect;
psmouse->cleanup = fsp_reset;
psmouse->pktsize = 4;
error = fsp_activate_protocol(psmouse);
if (error)
goto err_out;
/* Set up various supported input event bits */
error = fsp_set_input_params(psmouse);
if (error)
goto err_out;
error = sysfs_create_group(&psmouse->ps2dev.serio->dev.kobj,
&fsp_attribute_group);
if (error) {
psmouse_err(psmouse,
"Failed to create sysfs attributes (%d)", error);
goto err_out;
}
return 0;
err_out:
kfree(psmouse->private);
psmouse->private = NULL;
return error;
}
| gpl-2.0 |
thederekjay/android_kernel_samsung_tuna | arch/arm/plat-pxa/dma.c | 4129 | 10032 | /*
* linux/arch/arm/plat-pxa/dma.c
*
* PXA DMA registration and IRQ dispatching
*
* Author: Nicolas Pitre
* Created: Nov 15, 2001
* Copyright: MontaVista Software Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/dma-mapping.h>
#include <asm/system.h>
#include <asm/irq.h>
#include <asm/memory.h>
#include <mach/hardware.h>
#include <mach/dma.h>
#define DMA_DEBUG_NAME "pxa_dma"
#define DMA_MAX_REQUESTERS 64
struct dma_channel {
char *name;
pxa_dma_prio prio;
void (*irq_handler)(int, void *);
void *data;
spinlock_t lock;
};
static struct dma_channel *dma_channels;
static int num_dma_channels;
/*
* Debug fs
*/
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/seq_file.h>
static struct dentry *dbgfs_root, *dbgfs_state, **dbgfs_chan;
static int dbg_show_requester_chan(struct seq_file *s, void *p)
{
int pos = 0;
int chan = (int)s->private;
int i;
u32 drcmr;
pos += seq_printf(s, "DMA channel %d requesters list :\n", chan);
for (i = 0; i < DMA_MAX_REQUESTERS; i++) {
drcmr = DRCMR(i);
if ((drcmr & DRCMR_CHLNUM) == chan)
pos += seq_printf(s, "\tRequester %d (MAPVLD=%d)\n", i,
!!(drcmr & DRCMR_MAPVLD));
}
return pos;
}
static inline int dbg_burst_from_dcmd(u32 dcmd)
{
int burst = (dcmd >> 16) & 0x3;
return burst ? 4 << burst : 0;
}
static int is_phys_valid(unsigned long addr)
{
return pfn_valid(__phys_to_pfn(addr));
}
#define DCSR_STR(flag) (dcsr & DCSR_##flag ? #flag" " : "")
#define DCMD_STR(flag) (dcmd & DCMD_##flag ? #flag" " : "")
static int dbg_show_descriptors(struct seq_file *s, void *p)
{
int pos = 0;
int chan = (int)s->private;
int i, max_show = 20, burst, width;
u32 dcmd;
unsigned long phys_desc;
struct pxa_dma_desc *desc;
unsigned long flags;
spin_lock_irqsave(&dma_channels[chan].lock, flags);
phys_desc = DDADR(chan);
pos += seq_printf(s, "DMA channel %d descriptors :\n", chan);
pos += seq_printf(s, "[%03d] First descriptor unknown\n", 0);
for (i = 1; i < max_show && is_phys_valid(phys_desc); i++) {
desc = phys_to_virt(phys_desc);
dcmd = desc->dcmd;
burst = dbg_burst_from_dcmd(dcmd);
width = (1 << ((dcmd >> 14) & 0x3)) >> 1;
pos += seq_printf(s, "[%03d] Desc at %08lx(virt %p)\n",
i, phys_desc, desc);
pos += seq_printf(s, "\tDDADR = %08x\n", desc->ddadr);
pos += seq_printf(s, "\tDSADR = %08x\n", desc->dsadr);
pos += seq_printf(s, "\tDTADR = %08x\n", desc->dtadr);
pos += seq_printf(s, "\tDCMD = %08x (%s%s%s%s%s%s%sburst=%d"
" width=%d len=%d)\n",
dcmd,
DCMD_STR(INCSRCADDR), DCMD_STR(INCTRGADDR),
DCMD_STR(FLOWSRC), DCMD_STR(FLOWTRG),
DCMD_STR(STARTIRQEN), DCMD_STR(ENDIRQEN),
DCMD_STR(ENDIAN), burst, width,
dcmd & DCMD_LENGTH);
phys_desc = desc->ddadr;
}
if (i == max_show)
pos += seq_printf(s, "[%03d] Desc at %08lx ... max display reached\n",
i, phys_desc);
else
pos += seq_printf(s, "[%03d] Desc at %08lx is %s\n",
i, phys_desc, phys_desc == DDADR_STOP ?
"DDADR_STOP" : "invalid");
spin_unlock_irqrestore(&dma_channels[chan].lock, flags);
return pos;
}
static int dbg_show_chan_state(struct seq_file *s, void *p)
{
int pos = 0;
int chan = (int)s->private;
u32 dcsr, dcmd;
int burst, width;
static char *str_prio[] = { "high", "normal", "low" };
dcsr = DCSR(chan);
dcmd = DCMD(chan);
burst = dbg_burst_from_dcmd(dcmd);
width = (1 << ((dcmd >> 14) & 0x3)) >> 1;
pos += seq_printf(s, "DMA channel %d\n", chan);
pos += seq_printf(s, "\tPriority : %s\n",
str_prio[dma_channels[chan].prio]);
pos += seq_printf(s, "\tUnaligned transfer bit: %s\n",
DALGN & (1 << chan) ? "yes" : "no");
pos += seq_printf(s, "\tDCSR = %08x (%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
dcsr, DCSR_STR(RUN), DCSR_STR(NODESC),
DCSR_STR(STOPIRQEN), DCSR_STR(EORIRQEN),
DCSR_STR(EORJMPEN), DCSR_STR(EORSTOPEN),
DCSR_STR(SETCMPST), DCSR_STR(CLRCMPST),
DCSR_STR(CMPST), DCSR_STR(EORINTR), DCSR_STR(REQPEND),
DCSR_STR(STOPSTATE), DCSR_STR(ENDINTR),
DCSR_STR(STARTINTR), DCSR_STR(BUSERR));
pos += seq_printf(s, "\tDCMD = %08x (%s%s%s%s%s%s%sburst=%d width=%d"
" len=%d)\n",
dcmd,
DCMD_STR(INCSRCADDR), DCMD_STR(INCTRGADDR),
DCMD_STR(FLOWSRC), DCMD_STR(FLOWTRG),
DCMD_STR(STARTIRQEN), DCMD_STR(ENDIRQEN),
DCMD_STR(ENDIAN), burst, width, dcmd & DCMD_LENGTH);
pos += seq_printf(s, "\tDSADR = %08x\n", DSADR(chan));
pos += seq_printf(s, "\tDTADR = %08x\n", DTADR(chan));
pos += seq_printf(s, "\tDDADR = %08x\n", DDADR(chan));
return pos;
}
static int dbg_show_state(struct seq_file *s, void *p)
{
int pos = 0;
/* basic device status */
pos += seq_printf(s, "DMA engine status\n");
pos += seq_printf(s, "\tChannel number: %d\n", num_dma_channels);
return pos;
}
#define DBGFS_FUNC_DECL(name) \
static int dbg_open_##name(struct inode *inode, struct file *file) \
{ \
return single_open(file, dbg_show_##name, inode->i_private); \
} \
static const struct file_operations dbg_fops_##name = { \
.owner = THIS_MODULE, \
.open = dbg_open_##name, \
.llseek = seq_lseek, \
.read = seq_read, \
.release = single_release, \
}
DBGFS_FUNC_DECL(state);
DBGFS_FUNC_DECL(chan_state);
DBGFS_FUNC_DECL(descriptors);
DBGFS_FUNC_DECL(requester_chan);
static struct dentry *pxa_dma_dbg_alloc_chan(int ch, struct dentry *chandir)
{
char chan_name[11];
struct dentry *chan, *chan_state = NULL, *chan_descr = NULL;
struct dentry *chan_reqs = NULL;
void *dt;
scnprintf(chan_name, sizeof(chan_name), "%d", ch);
chan = debugfs_create_dir(chan_name, chandir);
dt = (void *)ch;
if (chan)
chan_state = debugfs_create_file("state", 0400, chan, dt,
&dbg_fops_chan_state);
if (chan_state)
chan_descr = debugfs_create_file("descriptors", 0400, chan, dt,
&dbg_fops_descriptors);
if (chan_descr)
chan_reqs = debugfs_create_file("requesters", 0400, chan, dt,
&dbg_fops_requester_chan);
if (!chan_reqs)
goto err_state;
return chan;
err_state:
debugfs_remove_recursive(chan);
return NULL;
}
static void pxa_dma_init_debugfs(void)
{
int i;
struct dentry *chandir;
dbgfs_root = debugfs_create_dir(DMA_DEBUG_NAME, NULL);
if (IS_ERR(dbgfs_root) || !dbgfs_root)
goto err_root;
dbgfs_state = debugfs_create_file("state", 0400, dbgfs_root, NULL,
&dbg_fops_state);
if (!dbgfs_state)
goto err_state;
dbgfs_chan = kmalloc(sizeof(*dbgfs_state) * num_dma_channels,
GFP_KERNEL);
if (!dbgfs_chan)
goto err_alloc;
chandir = debugfs_create_dir("channels", dbgfs_root);
if (!chandir)
goto err_chandir;
for (i = 0; i < num_dma_channels; i++) {
dbgfs_chan[i] = pxa_dma_dbg_alloc_chan(i, chandir);
if (!dbgfs_chan[i])
goto err_chans;
}
return;
err_chans:
err_chandir:
kfree(dbgfs_chan);
err_alloc:
err_state:
debugfs_remove_recursive(dbgfs_root);
err_root:
pr_err("pxa_dma: debugfs is not available\n");
}
static void __exit pxa_dma_cleanup_debugfs(void)
{
debugfs_remove_recursive(dbgfs_root);
}
#else
static inline void pxa_dma_init_debugfs(void) {}
static inline void pxa_dma_cleanup_debugfs(void) {}
#endif
int pxa_request_dma (char *name, pxa_dma_prio prio,
void (*irq_handler)(int, void *),
void *data)
{
unsigned long flags;
int i, found = 0;
/* basic sanity checks */
if (!name || !irq_handler)
return -EINVAL;
local_irq_save(flags);
do {
/* try grabbing a DMA channel with the requested priority */
for (i = 0; i < num_dma_channels; i++) {
if ((dma_channels[i].prio == prio) &&
!dma_channels[i].name) {
found = 1;
break;
}
}
/* if requested prio group is full, try a hier priority */
} while (!found && prio--);
if (found) {
DCSR(i) = DCSR_STARTINTR|DCSR_ENDINTR|DCSR_BUSERR;
dma_channels[i].name = name;
dma_channels[i].irq_handler = irq_handler;
dma_channels[i].data = data;
} else {
printk (KERN_WARNING "No more available DMA channels for %s\n", name);
i = -ENODEV;
}
local_irq_restore(flags);
return i;
}
EXPORT_SYMBOL(pxa_request_dma);
void pxa_free_dma (int dma_ch)
{
unsigned long flags;
if (!dma_channels[dma_ch].name) {
printk (KERN_CRIT
"%s: trying to free channel %d which is already freed\n",
__func__, dma_ch);
return;
}
local_irq_save(flags);
DCSR(dma_ch) = DCSR_STARTINTR|DCSR_ENDINTR|DCSR_BUSERR;
dma_channels[dma_ch].name = NULL;
local_irq_restore(flags);
}
EXPORT_SYMBOL(pxa_free_dma);
static irqreturn_t dma_irq_handler(int irq, void *dev_id)
{
int i, dint = DINT;
struct dma_channel *channel;
while (dint) {
i = __ffs(dint);
dint &= (dint - 1);
channel = &dma_channels[i];
if (channel->name && channel->irq_handler) {
channel->irq_handler(i, channel->data);
} else {
/*
* IRQ for an unregistered DMA channel:
* let's clear the interrupts and disable it.
*/
printk (KERN_WARNING "spurious IRQ for DMA channel %d\n", i);
DCSR(i) = DCSR_STARTINTR|DCSR_ENDINTR|DCSR_BUSERR;
}
}
return IRQ_HANDLED;
}
int __init pxa_init_dma(int irq, int num_ch)
{
int i, ret;
dma_channels = kzalloc(sizeof(struct dma_channel) * num_ch, GFP_KERNEL);
if (dma_channels == NULL)
return -ENOMEM;
/* dma channel priorities on pxa2xx processors:
* ch 0 - 3, 16 - 19 <--> (0) DMA_PRIO_HIGH
* ch 4 - 7, 20 - 23 <--> (1) DMA_PRIO_MEDIUM
* ch 8 - 15, 24 - 31 <--> (2) DMA_PRIO_LOW
*/
for (i = 0; i < num_ch; i++) {
DCSR(i) = 0;
dma_channels[i].prio = min((i & 0xf) >> 2, DMA_PRIO_LOW);
spin_lock_init(&dma_channels[i].lock);
}
ret = request_irq(irq, dma_irq_handler, IRQF_DISABLED, "DMA", NULL);
if (ret) {
printk (KERN_CRIT "Wow! Can't register IRQ for DMA\n");
kfree(dma_channels);
return ret;
}
num_dma_channels = num_ch;
pxa_dma_init_debugfs();
return 0;
}
| gpl-2.0 |
lostemp/lsk-3.4-android-12.09 | drivers/usb/host/ohci-tmio.c | 4897 | 9812 | /*
* OHCI HCD(Host Controller Driver) for USB.
*
*(C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at>
*(C) Copyright 2000-2002 David Brownell <dbrownell@users.sourceforge.net>
*(C) Copyright 2002 Hewlett-Packard Company
*
* Bus glue for Toshiba Mobile IO(TMIO) Controller's OHCI core
* (C) Copyright 2005 Chris Humbert <mahadri-usb@drigon.com>
* (C) Copyright 2007, 2008 Dmitry Baryshkov <dbaryshkov@gmail.com>
*
* This is known to work with the following variants:
* TC6393XB revision 3 (32kB SRAM)
*
* The TMIO's OHCI core DMAs through a small internal buffer that
* is directly addressable by the CPU.
*
* Written from sparse documentation from Toshiba and Sharp's driver
* for the 2.4 kernel,
* usb-ohci-tc6393.c(C) Copyright 2004 Lineo Solutions, 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/fs.h>
#include <linux/mount.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/namei.h>
#include <linux/sched.h>*/
#include <linux/platform_device.h>
#include <linux/mfd/core.h>
#include <linux/mfd/tmio.h>
#include <linux/dma-mapping.h>
/*-------------------------------------------------------------------------*/
/*
* USB Host Controller Configuration Register
*/
#define CCR_REVID 0x08 /* b Revision ID */
#define CCR_BASE 0x10 /* l USB Control Register Base Address Low */
#define CCR_ILME 0x40 /* b Internal Local Memory Enable */
#define CCR_PM 0x4c /* w Power Management */
#define CCR_INTC 0x50 /* b INT Control */
#define CCR_LMW1L 0x54 /* w Local Memory Window 1 LMADRS Low */
#define CCR_LMW1H 0x56 /* w Local Memory Window 1 LMADRS High */
#define CCR_LMW1BL 0x58 /* w Local Memory Window 1 Base Address Low */
#define CCR_LMW1BH 0x5A /* w Local Memory Window 1 Base Address High */
#define CCR_LMW2L 0x5C /* w Local Memory Window 2 LMADRS Low */
#define CCR_LMW2H 0x5E /* w Local Memory Window 2 LMADRS High */
#define CCR_LMW2BL 0x60 /* w Local Memory Window 2 Base Address Low */
#define CCR_LMW2BH 0x62 /* w Local Memory Window 2 Base Address High */
#define CCR_MISC 0xFC /* b MISC */
#define CCR_PM_GKEN 0x0001
#define CCR_PM_CKRNEN 0x0002
#define CCR_PM_USBPW1 0x0004
#define CCR_PM_USBPW2 0x0008
#define CCR_PM_USBPW3 0x0008
#define CCR_PM_PMEE 0x0100
#define CCR_PM_PMES 0x8000
/*-------------------------------------------------------------------------*/
struct tmio_hcd {
void __iomem *ccr;
spinlock_t lock; /* protects RMW cycles */
};
#define hcd_to_tmio(hcd) ((struct tmio_hcd *)(hcd_to_ohci(hcd) + 1))
/*-------------------------------------------------------------------------*/
static void tmio_write_pm(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct tmio_hcd *tmio = hcd_to_tmio(hcd);
u16 pm;
unsigned long flags;
spin_lock_irqsave(&tmio->lock, flags);
pm = CCR_PM_GKEN | CCR_PM_CKRNEN |
CCR_PM_PMEE | CCR_PM_PMES;
tmio_iowrite16(pm, tmio->ccr + CCR_PM);
spin_unlock_irqrestore(&tmio->lock, flags);
}
static void tmio_stop_hc(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
struct tmio_hcd *tmio = hcd_to_tmio(hcd);
u16 pm;
pm = CCR_PM_GKEN | CCR_PM_CKRNEN;
switch (ohci->num_ports) {
default:
dev_err(&dev->dev, "Unsupported amount of ports: %d\n", ohci->num_ports);
case 3:
pm |= CCR_PM_USBPW3;
case 2:
pm |= CCR_PM_USBPW2;
case 1:
pm |= CCR_PM_USBPW1;
}
tmio_iowrite8(0, tmio->ccr + CCR_INTC);
tmio_iowrite8(0, tmio->ccr + CCR_ILME);
tmio_iowrite16(0, tmio->ccr + CCR_BASE);
tmio_iowrite16(0, tmio->ccr + CCR_BASE + 2);
tmio_iowrite16(pm, tmio->ccr + CCR_PM);
}
static void tmio_start_hc(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct tmio_hcd *tmio = hcd_to_tmio(hcd);
unsigned long base = hcd->rsrc_start;
tmio_write_pm(dev);
tmio_iowrite16(base, tmio->ccr + CCR_BASE);
tmio_iowrite16(base >> 16, tmio->ccr + CCR_BASE + 2);
tmio_iowrite8(1, tmio->ccr + CCR_ILME);
tmio_iowrite8(2, tmio->ccr + CCR_INTC);
dev_info(&dev->dev, "revision %d @ 0x%08llx, irq %d\n",
tmio_ioread8(tmio->ccr + CCR_REVID), hcd->rsrc_start, hcd->irq);
}
static int ohci_tmio_start(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
int ret;
if ((ret = ohci_init(ohci)) < 0)
return ret;
if ((ret = ohci_run(ohci)) < 0) {
err("can't start %s", hcd->self.bus_name);
ohci_stop(hcd);
return ret;
}
return 0;
}
static const struct hc_driver ohci_tmio_hc_driver = {
.description = hcd_name,
.product_desc = "TMIO OHCI USB Host Controller",
.hcd_priv_size = sizeof(struct ohci_hcd) + sizeof (struct tmio_hcd),
/* generic hardware linkage */
.irq = ohci_irq,
.flags = HCD_USB11 | HCD_MEMORY | HCD_LOCAL_MEM,
/* basic lifecycle operations */
.start = ohci_tmio_start,
.stop = ohci_stop,
.shutdown = ohci_shutdown,
/* managing i/o requests and associated device resources */
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
/* scheduling support */
.get_frame_number = ohci_get_frame,
/* root hub support */
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
/*-------------------------------------------------------------------------*/
static struct platform_driver ohci_hcd_tmio_driver;
static int __devinit ohci_hcd_tmio_drv_probe(struct platform_device *dev)
{
const struct mfd_cell *cell = mfd_get_cell(dev);
struct resource *regs = platform_get_resource(dev, IORESOURCE_MEM, 0);
struct resource *config = platform_get_resource(dev, IORESOURCE_MEM, 1);
struct resource *sram = platform_get_resource(dev, IORESOURCE_MEM, 2);
int irq = platform_get_irq(dev, 0);
struct tmio_hcd *tmio;
struct ohci_hcd *ohci;
struct usb_hcd *hcd;
int ret;
if (usb_disabled())
return -ENODEV;
if (!cell)
return -EINVAL;
hcd = usb_create_hcd(&ohci_tmio_hc_driver, &dev->dev, dev_name(&dev->dev));
if (!hcd) {
ret = -ENOMEM;
goto err_usb_create_hcd;
}
hcd->rsrc_start = regs->start;
hcd->rsrc_len = resource_size(regs);
tmio = hcd_to_tmio(hcd);
spin_lock_init(&tmio->lock);
tmio->ccr = ioremap(config->start, resource_size(config));
if (!tmio->ccr) {
ret = -ENOMEM;
goto err_ioremap_ccr;
}
hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len);
if (!hcd->regs) {
ret = -ENOMEM;
goto err_ioremap_regs;
}
if (!dma_declare_coherent_memory(&dev->dev, sram->start,
sram->start,
resource_size(sram),
DMA_MEMORY_MAP | DMA_MEMORY_EXCLUSIVE)) {
ret = -EBUSY;
goto err_dma_declare;
}
if (cell->enable) {
ret = cell->enable(dev);
if (ret)
goto err_enable;
}
tmio_start_hc(dev);
ohci = hcd_to_ohci(hcd);
ohci_hcd_init(ohci);
ret = usb_add_hcd(hcd, irq, 0);
if (ret)
goto err_add_hcd;
if (ret == 0)
return ret;
usb_remove_hcd(hcd);
err_add_hcd:
tmio_stop_hc(dev);
if (cell->disable)
cell->disable(dev);
err_enable:
dma_release_declared_memory(&dev->dev);
err_dma_declare:
iounmap(hcd->regs);
err_ioremap_regs:
iounmap(tmio->ccr);
err_ioremap_ccr:
usb_put_hcd(hcd);
err_usb_create_hcd:
return ret;
}
static int __devexit ohci_hcd_tmio_drv_remove(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct tmio_hcd *tmio = hcd_to_tmio(hcd);
const struct mfd_cell *cell = mfd_get_cell(dev);
usb_remove_hcd(hcd);
tmio_stop_hc(dev);
if (cell->disable)
cell->disable(dev);
dma_release_declared_memory(&dev->dev);
iounmap(hcd->regs);
iounmap(tmio->ccr);
usb_put_hcd(hcd);
platform_set_drvdata(dev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int ohci_hcd_tmio_drv_suspend(struct platform_device *dev, pm_message_t state)
{
const struct mfd_cell *cell = mfd_get_cell(dev);
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
struct tmio_hcd *tmio = hcd_to_tmio(hcd);
unsigned long flags;
u8 misc;
int ret;
if (time_before(jiffies, ohci->next_statechange))
msleep(5);
ohci->next_statechange = jiffies;
spin_lock_irqsave(&tmio->lock, flags);
misc = tmio_ioread8(tmio->ccr + CCR_MISC);
misc |= 1 << 3; /* USSUSP */
tmio_iowrite8(misc, tmio->ccr + CCR_MISC);
spin_unlock_irqrestore(&tmio->lock, flags);
if (cell->suspend) {
ret = cell->suspend(dev);
if (ret)
return ret;
}
return 0;
}
static int ohci_hcd_tmio_drv_resume(struct platform_device *dev)
{
const struct mfd_cell *cell = mfd_get_cell(dev);
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
struct tmio_hcd *tmio = hcd_to_tmio(hcd);
unsigned long flags;
u8 misc;
int ret;
if (time_before(jiffies, ohci->next_statechange))
msleep(5);
ohci->next_statechange = jiffies;
if (cell->resume) {
ret = cell->resume(dev);
if (ret)
return ret;
}
tmio_start_hc(dev);
spin_lock_irqsave(&tmio->lock, flags);
misc = tmio_ioread8(tmio->ccr + CCR_MISC);
misc &= ~(1 << 3); /* USSUSP */
tmio_iowrite8(misc, tmio->ccr + CCR_MISC);
spin_unlock_irqrestore(&tmio->lock, flags);
ohci_finish_controller_resume(hcd);
return 0;
}
#else
#define ohci_hcd_tmio_drv_suspend NULL
#define ohci_hcd_tmio_drv_resume NULL
#endif
static struct platform_driver ohci_hcd_tmio_driver = {
.probe = ohci_hcd_tmio_drv_probe,
.remove = __devexit_p(ohci_hcd_tmio_drv_remove),
.shutdown = usb_hcd_platform_shutdown,
.suspend = ohci_hcd_tmio_drv_suspend,
.resume = ohci_hcd_tmio_drv_resume,
.driver = {
.name = "tmio-ohci",
.owner = THIS_MODULE,
},
};
| gpl-2.0 |
holyangel/HTC_M8_Sense-4.4.3 | drivers/net/irda/sh_sir.c | 4897 | 18170 | /*
* SuperH IrDA Driver
*
* Copyright (C) 2009 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on bfin_sir.c
* Copyright 2006-2009 Analog Devices 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/io.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <net/irda/wrapper.h>
#include <net/irda/irda_device.h>
#include <asm/clock.h>
#define DRIVER_NAME "sh_sir"
#define RX_PHASE (1 << 0)
#define TX_PHASE (1 << 1)
#define TX_COMP_PHASE (1 << 2) /* tx complete */
#define NONE_PHASE (1 << 31)
#define IRIF_RINTCLR 0x0016 /* DMA rx interrupt source clear */
#define IRIF_TINTCLR 0x0018 /* DMA tx interrupt source clear */
#define IRIF_SIR0 0x0020 /* IrDA-SIR10 control */
#define IRIF_SIR1 0x0022 /* IrDA-SIR10 baudrate error correction */
#define IRIF_SIR2 0x0024 /* IrDA-SIR10 baudrate count */
#define IRIF_SIR3 0x0026 /* IrDA-SIR10 status */
#define IRIF_SIR_FRM 0x0028 /* Hardware frame processing set */
#define IRIF_SIR_EOF 0x002A /* EOF value */
#define IRIF_SIR_FLG 0x002C /* Flag clear */
#define IRIF_UART_STS2 0x002E /* UART status 2 */
#define IRIF_UART0 0x0030 /* UART control */
#define IRIF_UART1 0x0032 /* UART status */
#define IRIF_UART2 0x0034 /* UART mode */
#define IRIF_UART3 0x0036 /* UART transmit data */
#define IRIF_UART4 0x0038 /* UART receive data */
#define IRIF_UART5 0x003A /* UART interrupt mask */
#define IRIF_UART6 0x003C /* UART baud rate error correction */
#define IRIF_UART7 0x003E /* UART baud rate count set */
#define IRIF_CRC0 0x0040 /* CRC engine control */
#define IRIF_CRC1 0x0042 /* CRC engine input data */
#define IRIF_CRC2 0x0044 /* CRC engine calculation */
#define IRIF_CRC3 0x0046 /* CRC engine output data 1 */
#define IRIF_CRC4 0x0048 /* CRC engine output data 2 */
/* IRIF_SIR0 */
#define IRTPW (1 << 1) /* transmit pulse width select */
#define IRERRC (1 << 0) /* Clear receive pulse width error */
/* IRIF_SIR3 */
#define IRERR (1 << 0) /* received pulse width Error */
/* IRIF_SIR_FRM */
#define EOFD (1 << 9) /* EOF detection flag */
#define FRER (1 << 8) /* Frame Error bit */
#define FRP (1 << 0) /* Frame processing set */
/* IRIF_UART_STS2 */
#define IRSME (1 << 6) /* Receive Sum Error flag */
#define IROVE (1 << 5) /* Receive Overrun Error flag */
#define IRFRE (1 << 4) /* Receive Framing Error flag */
#define IRPRE (1 << 3) /* Receive Parity Error flag */
/* IRIF_UART0_*/
#define TBEC (1 << 2) /* Transmit Data Clear */
#define RIE (1 << 1) /* Receive Enable */
#define TIE (1 << 0) /* Transmit Enable */
/* IRIF_UART1 */
#define URSME (1 << 6) /* Receive Sum Error Flag */
#define UROVE (1 << 5) /* Receive Overrun Error Flag */
#define URFRE (1 << 4) /* Receive Framing Error Flag */
#define URPRE (1 << 3) /* Receive Parity Error Flag */
#define RBF (1 << 2) /* Receive Buffer Full Flag */
#define TSBE (1 << 1) /* Transmit Shift Buffer Empty Flag */
#define TBE (1 << 0) /* Transmit Buffer Empty flag */
#define TBCOMP (TSBE | TBE)
/* IRIF_UART5 */
#define RSEIM (1 << 6) /* Receive Sum Error Flag IRQ Mask */
#define RBFIM (1 << 2) /* Receive Buffer Full Flag IRQ Mask */
#define TSBEIM (1 << 1) /* Transmit Shift Buffer Empty Flag IRQ Mask */
#define TBEIM (1 << 0) /* Transmit Buffer Empty Flag IRQ Mask */
#define RX_MASK (RSEIM | RBFIM)
/* IRIF_CRC0 */
#define CRC_RST (1 << 15) /* CRC Engine Reset */
#define CRC_CT_MASK 0x0FFF
/************************************************************************
structure
************************************************************************/
struct sh_sir_self {
void __iomem *membase;
unsigned int irq;
struct clk *clk;
struct net_device *ndev;
struct irlap_cb *irlap;
struct qos_info qos;
iobuff_t tx_buff;
iobuff_t rx_buff;
};
/************************************************************************
common function
************************************************************************/
static void sh_sir_write(struct sh_sir_self *self, u32 offset, u16 data)
{
iowrite16(data, self->membase + offset);
}
static u16 sh_sir_read(struct sh_sir_self *self, u32 offset)
{
return ioread16(self->membase + offset);
}
static void sh_sir_update_bits(struct sh_sir_self *self, u32 offset,
u16 mask, u16 data)
{
u16 old, new;
old = sh_sir_read(self, offset);
new = (old & ~mask) | data;
if (old != new)
sh_sir_write(self, offset, new);
}
/************************************************************************
CRC function
************************************************************************/
static void sh_sir_crc_reset(struct sh_sir_self *self)
{
sh_sir_write(self, IRIF_CRC0, CRC_RST);
}
static void sh_sir_crc_add(struct sh_sir_self *self, u8 data)
{
sh_sir_write(self, IRIF_CRC1, (u16)data);
}
static u16 sh_sir_crc_cnt(struct sh_sir_self *self)
{
return CRC_CT_MASK & sh_sir_read(self, IRIF_CRC0);
}
static u16 sh_sir_crc_out(struct sh_sir_self *self)
{
return sh_sir_read(self, IRIF_CRC4);
}
static int sh_sir_crc_init(struct sh_sir_self *self)
{
struct device *dev = &self->ndev->dev;
int ret = -EIO;
u16 val;
sh_sir_crc_reset(self);
sh_sir_crc_add(self, 0xCC);
sh_sir_crc_add(self, 0xF5);
sh_sir_crc_add(self, 0xF1);
sh_sir_crc_add(self, 0xA7);
val = sh_sir_crc_cnt(self);
if (4 != val) {
dev_err(dev, "CRC count error %x\n", val);
goto crc_init_out;
}
val = sh_sir_crc_out(self);
if (0x51DF != val) {
dev_err(dev, "CRC result error%x\n", val);
goto crc_init_out;
}
ret = 0;
crc_init_out:
sh_sir_crc_reset(self);
return ret;
}
/************************************************************************
baud rate functions
************************************************************************/
#define SCLK_BASE 1843200 /* 1.8432MHz */
static u32 sh_sir_find_sclk(struct clk *irda_clk)
{
struct cpufreq_frequency_table *freq_table = irda_clk->freq_table;
struct clk *pclk = clk_get(NULL, "peripheral_clk");
u32 limit, min = 0xffffffff, tmp;
int i, index = 0;
limit = clk_get_rate(pclk);
clk_put(pclk);
/* IrDA can not set over peripheral_clk */
for (i = 0;
freq_table[i].frequency != CPUFREQ_TABLE_END;
i++) {
u32 freq = freq_table[i].frequency;
if (freq == CPUFREQ_ENTRY_INVALID)
continue;
/* IrDA should not over peripheral_clk */
if (freq > limit)
continue;
tmp = freq % SCLK_BASE;
if (tmp < min) {
min = tmp;
index = i;
}
}
return freq_table[index].frequency;
}
#define ERR_ROUNDING(a) ((a + 5000) / 10000)
static int sh_sir_set_baudrate(struct sh_sir_self *self, u32 baudrate)
{
struct clk *clk;
struct device *dev = &self->ndev->dev;
u32 rate;
u16 uabca, uabc;
u16 irbca, irbc;
u32 min, rerr, tmp;
int i;
/* Baud Rate Error Correction x 10000 */
u32 rate_err_array[] = {
0, 625, 1250, 1875,
2500, 3125, 3750, 4375,
5000, 5625, 6250, 6875,
7500, 8125, 8750, 9375,
};
/*
* FIXME
*
* it support 9600 only now
*/
switch (baudrate) {
case 9600:
break;
default:
dev_err(dev, "un-supported baudrate %d\n", baudrate);
return -EIO;
}
clk = clk_get(NULL, "irda_clk");
if (!clk) {
dev_err(dev, "can not get irda_clk\n");
return -EIO;
}
clk_set_rate(clk, sh_sir_find_sclk(clk));
rate = clk_get_rate(clk);
clk_put(clk);
dev_dbg(dev, "selected sclk = %d\n", rate);
/*
* CALCULATION
*
* 1843200 = system rate / (irbca + (irbc + 1))
*/
irbc = rate / SCLK_BASE;
tmp = rate - (SCLK_BASE * irbc);
tmp *= 10000;
rerr = tmp / SCLK_BASE;
min = 0xffffffff;
irbca = 0;
for (i = 0; i < ARRAY_SIZE(rate_err_array); i++) {
tmp = abs(rate_err_array[i] - rerr);
if (min > tmp) {
min = tmp;
irbca = i;
}
}
tmp = rate / (irbc + ERR_ROUNDING(rate_err_array[irbca]));
if ((SCLK_BASE / 100) < abs(tmp - SCLK_BASE))
dev_warn(dev, "IrDA freq error margin over %d\n", tmp);
dev_dbg(dev, "target = %d, result = %d, infrared = %d.%d\n",
SCLK_BASE, tmp, irbc, rate_err_array[irbca]);
irbca = (irbca & 0xF) << 4;
irbc = (irbc - 1) & 0xF;
if (!irbc) {
dev_err(dev, "sh_sir can not set 0 in IRIF_SIR2\n");
return -EIO;
}
sh_sir_write(self, IRIF_SIR0, IRTPW | IRERRC);
sh_sir_write(self, IRIF_SIR1, irbca);
sh_sir_write(self, IRIF_SIR2, irbc);
/*
* CALCULATION
*
* BaudRate[bps] = system rate / (uabca + (uabc + 1) x 16)
*/
uabc = rate / baudrate;
uabc = (uabc / 16) - 1;
uabc = (uabc + 1) * 16;
tmp = rate - (uabc * baudrate);
tmp *= 10000;
rerr = tmp / baudrate;
min = 0xffffffff;
uabca = 0;
for (i = 0; i < ARRAY_SIZE(rate_err_array); i++) {
tmp = abs(rate_err_array[i] - rerr);
if (min > tmp) {
min = tmp;
uabca = i;
}
}
tmp = rate / (uabc + ERR_ROUNDING(rate_err_array[uabca]));
if ((baudrate / 100) < abs(tmp - baudrate))
dev_warn(dev, "UART freq error margin over %d\n", tmp);
dev_dbg(dev, "target = %d, result = %d, uart = %d.%d\n",
baudrate, tmp,
uabc, rate_err_array[uabca]);
uabca = (uabca & 0xF) << 4;
uabc = (uabc / 16) - 1;
sh_sir_write(self, IRIF_UART6, uabca);
sh_sir_write(self, IRIF_UART7, uabc);
return 0;
}
/************************************************************************
iobuf function
************************************************************************/
static int __sh_sir_init_iobuf(iobuff_t *io, int size)
{
io->head = kmalloc(size, GFP_KERNEL);
if (!io->head)
return -ENOMEM;
io->truesize = size;
io->in_frame = FALSE;
io->state = OUTSIDE_FRAME;
io->data = io->head;
return 0;
}
static void sh_sir_remove_iobuf(struct sh_sir_self *self)
{
kfree(self->rx_buff.head);
kfree(self->tx_buff.head);
self->rx_buff.head = NULL;
self->tx_buff.head = NULL;
}
static int sh_sir_init_iobuf(struct sh_sir_self *self, int rxsize, int txsize)
{
int err = -ENOMEM;
if (self->rx_buff.head ||
self->tx_buff.head) {
dev_err(&self->ndev->dev, "iobuff has already existed.");
return err;
}
err = __sh_sir_init_iobuf(&self->rx_buff, rxsize);
if (err)
goto iobuf_err;
err = __sh_sir_init_iobuf(&self->tx_buff, txsize);
iobuf_err:
if (err)
sh_sir_remove_iobuf(self);
return err;
}
/************************************************************************
status function
************************************************************************/
static void sh_sir_clear_all_err(struct sh_sir_self *self)
{
/* Clear error flag for receive pulse width */
sh_sir_update_bits(self, IRIF_SIR0, IRERRC, IRERRC);
/* Clear frame / EOF error flag */
sh_sir_write(self, IRIF_SIR_FLG, 0xffff);
/* Clear all status error */
sh_sir_write(self, IRIF_UART_STS2, 0);
}
static void sh_sir_set_phase(struct sh_sir_self *self, int phase)
{
u16 uart5 = 0;
u16 uart0 = 0;
switch (phase) {
case TX_PHASE:
uart5 = TBEIM;
uart0 = TBEC | TIE;
break;
case TX_COMP_PHASE:
uart5 = TSBEIM;
uart0 = TIE;
break;
case RX_PHASE:
uart5 = RX_MASK;
uart0 = RIE;
break;
default:
break;
}
sh_sir_write(self, IRIF_UART5, uart5);
sh_sir_write(self, IRIF_UART0, uart0);
}
static int sh_sir_is_which_phase(struct sh_sir_self *self)
{
u16 val = sh_sir_read(self, IRIF_UART5);
if (val & TBEIM)
return TX_PHASE;
if (val & TSBEIM)
return TX_COMP_PHASE;
if (val & RX_MASK)
return RX_PHASE;
return NONE_PHASE;
}
static void sh_sir_tx(struct sh_sir_self *self, int phase)
{
switch (phase) {
case TX_PHASE:
if (0 >= self->tx_buff.len) {
sh_sir_set_phase(self, TX_COMP_PHASE);
} else {
sh_sir_write(self, IRIF_UART3, self->tx_buff.data[0]);
self->tx_buff.len--;
self->tx_buff.data++;
}
break;
case TX_COMP_PHASE:
sh_sir_set_phase(self, RX_PHASE);
netif_wake_queue(self->ndev);
break;
default:
dev_err(&self->ndev->dev, "should not happen\n");
break;
}
}
static int sh_sir_read_data(struct sh_sir_self *self)
{
u16 val = 0;
int timeout = 1024;
while (timeout--) {
val = sh_sir_read(self, IRIF_UART1);
/* data get */
if (val & RBF) {
if (val & (URSME | UROVE | URFRE | URPRE))
break;
return (int)sh_sir_read(self, IRIF_UART4);
}
udelay(1);
}
dev_err(&self->ndev->dev, "UART1 %04x : STATUS %04x\n",
val, sh_sir_read(self, IRIF_UART_STS2));
/* read data register for clear error */
sh_sir_read(self, IRIF_UART4);
return -1;
}
static void sh_sir_rx(struct sh_sir_self *self)
{
int timeout = 1024;
int data;
while (timeout--) {
data = sh_sir_read_data(self);
if (data < 0)
break;
async_unwrap_char(self->ndev, &self->ndev->stats,
&self->rx_buff, (u8)data);
self->ndev->last_rx = jiffies;
if (EOFD & sh_sir_read(self, IRIF_SIR_FRM))
continue;
break;
}
}
static irqreturn_t sh_sir_irq(int irq, void *dev_id)
{
struct sh_sir_self *self = dev_id;
struct device *dev = &self->ndev->dev;
int phase = sh_sir_is_which_phase(self);
switch (phase) {
case TX_COMP_PHASE:
case TX_PHASE:
sh_sir_tx(self, phase);
break;
case RX_PHASE:
if (sh_sir_read(self, IRIF_SIR3))
dev_err(dev, "rcv pulse width error occurred\n");
sh_sir_rx(self);
sh_sir_clear_all_err(self);
break;
default:
dev_err(dev, "unknown interrupt\n");
}
return IRQ_HANDLED;
}
/************************************************************************
net_device_ops function
************************************************************************/
static int sh_sir_hard_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
int speed = irda_get_next_speed(skb);
if ((0 < speed) &&
(9600 != speed)) {
dev_err(&ndev->dev, "support 9600 only (%d)\n", speed);
return -EIO;
}
netif_stop_queue(ndev);
self->tx_buff.data = self->tx_buff.head;
self->tx_buff.len = 0;
if (skb->len)
self->tx_buff.len = async_wrap_skb(skb, self->tx_buff.data,
self->tx_buff.truesize);
sh_sir_set_phase(self, TX_PHASE);
dev_kfree_skb(skb);
return 0;
}
static int sh_sir_ioctl(struct net_device *ndev, struct ifreq *ifreq, int cmd)
{
/*
* FIXME
*
* This function is needed for irda framework.
* But nothing to do now
*/
return 0;
}
static struct net_device_stats *sh_sir_stats(struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
return &self->ndev->stats;
}
static int sh_sir_open(struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
int err;
clk_enable(self->clk);
err = sh_sir_crc_init(self);
if (err)
goto open_err;
sh_sir_set_baudrate(self, 9600);
self->irlap = irlap_open(ndev, &self->qos, DRIVER_NAME);
if (!self->irlap) {
err = -ENODEV;
goto open_err;
}
/*
* Now enable the interrupt then start the queue
*/
sh_sir_update_bits(self, IRIF_SIR_FRM, FRP, FRP);
sh_sir_read(self, IRIF_UART1); /* flag clear */
sh_sir_read(self, IRIF_UART4); /* flag clear */
sh_sir_set_phase(self, RX_PHASE);
netif_start_queue(ndev);
dev_info(&self->ndev->dev, "opened\n");
return 0;
open_err:
clk_disable(self->clk);
return err;
}
static int sh_sir_stop(struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
/* Stop IrLAP */
if (self->irlap) {
irlap_close(self->irlap);
self->irlap = NULL;
}
netif_stop_queue(ndev);
dev_info(&ndev->dev, "stoped\n");
return 0;
}
static const struct net_device_ops sh_sir_ndo = {
.ndo_open = sh_sir_open,
.ndo_stop = sh_sir_stop,
.ndo_start_xmit = sh_sir_hard_xmit,
.ndo_do_ioctl = sh_sir_ioctl,
.ndo_get_stats = sh_sir_stats,
};
/************************************************************************
platform_driver function
************************************************************************/
static int __devinit sh_sir_probe(struct platform_device *pdev)
{
struct net_device *ndev;
struct sh_sir_self *self;
struct resource *res;
char clk_name[8];
int irq;
int err = -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (!res || irq < 0) {
dev_err(&pdev->dev, "Not enough platform resources.\n");
goto exit;
}
ndev = alloc_irdadev(sizeof(*self));
if (!ndev)
goto exit;
self = netdev_priv(ndev);
self->membase = ioremap_nocache(res->start, resource_size(res));
if (!self->membase) {
err = -ENXIO;
dev_err(&pdev->dev, "Unable to ioremap.\n");
goto err_mem_1;
}
err = sh_sir_init_iobuf(self, IRDA_SKB_MAX_MTU, IRDA_SIR_MAX_FRAME);
if (err)
goto err_mem_2;
snprintf(clk_name, sizeof(clk_name), "irda%d", pdev->id);
self->clk = clk_get(&pdev->dev, clk_name);
if (IS_ERR(self->clk)) {
dev_err(&pdev->dev, "cannot get clock \"%s\"\n", clk_name);
goto err_mem_3;
}
irda_init_max_qos_capabilies(&self->qos);
ndev->netdev_ops = &sh_sir_ndo;
ndev->irq = irq;
self->ndev = ndev;
self->qos.baud_rate.bits &= IR_9600; /* FIXME */
self->qos.min_turn_time.bits = 1; /* 10 ms or more */
irda_qos_bits_to_value(&self->qos);
err = register_netdev(ndev);
if (err)
goto err_mem_4;
platform_set_drvdata(pdev, ndev);
if (request_irq(irq, sh_sir_irq, IRQF_DISABLED, "sh_sir", self)) {
dev_warn(&pdev->dev, "Unable to attach sh_sir interrupt\n");
goto err_mem_4;
}
dev_info(&pdev->dev, "SuperH IrDA probed\n");
goto exit;
err_mem_4:
clk_put(self->clk);
err_mem_3:
sh_sir_remove_iobuf(self);
err_mem_2:
iounmap(self->membase);
err_mem_1:
free_netdev(ndev);
exit:
return err;
}
static int __devexit sh_sir_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct sh_sir_self *self = netdev_priv(ndev);
if (!self)
return 0;
unregister_netdev(ndev);
clk_put(self->clk);
sh_sir_remove_iobuf(self);
iounmap(self->membase);
free_netdev(ndev);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver sh_sir_driver = {
.probe = sh_sir_probe,
.remove = __devexit_p(sh_sir_remove),
.driver = {
.name = DRIVER_NAME,
},
};
module_platform_driver(sh_sir_driver);
MODULE_AUTHOR("Kuninori Morimoto <morimoto.kuninori@renesas.com>");
MODULE_DESCRIPTION("SuperH IrDA driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
junkyde/vikinger | drivers/gpu/drm/i915/dvo_ch7xxx.c | 5665 | 7707 | /**************************************************************************
Copyright © 2006 Dave Airlie
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, sub license, 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 NON-INFRINGEMENT.
IN NO EVENT SHALL THE AUTHOR 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 "dvo.h"
#define CH7xxx_REG_VID 0x4a
#define CH7xxx_REG_DID 0x4b
#define CH7011_VID 0x83 /* 7010 as well */
#define CH7009A_VID 0x84
#define CH7009B_VID 0x85
#define CH7301_VID 0x95
#define CH7xxx_VID 0x84
#define CH7xxx_DID 0x17
#define CH7xxx_NUM_REGS 0x4c
#define CH7xxx_CM 0x1c
#define CH7xxx_CM_XCM (1<<0)
#define CH7xxx_CM_MCP (1<<2)
#define CH7xxx_INPUT_CLOCK 0x1d
#define CH7xxx_GPIO 0x1e
#define CH7xxx_GPIO_HPIR (1<<3)
#define CH7xxx_IDF 0x1f
#define CH7xxx_IDF_HSP (1<<3)
#define CH7xxx_IDF_VSP (1<<4)
#define CH7xxx_CONNECTION_DETECT 0x20
#define CH7xxx_CDET_DVI (1<<5)
#define CH7301_DAC_CNTL 0x21
#define CH7301_HOTPLUG 0x23
#define CH7xxx_TCTL 0x31
#define CH7xxx_TVCO 0x32
#define CH7xxx_TPCP 0x33
#define CH7xxx_TPD 0x34
#define CH7xxx_TPVT 0x35
#define CH7xxx_TLPF 0x36
#define CH7xxx_TCT 0x37
#define CH7301_TEST_PATTERN 0x48
#define CH7xxx_PM 0x49
#define CH7xxx_PM_FPD (1<<0)
#define CH7301_PM_DACPD0 (1<<1)
#define CH7301_PM_DACPD1 (1<<2)
#define CH7301_PM_DACPD2 (1<<3)
#define CH7xxx_PM_DVIL (1<<6)
#define CH7xxx_PM_DVIP (1<<7)
#define CH7301_SYNC_POLARITY 0x56
#define CH7301_SYNC_RGB_YUV (1<<0)
#define CH7301_SYNC_POL_DVI (1<<5)
/** @file
* driver for the Chrontel 7xxx DVI chip over DVO.
*/
static struct ch7xxx_id_struct {
uint8_t vid;
char *name;
} ch7xxx_ids[] = {
{ CH7011_VID, "CH7011" },
{ CH7009A_VID, "CH7009A" },
{ CH7009B_VID, "CH7009B" },
{ CH7301_VID, "CH7301" },
};
struct ch7xxx_priv {
bool quiet;
};
static char *ch7xxx_get_id(uint8_t vid)
{
int i;
for (i = 0; i < ARRAY_SIZE(ch7xxx_ids); i++) {
if (ch7xxx_ids[i].vid == vid)
return ch7xxx_ids[i].name;
}
return NULL;
}
/** Reads an 8 bit register */
static bool ch7xxx_readb(struct intel_dvo_device *dvo, int addr, uint8_t *ch)
{
struct ch7xxx_priv *ch7xxx = dvo->dev_priv;
struct i2c_adapter *adapter = dvo->i2c_bus;
u8 out_buf[2];
u8 in_buf[2];
struct i2c_msg msgs[] = {
{
.addr = dvo->slave_addr,
.flags = 0,
.len = 1,
.buf = out_buf,
},
{
.addr = dvo->slave_addr,
.flags = I2C_M_RD,
.len = 1,
.buf = in_buf,
}
};
out_buf[0] = addr;
out_buf[1] = 0;
if (i2c_transfer(adapter, msgs, 2) == 2) {
*ch = in_buf[0];
return true;
};
if (!ch7xxx->quiet) {
DRM_DEBUG_KMS("Unable to read register 0x%02x from %s:%02x.\n",
addr, adapter->name, dvo->slave_addr);
}
return false;
}
/** Writes an 8 bit register */
static bool ch7xxx_writeb(struct intel_dvo_device *dvo, int addr, uint8_t ch)
{
struct ch7xxx_priv *ch7xxx = dvo->dev_priv;
struct i2c_adapter *adapter = dvo->i2c_bus;
uint8_t out_buf[2];
struct i2c_msg msg = {
.addr = dvo->slave_addr,
.flags = 0,
.len = 2,
.buf = out_buf,
};
out_buf[0] = addr;
out_buf[1] = ch;
if (i2c_transfer(adapter, &msg, 1) == 1)
return true;
if (!ch7xxx->quiet) {
DRM_DEBUG_KMS("Unable to write register 0x%02x to %s:%d.\n",
addr, adapter->name, dvo->slave_addr);
}
return false;
}
static bool ch7xxx_init(struct intel_dvo_device *dvo,
struct i2c_adapter *adapter)
{
/* this will detect the CH7xxx chip on the specified i2c bus */
struct ch7xxx_priv *ch7xxx;
uint8_t vendor, device;
char *name;
ch7xxx = kzalloc(sizeof(struct ch7xxx_priv), GFP_KERNEL);
if (ch7xxx == NULL)
return false;
dvo->i2c_bus = adapter;
dvo->dev_priv = ch7xxx;
ch7xxx->quiet = true;
if (!ch7xxx_readb(dvo, CH7xxx_REG_VID, &vendor))
goto out;
name = ch7xxx_get_id(vendor);
if (!name) {
DRM_DEBUG_KMS("ch7xxx not detected; got 0x%02x from %s "
"slave %d.\n",
vendor, adapter->name, dvo->slave_addr);
goto out;
}
if (!ch7xxx_readb(dvo, CH7xxx_REG_DID, &device))
goto out;
if (device != CH7xxx_DID) {
DRM_DEBUG_KMS("ch7xxx not detected; got 0x%02x from %s "
"slave %d.\n",
vendor, adapter->name, dvo->slave_addr);
goto out;
}
ch7xxx->quiet = false;
DRM_DEBUG_KMS("Detected %s chipset, vendor/device ID 0x%02x/0x%02x\n",
name, vendor, device);
return true;
out:
kfree(ch7xxx);
return false;
}
static enum drm_connector_status ch7xxx_detect(struct intel_dvo_device *dvo)
{
uint8_t cdet, orig_pm, pm;
ch7xxx_readb(dvo, CH7xxx_PM, &orig_pm);
pm = orig_pm;
pm &= ~CH7xxx_PM_FPD;
pm |= CH7xxx_PM_DVIL | CH7xxx_PM_DVIP;
ch7xxx_writeb(dvo, CH7xxx_PM, pm);
ch7xxx_readb(dvo, CH7xxx_CONNECTION_DETECT, &cdet);
ch7xxx_writeb(dvo, CH7xxx_PM, orig_pm);
if (cdet & CH7xxx_CDET_DVI)
return connector_status_connected;
return connector_status_disconnected;
}
static enum drm_mode_status ch7xxx_mode_valid(struct intel_dvo_device *dvo,
struct drm_display_mode *mode)
{
if (mode->clock > 165000)
return MODE_CLOCK_HIGH;
return MODE_OK;
}
static void ch7xxx_mode_set(struct intel_dvo_device *dvo,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
uint8_t tvco, tpcp, tpd, tlpf, idf;
if (mode->clock <= 65000) {
tvco = 0x23;
tpcp = 0x08;
tpd = 0x16;
tlpf = 0x60;
} else {
tvco = 0x2d;
tpcp = 0x06;
tpd = 0x26;
tlpf = 0xa0;
}
ch7xxx_writeb(dvo, CH7xxx_TCTL, 0x00);
ch7xxx_writeb(dvo, CH7xxx_TVCO, tvco);
ch7xxx_writeb(dvo, CH7xxx_TPCP, tpcp);
ch7xxx_writeb(dvo, CH7xxx_TPD, tpd);
ch7xxx_writeb(dvo, CH7xxx_TPVT, 0x30);
ch7xxx_writeb(dvo, CH7xxx_TLPF, tlpf);
ch7xxx_writeb(dvo, CH7xxx_TCT, 0x00);
ch7xxx_readb(dvo, CH7xxx_IDF, &idf);
idf &= ~(CH7xxx_IDF_HSP | CH7xxx_IDF_VSP);
if (mode->flags & DRM_MODE_FLAG_PHSYNC)
idf |= CH7xxx_IDF_HSP;
if (mode->flags & DRM_MODE_FLAG_PVSYNC)
idf |= CH7xxx_IDF_HSP;
ch7xxx_writeb(dvo, CH7xxx_IDF, idf);
}
/* set the CH7xxx power state */
static void ch7xxx_dpms(struct intel_dvo_device *dvo, int mode)
{
if (mode == DRM_MODE_DPMS_ON)
ch7xxx_writeb(dvo, CH7xxx_PM, CH7xxx_PM_DVIL | CH7xxx_PM_DVIP);
else
ch7xxx_writeb(dvo, CH7xxx_PM, CH7xxx_PM_FPD);
}
static void ch7xxx_dump_regs(struct intel_dvo_device *dvo)
{
int i;
for (i = 0; i < CH7xxx_NUM_REGS; i++) {
uint8_t val;
if ((i % 8) == 0)
DRM_LOG_KMS("\n %02X: ", i);
ch7xxx_readb(dvo, i, &val);
DRM_LOG_KMS("%02X ", val);
}
}
static void ch7xxx_destroy(struct intel_dvo_device *dvo)
{
struct ch7xxx_priv *ch7xxx = dvo->dev_priv;
if (ch7xxx) {
kfree(ch7xxx);
dvo->dev_priv = NULL;
}
}
struct intel_dvo_dev_ops ch7xxx_ops = {
.init = ch7xxx_init,
.detect = ch7xxx_detect,
.mode_valid = ch7xxx_mode_valid,
.mode_set = ch7xxx_mode_set,
.dpms = ch7xxx_dpms,
.dump_regs = ch7xxx_dump_regs,
.destroy = ch7xxx_destroy,
};
| gpl-2.0 |
173210/omnirom_kernel_samsung_smdk4412 | drivers/gpu/drm/nouveau/nv50_mpeg.c | 5921 | 6813 | /*
* Copyright 2011 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_ramht.h"
struct nv50_mpeg_engine {
struct nouveau_exec_engine base;
};
static inline u32
CTX_PTR(struct drm_device *dev, u32 offset)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
if (dev_priv->chipset == 0x50)
offset += 0x0260;
else
offset += 0x0060;
return offset;
}
static int
nv50_mpeg_context_new(struct nouveau_channel *chan, int engine)
{
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_gpuobj *ramin = chan->ramin;
struct nouveau_gpuobj *ctx = NULL;
int ret;
NV_DEBUG(dev, "ch%d\n", chan->id);
ret = nouveau_gpuobj_new(dev, chan, 128 * 4, 0, NVOBJ_FLAG_ZERO_ALLOC |
NVOBJ_FLAG_ZERO_FREE, &ctx);
if (ret)
return ret;
nv_wo32(ramin, CTX_PTR(dev, 0x00), 0x80190002);
nv_wo32(ramin, CTX_PTR(dev, 0x04), ctx->vinst + ctx->size - 1);
nv_wo32(ramin, CTX_PTR(dev, 0x08), ctx->vinst);
nv_wo32(ramin, CTX_PTR(dev, 0x0c), 0);
nv_wo32(ramin, CTX_PTR(dev, 0x10), 0);
nv_wo32(ramin, CTX_PTR(dev, 0x14), 0x00010000);
nv_wo32(ctx, 0x70, 0x00801ec1);
nv_wo32(ctx, 0x7c, 0x0000037c);
dev_priv->engine.instmem.flush(dev);
chan->engctx[engine] = ctx;
return 0;
}
static void
nv50_mpeg_context_del(struct nouveau_channel *chan, int engine)
{
struct drm_nouveau_private *dev_priv = chan->dev->dev_private;
struct nouveau_gpuobj *ctx = chan->engctx[engine];
struct drm_device *dev = chan->dev;
unsigned long flags;
u32 inst, i;
if (!chan->ramin)
return;
inst = chan->ramin->vinst >> 12;
inst |= 0x80000000;
spin_lock_irqsave(&dev_priv->context_switch_lock, flags);
nv_mask(dev, 0x00b32c, 0x00000001, 0x00000000);
if (nv_rd32(dev, 0x00b318) == inst)
nv_mask(dev, 0x00b318, 0x80000000, 0x00000000);
nv_mask(dev, 0x00b32c, 0x00000001, 0x00000001);
spin_unlock_irqrestore(&dev_priv->context_switch_lock, flags);
for (i = 0x00; i <= 0x14; i += 4)
nv_wo32(chan->ramin, CTX_PTR(dev, i), 0x00000000);
nouveau_gpuobj_ref(NULL, &ctx);
chan->engctx[engine] = NULL;
}
static int
nv50_mpeg_object_new(struct nouveau_channel *chan, int engine,
u32 handle, u16 class)
{
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_gpuobj *obj = NULL;
int ret;
ret = nouveau_gpuobj_new(dev, chan, 16, 16, NVOBJ_FLAG_ZERO_FREE, &obj);
if (ret)
return ret;
obj->engine = 2;
obj->class = class;
nv_wo32(obj, 0x00, class);
nv_wo32(obj, 0x04, 0x00000000);
nv_wo32(obj, 0x08, 0x00000000);
nv_wo32(obj, 0x0c, 0x00000000);
dev_priv->engine.instmem.flush(dev);
ret = nouveau_ramht_insert(chan, handle, obj);
nouveau_gpuobj_ref(NULL, &obj);
return ret;
}
static void
nv50_mpeg_tlb_flush(struct drm_device *dev, int engine)
{
nv50_vm_flush_engine(dev, 0x08);
}
static int
nv50_mpeg_init(struct drm_device *dev, int engine)
{
nv_wr32(dev, 0x00b32c, 0x00000000);
nv_wr32(dev, 0x00b314, 0x00000100);
nv_wr32(dev, 0x00b0e0, 0x0000001a);
nv_wr32(dev, 0x00b220, 0x00000044);
nv_wr32(dev, 0x00b300, 0x00801ec1);
nv_wr32(dev, 0x00b390, 0x00000000);
nv_wr32(dev, 0x00b394, 0x00000000);
nv_wr32(dev, 0x00b398, 0x00000000);
nv_mask(dev, 0x00b32c, 0x00000001, 0x00000001);
nv_wr32(dev, 0x00b100, 0xffffffff);
nv_wr32(dev, 0x00b140, 0xffffffff);
if (!nv_wait(dev, 0x00b200, 0x00000001, 0x00000000)) {
NV_ERROR(dev, "PMPEG init: 0x%08x\n", nv_rd32(dev, 0x00b200));
return -EBUSY;
}
return 0;
}
static int
nv50_mpeg_fini(struct drm_device *dev, int engine, bool suspend)
{
/*XXX: context save for s/r */
nv_mask(dev, 0x00b32c, 0x00000001, 0x00000000);
nv_wr32(dev, 0x00b140, 0x00000000);
return 0;
}
static void
nv50_mpeg_isr(struct drm_device *dev)
{
u32 stat = nv_rd32(dev, 0x00b100);
u32 type = nv_rd32(dev, 0x00b230);
u32 mthd = nv_rd32(dev, 0x00b234);
u32 data = nv_rd32(dev, 0x00b238);
u32 show = stat;
if (stat & 0x01000000) {
/* happens on initial binding of the object */
if (type == 0x00000020 && mthd == 0x0000) {
nv_wr32(dev, 0x00b308, 0x00000100);
show &= ~0x01000000;
}
}
if (show && nouveau_ratelimit()) {
NV_INFO(dev, "PMPEG - 0x%08x 0x%08x 0x%08x 0x%08x\n",
stat, type, mthd, data);
}
nv_wr32(dev, 0x00b100, stat);
nv_wr32(dev, 0x00b230, 0x00000001);
nv50_fb_vm_trap(dev, 1);
}
static void
nv50_vpe_isr(struct drm_device *dev)
{
if (nv_rd32(dev, 0x00b100))
nv50_mpeg_isr(dev);
if (nv_rd32(dev, 0x00b800)) {
u32 stat = nv_rd32(dev, 0x00b800);
NV_INFO(dev, "PMSRCH: 0x%08x\n", stat);
nv_wr32(dev, 0xb800, stat);
}
}
static void
nv50_mpeg_destroy(struct drm_device *dev, int engine)
{
struct nv50_mpeg_engine *pmpeg = nv_engine(dev, engine);
nouveau_irq_unregister(dev, 0);
NVOBJ_ENGINE_DEL(dev, MPEG);
kfree(pmpeg);
}
int
nv50_mpeg_create(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nv50_mpeg_engine *pmpeg;
pmpeg = kzalloc(sizeof(*pmpeg), GFP_KERNEL);
if (!pmpeg)
return -ENOMEM;
pmpeg->base.destroy = nv50_mpeg_destroy;
pmpeg->base.init = nv50_mpeg_init;
pmpeg->base.fini = nv50_mpeg_fini;
pmpeg->base.context_new = nv50_mpeg_context_new;
pmpeg->base.context_del = nv50_mpeg_context_del;
pmpeg->base.object_new = nv50_mpeg_object_new;
pmpeg->base.tlb_flush = nv50_mpeg_tlb_flush;
if (dev_priv->chipset == 0x50) {
nouveau_irq_register(dev, 0, nv50_vpe_isr);
NVOBJ_ENGINE_ADD(dev, MPEG, &pmpeg->base);
NVOBJ_CLASS(dev, 0x3174, MPEG);
#if 0
NVOBJ_ENGINE_ADD(dev, ME, &pme->base);
NVOBJ_CLASS(dev, 0x4075, ME);
#endif
} else {
nouveau_irq_register(dev, 0, nv50_mpeg_isr);
NVOBJ_ENGINE_ADD(dev, MPEG, &pmpeg->base);
NVOBJ_CLASS(dev, 0x8274, MPEG);
}
return 0;
}
| gpl-2.0 |
JaeYoulLee/Linux-Kernel | fs/ocfs2/stackglue.c | 11553 | 17237 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* stackglue.c
*
* Code which implements an OCFS2 specific interface to underlying
* cluster stacks.
*
* Copyright (C) 2007, 2009 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License 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/list.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/fs.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/sysctl.h>
#include "ocfs2_fs.h"
#include "stackglue.h"
#define OCFS2_STACK_PLUGIN_O2CB "o2cb"
#define OCFS2_STACK_PLUGIN_USER "user"
#define OCFS2_MAX_HB_CTL_PATH 256
static struct ocfs2_protocol_version locking_max_version;
static DEFINE_SPINLOCK(ocfs2_stack_lock);
static LIST_HEAD(ocfs2_stack_list);
static char cluster_stack_name[OCFS2_STACK_LABEL_LEN + 1];
static char ocfs2_hb_ctl_path[OCFS2_MAX_HB_CTL_PATH] = "/sbin/ocfs2_hb_ctl";
/*
* The stack currently in use. If not null, active_stack->sp_count > 0,
* the module is pinned, and the locking protocol cannot be changed.
*/
static struct ocfs2_stack_plugin *active_stack;
static struct ocfs2_stack_plugin *ocfs2_stack_lookup(const char *name)
{
struct ocfs2_stack_plugin *p;
assert_spin_locked(&ocfs2_stack_lock);
list_for_each_entry(p, &ocfs2_stack_list, sp_list) {
if (!strcmp(p->sp_name, name))
return p;
}
return NULL;
}
static int ocfs2_stack_driver_request(const char *stack_name,
const char *plugin_name)
{
int rc;
struct ocfs2_stack_plugin *p;
spin_lock(&ocfs2_stack_lock);
/*
* If the stack passed by the filesystem isn't the selected one,
* we can't continue.
*/
if (strcmp(stack_name, cluster_stack_name)) {
rc = -EBUSY;
goto out;
}
if (active_stack) {
/*
* If the active stack isn't the one we want, it cannot
* be selected right now.
*/
if (!strcmp(active_stack->sp_name, plugin_name))
rc = 0;
else
rc = -EBUSY;
goto out;
}
p = ocfs2_stack_lookup(plugin_name);
if (!p || !try_module_get(p->sp_owner)) {
rc = -ENOENT;
goto out;
}
active_stack = p;
rc = 0;
out:
/* If we found it, pin it */
if (!rc)
active_stack->sp_count++;
spin_unlock(&ocfs2_stack_lock);
return rc;
}
/*
* This function looks up the appropriate stack and makes it active. If
* there is no stack, it tries to load it. It will fail if the stack still
* cannot be found. It will also fail if a different stack is in use.
*/
static int ocfs2_stack_driver_get(const char *stack_name)
{
int rc;
char *plugin_name = OCFS2_STACK_PLUGIN_O2CB;
/*
* Classic stack does not pass in a stack name. This is
* compatible with older tools as well.
*/
if (!stack_name || !*stack_name)
stack_name = OCFS2_STACK_PLUGIN_O2CB;
if (strlen(stack_name) != OCFS2_STACK_LABEL_LEN) {
printk(KERN_ERR
"ocfs2 passed an invalid cluster stack label: \"%s\"\n",
stack_name);
return -EINVAL;
}
/* Anything that isn't the classic stack is a user stack */
if (strcmp(stack_name, OCFS2_STACK_PLUGIN_O2CB))
plugin_name = OCFS2_STACK_PLUGIN_USER;
rc = ocfs2_stack_driver_request(stack_name, plugin_name);
if (rc == -ENOENT) {
request_module("ocfs2_stack_%s", plugin_name);
rc = ocfs2_stack_driver_request(stack_name, plugin_name);
}
if (rc == -ENOENT) {
printk(KERN_ERR
"ocfs2: Cluster stack driver \"%s\" cannot be found\n",
plugin_name);
} else if (rc == -EBUSY) {
printk(KERN_ERR
"ocfs2: A different cluster stack is in use\n");
}
return rc;
}
static void ocfs2_stack_driver_put(void)
{
spin_lock(&ocfs2_stack_lock);
BUG_ON(active_stack == NULL);
BUG_ON(active_stack->sp_count == 0);
active_stack->sp_count--;
if (!active_stack->sp_count) {
module_put(active_stack->sp_owner);
active_stack = NULL;
}
spin_unlock(&ocfs2_stack_lock);
}
int ocfs2_stack_glue_register(struct ocfs2_stack_plugin *plugin)
{
int rc;
spin_lock(&ocfs2_stack_lock);
if (!ocfs2_stack_lookup(plugin->sp_name)) {
plugin->sp_count = 0;
plugin->sp_max_proto = locking_max_version;
list_add(&plugin->sp_list, &ocfs2_stack_list);
printk(KERN_INFO "ocfs2: Registered cluster interface %s\n",
plugin->sp_name);
rc = 0;
} else {
printk(KERN_ERR "ocfs2: Stack \"%s\" already registered\n",
plugin->sp_name);
rc = -EEXIST;
}
spin_unlock(&ocfs2_stack_lock);
return rc;
}
EXPORT_SYMBOL_GPL(ocfs2_stack_glue_register);
void ocfs2_stack_glue_unregister(struct ocfs2_stack_plugin *plugin)
{
struct ocfs2_stack_plugin *p;
spin_lock(&ocfs2_stack_lock);
p = ocfs2_stack_lookup(plugin->sp_name);
if (p) {
BUG_ON(p != plugin);
BUG_ON(plugin == active_stack);
BUG_ON(plugin->sp_count != 0);
list_del_init(&plugin->sp_list);
printk(KERN_INFO "ocfs2: Unregistered cluster interface %s\n",
plugin->sp_name);
} else {
printk(KERN_ERR "Stack \"%s\" is not registered\n",
plugin->sp_name);
}
spin_unlock(&ocfs2_stack_lock);
}
EXPORT_SYMBOL_GPL(ocfs2_stack_glue_unregister);
void ocfs2_stack_glue_set_max_proto_version(struct ocfs2_protocol_version *max_proto)
{
struct ocfs2_stack_plugin *p;
spin_lock(&ocfs2_stack_lock);
if (memcmp(max_proto, &locking_max_version,
sizeof(struct ocfs2_protocol_version))) {
BUG_ON(locking_max_version.pv_major != 0);
locking_max_version = *max_proto;
list_for_each_entry(p, &ocfs2_stack_list, sp_list) {
p->sp_max_proto = locking_max_version;
}
}
spin_unlock(&ocfs2_stack_lock);
}
EXPORT_SYMBOL_GPL(ocfs2_stack_glue_set_max_proto_version);
/*
* The ocfs2_dlm_lock() and ocfs2_dlm_unlock() functions take no argument
* for the ast and bast functions. They will pass the lksb to the ast
* and bast. The caller can wrap the lksb with their own structure to
* get more information.
*/
int ocfs2_dlm_lock(struct ocfs2_cluster_connection *conn,
int mode,
struct ocfs2_dlm_lksb *lksb,
u32 flags,
void *name,
unsigned int namelen)
{
if (!lksb->lksb_conn)
lksb->lksb_conn = conn;
else
BUG_ON(lksb->lksb_conn != conn);
return active_stack->sp_ops->dlm_lock(conn, mode, lksb, flags,
name, namelen);
}
EXPORT_SYMBOL_GPL(ocfs2_dlm_lock);
int ocfs2_dlm_unlock(struct ocfs2_cluster_connection *conn,
struct ocfs2_dlm_lksb *lksb,
u32 flags)
{
BUG_ON(lksb->lksb_conn == NULL);
return active_stack->sp_ops->dlm_unlock(conn, lksb, flags);
}
EXPORT_SYMBOL_GPL(ocfs2_dlm_unlock);
int ocfs2_dlm_lock_status(struct ocfs2_dlm_lksb *lksb)
{
return active_stack->sp_ops->lock_status(lksb);
}
EXPORT_SYMBOL_GPL(ocfs2_dlm_lock_status);
int ocfs2_dlm_lvb_valid(struct ocfs2_dlm_lksb *lksb)
{
return active_stack->sp_ops->lvb_valid(lksb);
}
EXPORT_SYMBOL_GPL(ocfs2_dlm_lvb_valid);
void *ocfs2_dlm_lvb(struct ocfs2_dlm_lksb *lksb)
{
return active_stack->sp_ops->lock_lvb(lksb);
}
EXPORT_SYMBOL_GPL(ocfs2_dlm_lvb);
void ocfs2_dlm_dump_lksb(struct ocfs2_dlm_lksb *lksb)
{
active_stack->sp_ops->dump_lksb(lksb);
}
EXPORT_SYMBOL_GPL(ocfs2_dlm_dump_lksb);
int ocfs2_stack_supports_plocks(void)
{
return active_stack && active_stack->sp_ops->plock;
}
EXPORT_SYMBOL_GPL(ocfs2_stack_supports_plocks);
/*
* ocfs2_plock() can only be safely called if
* ocfs2_stack_supports_plocks() returned true
*/
int ocfs2_plock(struct ocfs2_cluster_connection *conn, u64 ino,
struct file *file, int cmd, struct file_lock *fl)
{
WARN_ON_ONCE(active_stack->sp_ops->plock == NULL);
if (active_stack->sp_ops->plock)
return active_stack->sp_ops->plock(conn, ino, file, cmd, fl);
return -EOPNOTSUPP;
}
EXPORT_SYMBOL_GPL(ocfs2_plock);
int ocfs2_cluster_connect(const char *stack_name,
const char *group,
int grouplen,
struct ocfs2_locking_protocol *lproto,
void (*recovery_handler)(int node_num,
void *recovery_data),
void *recovery_data,
struct ocfs2_cluster_connection **conn)
{
int rc = 0;
struct ocfs2_cluster_connection *new_conn;
BUG_ON(group == NULL);
BUG_ON(conn == NULL);
BUG_ON(recovery_handler == NULL);
if (grouplen > GROUP_NAME_MAX) {
rc = -EINVAL;
goto out;
}
if (memcmp(&lproto->lp_max_version, &locking_max_version,
sizeof(struct ocfs2_protocol_version))) {
rc = -EINVAL;
goto out;
}
new_conn = kzalloc(sizeof(struct ocfs2_cluster_connection),
GFP_KERNEL);
if (!new_conn) {
rc = -ENOMEM;
goto out;
}
memcpy(new_conn->cc_name, group, grouplen);
new_conn->cc_namelen = grouplen;
new_conn->cc_recovery_handler = recovery_handler;
new_conn->cc_recovery_data = recovery_data;
new_conn->cc_proto = lproto;
/* Start the new connection at our maximum compatibility level */
new_conn->cc_version = lproto->lp_max_version;
/* This will pin the stack driver if successful */
rc = ocfs2_stack_driver_get(stack_name);
if (rc)
goto out_free;
rc = active_stack->sp_ops->connect(new_conn);
if (rc) {
ocfs2_stack_driver_put();
goto out_free;
}
*conn = new_conn;
out_free:
if (rc)
kfree(new_conn);
out:
return rc;
}
EXPORT_SYMBOL_GPL(ocfs2_cluster_connect);
/* The caller will ensure all nodes have the same cluster stack */
int ocfs2_cluster_connect_agnostic(const char *group,
int grouplen,
struct ocfs2_locking_protocol *lproto,
void (*recovery_handler)(int node_num,
void *recovery_data),
void *recovery_data,
struct ocfs2_cluster_connection **conn)
{
char *stack_name = NULL;
if (cluster_stack_name[0])
stack_name = cluster_stack_name;
return ocfs2_cluster_connect(stack_name, group, grouplen, lproto,
recovery_handler, recovery_data, conn);
}
EXPORT_SYMBOL_GPL(ocfs2_cluster_connect_agnostic);
/* If hangup_pending is 0, the stack driver will be dropped */
int ocfs2_cluster_disconnect(struct ocfs2_cluster_connection *conn,
int hangup_pending)
{
int ret;
BUG_ON(conn == NULL);
ret = active_stack->sp_ops->disconnect(conn);
/* XXX Should we free it anyway? */
if (!ret) {
kfree(conn);
if (!hangup_pending)
ocfs2_stack_driver_put();
}
return ret;
}
EXPORT_SYMBOL_GPL(ocfs2_cluster_disconnect);
/*
* Leave the group for this filesystem. This is executed by a userspace
* program (stored in ocfs2_hb_ctl_path).
*/
static void ocfs2_leave_group(const char *group)
{
int ret;
char *argv[5], *envp[3];
argv[0] = ocfs2_hb_ctl_path;
argv[1] = "-K";
argv[2] = "-u";
argv[3] = (char *)group;
argv[4] = NULL;
/* minimal command environment taken from cpu_run_sbin_hotplug */
envp[0] = "HOME=/";
envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
envp[2] = NULL;
ret = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
if (ret < 0) {
printk(KERN_ERR
"ocfs2: Error %d running user helper "
"\"%s %s %s %s\"\n",
ret, argv[0], argv[1], argv[2], argv[3]);
}
}
/*
* Hangup is a required post-umount. ocfs2-tools software expects the
* filesystem to call "ocfs2_hb_ctl" during unmount. This happens
* regardless of whether the DLM got started, so we can't do it
* in ocfs2_cluster_disconnect(). The ocfs2_leave_group() function does
* the actual work.
*/
void ocfs2_cluster_hangup(const char *group, int grouplen)
{
BUG_ON(group == NULL);
BUG_ON(group[grouplen] != '\0');
ocfs2_leave_group(group);
/* cluster_disconnect() was called with hangup_pending==1 */
ocfs2_stack_driver_put();
}
EXPORT_SYMBOL_GPL(ocfs2_cluster_hangup);
int ocfs2_cluster_this_node(unsigned int *node)
{
return active_stack->sp_ops->this_node(node);
}
EXPORT_SYMBOL_GPL(ocfs2_cluster_this_node);
/*
* Sysfs bits
*/
static ssize_t ocfs2_max_locking_protocol_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
ssize_t ret = 0;
spin_lock(&ocfs2_stack_lock);
if (locking_max_version.pv_major)
ret = snprintf(buf, PAGE_SIZE, "%u.%u\n",
locking_max_version.pv_major,
locking_max_version.pv_minor);
spin_unlock(&ocfs2_stack_lock);
return ret;
}
static struct kobj_attribute ocfs2_attr_max_locking_protocol =
__ATTR(max_locking_protocol, S_IFREG | S_IRUGO,
ocfs2_max_locking_protocol_show, NULL);
static ssize_t ocfs2_loaded_cluster_plugins_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
ssize_t ret = 0, total = 0, remain = PAGE_SIZE;
struct ocfs2_stack_plugin *p;
spin_lock(&ocfs2_stack_lock);
list_for_each_entry(p, &ocfs2_stack_list, sp_list) {
ret = snprintf(buf, remain, "%s\n",
p->sp_name);
if (ret < 0) {
total = ret;
break;
}
if (ret == remain) {
/* snprintf() didn't fit */
total = -E2BIG;
break;
}
total += ret;
remain -= ret;
}
spin_unlock(&ocfs2_stack_lock);
return total;
}
static struct kobj_attribute ocfs2_attr_loaded_cluster_plugins =
__ATTR(loaded_cluster_plugins, S_IFREG | S_IRUGO,
ocfs2_loaded_cluster_plugins_show, NULL);
static ssize_t ocfs2_active_cluster_plugin_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
ssize_t ret = 0;
spin_lock(&ocfs2_stack_lock);
if (active_stack) {
ret = snprintf(buf, PAGE_SIZE, "%s\n",
active_stack->sp_name);
if (ret == PAGE_SIZE)
ret = -E2BIG;
}
spin_unlock(&ocfs2_stack_lock);
return ret;
}
static struct kobj_attribute ocfs2_attr_active_cluster_plugin =
__ATTR(active_cluster_plugin, S_IFREG | S_IRUGO,
ocfs2_active_cluster_plugin_show, NULL);
static ssize_t ocfs2_cluster_stack_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
ssize_t ret;
spin_lock(&ocfs2_stack_lock);
ret = snprintf(buf, PAGE_SIZE, "%s\n", cluster_stack_name);
spin_unlock(&ocfs2_stack_lock);
return ret;
}
static ssize_t ocfs2_cluster_stack_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
size_t len = count;
ssize_t ret;
if (len == 0)
return len;
if (buf[len - 1] == '\n')
len--;
if ((len != OCFS2_STACK_LABEL_LEN) ||
(strnlen(buf, len) != len))
return -EINVAL;
spin_lock(&ocfs2_stack_lock);
if (active_stack) {
if (!strncmp(buf, cluster_stack_name, len))
ret = count;
else
ret = -EBUSY;
} else {
memcpy(cluster_stack_name, buf, len);
ret = count;
}
spin_unlock(&ocfs2_stack_lock);
return ret;
}
static struct kobj_attribute ocfs2_attr_cluster_stack =
__ATTR(cluster_stack, S_IFREG | S_IRUGO | S_IWUSR,
ocfs2_cluster_stack_show,
ocfs2_cluster_stack_store);
static struct attribute *ocfs2_attrs[] = {
&ocfs2_attr_max_locking_protocol.attr,
&ocfs2_attr_loaded_cluster_plugins.attr,
&ocfs2_attr_active_cluster_plugin.attr,
&ocfs2_attr_cluster_stack.attr,
NULL,
};
static struct attribute_group ocfs2_attr_group = {
.attrs = ocfs2_attrs,
};
static struct kset *ocfs2_kset;
static void ocfs2_sysfs_exit(void)
{
kset_unregister(ocfs2_kset);
}
static int ocfs2_sysfs_init(void)
{
int ret;
ocfs2_kset = kset_create_and_add("ocfs2", NULL, fs_kobj);
if (!ocfs2_kset)
return -ENOMEM;
ret = sysfs_create_group(&ocfs2_kset->kobj, &ocfs2_attr_group);
if (ret)
goto error;
return 0;
error:
kset_unregister(ocfs2_kset);
return ret;
}
/*
* Sysctl bits
*
* The sysctl lives at /proc/sys/fs/ocfs2/nm/hb_ctl_path. The 'nm' doesn't
* make as much sense in a multiple cluster stack world, but it's safer
* and easier to preserve the name.
*/
#define FS_OCFS2_NM 1
static ctl_table ocfs2_nm_table[] = {
{
.procname = "hb_ctl_path",
.data = ocfs2_hb_ctl_path,
.maxlen = OCFS2_MAX_HB_CTL_PATH,
.mode = 0644,
.proc_handler = proc_dostring,
},
{ }
};
static ctl_table ocfs2_mod_table[] = {
{
.procname = "nm",
.data = NULL,
.maxlen = 0,
.mode = 0555,
.child = ocfs2_nm_table
},
{ }
};
static ctl_table ocfs2_kern_table[] = {
{
.procname = "ocfs2",
.data = NULL,
.maxlen = 0,
.mode = 0555,
.child = ocfs2_mod_table
},
{ }
};
static ctl_table ocfs2_root_table[] = {
{
.procname = "fs",
.data = NULL,
.maxlen = 0,
.mode = 0555,
.child = ocfs2_kern_table
},
{ }
};
static struct ctl_table_header *ocfs2_table_header = NULL;
/*
* Initialization
*/
static int __init ocfs2_stack_glue_init(void)
{
strcpy(cluster_stack_name, OCFS2_STACK_PLUGIN_O2CB);
ocfs2_table_header = register_sysctl_table(ocfs2_root_table);
if (!ocfs2_table_header) {
printk(KERN_ERR
"ocfs2 stack glue: unable to register sysctl\n");
return -ENOMEM; /* or something. */
}
return ocfs2_sysfs_init();
}
static void __exit ocfs2_stack_glue_exit(void)
{
memset(&locking_max_version, 0,
sizeof(struct ocfs2_protocol_version));
locking_max_version.pv_major = 0;
locking_max_version.pv_minor = 0;
ocfs2_sysfs_exit();
if (ocfs2_table_header)
unregister_sysctl_table(ocfs2_table_header);
}
MODULE_AUTHOR("Oracle");
MODULE_DESCRIPTION("ocfs2 cluter stack glue layer");
MODULE_LICENSE("GPL");
module_init(ocfs2_stack_glue_init);
module_exit(ocfs2_stack_glue_exit);
| gpl-2.0 |
krexus-partners/kernel_moto_shamu | block/partitions/sun.c | 13089 | 3827 | /*
* fs/partitions/sun.c
*
* Code extracted from drivers/block/genhd.c
*
* Copyright (C) 1991-1998 Linus Torvalds
* Re-organised Feb 1998 Russell King
*/
#include "check.h"
#include "sun.h"
int sun_partition(struct parsed_partitions *state)
{
int i;
__be16 csum;
int slot = 1;
__be16 *ush;
Sector sect;
struct sun_disklabel {
unsigned char info[128]; /* Informative text string */
struct sun_vtoc {
__be32 version; /* Layout version */
char volume[8]; /* Volume name */
__be16 nparts; /* Number of partitions */
struct sun_info { /* Partition hdrs, sec 2 */
__be16 id;
__be16 flags;
} infos[8];
__be16 padding; /* Alignment padding */
__be32 bootinfo[3]; /* Info needed by mboot */
__be32 sanity; /* To verify vtoc sanity */
__be32 reserved[10]; /* Free space */
__be32 timestamp[8]; /* Partition timestamp */
} vtoc;
__be32 write_reinstruct; /* sectors to skip, writes */
__be32 read_reinstruct; /* sectors to skip, reads */
unsigned char spare[148]; /* Padding */
__be16 rspeed; /* Disk rotational speed */
__be16 pcylcount; /* Physical cylinder count */
__be16 sparecyl; /* extra sects per cylinder */
__be16 obs1; /* gap1 */
__be16 obs2; /* gap2 */
__be16 ilfact; /* Interleave factor */
__be16 ncyl; /* Data cylinder count */
__be16 nacyl; /* Alt. cylinder count */
__be16 ntrks; /* Tracks per cylinder */
__be16 nsect; /* Sectors per track */
__be16 obs3; /* bhead - Label head offset */
__be16 obs4; /* ppart - Physical Partition */
struct sun_partition {
__be32 start_cylinder;
__be32 num_sectors;
} partitions[8];
__be16 magic; /* Magic number */
__be16 csum; /* Label xor'd checksum */
} * label;
struct sun_partition *p;
unsigned long spc;
char b[BDEVNAME_SIZE];
int use_vtoc;
int nparts;
label = read_part_sector(state, 0, §);
if (!label)
return -1;
p = label->partitions;
if (be16_to_cpu(label->magic) != SUN_LABEL_MAGIC) {
/* printk(KERN_INFO "Dev %s Sun disklabel: bad magic %04x\n",
bdevname(bdev, b), be16_to_cpu(label->magic)); */
put_dev_sector(sect);
return 0;
}
/* Look at the checksum */
ush = ((__be16 *) (label+1)) - 1;
for (csum = 0; ush >= ((__be16 *) label);)
csum ^= *ush--;
if (csum) {
printk("Dev %s Sun disklabel: Csum bad, label corrupted\n",
bdevname(state->bdev, b));
put_dev_sector(sect);
return 0;
}
/* Check to see if we can use the VTOC table */
use_vtoc = ((be32_to_cpu(label->vtoc.sanity) == SUN_VTOC_SANITY) &&
(be32_to_cpu(label->vtoc.version) == 1) &&
(be16_to_cpu(label->vtoc.nparts) <= 8));
/* Use 8 partition entries if not specified in validated VTOC */
nparts = (use_vtoc) ? be16_to_cpu(label->vtoc.nparts) : 8;
/*
* So that old Linux-Sun partitions continue to work,
* alow the VTOC to be used under the additional condition ...
*/
use_vtoc = use_vtoc || !(label->vtoc.sanity ||
label->vtoc.version || label->vtoc.nparts);
spc = be16_to_cpu(label->ntrks) * be16_to_cpu(label->nsect);
for (i = 0; i < nparts; i++, p++) {
unsigned long st_sector;
unsigned int num_sectors;
st_sector = be32_to_cpu(p->start_cylinder) * spc;
num_sectors = be32_to_cpu(p->num_sectors);
if (num_sectors) {
put_partition(state, slot, st_sector, num_sectors);
state->parts[slot].flags = 0;
if (use_vtoc) {
if (be16_to_cpu(label->vtoc.infos[i].id) == LINUX_RAID_PARTITION)
state->parts[slot].flags |= ADDPART_FLAG_RAID;
else if (be16_to_cpu(label->vtoc.infos[i].id) == SUN_WHOLE_DISK)
state->parts[slot].flags |= ADDPART_FLAG_WHOLEDISK;
}
}
slot++;
}
strlcat(state->pp_buf, "\n", PAGE_SIZE);
put_dev_sector(sect);
return 1;
}
| gpl-2.0 |
SMAICP/kernel_amazon_otter-common | arch/mips/pci/fixup-rbtx4938.c | 13857 | 1221 | /*
* Toshiba rbtx4938 pci routines
* Copyright (C) 2000-2001 Toshiba Corporation
*
* 2003-2005 (c) MontaVista Software, Inc. This file is licensed under the
* terms of the GNU General Public License version 2. This program is
* licensed "as is" without any warranty of any kind, whether express
* or implied.
*
* Support for TX4938 in 2.6 - Manish Lachwani (mlachwani@mvista.com)
*/
#include <linux/types.h>
#include <asm/txx9/pci.h>
#include <asm/txx9/rbtx4938.h>
int __init rbtx4938_pci_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
int irq = tx4938_pcic1_map_irq(dev, slot);
if (irq >= 0)
return irq;
irq = pin;
/* IRQ rotation */
irq--; /* 0-3 */
if (slot == TX4927_PCIC_IDSEL_AD_TO_SLOT(23)) {
/* PCI CardSlot (IDSEL=A23) */
/* PCIA => PCIA (IDSEL=A23) */
irq = (irq + 0 + slot) % 4;
} else {
/* PCI Backplane */
if (txx9_pci_option & TXX9_PCI_OPT_PICMG)
irq = (irq + 33 - slot) % 4;
else
irq = (irq + 3 + slot) % 4;
}
irq++; /* 1-4 */
switch (irq) {
case 1:
irq = RBTX4938_IRQ_IOC_PCIA;
break;
case 2:
irq = RBTX4938_IRQ_IOC_PCIB;
break;
case 3:
irq = RBTX4938_IRQ_IOC_PCIC;
break;
case 4:
irq = RBTX4938_IRQ_IOC_PCID;
break;
}
return irq;
}
| gpl-2.0 |
k5t4j5/kernel_htc_m8 | drivers/net/ethernet/amd/ariadne.c | 34 | 18354 | /*
* Amiga Linux/m68k Ariadne Ethernet Driver
*
* © Copyright 1995-2003 by Geert Uytterhoeven (geert@linux-m68k.org)
* Peter De Schrijver (p2@mind.be)
*
* ---------------------------------------------------------------------------
*
* This program is based on
*
* lance.c: An AMD LANCE ethernet driver for linux.
* Written 1993-94 by Donald Becker.
*
* Am79C960: PCnet(tm)-ISA Single-Chip Ethernet Controller
* Advanced Micro Devices
* Publication #16907, Rev. B, Amendment/0, May 1994
*
* MC68230: Parallel Interface/Timer (PI/T)
* Motorola Semiconductors, December, 1983
*
* ---------------------------------------------------------------------------
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of the Linux
* distribution for more details.
*
* ---------------------------------------------------------------------------
*
* The Ariadne is a Zorro-II board made by Village Tronic. It contains:
*
* - an Am79C960 PCnet-ISA Single-Chip Ethernet Controller with both
* 10BASE-2 (thin coax) and 10BASE-T (UTP) connectors
*
* - an MC68230 Parallel Interface/Timer configured as 2 parallel ports
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/zorro.h>
#include <linux/bitops.h>
#include <asm/amigaints.h>
#include <asm/amigahw.h>
#include <asm/irq.h>
#include "ariadne.h"
#ifdef ARIADNE_DEBUG
int ariadne_debug = ARIADNE_DEBUG;
#else
int ariadne_debug = 1;
#endif
#define swapw(x) (((x >> 8) & 0x00ff) | ((x << 8) & 0xff00))
#define lowb(x) (x & 0xff)
#define swhighw(x) ((((x) >> 8) & 0xff00) | (((x) >> 24) & 0x00ff))
#define swloww(x) ((((x) << 8) & 0xff00) | (((x) >> 8) & 0x00ff))
#define TX_RING_SIZE 5
#define RX_RING_SIZE 16
#define PKT_BUF_SIZE 1520
struct ariadne_private {
volatile struct TDRE *tx_ring[TX_RING_SIZE];
volatile struct RDRE *rx_ring[RX_RING_SIZE];
volatile u_short *tx_buff[TX_RING_SIZE];
volatile u_short *rx_buff[RX_RING_SIZE];
int cur_tx, cur_rx;
int dirty_tx;
char tx_full;
};
struct lancedata {
struct TDRE tx_ring[TX_RING_SIZE];
struct RDRE rx_ring[RX_RING_SIZE];
u_short tx_buff[TX_RING_SIZE][PKT_BUF_SIZE / sizeof(u_short)];
u_short rx_buff[RX_RING_SIZE][PKT_BUF_SIZE / sizeof(u_short)];
};
static void memcpyw(volatile u_short *dest, u_short *src, int len)
{
while (len >= 2) {
*(dest++) = *(src++);
len -= 2;
}
if (len == 1)
*dest = (*(u_char *)src) << 8;
}
static void ariadne_init_ring(struct net_device *dev)
{
struct ariadne_private *priv = netdev_priv(dev);
volatile struct lancedata *lancedata = (struct lancedata *)dev->mem_start;
int i;
netif_stop_queue(dev);
priv->tx_full = 0;
priv->cur_rx = priv->cur_tx = 0;
priv->dirty_tx = 0;
for (i = 0; i < TX_RING_SIZE; i++) {
volatile struct TDRE *t = &lancedata->tx_ring[i];
t->TMD0 = swloww(ARIADNE_RAM +
offsetof(struct lancedata, tx_buff[i]));
t->TMD1 = swhighw(ARIADNE_RAM +
offsetof(struct lancedata, tx_buff[i])) |
TF_STP | TF_ENP;
t->TMD2 = swapw((u_short)-PKT_BUF_SIZE);
t->TMD3 = 0;
priv->tx_ring[i] = &lancedata->tx_ring[i];
priv->tx_buff[i] = lancedata->tx_buff[i];
netdev_dbg(dev, "TX Entry %2d at %p, Buf at %p\n",
i, &lancedata->tx_ring[i], lancedata->tx_buff[i]);
}
for (i = 0; i < RX_RING_SIZE; i++) {
volatile struct RDRE *r = &lancedata->rx_ring[i];
r->RMD0 = swloww(ARIADNE_RAM +
offsetof(struct lancedata, rx_buff[i]));
r->RMD1 = swhighw(ARIADNE_RAM +
offsetof(struct lancedata, rx_buff[i])) |
RF_OWN;
r->RMD2 = swapw((u_short)-PKT_BUF_SIZE);
r->RMD3 = 0x0000;
priv->rx_ring[i] = &lancedata->rx_ring[i];
priv->rx_buff[i] = lancedata->rx_buff[i];
netdev_dbg(dev, "RX Entry %2d at %p, Buf at %p\n",
i, &lancedata->rx_ring[i], lancedata->rx_buff[i]);
}
}
static int ariadne_rx(struct net_device *dev)
{
struct ariadne_private *priv = netdev_priv(dev);
int entry = priv->cur_rx % RX_RING_SIZE;
int i;
while (!(lowb(priv->rx_ring[entry]->RMD1) & RF_OWN)) {
int status = lowb(priv->rx_ring[entry]->RMD1);
if (status != (RF_STP | RF_ENP)) {
if (status & RF_ENP)
dev->stats.rx_errors++;
if (status & RF_FRAM)
dev->stats.rx_frame_errors++;
if (status & RF_OFLO)
dev->stats.rx_over_errors++;
if (status & RF_CRC)
dev->stats.rx_crc_errors++;
if (status & RF_BUFF)
dev->stats.rx_fifo_errors++;
priv->rx_ring[entry]->RMD1 &= 0xff00 | RF_STP | RF_ENP;
} else {
short pkt_len = swapw(priv->rx_ring[entry]->RMD3);
struct sk_buff *skb;
skb = netdev_alloc_skb(dev, pkt_len + 2);
if (skb == NULL) {
netdev_warn(dev, "Memory squeeze, deferring packet\n");
for (i = 0; i < RX_RING_SIZE; i++)
if (lowb(priv->rx_ring[(entry + i) % RX_RING_SIZE]->RMD1) & RF_OWN)
break;
if (i > RX_RING_SIZE - 2) {
dev->stats.rx_dropped++;
priv->rx_ring[entry]->RMD1 |= RF_OWN;
priv->cur_rx++;
}
break;
}
skb_reserve(skb, 2);
skb_put(skb, pkt_len);
skb_copy_to_linear_data(skb,
(const void *)priv->rx_buff[entry],
pkt_len);
skb->protocol = eth_type_trans(skb, dev);
netdev_dbg(dev, "RX pkt type 0x%04x from %pM to %pM data 0x%08x len %d\n",
((u_short *)skb->data)[6],
skb->data + 6, skb->data,
(int)skb->data, (int)skb->len);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
priv->rx_ring[entry]->RMD1 |= RF_OWN;
entry = (++priv->cur_rx) % RX_RING_SIZE;
}
priv->cur_rx = priv->cur_rx % RX_RING_SIZE;
return 0;
}
static irqreturn_t ariadne_interrupt(int irq, void *data)
{
struct net_device *dev = (struct net_device *)data;
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
struct ariadne_private *priv;
int csr0, boguscnt;
int handled = 0;
lance->RAP = CSR0;
if (!(lance->RDP & INTR))
return IRQ_NONE;
priv = netdev_priv(dev);
boguscnt = 10;
while ((csr0 = lance->RDP) & (ERR | RINT | TINT) && --boguscnt >= 0) {
lance->RDP = csr0 & ~(INEA | TDMD | STOP | STRT | INIT);
#ifdef DEBUG
if (ariadne_debug > 5) {
netdev_dbg(dev, "interrupt csr0=%#02x new csr=%#02x [",
csr0, lance->RDP);
if (csr0 & INTR)
pr_cont(" INTR");
if (csr0 & INEA)
pr_cont(" INEA");
if (csr0 & RXON)
pr_cont(" RXON");
if (csr0 & TXON)
pr_cont(" TXON");
if (csr0 & TDMD)
pr_cont(" TDMD");
if (csr0 & STOP)
pr_cont(" STOP");
if (csr0 & STRT)
pr_cont(" STRT");
if (csr0 & INIT)
pr_cont(" INIT");
if (csr0 & ERR)
pr_cont(" ERR");
if (csr0 & BABL)
pr_cont(" BABL");
if (csr0 & CERR)
pr_cont(" CERR");
if (csr0 & MISS)
pr_cont(" MISS");
if (csr0 & MERR)
pr_cont(" MERR");
if (csr0 & RINT)
pr_cont(" RINT");
if (csr0 & TINT)
pr_cont(" TINT");
if (csr0 & IDON)
pr_cont(" IDON");
pr_cont(" ]\n");
}
#endif
if (csr0 & RINT) {
handled = 1;
ariadne_rx(dev);
}
if (csr0 & TINT) {
int dirty_tx = priv->dirty_tx;
handled = 1;
while (dirty_tx < priv->cur_tx) {
int entry = dirty_tx % TX_RING_SIZE;
int status = lowb(priv->tx_ring[entry]->TMD1);
if (status & TF_OWN)
break;
priv->tx_ring[entry]->TMD1 &= 0xff00;
if (status & TF_ERR) {
int err_status = priv->tx_ring[entry]->TMD3;
dev->stats.tx_errors++;
if (err_status & EF_RTRY)
dev->stats.tx_aborted_errors++;
if (err_status & EF_LCAR)
dev->stats.tx_carrier_errors++;
if (err_status & EF_LCOL)
dev->stats.tx_window_errors++;
if (err_status & EF_UFLO) {
dev->stats.tx_fifo_errors++;
netdev_err(dev, "Tx FIFO error! Status %04x\n",
csr0);
lance->RDP = STRT;
}
} else {
if (status & (TF_MORE | TF_ONE))
dev->stats.collisions++;
dev->stats.tx_packets++;
}
dirty_tx++;
}
#ifndef final_version
if (priv->cur_tx - dirty_tx >= TX_RING_SIZE) {
netdev_err(dev, "out-of-sync dirty pointer, %d vs. %d, full=%d\n",
dirty_tx, priv->cur_tx,
priv->tx_full);
dirty_tx += TX_RING_SIZE;
}
#endif
if (priv->tx_full && netif_queue_stopped(dev) &&
dirty_tx > priv->cur_tx - TX_RING_SIZE + 2) {
priv->tx_full = 0;
netif_wake_queue(dev);
}
priv->dirty_tx = dirty_tx;
}
if (csr0 & BABL) {
handled = 1;
dev->stats.tx_errors++;
}
if (csr0 & MISS) {
handled = 1;
dev->stats.rx_errors++;
}
if (csr0 & MERR) {
handled = 1;
netdev_err(dev, "Bus master arbitration failure, status %04x\n",
csr0);
lance->RDP = STRT;
}
}
lance->RAP = CSR0;
lance->RDP = INEA | BABL | CERR | MISS | MERR | IDON;
if (ariadne_debug > 4)
netdev_dbg(dev, "exiting interrupt, csr%d=%#04x\n",
lance->RAP, lance->RDP);
return IRQ_RETVAL(handled);
}
static int ariadne_open(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
u_short in;
u_long version;
int i;
in = lance->Reset;
lance->RAP = CSR0;
lance->RDP = STOP;
lance->RAP = CSR88;
version = swapw(lance->RDP);
lance->RAP = CSR89;
version |= swapw(lance->RDP) << 16;
if ((version & 0x00000fff) != 0x00000003) {
pr_warn("Couldn't find AMD Ethernet Chip\n");
return -EAGAIN;
}
if ((version & 0x0ffff000) != 0x00003000) {
pr_warn("Couldn't find Am79C960 (Wrong part number = %ld)\n",
(version & 0x0ffff000) >> 12);
return -EAGAIN;
}
netdev_dbg(dev, "Am79C960 (PCnet-ISA) Revision %ld\n",
(version & 0xf0000000) >> 28);
ariadne_init_ring(dev);
lance->RAP = CSR3;
lance->RDP = 0x0000;
lance->RAP = CSR4;
lance->RDP = DPOLL | APAD_XMT | MFCOM | RCVCCOM | TXSTRTM | JABM;
lance->RAP = CSR8;
lance->RDP = 0x0000;
lance->RAP = CSR9;
lance->RDP = 0x0000;
lance->RAP = CSR10;
lance->RDP = 0x0000;
lance->RAP = CSR11;
lance->RDP = 0x0000;
lance->RAP = CSR12;
lance->RDP = ((u_short *)&dev->dev_addr[0])[0];
lance->RAP = CSR13;
lance->RDP = ((u_short *)&dev->dev_addr[0])[1];
lance->RAP = CSR14;
lance->RDP = ((u_short *)&dev->dev_addr[0])[2];
lance->RAP = CSR15;
lance->RDP = 0x0000;
lance->RAP = CSR30;
lance->RDP = swloww(ARIADNE_RAM + offsetof(struct lancedata, tx_ring));
lance->RAP = CSR31;
lance->RDP = swhighw(ARIADNE_RAM + offsetof(struct lancedata, tx_ring));
lance->RAP = CSR24;
lance->RDP = swloww(ARIADNE_RAM + offsetof(struct lancedata, rx_ring));
lance->RAP = CSR25;
lance->RDP = swhighw(ARIADNE_RAM + offsetof(struct lancedata, rx_ring));
lance->RAP = CSR76;
lance->RDP = swapw(((u_short)-RX_RING_SIZE));
lance->RAP = CSR78;
lance->RDP = swapw(((u_short)-TX_RING_SIZE));
lance->RAP = ISACSR2;
lance->IDP = ASEL;
lance->RAP = ISACSR5;
lance->IDP = PSE|XMTE;
lance->RAP = ISACSR6;
lance->IDP = PSE|COLE;
lance->RAP = ISACSR7;
lance->IDP = PSE|RCVE;
netif_start_queue(dev);
i = request_irq(IRQ_AMIGA_PORTS, ariadne_interrupt, IRQF_SHARED,
dev->name, dev);
if (i)
return i;
lance->RAP = CSR0;
lance->RDP = INEA | STRT;
return 0;
}
static int ariadne_close(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
netif_stop_queue(dev);
lance->RAP = CSR112;
dev->stats.rx_missed_errors = swapw(lance->RDP);
lance->RAP = CSR0;
if (ariadne_debug > 1) {
netdev_dbg(dev, "Shutting down ethercard, status was %02x\n",
lance->RDP);
netdev_dbg(dev, "%lu packets missed\n",
dev->stats.rx_missed_errors);
}
lance->RDP = STOP;
free_irq(IRQ_AMIGA_PORTS, dev);
return 0;
}
static inline void ariadne_reset(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
lance->RAP = CSR0;
lance->RDP = STOP;
ariadne_init_ring(dev);
lance->RDP = INEA | STRT;
netif_start_queue(dev);
}
static void ariadne_tx_timeout(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
netdev_err(dev, "transmit timed out, status %04x, resetting\n",
lance->RDP);
ariadne_reset(dev);
netif_wake_queue(dev);
}
static netdev_tx_t ariadne_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ariadne_private *priv = netdev_priv(dev);
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
int entry;
unsigned long flags;
int len = skb->len;
#if 0
if (ariadne_debug > 3) {
lance->RAP = CSR0;
netdev_dbg(dev, "%s: csr0 %04x\n", __func__, lance->RDP);
lance->RDP = 0x0000;
}
#endif
if (skb->len < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
len = ETH_ZLEN;
}
netdev_dbg(dev, "TX pkt type 0x%04x from %pM to %pM data 0x%08x len %d\n",
((u_short *)skb->data)[6],
skb->data + 6, skb->data,
(int)skb->data, (int)skb->len);
local_irq_save(flags);
entry = priv->cur_tx % TX_RING_SIZE;
priv->tx_ring[entry]->TMD2 = swapw((u_short)-skb->len);
priv->tx_ring[entry]->TMD3 = 0x0000;
memcpyw(priv->tx_buff[entry], (u_short *)skb->data, len);
#ifdef DEBUG
print_hex_dump(KERN_DEBUG, "tx_buff: ", DUMP_PREFIX_OFFSET, 16, 1,
(void *)priv->tx_buff[entry],
skb->len > 64 ? 64 : skb->len, true);
#endif
priv->tx_ring[entry]->TMD1 = (priv->tx_ring[entry]->TMD1 & 0xff00)
| TF_OWN | TF_STP | TF_ENP;
dev_kfree_skb(skb);
priv->cur_tx++;
if ((priv->cur_tx >= TX_RING_SIZE) &&
(priv->dirty_tx >= TX_RING_SIZE)) {
netdev_dbg(dev, "*** Subtracting TX_RING_SIZE from cur_tx (%d) and dirty_tx (%d)\n",
priv->cur_tx, priv->dirty_tx);
priv->cur_tx -= TX_RING_SIZE;
priv->dirty_tx -= TX_RING_SIZE;
}
dev->stats.tx_bytes += len;
lance->RAP = CSR0;
lance->RDP = INEA | TDMD;
if (lowb(priv->tx_ring[(entry + 1) % TX_RING_SIZE]->TMD1) != 0) {
netif_stop_queue(dev);
priv->tx_full = 1;
}
local_irq_restore(flags);
return NETDEV_TX_OK;
}
static struct net_device_stats *ariadne_get_stats(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
short saved_addr;
unsigned long flags;
local_irq_save(flags);
saved_addr = lance->RAP;
lance->RAP = CSR112;
dev->stats.rx_missed_errors = swapw(lance->RDP);
lance->RAP = saved_addr;
local_irq_restore(flags);
return &dev->stats;
}
static void set_multicast_list(struct net_device *dev)
{
volatile struct Am79C960 *lance = (struct Am79C960 *)dev->base_addr;
if (!netif_running(dev))
return;
netif_stop_queue(dev);
lance->RAP = CSR0;
lance->RDP = STOP;
ariadne_init_ring(dev);
if (dev->flags & IFF_PROMISC) {
lance->RAP = CSR15;
lance->RDP = PROM;
} else {
short multicast_table[4];
int num_addrs = netdev_mc_count(dev);
int i;
memset(multicast_table, (num_addrs == 0) ? 0 : -1,
sizeof(multicast_table));
for (i = 0; i < 4; i++) {
lance->RAP = CSR8 + (i << 8);
lance->RDP = swapw(multicast_table[i]);
}
lance->RAP = CSR15;
lance->RDP = 0x0000;
}
lance->RAP = CSR0;
lance->RDP = INEA | STRT | IDON;
netif_wake_queue(dev);
}
static void __devexit ariadne_remove_one(struct zorro_dev *z)
{
struct net_device *dev = zorro_get_drvdata(z);
unregister_netdev(dev);
release_mem_region(ZTWO_PADDR(dev->base_addr), sizeof(struct Am79C960));
release_mem_region(ZTWO_PADDR(dev->mem_start), ARIADNE_RAM_SIZE);
free_netdev(dev);
}
static struct zorro_device_id ariadne_zorro_tbl[] __devinitdata = {
{ ZORRO_PROD_VILLAGE_TRONIC_ARIADNE },
{ 0 }
};
MODULE_DEVICE_TABLE(zorro, ariadne_zorro_tbl);
static const struct net_device_ops ariadne_netdev_ops = {
.ndo_open = ariadne_open,
.ndo_stop = ariadne_close,
.ndo_start_xmit = ariadne_start_xmit,
.ndo_tx_timeout = ariadne_tx_timeout,
.ndo_get_stats = ariadne_get_stats,
.ndo_set_rx_mode = set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
};
static int __devinit ariadne_init_one(struct zorro_dev *z,
const struct zorro_device_id *ent)
{
unsigned long board = z->resource.start;
unsigned long base_addr = board + ARIADNE_LANCE;
unsigned long mem_start = board + ARIADNE_RAM;
struct resource *r1, *r2;
struct net_device *dev;
struct ariadne_private *priv;
int err;
r1 = request_mem_region(base_addr, sizeof(struct Am79C960), "Am79C960");
if (!r1)
return -EBUSY;
r2 = request_mem_region(mem_start, ARIADNE_RAM_SIZE, "RAM");
if (!r2) {
release_mem_region(base_addr, sizeof(struct Am79C960));
return -EBUSY;
}
dev = alloc_etherdev(sizeof(struct ariadne_private));
if (dev == NULL) {
release_mem_region(base_addr, sizeof(struct Am79C960));
release_mem_region(mem_start, ARIADNE_RAM_SIZE);
return -ENOMEM;
}
priv = netdev_priv(dev);
r1->name = dev->name;
r2->name = dev->name;
dev->dev_addr[0] = 0x00;
dev->dev_addr[1] = 0x60;
dev->dev_addr[2] = 0x30;
dev->dev_addr[3] = (z->rom.er_SerialNumber >> 16) & 0xff;
dev->dev_addr[4] = (z->rom.er_SerialNumber >> 8) & 0xff;
dev->dev_addr[5] = z->rom.er_SerialNumber & 0xff;
dev->base_addr = ZTWO_VADDR(base_addr);
dev->mem_start = ZTWO_VADDR(mem_start);
dev->mem_end = dev->mem_start + ARIADNE_RAM_SIZE;
dev->netdev_ops = &ariadne_netdev_ops;
dev->watchdog_timeo = 5 * HZ;
err = register_netdev(dev);
if (err) {
release_mem_region(base_addr, sizeof(struct Am79C960));
release_mem_region(mem_start, ARIADNE_RAM_SIZE);
free_netdev(dev);
return err;
}
zorro_set_drvdata(z, dev);
netdev_info(dev, "Ariadne at 0x%08lx, Ethernet Address %pM\n",
board, dev->dev_addr);
return 0;
}
static struct zorro_driver ariadne_driver = {
.name = "ariadne",
.id_table = ariadne_zorro_tbl,
.probe = ariadne_init_one,
.remove = __devexit_p(ariadne_remove_one),
};
static int __init ariadne_init_module(void)
{
return zorro_register_driver(&ariadne_driver);
}
static void __exit ariadne_cleanup_module(void)
{
zorro_unregister_driver(&ariadne_driver);
}
module_init(ariadne_init_module);
module_exit(ariadne_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
flar2/m8-Sense | arch/sparc/kernel/leon_smp.c | 34 | 11790 | /* leon_smp.c: Sparc-Leon SMP support.
*
* based on sun4m_smp.c
* Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 2009 Daniel Hellstrom (daniel@gaisler.com) Aeroflex Gaisler AB
* Copyright (C) 2009 Konrad Eisele (konrad@gaisler.com) Aeroflex Gaisler AB
*/
#include <asm/head.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/threads.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/of.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/profile.h>
#include <linux/pm.h>
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/cpu.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/ptrace.h>
#include <linux/atomic.h>
#include <asm/irq_regs.h>
#include <asm/traps.h>
#include <asm/delay.h>
#include <asm/irq.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/oplib.h>
#include <asm/cpudata.h>
#include <asm/asi.h>
#include <asm/leon.h>
#include <asm/leon_amba.h>
#include "kernel.h"
#ifdef CONFIG_SPARC_LEON
#include "irq.h"
extern ctxd_t *srmmu_ctx_table_phys;
static int smp_processors_ready;
extern volatile unsigned long cpu_callin_map[NR_CPUS];
extern cpumask_t smp_commenced_mask;
void __init leon_configure_cache_smp(void);
static void leon_ipi_init(void);
int leon_ipi_irq = LEON3_IRQ_IPI_DEFAULT;
static inline unsigned long do_swap(volatile unsigned long *ptr,
unsigned long val)
{
__asm__ __volatile__("swapa [%2] %3, %0\n\t" : "=&r"(val)
: "0"(val), "r"(ptr), "i"(ASI_LEON_DCACHE_MISS)
: "memory");
return val;
}
static void smp_setup_percpu_timer(void);
void __cpuinit leon_callin(void)
{
int cpuid = hard_smpleon_processor_id();
local_flush_cache_all();
local_flush_tlb_all();
leon_configure_cache_smp();
notify_cpu_starting(cpuid);
smp_setup_percpu_timer();
calibrate_delay();
smp_store_cpu_info(cpuid);
local_flush_cache_all();
local_flush_tlb_all();
do_swap(&cpu_callin_map[cpuid], 1);
local_flush_cache_all();
local_flush_tlb_all();
__asm__ __volatile__("ld [%0], %%g6\n\t" : : "r"(¤t_set[cpuid])
: "memory" );
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
while (!cpumask_test_cpu(cpuid, &smp_commenced_mask))
mb();
local_irq_enable();
set_cpu_online(cpuid, true);
}
extern struct linux_prom_registers smp_penguin_ctable;
void __init leon_configure_cache_smp(void)
{
unsigned long cfg = sparc_leon3_get_dcachecfg();
int me = smp_processor_id();
if (ASI_LEON3_SYSCTRL_CFG_SSIZE(cfg) > 4) {
printk(KERN_INFO "Note: SMP with snooping only works on 4k cache, found %dk(0x%x) on cpu %d, disabling caches\n",
(unsigned int)ASI_LEON3_SYSCTRL_CFG_SSIZE(cfg),
(unsigned int)cfg, (unsigned int)me);
sparc_leon3_disable_cache();
} else {
if (cfg & ASI_LEON3_SYSCTRL_CFG_SNOOPING) {
sparc_leon3_enable_snooping();
} else {
printk(KERN_INFO "Note: You have to enable snooping in the vhdl model cpu %d, disabling caches\n",
me);
sparc_leon3_disable_cache();
}
}
local_flush_cache_all();
local_flush_tlb_all();
}
void leon_smp_setbroadcast(unsigned int mask)
{
int broadcast =
((LEON3_BYPASS_LOAD_PA(&(leon3_irqctrl_regs->mpstatus)) >>
LEON3_IRQMPSTATUS_BROADCAST) & 1);
if (!broadcast) {
prom_printf("######## !!!! The irqmp-ctrl must have broadcast enabled, smp wont work !!!!! ####### nr cpus: %d\n",
leon_smp_nrcpus());
if (leon_smp_nrcpus() > 1) {
BUG();
} else {
prom_printf("continue anyway\n");
return;
}
}
LEON_BYPASS_STORE_PA(&(leon3_irqctrl_regs->mpbroadcast), mask);
}
unsigned int leon_smp_getbroadcast(void)
{
unsigned int mask;
mask = LEON_BYPASS_LOAD_PA(&(leon3_irqctrl_regs->mpbroadcast));
return mask;
}
int leon_smp_nrcpus(void)
{
int nrcpu =
((LEON3_BYPASS_LOAD_PA(&(leon3_irqctrl_regs->mpstatus)) >>
LEON3_IRQMPSTATUS_CPUNR) & 0xf) + 1;
return nrcpu;
}
void __init leon_boot_cpus(void)
{
int nrcpu = leon_smp_nrcpus();
int me = smp_processor_id();
leon_ipi_init();
printk(KERN_INFO "%d:(%d:%d) cpus mpirq at 0x%x\n", (unsigned int)me,
(unsigned int)nrcpu, (unsigned int)NR_CPUS,
(unsigned int)&(leon3_irqctrl_regs->mpstatus));
leon_enable_irq_cpu(LEON3_IRQ_CROSS_CALL, me);
leon_enable_irq_cpu(LEON3_IRQ_TICKER, me);
leon_enable_irq_cpu(leon_ipi_irq, me);
leon_smp_setbroadcast(1 << LEON3_IRQ_TICKER);
leon_configure_cache_smp();
smp_setup_percpu_timer();
local_flush_cache_all();
}
int __cpuinit leon_boot_one_cpu(int i)
{
struct task_struct *p;
int timeout;
p = fork_idle(i);
current_set[i] = task_thread_info(p);
smp_penguin_ctable.which_io = 0;
smp_penguin_ctable.phys_addr = (unsigned int)srmmu_ctx_table_phys;
smp_penguin_ctable.reg_size = 0;
printk(KERN_INFO "Starting CPU %d : (irqmp: 0x%x)\n", (unsigned int)i,
(unsigned int)&leon3_irqctrl_regs->mpstatus);
local_flush_cache_all();
LEON_BYPASS_STORE_PA(&leon3_irqctrl_regs->mask[i], 0);
LEON_BYPASS_STORE_PA(&(leon3_irqctrl_regs->mpstatus), 1 << i);
for (timeout = 0; timeout < 10000; timeout++) {
if (cpu_callin_map[i])
break;
udelay(200);
}
printk(KERN_INFO "Started CPU %d\n", (unsigned int)i);
if (!(cpu_callin_map[i])) {
printk(KERN_ERR "Processor %d is stuck.\n", i);
return -ENODEV;
} else {
leon_enable_irq_cpu(LEON3_IRQ_CROSS_CALL, i);
leon_enable_irq_cpu(LEON3_IRQ_TICKER, i);
leon_enable_irq_cpu(leon_ipi_irq, i);
}
local_flush_cache_all();
return 0;
}
void __init leon_smp_done(void)
{
int i, first;
int *prev;
first = 0;
prev = &first;
for (i = 0; i < NR_CPUS; i++) {
if (cpu_online(i)) {
*prev = i;
prev = &cpu_data(i).next;
}
}
*prev = first;
local_flush_cache_all();
if (!cpu_present(1)) {
ClearPageReserved(virt_to_page(&trapbase_cpu1));
init_page_count(virt_to_page(&trapbase_cpu1));
free_page((unsigned long)&trapbase_cpu1);
totalram_pages++;
num_physpages++;
}
if (!cpu_present(2)) {
ClearPageReserved(virt_to_page(&trapbase_cpu2));
init_page_count(virt_to_page(&trapbase_cpu2));
free_page((unsigned long)&trapbase_cpu2);
totalram_pages++;
num_physpages++;
}
if (!cpu_present(3)) {
ClearPageReserved(virt_to_page(&trapbase_cpu3));
init_page_count(virt_to_page(&trapbase_cpu3));
free_page((unsigned long)&trapbase_cpu3);
totalram_pages++;
num_physpages++;
}
smp_processors_ready = 1;
}
void leon_irq_rotate(int cpu)
{
}
struct leon_ipi_work {
int single;
int msk;
int resched;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct leon_ipi_work, leon_ipi_work);
static void __init leon_ipi_init(void)
{
int cpu, len;
struct leon_ipi_work *work;
struct property *pp;
struct device_node *rootnp;
struct tt_entry *trap_table;
unsigned long flags;
rootnp = of_find_node_by_path("/ambapp0");
if (rootnp) {
pp = of_find_property(rootnp, "ipi_num", &len);
if (pp && (*(int *)pp->value))
leon_ipi_irq = *(int *)pp->value;
}
printk(KERN_INFO "leon: SMP IPIs at IRQ %d\n", leon_ipi_irq);
local_irq_save(flags);
trap_table = &sparc_ttable[SP_TRAP_IRQ1 + (leon_ipi_irq - 1)];
trap_table->inst_three += smpleon_ipi - real_irq_entry;
local_flush_cache_all();
local_irq_restore(flags);
for_each_possible_cpu(cpu) {
work = &per_cpu(leon_ipi_work, cpu);
work->single = work->msk = work->resched = 0;
}
}
static void leon_ipi_single(int cpu)
{
struct leon_ipi_work *work = &per_cpu(leon_ipi_work, cpu);
work->single = 1;
set_cpu_int(cpu, leon_ipi_irq);
}
static void leon_ipi_mask_one(int cpu)
{
struct leon_ipi_work *work = &per_cpu(leon_ipi_work, cpu);
work->msk = 1;
set_cpu_int(cpu, leon_ipi_irq);
}
static void leon_ipi_resched(int cpu)
{
struct leon_ipi_work *work = &per_cpu(leon_ipi_work, cpu);
work->resched = 1;
set_cpu_int(cpu, leon_ipi_irq);
}
void leonsmp_ipi_interrupt(void)
{
struct leon_ipi_work *work = &__get_cpu_var(leon_ipi_work);
if (work->single) {
work->single = 0;
smp_call_function_single_interrupt();
}
if (work->msk) {
work->msk = 0;
smp_call_function_interrupt();
}
if (work->resched) {
work->resched = 0;
smp_resched_interrupt();
}
}
static struct smp_funcall {
smpfunc_t func;
unsigned long arg1;
unsigned long arg2;
unsigned long arg3;
unsigned long arg4;
unsigned long arg5;
unsigned long processors_in[NR_CPUS];
unsigned long processors_out[NR_CPUS];
} ccall_info;
static DEFINE_SPINLOCK(cross_call_lock);
static void leon_cross_call(smpfunc_t func, cpumask_t mask, unsigned long arg1,
unsigned long arg2, unsigned long arg3,
unsigned long arg4)
{
if (smp_processors_ready) {
register int high = NR_CPUS - 1;
unsigned long flags;
spin_lock_irqsave(&cross_call_lock, flags);
{
register smpfunc_t f asm("i0") = func;
register unsigned long a1 asm("i1") = arg1;
register unsigned long a2 asm("i2") = arg2;
register unsigned long a3 asm("i3") = arg3;
register unsigned long a4 asm("i4") = arg4;
register unsigned long a5 asm("i5") = 0;
__asm__ __volatile__("std %0, [%6]\n\t"
"std %2, [%6 + 8]\n\t"
"std %4, [%6 + 16]\n\t" : :
"r"(f), "r"(a1), "r"(a2), "r"(a3),
"r"(a4), "r"(a5),
"r"(&ccall_info.func));
}
{
register int i;
cpumask_clear_cpu(smp_processor_id(), &mask);
cpumask_and(&mask, cpu_online_mask, &mask);
for (i = 0; i <= high; i++) {
if (cpumask_test_cpu(i, &mask)) {
ccall_info.processors_in[i] = 0;
ccall_info.processors_out[i] = 0;
set_cpu_int(i, LEON3_IRQ_CROSS_CALL);
}
}
}
{
register int i;
i = 0;
do {
if (!cpumask_test_cpu(i, &mask))
continue;
while (!ccall_info.processors_in[i])
barrier();
} while (++i <= high);
i = 0;
do {
if (!cpumask_test_cpu(i, &mask))
continue;
while (!ccall_info.processors_out[i])
barrier();
} while (++i <= high);
}
spin_unlock_irqrestore(&cross_call_lock, flags);
}
}
void leon_cross_call_irq(void)
{
int i = smp_processor_id();
ccall_info.processors_in[i] = 1;
ccall_info.func(ccall_info.arg1, ccall_info.arg2, ccall_info.arg3,
ccall_info.arg4, ccall_info.arg5);
ccall_info.processors_out[i] = 1;
}
irqreturn_t leon_percpu_timer_interrupt(int irq, void *unused)
{
int cpu = smp_processor_id();
leon_clear_profile_irq(cpu);
profile_tick(CPU_PROFILING);
if (!--prof_counter(cpu)) {
int user = user_mode(get_irq_regs());
update_process_times(user);
prof_counter(cpu) = prof_multiplier(cpu);
}
return IRQ_HANDLED;
}
static void __init smp_setup_percpu_timer(void)
{
int cpu = smp_processor_id();
prof_counter(cpu) = prof_multiplier(cpu) = 1;
}
void __init leon_blackbox_id(unsigned *addr)
{
int rd = *addr & 0x3e000000;
int rs1 = rd >> 11;
addr[0] = 0x81444000 | rd;
addr[1] = 0x8130201c | rd | rs1;
addr[2] = 0x01000000;
}
void __init leon_blackbox_current(unsigned *addr)
{
int rd = *addr & 0x3e000000;
int rs1 = rd >> 11;
addr[0] = 0x81444000 | rd;
addr[2] = 0x8130201c | rd | rs1;
addr[4] = 0x81282002 | rd | rs1;
}
void __init leon_init_smp(void)
{
t_nmi[1] = t_nmi[1] + (linux_trap_ipi15_leon - linux_trap_ipi15_sun4m);
BTFIXUPSET_BLACKBOX(hard_smp_processor_id, leon_blackbox_id);
BTFIXUPSET_BLACKBOX(load_current, leon_blackbox_current);
BTFIXUPSET_CALL(smp_cross_call, leon_cross_call, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(__hard_smp_processor_id, __leon_processor_id,
BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(smp_ipi_resched, leon_ipi_resched, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(smp_ipi_single, leon_ipi_single, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(smp_ipi_mask_one, leon_ipi_mask_one, BTFIXUPCALL_NORM);
}
#endif
| gpl-2.0 |
ljalves/linux_media | arch/openrisc/kernel/process.c | 34 | 7393 | /*
* OpenRISC process.c
*
* Linux architectural port borrowing liberally from similar works of
* others. All original copyrights apply as per the original source
* declaration.
*
* Modifications for the OpenRISC architecture:
* Copyright (C) 2003 Matjaz Breskvar <phoenix@bsemi.com>
* Copyright (C) 2010-2011 Jonas Bonn <jonas@southpole.se>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* This file handles the architecture-dependent parts of process handling...
*/
#define __KERNEL_SYSCALLS__
#include <stdarg.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/elfcore.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/init_task.h>
#include <linux/mqueue.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <asm/pgtable.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/spr_defs.h>
#include <linux/smp.h>
/*
* Pointer to Current thread info structure.
*
* Used at user space -> kernel transitions.
*/
struct thread_info *current_thread_info_set[NR_CPUS] = { &init_thread_info, };
void machine_restart(void)
{
printk(KERN_INFO "*** MACHINE RESTART ***\n");
__asm__("l.nop 1");
}
/*
* Similar to machine_power_off, but don't shut off power. Add code
* here to freeze the system for e.g. post-mortem debug purpose when
* possible. This halt has nothing to do with the idle halt.
*/
void machine_halt(void)
{
printk(KERN_INFO "*** MACHINE HALT ***\n");
__asm__("l.nop 1");
}
/* If or when software power-off is implemented, add code here. */
void machine_power_off(void)
{
printk(KERN_INFO "*** MACHINE POWER OFF ***\n");
__asm__("l.nop 1");
}
void (*pm_power_off) (void) = machine_power_off;
/*
* When a process does an "exec", machine state like FPU and debug
* registers need to be reset. This is a hook function for that.
* Currently we don't have any such state to reset, so this is empty.
*/
void flush_thread(void)
{
}
void show_regs(struct pt_regs *regs)
{
extern void show_registers(struct pt_regs *regs);
show_regs_print_info(KERN_DEFAULT);
/* __PHX__ cleanup this mess */
show_registers(regs);
}
unsigned long thread_saved_pc(struct task_struct *t)
{
return (unsigned long)user_regs(t->stack)->pc;
}
void release_thread(struct task_struct *dead_task)
{
}
/*
* Copy the thread-specific (arch specific) info from the current
* process to the new one p
*/
extern asmlinkage void ret_from_fork(void);
/*
* copy_thread
* @clone_flags: flags
* @usp: user stack pointer or fn for kernel thread
* @arg: arg to fn for kernel thread; always NULL for userspace thread
* @p: the newly created task
* @regs: CPU context to copy for userspace thread; always NULL for kthread
*
* At the top of a newly initialized kernel stack are two stacked pt_reg
* structures. The first (topmost) is the userspace context of the thread.
* The second is the kernelspace context of the thread.
*
* A kernel thread will not be returning to userspace, so the topmost pt_regs
* struct can be uninitialized; it _does_ need to exist, though, because
* a kernel thread can become a userspace thread by doing a kernel_execve, in
* which case the topmost context will be initialized and used for 'returning'
* to userspace.
*
* The second pt_reg struct needs to be initialized to 'return' to
* ret_from_fork. A kernel thread will need to set r20 to the address of
* a function to call into (with arg in r22); userspace threads need to set
* r20 to NULL in which case ret_from_fork will just continue a return to
* userspace.
*
* A kernel thread 'fn' may return; this is effectively what happens when
* kernel_execve is called. In that case, the userspace pt_regs must have
* been initialized (which kernel_execve takes care of, see start_thread
* below); ret_from_fork will then continue its execution causing the
* 'kernel thread' to return to userspace as a userspace thread.
*/
int
copy_thread(unsigned long clone_flags, unsigned long usp,
unsigned long arg, struct task_struct *p)
{
struct pt_regs *userregs;
struct pt_regs *kregs;
unsigned long sp = (unsigned long)task_stack_page(p) + THREAD_SIZE;
unsigned long top_of_kernel_stack;
top_of_kernel_stack = sp;
p->set_child_tid = p->clear_child_tid = NULL;
/* Locate userspace context on stack... */
sp -= STACK_FRAME_OVERHEAD; /* redzone */
sp -= sizeof(struct pt_regs);
userregs = (struct pt_regs *) sp;
/* ...and kernel context */
sp -= STACK_FRAME_OVERHEAD; /* redzone */
sp -= sizeof(struct pt_regs);
kregs = (struct pt_regs *)sp;
if (unlikely(p->flags & PF_KTHREAD)) {
memset(kregs, 0, sizeof(struct pt_regs));
kregs->gpr[20] = usp; /* fn, kernel thread */
kregs->gpr[22] = arg;
} else {
*userregs = *current_pt_regs();
if (usp)
userregs->sp = usp;
/*
* For CLONE_SETTLS set "tp" (r10) to the TLS pointer passed to sys_clone.
*
* The kernel entry is:
* int clone (long flags, void *child_stack, int *parent_tid,
* int *child_tid, struct void *tls)
*
* This makes the source r7 in the kernel registers.
*/
if (clone_flags & CLONE_SETTLS)
userregs->gpr[10] = userregs->gpr[7];
userregs->gpr[11] = 0; /* Result from fork() */
kregs->gpr[20] = 0; /* Userspace thread */
}
/*
* _switch wants the kernel stack page in pt_regs->sp so that it
* can restore it to thread_info->ksp... see _switch for details.
*/
kregs->sp = top_of_kernel_stack;
kregs->gpr[9] = (unsigned long)ret_from_fork;
task_thread_info(p)->ksp = (unsigned long)kregs;
return 0;
}
/*
* Set up a thread for executing a new program
*/
void start_thread(struct pt_regs *regs, unsigned long pc, unsigned long sp)
{
unsigned long sr = mfspr(SPR_SR) & ~SPR_SR_SM;
memset(regs, 0, sizeof(struct pt_regs));
regs->pc = pc;
regs->sr = sr;
regs->sp = sp;
}
/* Fill in the fpu structure for a core dump. */
int dump_fpu(struct pt_regs *regs, elf_fpregset_t * fpu)
{
/* TODO */
return 0;
}
extern struct thread_info *_switch(struct thread_info *old_ti,
struct thread_info *new_ti);
struct task_struct *__switch_to(struct task_struct *old,
struct task_struct *new)
{
struct task_struct *last;
struct thread_info *new_ti, *old_ti;
unsigned long flags;
local_irq_save(flags);
/* current_set is an array of saved current pointers
* (one for each cpu). we need them at user->kernel transition,
* while we save them at kernel->user transition
*/
new_ti = new->stack;
old_ti = old->stack;
current_thread_info_set[smp_processor_id()] = new_ti;
last = (_switch(old_ti, new_ti))->task;
local_irq_restore(flags);
return last;
}
/*
* Write out registers in core dump format, as defined by the
* struct user_regs_struct
*/
void dump_elf_thread(elf_greg_t *dest, struct pt_regs* regs)
{
dest[0] = 0; /* r0 */
memcpy(dest+1, regs->gpr+1, 31*sizeof(unsigned long));
dest[32] = regs->pc;
dest[33] = regs->sr;
dest[34] = 0;
dest[35] = 0;
}
unsigned long get_wchan(struct task_struct *p)
{
/* TODO */
return 0;
}
| gpl-2.0 |
standak3/ElementalX_4.4.2 | net/rds/ib_send.c | 34 | 23256 | /*
* Copyright (c) 2006 Oracle. 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/kernel.h>
#include <linux/in.h>
#include <linux/device.h>
#include <linux/dmapool.h>
#include <linux/ratelimit.h>
#include "rds.h"
#include "ib.h"
static char *rds_ib_wc_status_strings[] = {
#define RDS_IB_WC_STATUS_STR(foo) \
[IB_WC_##foo] = __stringify(IB_WC_##foo)
RDS_IB_WC_STATUS_STR(SUCCESS),
RDS_IB_WC_STATUS_STR(LOC_LEN_ERR),
RDS_IB_WC_STATUS_STR(LOC_QP_OP_ERR),
RDS_IB_WC_STATUS_STR(LOC_EEC_OP_ERR),
RDS_IB_WC_STATUS_STR(LOC_PROT_ERR),
RDS_IB_WC_STATUS_STR(WR_FLUSH_ERR),
RDS_IB_WC_STATUS_STR(MW_BIND_ERR),
RDS_IB_WC_STATUS_STR(BAD_RESP_ERR),
RDS_IB_WC_STATUS_STR(LOC_ACCESS_ERR),
RDS_IB_WC_STATUS_STR(REM_INV_REQ_ERR),
RDS_IB_WC_STATUS_STR(REM_ACCESS_ERR),
RDS_IB_WC_STATUS_STR(REM_OP_ERR),
RDS_IB_WC_STATUS_STR(RETRY_EXC_ERR),
RDS_IB_WC_STATUS_STR(RNR_RETRY_EXC_ERR),
RDS_IB_WC_STATUS_STR(LOC_RDD_VIOL_ERR),
RDS_IB_WC_STATUS_STR(REM_INV_RD_REQ_ERR),
RDS_IB_WC_STATUS_STR(REM_ABORT_ERR),
RDS_IB_WC_STATUS_STR(INV_EECN_ERR),
RDS_IB_WC_STATUS_STR(INV_EEC_STATE_ERR),
RDS_IB_WC_STATUS_STR(FATAL_ERR),
RDS_IB_WC_STATUS_STR(RESP_TIMEOUT_ERR),
RDS_IB_WC_STATUS_STR(GENERAL_ERR),
#undef RDS_IB_WC_STATUS_STR
};
char *rds_ib_wc_status_str(enum ib_wc_status status)
{
return rds_str_array(rds_ib_wc_status_strings,
ARRAY_SIZE(rds_ib_wc_status_strings), status);
}
static void rds_ib_send_complete(struct rds_message *rm,
int wc_status,
void (*complete)(struct rds_message *rm, int status))
{
int notify_status;
switch (wc_status) {
case IB_WC_WR_FLUSH_ERR:
return;
case IB_WC_SUCCESS:
notify_status = RDS_RDMA_SUCCESS;
break;
case IB_WC_REM_ACCESS_ERR:
notify_status = RDS_RDMA_REMOTE_ERROR;
break;
default:
notify_status = RDS_RDMA_OTHER_ERROR;
break;
}
complete(rm, notify_status);
}
static void rds_ib_send_unmap_data(struct rds_ib_connection *ic,
struct rm_data_op *op,
int wc_status)
{
if (op->op_nents)
ib_dma_unmap_sg(ic->i_cm_id->device,
op->op_sg, op->op_nents,
DMA_TO_DEVICE);
}
static void rds_ib_send_unmap_rdma(struct rds_ib_connection *ic,
struct rm_rdma_op *op,
int wc_status)
{
if (op->op_mapped) {
ib_dma_unmap_sg(ic->i_cm_id->device,
op->op_sg, op->op_nents,
op->op_write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
op->op_mapped = 0;
}
rds_ib_send_complete(container_of(op, struct rds_message, rdma),
wc_status, rds_rdma_send_complete);
if (op->op_write)
rds_stats_add(s_send_rdma_bytes, op->op_bytes);
else
rds_stats_add(s_recv_rdma_bytes, op->op_bytes);
}
static void rds_ib_send_unmap_atomic(struct rds_ib_connection *ic,
struct rm_atomic_op *op,
int wc_status)
{
if (op->op_mapped) {
ib_dma_unmap_sg(ic->i_cm_id->device, op->op_sg, 1,
DMA_FROM_DEVICE);
op->op_mapped = 0;
}
rds_ib_send_complete(container_of(op, struct rds_message, atomic),
wc_status, rds_atomic_send_complete);
if (op->op_type == RDS_ATOMIC_TYPE_CSWP)
rds_ib_stats_inc(s_ib_atomic_cswp);
else
rds_ib_stats_inc(s_ib_atomic_fadd);
}
static struct rds_message *rds_ib_send_unmap_op(struct rds_ib_connection *ic,
struct rds_ib_send_work *send,
int wc_status)
{
struct rds_message *rm = NULL;
switch (send->s_wr.opcode) {
case IB_WR_SEND:
if (send->s_op) {
rm = container_of(send->s_op, struct rds_message, data);
rds_ib_send_unmap_data(ic, send->s_op, wc_status);
}
break;
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_READ:
if (send->s_op) {
rm = container_of(send->s_op, struct rds_message, rdma);
rds_ib_send_unmap_rdma(ic, send->s_op, wc_status);
}
break;
case IB_WR_ATOMIC_FETCH_AND_ADD:
case IB_WR_ATOMIC_CMP_AND_SWP:
if (send->s_op) {
rm = container_of(send->s_op, struct rds_message, atomic);
rds_ib_send_unmap_atomic(ic, send->s_op, wc_status);
}
break;
default:
printk_ratelimited(KERN_NOTICE
"RDS/IB: %s: unexpected opcode 0x%x in WR!\n",
__func__, send->s_wr.opcode);
break;
}
send->s_wr.opcode = 0xdead;
return rm;
}
void rds_ib_send_init_ring(struct rds_ib_connection *ic)
{
struct rds_ib_send_work *send;
u32 i;
for (i = 0, send = ic->i_sends; i < ic->i_send_ring.w_nr; i++, send++) {
struct ib_sge *sge;
send->s_op = NULL;
send->s_wr.wr_id = i;
send->s_wr.sg_list = send->s_sge;
send->s_wr.ex.imm_data = 0;
sge = &send->s_sge[0];
sge->addr = ic->i_send_hdrs_dma + (i * sizeof(struct rds_header));
sge->length = sizeof(struct rds_header);
sge->lkey = ic->i_mr->lkey;
send->s_sge[1].lkey = ic->i_mr->lkey;
}
}
void rds_ib_send_clear_ring(struct rds_ib_connection *ic)
{
struct rds_ib_send_work *send;
u32 i;
for (i = 0, send = ic->i_sends; i < ic->i_send_ring.w_nr; i++, send++) {
if (send->s_op && send->s_wr.opcode != 0xdead)
rds_ib_send_unmap_op(ic, send, IB_WC_WR_FLUSH_ERR);
}
}
static void rds_ib_sub_signaled(struct rds_ib_connection *ic, int nr)
{
if ((atomic_sub_return(nr, &ic->i_signaled_sends) == 0) &&
waitqueue_active(&rds_ib_ring_empty_wait))
wake_up(&rds_ib_ring_empty_wait);
BUG_ON(atomic_read(&ic->i_signaled_sends) < 0);
}
void rds_ib_send_cq_comp_handler(struct ib_cq *cq, void *context)
{
struct rds_connection *conn = context;
struct rds_ib_connection *ic = conn->c_transport_data;
struct rds_message *rm = NULL;
struct ib_wc wc;
struct rds_ib_send_work *send;
u32 completed;
u32 oldest;
u32 i = 0;
int ret;
int nr_sig = 0;
rdsdebug("cq %p conn %p\n", cq, conn);
rds_ib_stats_inc(s_ib_tx_cq_call);
ret = ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
if (ret)
rdsdebug("ib_req_notify_cq send failed: %d\n", ret);
while (ib_poll_cq(cq, 1, &wc) > 0) {
rdsdebug("wc wr_id 0x%llx status %u (%s) byte_len %u imm_data %u\n",
(unsigned long long)wc.wr_id, wc.status,
rds_ib_wc_status_str(wc.status), wc.byte_len,
be32_to_cpu(wc.ex.imm_data));
rds_ib_stats_inc(s_ib_tx_cq_event);
if (wc.wr_id == RDS_IB_ACK_WR_ID) {
if (ic->i_ack_queued + HZ/2 < jiffies)
rds_ib_stats_inc(s_ib_tx_stalled);
rds_ib_ack_send_complete(ic);
continue;
}
oldest = rds_ib_ring_oldest(&ic->i_send_ring);
completed = rds_ib_ring_completed(&ic->i_send_ring, wc.wr_id, oldest);
for (i = 0; i < completed; i++) {
send = &ic->i_sends[oldest];
if (send->s_wr.send_flags & IB_SEND_SIGNALED)
nr_sig++;
rm = rds_ib_send_unmap_op(ic, send, wc.status);
if (send->s_queued + HZ/2 < jiffies)
rds_ib_stats_inc(s_ib_tx_stalled);
if (send->s_op) {
if (send->s_op == rm->m_final_op) {
rds_message_unmapped(rm);
}
rds_message_put(rm);
send->s_op = NULL;
}
oldest = (oldest + 1) % ic->i_send_ring.w_nr;
}
rds_ib_ring_free(&ic->i_send_ring, completed);
rds_ib_sub_signaled(ic, nr_sig);
nr_sig = 0;
if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags) ||
test_bit(0, &conn->c_map_queued))
queue_delayed_work(rds_wq, &conn->c_send_w, 0);
if (wc.status != IB_WC_SUCCESS && rds_conn_up(conn)) {
rds_ib_conn_error(conn, "send completion on %pI4 had status "
"%u (%s), disconnecting and reconnecting\n",
&conn->c_faddr, wc.status,
rds_ib_wc_status_str(wc.status));
}
}
}
int rds_ib_send_grab_credits(struct rds_ib_connection *ic,
u32 wanted, u32 *adv_credits, int need_posted, int max_posted)
{
unsigned int avail, posted, got = 0, advertise;
long oldval, newval;
*adv_credits = 0;
if (!ic->i_flowctl)
return wanted;
try_again:
advertise = 0;
oldval = newval = atomic_read(&ic->i_credits);
posted = IB_GET_POST_CREDITS(oldval);
avail = IB_GET_SEND_CREDITS(oldval);
rdsdebug("rds_ib_send_grab_credits(%u): credits=%u posted=%u\n",
wanted, avail, posted);
if (avail && !posted)
avail--;
if (avail < wanted) {
struct rds_connection *conn = ic->i_cm_id->context;
set_bit(RDS_LL_SEND_FULL, &conn->c_flags);
got = avail;
} else {
got = wanted;
}
newval -= IB_SET_SEND_CREDITS(got);
if (posted && (got || need_posted)) {
advertise = min_t(unsigned int, posted, max_posted);
newval -= IB_SET_POST_CREDITS(advertise);
}
if (atomic_cmpxchg(&ic->i_credits, oldval, newval) != oldval)
goto try_again;
*adv_credits = advertise;
return got;
}
void rds_ib_send_add_credits(struct rds_connection *conn, unsigned int credits)
{
struct rds_ib_connection *ic = conn->c_transport_data;
if (credits == 0)
return;
rdsdebug("rds_ib_send_add_credits(%u): current=%u%s\n",
credits,
IB_GET_SEND_CREDITS(atomic_read(&ic->i_credits)),
test_bit(RDS_LL_SEND_FULL, &conn->c_flags) ? ", ll_send_full" : "");
atomic_add(IB_SET_SEND_CREDITS(credits), &ic->i_credits);
if (test_and_clear_bit(RDS_LL_SEND_FULL, &conn->c_flags))
queue_delayed_work(rds_wq, &conn->c_send_w, 0);
WARN_ON(IB_GET_SEND_CREDITS(credits) >= 16384);
rds_ib_stats_inc(s_ib_rx_credit_updates);
}
void rds_ib_advertise_credits(struct rds_connection *conn, unsigned int posted)
{
struct rds_ib_connection *ic = conn->c_transport_data;
if (posted == 0)
return;
atomic_add(IB_SET_POST_CREDITS(posted), &ic->i_credits);
if (IB_GET_POST_CREDITS(atomic_read(&ic->i_credits)) >= 16)
set_bit(IB_ACK_REQUESTED, &ic->i_ack_flags);
}
static inline int rds_ib_set_wr_signal_state(struct rds_ib_connection *ic,
struct rds_ib_send_work *send,
bool notify)
{
if (ic->i_unsignaled_wrs-- == 0 || notify) {
ic->i_unsignaled_wrs = rds_ib_sysctl_max_unsig_wrs;
send->s_wr.send_flags |= IB_SEND_SIGNALED;
return 1;
}
return 0;
}
int rds_ib_xmit(struct rds_connection *conn, struct rds_message *rm,
unsigned int hdr_off, unsigned int sg, unsigned int off)
{
struct rds_ib_connection *ic = conn->c_transport_data;
struct ib_device *dev = ic->i_cm_id->device;
struct rds_ib_send_work *send = NULL;
struct rds_ib_send_work *first;
struct rds_ib_send_work *prev;
struct ib_send_wr *failed_wr;
struct scatterlist *scat;
u32 pos;
u32 i;
u32 work_alloc;
u32 credit_alloc = 0;
u32 posted;
u32 adv_credits = 0;
int send_flags = 0;
int bytes_sent = 0;
int ret;
int flow_controlled = 0;
int nr_sig = 0;
BUG_ON(off % RDS_FRAG_SIZE);
BUG_ON(hdr_off != 0 && hdr_off != sizeof(struct rds_header));
if (conn->c_loopback
&& rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) {
rds_cong_map_updated(conn->c_fcong, ~(u64) 0);
scat = &rm->data.op_sg[sg];
ret = sizeof(struct rds_header) + RDS_CONG_MAP_BYTES;
ret = min_t(int, ret, scat->length - conn->c_xmit_data_off);
return ret;
}
if (be32_to_cpu(rm->m_inc.i_hdr.h_len) == 0)
i = 1;
else
i = ceil(be32_to_cpu(rm->m_inc.i_hdr.h_len), RDS_FRAG_SIZE);
work_alloc = rds_ib_ring_alloc(&ic->i_send_ring, i, &pos);
if (work_alloc == 0) {
set_bit(RDS_LL_SEND_FULL, &conn->c_flags);
rds_ib_stats_inc(s_ib_tx_ring_full);
ret = -ENOMEM;
goto out;
}
if (ic->i_flowctl) {
credit_alloc = rds_ib_send_grab_credits(ic, work_alloc, &posted, 0, RDS_MAX_ADV_CREDIT);
adv_credits += posted;
if (credit_alloc < work_alloc) {
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - credit_alloc);
work_alloc = credit_alloc;
flow_controlled = 1;
}
if (work_alloc == 0) {
set_bit(RDS_LL_SEND_FULL, &conn->c_flags);
rds_ib_stats_inc(s_ib_tx_throttle);
ret = -ENOMEM;
goto out;
}
}
if (!ic->i_data_op) {
if (rm->data.op_nents) {
rm->data.op_count = ib_dma_map_sg(dev,
rm->data.op_sg,
rm->data.op_nents,
DMA_TO_DEVICE);
rdsdebug("ic %p mapping rm %p: %d\n", ic, rm, rm->data.op_count);
if (rm->data.op_count == 0) {
rds_ib_stats_inc(s_ib_tx_sg_mapping_failure);
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
ret = -ENOMEM;
goto out;
}
} else {
rm->data.op_count = 0;
}
rds_message_addref(rm);
ic->i_data_op = &rm->data;
if (test_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags))
rm->m_inc.i_hdr.h_flags |= RDS_FLAG_ACK_REQUIRED;
if (test_bit(RDS_MSG_RETRANSMITTED, &rm->m_flags))
rm->m_inc.i_hdr.h_flags |= RDS_FLAG_RETRANSMITTED;
if (rm->rdma.op_active) {
struct rds_ext_header_rdma ext_hdr;
ext_hdr.h_rdma_rkey = cpu_to_be32(rm->rdma.op_rkey);
rds_message_add_extension(&rm->m_inc.i_hdr,
RDS_EXTHDR_RDMA, &ext_hdr, sizeof(ext_hdr));
}
if (rm->m_rdma_cookie) {
rds_message_add_rdma_dest_extension(&rm->m_inc.i_hdr,
rds_rdma_cookie_key(rm->m_rdma_cookie),
rds_rdma_cookie_offset(rm->m_rdma_cookie));
}
rm->m_inc.i_hdr.h_ack = cpu_to_be64(rds_ib_piggyb_ack(ic));
rds_message_make_checksum(&rm->m_inc.i_hdr);
if (ic->i_flowctl) {
rds_ib_send_grab_credits(ic, 0, &posted, 1, RDS_MAX_ADV_CREDIT - adv_credits);
adv_credits += posted;
BUG_ON(adv_credits > 255);
}
}
if (rm->rdma.op_active && rm->rdma.op_fence)
send_flags = IB_SEND_FENCE;
send = &ic->i_sends[pos];
first = send;
prev = NULL;
scat = &ic->i_data_op->op_sg[sg];
i = 0;
do {
unsigned int len = 0;
send->s_wr.send_flags = send_flags;
send->s_wr.opcode = IB_WR_SEND;
send->s_wr.num_sge = 1;
send->s_wr.next = NULL;
send->s_queued = jiffies;
send->s_op = NULL;
send->s_sge[0].addr = ic->i_send_hdrs_dma
+ (pos * sizeof(struct rds_header));
send->s_sge[0].length = sizeof(struct rds_header);
memcpy(&ic->i_send_hdrs[pos], &rm->m_inc.i_hdr, sizeof(struct rds_header));
if (i < work_alloc
&& scat != &rm->data.op_sg[rm->data.op_count]) {
len = min(RDS_FRAG_SIZE, ib_sg_dma_len(dev, scat) - off);
send->s_wr.num_sge = 2;
send->s_sge[1].addr = ib_sg_dma_address(dev, scat) + off;
send->s_sge[1].length = len;
bytes_sent += len;
off += len;
if (off == ib_sg_dma_len(dev, scat)) {
scat++;
off = 0;
}
}
rds_ib_set_wr_signal_state(ic, send, 0);
if (ic->i_flowctl && flow_controlled && i == (work_alloc-1))
send->s_wr.send_flags |= IB_SEND_SIGNALED | IB_SEND_SOLICITED;
if (send->s_wr.send_flags & IB_SEND_SIGNALED)
nr_sig++;
rdsdebug("send %p wr %p num_sge %u next %p\n", send,
&send->s_wr, send->s_wr.num_sge, send->s_wr.next);
if (ic->i_flowctl && adv_credits) {
struct rds_header *hdr = &ic->i_send_hdrs[pos];
hdr->h_credit = adv_credits;
rds_message_make_checksum(hdr);
adv_credits = 0;
rds_ib_stats_inc(s_ib_tx_credit_updates);
}
if (prev)
prev->s_wr.next = &send->s_wr;
prev = send;
pos = (pos + 1) % ic->i_send_ring.w_nr;
send = &ic->i_sends[pos];
i++;
} while (i < work_alloc
&& scat != &rm->data.op_sg[rm->data.op_count]);
if (hdr_off == 0)
bytes_sent += sizeof(struct rds_header);
if (scat == &rm->data.op_sg[rm->data.op_count]) {
prev->s_op = ic->i_data_op;
prev->s_wr.send_flags |= IB_SEND_SOLICITED;
ic->i_data_op = NULL;
}
if (i < work_alloc) {
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - i);
work_alloc = i;
}
if (ic->i_flowctl && i < credit_alloc)
rds_ib_send_add_credits(conn, credit_alloc - i);
if (nr_sig)
atomic_add(nr_sig, &ic->i_signaled_sends);
failed_wr = &first->s_wr;
ret = ib_post_send(ic->i_cm_id->qp, &first->s_wr, &failed_wr);
rdsdebug("ic %p first %p (wr %p) ret %d wr %p\n", ic,
first, &first->s_wr, ret, failed_wr);
BUG_ON(failed_wr != &first->s_wr);
if (ret) {
printk(KERN_WARNING "RDS/IB: ib_post_send to %pI4 "
"returned %d\n", &conn->c_faddr, ret);
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
rds_ib_sub_signaled(ic, nr_sig);
if (prev->s_op) {
ic->i_data_op = prev->s_op;
prev->s_op = NULL;
}
rds_ib_conn_error(ic->conn, "ib_post_send failed\n");
goto out;
}
ret = bytes_sent;
out:
BUG_ON(adv_credits);
return ret;
}
int rds_ib_xmit_atomic(struct rds_connection *conn, struct rm_atomic_op *op)
{
struct rds_ib_connection *ic = conn->c_transport_data;
struct rds_ib_send_work *send = NULL;
struct ib_send_wr *failed_wr;
struct rds_ib_device *rds_ibdev;
u32 pos;
u32 work_alloc;
int ret;
int nr_sig = 0;
rds_ibdev = ib_get_client_data(ic->i_cm_id->device, &rds_ib_client);
work_alloc = rds_ib_ring_alloc(&ic->i_send_ring, 1, &pos);
if (work_alloc != 1) {
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
rds_ib_stats_inc(s_ib_tx_ring_full);
ret = -ENOMEM;
goto out;
}
send = &ic->i_sends[pos];
send->s_queued = jiffies;
if (op->op_type == RDS_ATOMIC_TYPE_CSWP) {
send->s_wr.opcode = IB_WR_MASKED_ATOMIC_CMP_AND_SWP;
send->s_wr.wr.atomic.compare_add = op->op_m_cswp.compare;
send->s_wr.wr.atomic.swap = op->op_m_cswp.swap;
send->s_wr.wr.atomic.compare_add_mask = op->op_m_cswp.compare_mask;
send->s_wr.wr.atomic.swap_mask = op->op_m_cswp.swap_mask;
} else {
send->s_wr.opcode = IB_WR_MASKED_ATOMIC_FETCH_AND_ADD;
send->s_wr.wr.atomic.compare_add = op->op_m_fadd.add;
send->s_wr.wr.atomic.swap = 0;
send->s_wr.wr.atomic.compare_add_mask = op->op_m_fadd.nocarry_mask;
send->s_wr.wr.atomic.swap_mask = 0;
}
nr_sig = rds_ib_set_wr_signal_state(ic, send, op->op_notify);
send->s_wr.num_sge = 1;
send->s_wr.next = NULL;
send->s_wr.wr.atomic.remote_addr = op->op_remote_addr;
send->s_wr.wr.atomic.rkey = op->op_rkey;
send->s_op = op;
rds_message_addref(container_of(send->s_op, struct rds_message, atomic));
ret = ib_dma_map_sg(ic->i_cm_id->device, op->op_sg, 1, DMA_FROM_DEVICE);
rdsdebug("ic %p mapping atomic op %p. mapped %d pg\n", ic, op, ret);
if (ret != 1) {
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
rds_ib_stats_inc(s_ib_tx_sg_mapping_failure);
ret = -ENOMEM;
goto out;
}
send->s_sge[0].addr = ib_sg_dma_address(ic->i_cm_id->device, op->op_sg);
send->s_sge[0].length = ib_sg_dma_len(ic->i_cm_id->device, op->op_sg);
send->s_sge[0].lkey = ic->i_mr->lkey;
rdsdebug("rva %Lx rpa %Lx len %u\n", op->op_remote_addr,
send->s_sge[0].addr, send->s_sge[0].length);
if (nr_sig)
atomic_add(nr_sig, &ic->i_signaled_sends);
failed_wr = &send->s_wr;
ret = ib_post_send(ic->i_cm_id->qp, &send->s_wr, &failed_wr);
rdsdebug("ic %p send %p (wr %p) ret %d wr %p\n", ic,
send, &send->s_wr, ret, failed_wr);
BUG_ON(failed_wr != &send->s_wr);
if (ret) {
printk(KERN_WARNING "RDS/IB: atomic ib_post_send to %pI4 "
"returned %d\n", &conn->c_faddr, ret);
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
rds_ib_sub_signaled(ic, nr_sig);
goto out;
}
if (unlikely(failed_wr != &send->s_wr)) {
printk(KERN_WARNING "RDS/IB: atomic ib_post_send() rc=%d, but failed_wqe updated!\n", ret);
BUG_ON(failed_wr != &send->s_wr);
}
out:
return ret;
}
int rds_ib_xmit_rdma(struct rds_connection *conn, struct rm_rdma_op *op)
{
struct rds_ib_connection *ic = conn->c_transport_data;
struct rds_ib_send_work *send = NULL;
struct rds_ib_send_work *first;
struct rds_ib_send_work *prev;
struct ib_send_wr *failed_wr;
struct scatterlist *scat;
unsigned long len;
u64 remote_addr = op->op_remote_addr;
u32 max_sge = ic->rds_ibdev->max_sge;
u32 pos;
u32 work_alloc;
u32 i;
u32 j;
int sent;
int ret;
int num_sge;
int nr_sig = 0;
if (!op->op_mapped) {
op->op_count = ib_dma_map_sg(ic->i_cm_id->device,
op->op_sg, op->op_nents, (op->op_write) ?
DMA_TO_DEVICE : DMA_FROM_DEVICE);
rdsdebug("ic %p mapping op %p: %d\n", ic, op, op->op_count);
if (op->op_count == 0) {
rds_ib_stats_inc(s_ib_tx_sg_mapping_failure);
ret = -ENOMEM;
goto out;
}
op->op_mapped = 1;
}
i = ceil(op->op_count, max_sge);
work_alloc = rds_ib_ring_alloc(&ic->i_send_ring, i, &pos);
if (work_alloc != i) {
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
rds_ib_stats_inc(s_ib_tx_ring_full);
ret = -ENOMEM;
goto out;
}
send = &ic->i_sends[pos];
first = send;
prev = NULL;
scat = &op->op_sg[0];
sent = 0;
num_sge = op->op_count;
for (i = 0; i < work_alloc && scat != &op->op_sg[op->op_count]; i++) {
send->s_wr.send_flags = 0;
send->s_queued = jiffies;
send->s_op = NULL;
nr_sig += rds_ib_set_wr_signal_state(ic, send, op->op_notify);
send->s_wr.opcode = op->op_write ? IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
send->s_wr.wr.rdma.remote_addr = remote_addr;
send->s_wr.wr.rdma.rkey = op->op_rkey;
if (num_sge > max_sge) {
send->s_wr.num_sge = max_sge;
num_sge -= max_sge;
} else {
send->s_wr.num_sge = num_sge;
}
send->s_wr.next = NULL;
if (prev)
prev->s_wr.next = &send->s_wr;
for (j = 0; j < send->s_wr.num_sge && scat != &op->op_sg[op->op_count]; j++) {
len = ib_sg_dma_len(ic->i_cm_id->device, scat);
send->s_sge[j].addr =
ib_sg_dma_address(ic->i_cm_id->device, scat);
send->s_sge[j].length = len;
send->s_sge[j].lkey = ic->i_mr->lkey;
sent += len;
rdsdebug("ic %p sent %d remote_addr %llu\n", ic, sent, remote_addr);
remote_addr += len;
scat++;
}
rdsdebug("send %p wr %p num_sge %u next %p\n", send,
&send->s_wr, send->s_wr.num_sge, send->s_wr.next);
prev = send;
if (++send == &ic->i_sends[ic->i_send_ring.w_nr])
send = ic->i_sends;
}
if (scat == &op->op_sg[op->op_count]) {
prev->s_op = op;
rds_message_addref(container_of(op, struct rds_message, rdma));
}
if (i < work_alloc) {
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - i);
work_alloc = i;
}
if (nr_sig)
atomic_add(nr_sig, &ic->i_signaled_sends);
failed_wr = &first->s_wr;
ret = ib_post_send(ic->i_cm_id->qp, &first->s_wr, &failed_wr);
rdsdebug("ic %p first %p (wr %p) ret %d wr %p\n", ic,
first, &first->s_wr, ret, failed_wr);
BUG_ON(failed_wr != &first->s_wr);
if (ret) {
printk(KERN_WARNING "RDS/IB: rdma ib_post_send to %pI4 "
"returned %d\n", &conn->c_faddr, ret);
rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc);
rds_ib_sub_signaled(ic, nr_sig);
goto out;
}
if (unlikely(failed_wr != &first->s_wr)) {
printk(KERN_WARNING "RDS/IB: ib_post_send() rc=%d, but failed_wqe updated!\n", ret);
BUG_ON(failed_wr != &first->s_wr);
}
out:
return ret;
}
void rds_ib_xmit_complete(struct rds_connection *conn)
{
struct rds_ib_connection *ic = conn->c_transport_data;
rds_ib_attempt_ack(ic);
}
| gpl-2.0 |
maxrdlf95/htc_m8_maxkernel | arch/mips/mm/c-r3k.c | 34 | 7864 | /*
* r2300.c: R2000 and R3000 specific mmu/cache code.
*
* Copyright (C) 1996 David S. Miller (davem@davemloft.net)
*
* with a lot of changes to make this thing work for R3000s
* Tx39XX R4k style caches added. HK
* Copyright (C) 1998, 1999, 2000 Harald Koerfgen
* Copyright (C) 1998 Gleb Raiko & Vladimir Roganov
* Copyright (C) 2001, 2004, 2007 Maciej W. Rozycki
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/mm.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/mmu_context.h>
#include <asm/isadep.h>
#include <asm/io.h>
#include <asm/bootinfo.h>
#include <asm/cpu.h>
static unsigned long icache_size, dcache_size;
static unsigned long icache_lsize, dcache_lsize;
unsigned long __cpuinit r3k_cache_size(unsigned long ca_flags)
{
unsigned long flags, status, dummy, size;
volatile unsigned long *p;
p = (volatile unsigned long *) KSEG0;
flags = read_c0_status();
write_c0_status((ca_flags|flags)&~ST0_IEC);
*p = 0xa5a55a5a;
dummy = *p;
status = read_c0_status();
if (dummy != 0xa5a55a5a || (status & ST0_CM)) {
size = 0;
} else {
for (size = 128; size <= 0x40000; size <<= 1)
*(p + size) = 0;
*p = -1;
for (size = 128;
(size <= 0x40000) && (*(p + size) == 0);
size <<= 1)
;
if (size > 0x40000)
size = 0;
}
write_c0_status(flags);
return size * sizeof(*p);
}
unsigned long __cpuinit r3k_cache_lsize(unsigned long ca_flags)
{
unsigned long flags, status, lsize, i;
volatile unsigned long *p;
p = (volatile unsigned long *) KSEG0;
flags = read_c0_status();
write_c0_status((ca_flags|flags)&~ST0_IEC);
for (i = 0; i < 128; i++)
*(p + i) = 0;
*(volatile unsigned char *)p = 0;
for (lsize = 1; lsize < 128; lsize <<= 1) {
*(p + lsize);
status = read_c0_status();
if (!(status & ST0_CM))
break;
}
for (i = 0; i < 128; i += lsize)
*(volatile unsigned char *)(p + i) = 0;
write_c0_status(flags);
return lsize * sizeof(*p);
}
static void __cpuinit r3k_probe_cache(void)
{
dcache_size = r3k_cache_size(ST0_ISC);
if (dcache_size)
dcache_lsize = r3k_cache_lsize(ST0_ISC);
icache_size = r3k_cache_size(ST0_ISC|ST0_SWC);
if (icache_size)
icache_lsize = r3k_cache_lsize(ST0_ISC|ST0_SWC);
}
static void r3k_flush_icache_range(unsigned long start, unsigned long end)
{
unsigned long size, i, flags;
volatile unsigned char *p;
size = end - start;
if (size > icache_size || KSEGX(start) != KSEG0) {
start = KSEG0;
size = icache_size;
}
p = (char *)start;
flags = read_c0_status();
write_c0_status((ST0_ISC|ST0_SWC|flags)&~ST0_IEC);
for (i = 0; i < size; i += 0x080) {
asm( "sb\t$0, 0x000(%0)\n\t"
"sb\t$0, 0x004(%0)\n\t"
"sb\t$0, 0x008(%0)\n\t"
"sb\t$0, 0x00c(%0)\n\t"
"sb\t$0, 0x010(%0)\n\t"
"sb\t$0, 0x014(%0)\n\t"
"sb\t$0, 0x018(%0)\n\t"
"sb\t$0, 0x01c(%0)\n\t"
"sb\t$0, 0x020(%0)\n\t"
"sb\t$0, 0x024(%0)\n\t"
"sb\t$0, 0x028(%0)\n\t"
"sb\t$0, 0x02c(%0)\n\t"
"sb\t$0, 0x030(%0)\n\t"
"sb\t$0, 0x034(%0)\n\t"
"sb\t$0, 0x038(%0)\n\t"
"sb\t$0, 0x03c(%0)\n\t"
"sb\t$0, 0x040(%0)\n\t"
"sb\t$0, 0x044(%0)\n\t"
"sb\t$0, 0x048(%0)\n\t"
"sb\t$0, 0x04c(%0)\n\t"
"sb\t$0, 0x050(%0)\n\t"
"sb\t$0, 0x054(%0)\n\t"
"sb\t$0, 0x058(%0)\n\t"
"sb\t$0, 0x05c(%0)\n\t"
"sb\t$0, 0x060(%0)\n\t"
"sb\t$0, 0x064(%0)\n\t"
"sb\t$0, 0x068(%0)\n\t"
"sb\t$0, 0x06c(%0)\n\t"
"sb\t$0, 0x070(%0)\n\t"
"sb\t$0, 0x074(%0)\n\t"
"sb\t$0, 0x078(%0)\n\t"
"sb\t$0, 0x07c(%0)\n\t"
: : "r" (p) );
p += 0x080;
}
write_c0_status(flags);
}
static void r3k_flush_dcache_range(unsigned long start, unsigned long end)
{
unsigned long size, i, flags;
volatile unsigned char *p;
size = end - start;
if (size > dcache_size || KSEGX(start) != KSEG0) {
start = KSEG0;
size = dcache_size;
}
p = (char *)start;
flags = read_c0_status();
write_c0_status((ST0_ISC|flags)&~ST0_IEC);
for (i = 0; i < size; i += 0x080) {
asm( "sb\t$0, 0x000(%0)\n\t"
"sb\t$0, 0x004(%0)\n\t"
"sb\t$0, 0x008(%0)\n\t"
"sb\t$0, 0x00c(%0)\n\t"
"sb\t$0, 0x010(%0)\n\t"
"sb\t$0, 0x014(%0)\n\t"
"sb\t$0, 0x018(%0)\n\t"
"sb\t$0, 0x01c(%0)\n\t"
"sb\t$0, 0x020(%0)\n\t"
"sb\t$0, 0x024(%0)\n\t"
"sb\t$0, 0x028(%0)\n\t"
"sb\t$0, 0x02c(%0)\n\t"
"sb\t$0, 0x030(%0)\n\t"
"sb\t$0, 0x034(%0)\n\t"
"sb\t$0, 0x038(%0)\n\t"
"sb\t$0, 0x03c(%0)\n\t"
"sb\t$0, 0x040(%0)\n\t"
"sb\t$0, 0x044(%0)\n\t"
"sb\t$0, 0x048(%0)\n\t"
"sb\t$0, 0x04c(%0)\n\t"
"sb\t$0, 0x050(%0)\n\t"
"sb\t$0, 0x054(%0)\n\t"
"sb\t$0, 0x058(%0)\n\t"
"sb\t$0, 0x05c(%0)\n\t"
"sb\t$0, 0x060(%0)\n\t"
"sb\t$0, 0x064(%0)\n\t"
"sb\t$0, 0x068(%0)\n\t"
"sb\t$0, 0x06c(%0)\n\t"
"sb\t$0, 0x070(%0)\n\t"
"sb\t$0, 0x074(%0)\n\t"
"sb\t$0, 0x078(%0)\n\t"
"sb\t$0, 0x07c(%0)\n\t"
: : "r" (p) );
p += 0x080;
}
write_c0_status(flags);
}
static inline void r3k_flush_cache_all(void)
{
}
static inline void r3k___flush_cache_all(void)
{
r3k_flush_dcache_range(KSEG0, KSEG0 + dcache_size);
r3k_flush_icache_range(KSEG0, KSEG0 + icache_size);
}
static void r3k_flush_cache_mm(struct mm_struct *mm)
{
}
static void r3k_flush_cache_range(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
}
static void r3k_flush_cache_page(struct vm_area_struct *vma,
unsigned long addr, unsigned long pfn)
{
unsigned long kaddr = KSEG0ADDR(pfn << PAGE_SHIFT);
int exec = vma->vm_flags & VM_EXEC;
struct mm_struct *mm = vma->vm_mm;
pgd_t *pgdp;
pud_t *pudp;
pmd_t *pmdp;
pte_t *ptep;
pr_debug("cpage[%08lx,%08lx]\n",
cpu_context(smp_processor_id(), mm), addr);
if (cpu_context(smp_processor_id(), mm) == 0)
return;
pgdp = pgd_offset(mm, addr);
pudp = pud_offset(pgdp, addr);
pmdp = pmd_offset(pudp, addr);
ptep = pte_offset(pmdp, addr);
if (!(pte_val(*ptep) & _PAGE_PRESENT))
return;
r3k_flush_dcache_range(kaddr, kaddr + PAGE_SIZE);
if (exec)
r3k_flush_icache_range(kaddr, kaddr + PAGE_SIZE);
}
static void local_r3k_flush_data_cache_page(void *addr)
{
}
static void r3k_flush_data_cache_page(unsigned long addr)
{
}
static void r3k_flush_cache_sigtramp(unsigned long addr)
{
unsigned long flags;
pr_debug("csigtramp[%08lx]\n", addr);
flags = read_c0_status();
write_c0_status(flags&~ST0_IEC);
asm( "lw\t$0, 0x000(%0)\n\t"
"lw\t$0, 0x004(%0)\n\t"
: : "r" (addr) );
write_c0_status((ST0_ISC|ST0_SWC|flags)&~ST0_IEC);
asm( "sb\t$0, 0x000(%0)\n\t"
"sb\t$0, 0x004(%0)\n\t"
: : "r" (addr) );
write_c0_status(flags);
}
static void r3k_flush_kernel_vmap_range(unsigned long vaddr, int size)
{
BUG();
}
static void r3k_dma_cache_wback_inv(unsigned long start, unsigned long size)
{
BUG_ON(size == 0);
iob();
r3k_flush_dcache_range(start, start + size);
}
void __cpuinit r3k_cache_init(void)
{
extern void build_clear_page(void);
extern void build_copy_page(void);
r3k_probe_cache();
flush_cache_all = r3k_flush_cache_all;
__flush_cache_all = r3k___flush_cache_all;
flush_cache_mm = r3k_flush_cache_mm;
flush_cache_range = r3k_flush_cache_range;
flush_cache_page = r3k_flush_cache_page;
flush_icache_range = r3k_flush_icache_range;
local_flush_icache_range = r3k_flush_icache_range;
__flush_kernel_vmap_range = r3k_flush_kernel_vmap_range;
flush_cache_sigtramp = r3k_flush_cache_sigtramp;
local_flush_data_cache_page = local_r3k_flush_data_cache_page;
flush_data_cache_page = r3k_flush_data_cache_page;
_dma_cache_wback_inv = r3k_dma_cache_wback_inv;
_dma_cache_wback = r3k_dma_cache_wback_inv;
_dma_cache_inv = r3k_dma_cache_wback_inv;
printk("Primary instruction cache %ldkB, linesize %ld bytes.\n",
icache_size >> 10, icache_lsize);
printk("Primary data cache %ldkB, linesize %ld bytes.\n",
dcache_size >> 10, dcache_lsize);
build_clear_page();
build_copy_page();
}
| gpl-2.0 |
Skin1980/sturgeon | drivers/devfreq/governor_bw_hwmon.c | 34 | 10396 | /*
* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "bw-hwmon: " fmt
#include <linux/kernel.h>
#include <linux/sizes.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/ktime.h>
#include <linux/time.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/devfreq.h>
#include "governor.h"
#include "governor_bw_hwmon.h"
struct hwmon_node {
unsigned int tolerance_percent;
unsigned int guard_band_mbps;
unsigned int decay_rate;
unsigned int io_percent;
unsigned int bw_step;
unsigned long prev_ab;
unsigned long *dev_ab;
ktime_t prev_ts;
bool mon_started;
struct list_head list;
void *orig_data;
struct bw_hwmon *hw;
struct devfreq_governor *gov;
struct attribute_group *attr_grp;
};
static LIST_HEAD(hwmon_list);
static DEFINE_MUTEX(list_lock);
static int use_cnt;
static DEFINE_MUTEX(state_lock);
#define show_attr(name) \
static ssize_t show_##name(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct devfreq *df = to_devfreq(dev); \
struct hwmon_node *hw = df->data; \
return snprintf(buf, PAGE_SIZE, "%u\n", hw->name); \
}
#define store_attr(name, _min, _max) \
static ssize_t store_##name(struct device *dev, \
struct device_attribute *attr, const char *buf, \
size_t count) \
{ \
struct devfreq *df = to_devfreq(dev); \
struct hwmon_node *hw = df->data; \
int ret; \
unsigned int val; \
ret = sscanf(buf, "%u", &val); \
if (ret != 1) \
return -EINVAL; \
val = max(val, _min); \
val = min(val, _max); \
hw->name = val; \
return count; \
}
#define gov_attr(__attr, min, max) \
show_attr(__attr) \
store_attr(__attr, min, max) \
static DEVICE_ATTR(__attr, 0644, show_##__attr, store_##__attr)
#define MIN_MS 10U
#define MAX_MS 500U
static unsigned long measure_bw_and_set_irq(struct hwmon_node *node)
{
ktime_t ts;
unsigned int us;
unsigned long mbps;
struct bw_hwmon *hw = node->hw;
/*
* Since we are stopping the counters, we don't want this short work
* to be interrupted by other tasks and cause the measurements to be
* wrong. Not blocking interrupts to avoid affecting interrupt
* latency and since they should be short anyway because they run in
* atomic context.
*/
preempt_disable();
ts = ktime_get();
us = ktime_to_us(ktime_sub(ts, node->prev_ts));
if (!us)
us = 1;
mbps = hw->meas_bw_and_set_irq(hw, node->tolerance_percent, us);
node->prev_ts = ts;
preempt_enable();
dev_dbg(hw->df->dev.parent, "BW MBps = %6lu, period = %u\n", mbps, us);
return mbps;
}
static void compute_bw(struct hwmon_node *node, int mbps,
unsigned long *freq, unsigned long *ab)
{
int new_bw;
mbps += node->guard_band_mbps;
if (mbps > node->prev_ab) {
new_bw = mbps;
} else {
new_bw = mbps * node->decay_rate
+ node->prev_ab * (100 - node->decay_rate);
new_bw /= 100;
}
node->prev_ab = new_bw;
if (ab)
*ab = roundup(new_bw, node->bw_step);
*freq = (new_bw * 100) / node->io_percent;
}
static struct hwmon_node *find_hwmon_node(struct devfreq *df)
{
struct hwmon_node *node, *found = NULL;
mutex_lock(&list_lock);
list_for_each_entry(node, &hwmon_list, list)
if (node->hw->dev == df->dev.parent ||
node->hw->of_node == df->dev.parent->of_node ||
(!node->hw->dev && !node->hw->of_node &&
node->gov == df->governor)) {
found = node;
break;
}
mutex_unlock(&list_lock);
return found;
}
#define TOO_SOON_US (1 * USEC_PER_MSEC)
int update_bw_hwmon(struct bw_hwmon *hwmon)
{
struct devfreq *df;
struct hwmon_node *node;
ktime_t ts;
unsigned int us;
int ret;
if (!hwmon)
return -EINVAL;
df = hwmon->df;
if (!df)
return -ENODEV;
node = find_hwmon_node(df);
if (!node)
return -ENODEV;
if (!node->mon_started)
return -EBUSY;
dev_dbg(df->dev.parent, "Got update request\n");
devfreq_monitor_stop(df);
/*
* Don't recalc bandwidth if the interrupt comes right after a
* previous bandwidth calculation. This is done for two reasons:
*
* 1. Sampling the BW during a very short duration can result in a
* very inaccurate measurement due to very short bursts.
* 2. This can only happen if the limit was hit very close to the end
* of the previous sample period. Which means the current BW
* estimate is not very off and doesn't need to be readjusted.
*/
ts = ktime_get();
us = ktime_to_us(ktime_sub(ts, node->prev_ts));
if (us > TOO_SOON_US) {
mutex_lock(&df->lock);
ret = update_devfreq(df);
if (ret)
dev_err(df->dev.parent,
"Unable to update freq on request!\n");
mutex_unlock(&df->lock);
}
devfreq_monitor_start(df);
return 0;
}
static int start_monitoring(struct devfreq *df)
{
int ret = 0;
unsigned long mbps;
struct device *dev = df->dev.parent;
struct hwmon_node *node;
struct bw_hwmon *hw;
struct devfreq_dev_status stat;
node = find_hwmon_node(df);
if (!node) {
dev_err(dev, "Unable to find HW monitor!\n");
return -ENODEV;
}
hw = node->hw;
stat.private_data = NULL;
if (df->profile->get_dev_status)
ret = df->profile->get_dev_status(df->dev.parent, &stat);
if (ret || !stat.private_data)
dev_warn(dev, "Device doesn't take AB votes!\n");
else
node->dev_ab = stat.private_data;
hw->df = df;
node->orig_data = df->data;
df->data = node;
node->prev_ts = ktime_get();
node->prev_ab = 0;
mbps = (df->previous_freq * node->io_percent) / 100;
ret = hw->start_hwmon(hw, mbps);
if (ret) {
dev_err(dev, "Unable to start HW monitor!\n");
goto err_start;
}
devfreq_monitor_start(df);
node->mon_started = true;
ret = sysfs_create_group(&df->dev.kobj, node->attr_grp);
if (ret)
goto err_sysfs;
return 0;
err_sysfs:
node->mon_started = false;
devfreq_monitor_stop(df);
hw->stop_hwmon(hw);
err_start:
df->data = node->orig_data;
node->orig_data = NULL;
hw->df = NULL;
node->dev_ab = NULL;
return ret;
}
static void stop_monitoring(struct devfreq *df)
{
struct hwmon_node *node = df->data;
struct bw_hwmon *hw = node->hw;
sysfs_remove_group(&df->dev.kobj, node->attr_grp);
node->mon_started = false;
devfreq_monitor_stop(df);
hw->stop_hwmon(hw);
df->data = node->orig_data;
node->orig_data = NULL;
hw->df = NULL;
/*
* Not all governors know about this additional extended device
* configuration. To avoid leaving the extended configuration at a
* stale state, set it to 0 and let the next governor take it from
* there.
*/
if (node->dev_ab)
*node->dev_ab = 0;
node->dev_ab = NULL;
}
static int devfreq_bw_hwmon_get_freq(struct devfreq *df,
unsigned long *freq,
u32 *flag)
{
unsigned long mbps;
struct hwmon_node *node = df->data;
mbps = measure_bw_and_set_irq(node);
compute_bw(node, mbps, freq, node->dev_ab);
return 0;
}
gov_attr(tolerance_percent, 0U, 30U);
gov_attr(guard_band_mbps, 0U, 2000U);
gov_attr(decay_rate, 0U, 100U);
gov_attr(io_percent, 1U, 100U);
gov_attr(bw_step, 50U, 1000U);
static struct attribute *dev_attr[] = {
&dev_attr_tolerance_percent.attr,
&dev_attr_guard_band_mbps.attr,
&dev_attr_decay_rate.attr,
&dev_attr_io_percent.attr,
&dev_attr_bw_step.attr,
NULL,
};
static struct attribute_group dev_attr_group = {
.name = "bw_hwmon",
.attrs = dev_attr,
};
static int devfreq_bw_hwmon_ev_handler(struct devfreq *df,
unsigned int event, void *data)
{
int ret;
unsigned int sample_ms;
switch (event) {
case DEVFREQ_GOV_START:
sample_ms = df->profile->polling_ms;
sample_ms = max(MIN_MS, sample_ms);
sample_ms = min(MAX_MS, sample_ms);
df->profile->polling_ms = sample_ms;
ret = start_monitoring(df);
if (ret)
return ret;
dev_dbg(df->dev.parent,
"Enabled dev BW HW monitor governor\n");
break;
case DEVFREQ_GOV_STOP:
stop_monitoring(df);
dev_dbg(df->dev.parent,
"Disabled dev BW HW monitor governor\n");
break;
case DEVFREQ_GOV_INTERVAL:
sample_ms = *(unsigned int *)data;
sample_ms = max(MIN_MS, sample_ms);
sample_ms = min(MAX_MS, sample_ms);
devfreq_interval_update(df, &sample_ms);
break;
}
return 0;
}
static struct devfreq_governor devfreq_gov_bw_hwmon = {
.name = "bw_hwmon",
.get_target_freq = devfreq_bw_hwmon_get_freq,
.event_handler = devfreq_bw_hwmon_ev_handler,
};
int register_bw_hwmon(struct device *dev, struct bw_hwmon *hwmon)
{
int ret = 0;
struct hwmon_node *node;
struct attribute_group *attr_grp;
if (!hwmon->gov && !hwmon->dev && !hwmon->of_node)
return -EINVAL;
node = devm_kzalloc(dev, sizeof(*node), GFP_KERNEL);
if (!node) {
dev_err(dev, "Unable to register gov. Out of memory!\n");
return -ENOMEM;
}
if (hwmon->gov) {
attr_grp = devm_kzalloc(dev, sizeof(*attr_grp), GFP_KERNEL);
if (!attr_grp)
return -ENOMEM;
hwmon->gov->get_target_freq = devfreq_bw_hwmon_get_freq;
hwmon->gov->event_handler = devfreq_bw_hwmon_ev_handler;
attr_grp->name = hwmon->gov->name;
attr_grp->attrs = dev_attr;
node->gov = hwmon->gov;
node->attr_grp = attr_grp;
} else {
node->gov = &devfreq_gov_bw_hwmon;
node->attr_grp = &dev_attr_group;
}
node->tolerance_percent = 10;
node->guard_band_mbps = 100;
node->decay_rate = 90;
node->io_percent = 16;
node->bw_step = 190;
node->hw = hwmon;
mutex_lock(&list_lock);
list_add_tail(&node->list, &hwmon_list);
mutex_unlock(&list_lock);
if (hwmon->gov) {
ret = devfreq_add_governor(hwmon->gov);
} else {
mutex_lock(&state_lock);
if (!use_cnt)
ret = devfreq_add_governor(&devfreq_gov_bw_hwmon);
if (!ret)
use_cnt++;
mutex_unlock(&state_lock);
}
if (!ret)
dev_info(dev, "BW HWmon governor registered.\n");
else
dev_err(dev, "BW HWmon governor registration failed!\n");
return ret;
}
MODULE_DESCRIPTION("HW monitor based dev DDR bandwidth voting driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
lonelydra/furnace_kernel_htc_m8 | net/ipv4/netfilter/nf_nat_snmp_basic.c | 34 | 25646 | /*
* nf_nat_snmp_basic.c
*
* Basic SNMP Application Layer Gateway
*
* This IP NAT module is intended for use with SNMP network
* discovery and monitoring applications where target networks use
* conflicting private address realms.
*
* Static NAT is used to remap the networks from the view of the network
* management system at the IP layer, and this module remaps some application
* layer addresses to match.
*
* The simplest form of ALG is performed, where only tagged IP addresses
* are modified. The module does not need to be MIB aware and only scans
* messages at the ASN.1/BER level.
*
* Currently, only SNMPv1 and SNMPv2 are supported.
*
* More information on ALG and associated issues can be found in
* RFC 2962
*
* The ASB.1/BER parsing code is derived from the gxsnmp package by Gregory
* McLean & Jochen Friedrich, stripped down for use in the kernel.
*
* Copyright (c) 2000 RP Internet (www.rpi.net.au).
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* 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
*
* Author: James Morris <jmorris@intercode.com.au>
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <net/checksum.h>
#include <net/udp.h>
#include <net/netfilter/nf_nat.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_nat_helper.h>
#include <linux/netfilter/nf_conntrack_snmp.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Morris <jmorris@intercode.com.au>");
MODULE_DESCRIPTION("Basic SNMP Application Layer Gateway");
MODULE_ALIAS("ip_nat_snmp_basic");
#define SNMP_PORT 161
#define SNMP_TRAP_PORT 162
#define NOCT1(n) (*(u8 *)(n))
static int debug;
static DEFINE_SPINLOCK(snmp_lock);
struct oct1_map
{
u_int8_t from;
u_int8_t to;
};
#define ASN1_UNI 0
#define ASN1_APL 1
#define ASN1_CTX 2
#define ASN1_PRV 3
#define ASN1_EOC 0
#define ASN1_BOL 1
#define ASN1_INT 2
#define ASN1_BTS 3
#define ASN1_OTS 4
#define ASN1_NUL 5
#define ASN1_OJI 6
#define ASN1_OJD 7
#define ASN1_EXT 8
#define ASN1_SEQ 16
#define ASN1_SET 17
#define ASN1_NUMSTR 18
#define ASN1_PRNSTR 19
#define ASN1_TEXSTR 20
#define ASN1_VIDSTR 21
#define ASN1_IA5STR 22
#define ASN1_UNITIM 23
#define ASN1_GENTIM 24
#define ASN1_GRASTR 25
#define ASN1_VISSTR 26
#define ASN1_GENSTR 27
#define ASN1_PRI 0
#define ASN1_CON 1
#define ASN1_ERR_NOERROR 0
#define ASN1_ERR_DEC_EMPTY 2
#define ASN1_ERR_DEC_EOC_MISMATCH 3
#define ASN1_ERR_DEC_LENGTH_MISMATCH 4
#define ASN1_ERR_DEC_BADVALUE 5
struct asn1_ctx
{
int error;
unsigned char *pointer;
unsigned char *begin;
unsigned char *end;
};
struct asn1_octstr
{
unsigned char *data;
unsigned int len;
};
static void asn1_open(struct asn1_ctx *ctx,
unsigned char *buf,
unsigned int len)
{
ctx->begin = buf;
ctx->end = buf + len;
ctx->pointer = buf;
ctx->error = ASN1_ERR_NOERROR;
}
static unsigned char asn1_octet_decode(struct asn1_ctx *ctx, unsigned char *ch)
{
if (ctx->pointer >= ctx->end) {
ctx->error = ASN1_ERR_DEC_EMPTY;
return 0;
}
*ch = *(ctx->pointer)++;
return 1;
}
static unsigned char asn1_tag_decode(struct asn1_ctx *ctx, unsigned int *tag)
{
unsigned char ch;
*tag = 0;
do
{
if (!asn1_octet_decode(ctx, &ch))
return 0;
*tag <<= 7;
*tag |= ch & 0x7F;
} while ((ch & 0x80) == 0x80);
return 1;
}
static unsigned char asn1_id_decode(struct asn1_ctx *ctx,
unsigned int *cls,
unsigned int *con,
unsigned int *tag)
{
unsigned char ch;
if (!asn1_octet_decode(ctx, &ch))
return 0;
*cls = (ch & 0xC0) >> 6;
*con = (ch & 0x20) >> 5;
*tag = (ch & 0x1F);
if (*tag == 0x1F) {
if (!asn1_tag_decode(ctx, tag))
return 0;
}
return 1;
}
static unsigned char asn1_length_decode(struct asn1_ctx *ctx,
unsigned int *def,
unsigned int *len)
{
unsigned char ch, cnt;
if (!asn1_octet_decode(ctx, &ch))
return 0;
if (ch == 0x80)
*def = 0;
else {
*def = 1;
if (ch < 0x80)
*len = ch;
else {
cnt = ch & 0x7F;
*len = 0;
while (cnt > 0) {
if (!asn1_octet_decode(ctx, &ch))
return 0;
*len <<= 8;
*len |= ch;
cnt--;
}
}
}
if (*len > ctx->end - ctx->pointer)
return 0;
return 1;
}
static unsigned char asn1_header_decode(struct asn1_ctx *ctx,
unsigned char **eoc,
unsigned int *cls,
unsigned int *con,
unsigned int *tag)
{
unsigned int def, len;
if (!asn1_id_decode(ctx, cls, con, tag))
return 0;
def = len = 0;
if (!asn1_length_decode(ctx, &def, &len))
return 0;
if (*con == ASN1_PRI && !def)
return 0;
if (def)
*eoc = ctx->pointer + len;
else
*eoc = NULL;
return 1;
}
static unsigned char asn1_eoc_decode(struct asn1_ctx *ctx, unsigned char *eoc)
{
unsigned char ch;
if (eoc == NULL) {
if (!asn1_octet_decode(ctx, &ch))
return 0;
if (ch != 0x00) {
ctx->error = ASN1_ERR_DEC_EOC_MISMATCH;
return 0;
}
if (!asn1_octet_decode(ctx, &ch))
return 0;
if (ch != 0x00) {
ctx->error = ASN1_ERR_DEC_EOC_MISMATCH;
return 0;
}
return 1;
} else {
if (ctx->pointer != eoc) {
ctx->error = ASN1_ERR_DEC_LENGTH_MISMATCH;
return 0;
}
return 1;
}
}
static unsigned char asn1_null_decode(struct asn1_ctx *ctx, unsigned char *eoc)
{
ctx->pointer = eoc;
return 1;
}
static unsigned char asn1_long_decode(struct asn1_ctx *ctx,
unsigned char *eoc,
long *integer)
{
unsigned char ch;
unsigned int len;
if (!asn1_octet_decode(ctx, &ch))
return 0;
*integer = (signed char) ch;
len = 1;
while (ctx->pointer < eoc) {
if (++len > sizeof (long)) {
ctx->error = ASN1_ERR_DEC_BADVALUE;
return 0;
}
if (!asn1_octet_decode(ctx, &ch))
return 0;
*integer <<= 8;
*integer |= ch;
}
return 1;
}
static unsigned char asn1_uint_decode(struct asn1_ctx *ctx,
unsigned char *eoc,
unsigned int *integer)
{
unsigned char ch;
unsigned int len;
if (!asn1_octet_decode(ctx, &ch))
return 0;
*integer = ch;
if (ch == 0) len = 0;
else len = 1;
while (ctx->pointer < eoc) {
if (++len > sizeof (unsigned int)) {
ctx->error = ASN1_ERR_DEC_BADVALUE;
return 0;
}
if (!asn1_octet_decode(ctx, &ch))
return 0;
*integer <<= 8;
*integer |= ch;
}
return 1;
}
static unsigned char asn1_ulong_decode(struct asn1_ctx *ctx,
unsigned char *eoc,
unsigned long *integer)
{
unsigned char ch;
unsigned int len;
if (!asn1_octet_decode(ctx, &ch))
return 0;
*integer = ch;
if (ch == 0) len = 0;
else len = 1;
while (ctx->pointer < eoc) {
if (++len > sizeof (unsigned long)) {
ctx->error = ASN1_ERR_DEC_BADVALUE;
return 0;
}
if (!asn1_octet_decode(ctx, &ch))
return 0;
*integer <<= 8;
*integer |= ch;
}
return 1;
}
static unsigned char asn1_octets_decode(struct asn1_ctx *ctx,
unsigned char *eoc,
unsigned char **octets,
unsigned int *len)
{
unsigned char *ptr;
*len = 0;
*octets = kmalloc(eoc - ctx->pointer, GFP_ATOMIC);
if (*octets == NULL)
return 0;
ptr = *octets;
while (ctx->pointer < eoc) {
if (!asn1_octet_decode(ctx, (unsigned char *)ptr++)) {
kfree(*octets);
*octets = NULL;
return 0;
}
(*len)++;
}
return 1;
}
static unsigned char asn1_subid_decode(struct asn1_ctx *ctx,
unsigned long *subid)
{
unsigned char ch;
*subid = 0;
do {
if (!asn1_octet_decode(ctx, &ch))
return 0;
*subid <<= 7;
*subid |= ch & 0x7F;
} while ((ch & 0x80) == 0x80);
return 1;
}
static unsigned char asn1_oid_decode(struct asn1_ctx *ctx,
unsigned char *eoc,
unsigned long **oid,
unsigned int *len)
{
unsigned long subid;
unsigned long *optr;
size_t size;
size = eoc - ctx->pointer + 1;
if (size < 2 || size > ULONG_MAX/sizeof(unsigned long))
return 0;
*oid = kmalloc(size * sizeof(unsigned long), GFP_ATOMIC);
if (*oid == NULL)
return 0;
optr = *oid;
if (!asn1_subid_decode(ctx, &subid)) {
kfree(*oid);
*oid = NULL;
return 0;
}
if (subid < 40) {
optr [0] = 0;
optr [1] = subid;
} else if (subid < 80) {
optr [0] = 1;
optr [1] = subid - 40;
} else {
optr [0] = 2;
optr [1] = subid - 80;
}
*len = 2;
optr += 2;
while (ctx->pointer < eoc) {
if (++(*len) > size) {
ctx->error = ASN1_ERR_DEC_BADVALUE;
kfree(*oid);
*oid = NULL;
return 0;
}
if (!asn1_subid_decode(ctx, optr++)) {
kfree(*oid);
*oid = NULL;
return 0;
}
}
return 1;
}
#define SNMP_V1 0
#define SNMP_V2C 1
#define SNMP_V2 2
#define SNMP_V3 3
#define SNMP_SIZE_COMM 256
#define SNMP_SIZE_OBJECTID 128
#define SNMP_SIZE_BUFCHR 256
#define SNMP_SIZE_BUFINT 128
#define SNMP_SIZE_SMALLOBJECTID 16
#define SNMP_PDU_GET 0
#define SNMP_PDU_NEXT 1
#define SNMP_PDU_RESPONSE 2
#define SNMP_PDU_SET 3
#define SNMP_PDU_TRAP1 4
#define SNMP_PDU_BULK 5
#define SNMP_PDU_INFORM 6
#define SNMP_PDU_TRAP2 7
#define SNMP_NOERROR 0
#define SNMP_TOOBIG 1
#define SNMP_NOSUCHNAME 2
#define SNMP_BADVALUE 3
#define SNMP_READONLY 4
#define SNMP_GENERROR 5
#define SNMP_NOACCESS 6
#define SNMP_WRONGTYPE 7
#define SNMP_WRONGLENGTH 8
#define SNMP_WRONGENCODING 9
#define SNMP_WRONGVALUE 10
#define SNMP_NOCREATION 11
#define SNMP_INCONSISTENTVALUE 12
#define SNMP_RESOURCEUNAVAILABLE 13
#define SNMP_COMMITFAILED 14
#define SNMP_UNDOFAILED 15
#define SNMP_AUTHORIZATIONERROR 16
#define SNMP_NOTWRITABLE 17
#define SNMP_INCONSISTENTNAME 18
#define SNMP_TRAP_COLDSTART 0
#define SNMP_TRAP_WARMSTART 1
#define SNMP_TRAP_LINKDOWN 2
#define SNMP_TRAP_LINKUP 3
#define SNMP_TRAP_AUTFAILURE 4
#define SNMP_TRAP_EQPNEIGHBORLOSS 5
#define SNMP_TRAP_ENTSPECIFIC 6
#define SNMP_NULL 0
#define SNMP_INTEGER 1
#define SNMP_OCTETSTR 2
#define SNMP_DISPLAYSTR 2
#define SNMP_OBJECTID 3
#define SNMP_IPADDR 4
#define SNMP_COUNTER 5
#define SNMP_GAUGE 6
#define SNMP_TIMETICKS 7
#define SNMP_OPAQUE 8
#define SNMP_UINTEGER 5
#define SNMP_BITSTR 9
#define SNMP_NSAP 10
#define SNMP_COUNTER64 11
#define SNMP_NOSUCHOBJECT 12
#define SNMP_NOSUCHINSTANCE 13
#define SNMP_ENDOFMIBVIEW 14
union snmp_syntax
{
unsigned char uc[0];
char c[0];
unsigned long ul[0];
long l[0];
};
struct snmp_object
{
unsigned long *id;
unsigned int id_len;
unsigned short type;
unsigned int syntax_len;
union snmp_syntax syntax;
};
struct snmp_request
{
unsigned long id;
unsigned int error_status;
unsigned int error_index;
};
struct snmp_v1_trap
{
unsigned long *id;
unsigned int id_len;
unsigned long ip_address;
unsigned int general;
unsigned int specific;
unsigned long time;
};
#define SNMP_IPA 0
#define SNMP_CNT 1
#define SNMP_GGE 2
#define SNMP_TIT 3
#define SNMP_OPQ 4
#define SNMP_C64 6
#define SERR_NSO 0
#define SERR_NSI 1
#define SERR_EOM 2
static inline void mangle_address(unsigned char *begin,
unsigned char *addr,
const struct oct1_map *map,
__sum16 *check);
struct snmp_cnv
{
unsigned int class;
unsigned int tag;
int syntax;
};
static const struct snmp_cnv snmp_conv[] = {
{ASN1_UNI, ASN1_NUL, SNMP_NULL},
{ASN1_UNI, ASN1_INT, SNMP_INTEGER},
{ASN1_UNI, ASN1_OTS, SNMP_OCTETSTR},
{ASN1_UNI, ASN1_OTS, SNMP_DISPLAYSTR},
{ASN1_UNI, ASN1_OJI, SNMP_OBJECTID},
{ASN1_APL, SNMP_IPA, SNMP_IPADDR},
{ASN1_APL, SNMP_CNT, SNMP_COUNTER},
{ASN1_APL, SNMP_GGE, SNMP_GAUGE},
{ASN1_APL, SNMP_TIT, SNMP_TIMETICKS},
{ASN1_APL, SNMP_OPQ, SNMP_OPAQUE},
{ASN1_UNI, ASN1_BTS, SNMP_BITSTR},
{ASN1_APL, SNMP_C64, SNMP_COUNTER64},
{ASN1_CTX, SERR_NSO, SNMP_NOSUCHOBJECT},
{ASN1_CTX, SERR_NSI, SNMP_NOSUCHINSTANCE},
{ASN1_CTX, SERR_EOM, SNMP_ENDOFMIBVIEW},
{0, 0, -1}
};
static unsigned char snmp_tag_cls2syntax(unsigned int tag,
unsigned int cls,
unsigned short *syntax)
{
const struct snmp_cnv *cnv;
cnv = snmp_conv;
while (cnv->syntax != -1) {
if (cnv->tag == tag && cnv->class == cls) {
*syntax = cnv->syntax;
return 1;
}
cnv++;
}
return 0;
}
static unsigned char snmp_object_decode(struct asn1_ctx *ctx,
struct snmp_object **obj)
{
unsigned int cls, con, tag, len, idlen;
unsigned short type;
unsigned char *eoc, *end, *p;
unsigned long *lp, *id;
unsigned long ul;
long l;
*obj = NULL;
id = NULL;
if (!asn1_header_decode(ctx, &eoc, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SEQ)
return 0;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_OJI)
return 0;
if (!asn1_oid_decode(ctx, end, &id, &idlen))
return 0;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag)) {
kfree(id);
return 0;
}
if (con != ASN1_PRI) {
kfree(id);
return 0;
}
type = 0;
if (!snmp_tag_cls2syntax(tag, cls, &type)) {
kfree(id);
return 0;
}
l = 0;
switch (type) {
case SNMP_INTEGER:
len = sizeof(long);
if (!asn1_long_decode(ctx, end, &l)) {
kfree(id);
return 0;
}
*obj = kmalloc(sizeof(struct snmp_object) + len, GFP_ATOMIC);
if (*obj == NULL) {
kfree(id);
return 0;
}
(*obj)->syntax.l[0] = l;
break;
case SNMP_OCTETSTR:
case SNMP_OPAQUE:
if (!asn1_octets_decode(ctx, end, &p, &len)) {
kfree(id);
return 0;
}
*obj = kmalloc(sizeof(struct snmp_object) + len, GFP_ATOMIC);
if (*obj == NULL) {
kfree(p);
kfree(id);
return 0;
}
memcpy((*obj)->syntax.c, p, len);
kfree(p);
break;
case SNMP_NULL:
case SNMP_NOSUCHOBJECT:
case SNMP_NOSUCHINSTANCE:
case SNMP_ENDOFMIBVIEW:
len = 0;
*obj = kmalloc(sizeof(struct snmp_object), GFP_ATOMIC);
if (*obj == NULL) {
kfree(id);
return 0;
}
if (!asn1_null_decode(ctx, end)) {
kfree(id);
kfree(*obj);
*obj = NULL;
return 0;
}
break;
case SNMP_OBJECTID:
if (!asn1_oid_decode(ctx, end, (unsigned long **)&lp, &len)) {
kfree(id);
return 0;
}
len *= sizeof(unsigned long);
*obj = kmalloc(sizeof(struct snmp_object) + len, GFP_ATOMIC);
if (*obj == NULL) {
kfree(lp);
kfree(id);
return 0;
}
memcpy((*obj)->syntax.ul, lp, len);
kfree(lp);
break;
case SNMP_IPADDR:
if (!asn1_octets_decode(ctx, end, &p, &len)) {
kfree(id);
return 0;
}
if (len != 4) {
kfree(p);
kfree(id);
return 0;
}
*obj = kmalloc(sizeof(struct snmp_object) + len, GFP_ATOMIC);
if (*obj == NULL) {
kfree(p);
kfree(id);
return 0;
}
memcpy((*obj)->syntax.uc, p, len);
kfree(p);
break;
case SNMP_COUNTER:
case SNMP_GAUGE:
case SNMP_TIMETICKS:
len = sizeof(unsigned long);
if (!asn1_ulong_decode(ctx, end, &ul)) {
kfree(id);
return 0;
}
*obj = kmalloc(sizeof(struct snmp_object) + len, GFP_ATOMIC);
if (*obj == NULL) {
kfree(id);
return 0;
}
(*obj)->syntax.ul[0] = ul;
break;
default:
kfree(id);
return 0;
}
(*obj)->syntax_len = len;
(*obj)->type = type;
(*obj)->id = id;
(*obj)->id_len = idlen;
if (!asn1_eoc_decode(ctx, eoc)) {
kfree(id);
kfree(*obj);
*obj = NULL;
return 0;
}
return 1;
}
static unsigned char snmp_request_decode(struct asn1_ctx *ctx,
struct snmp_request *request)
{
unsigned int cls, con, tag;
unsigned char *end;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_INT)
return 0;
if (!asn1_ulong_decode(ctx, end, &request->id))
return 0;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_INT)
return 0;
if (!asn1_uint_decode(ctx, end, &request->error_status))
return 0;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_INT)
return 0;
if (!asn1_uint_decode(ctx, end, &request->error_index))
return 0;
return 1;
}
static void fast_csum(__sum16 *csum,
const unsigned char *optr,
const unsigned char *nptr,
int offset)
{
unsigned char s[4];
if (offset & 1) {
s[0] = ~0;
s[1] = ~*optr;
s[2] = 0;
s[3] = *nptr;
} else {
s[0] = ~*optr;
s[1] = ~0;
s[2] = *nptr;
s[3] = 0;
}
*csum = csum_fold(csum_partial(s, 4, ~csum_unfold(*csum)));
}
static inline void mangle_address(unsigned char *begin,
unsigned char *addr,
const struct oct1_map *map,
__sum16 *check)
{
if (map->from == NOCT1(addr)) {
u_int32_t old;
if (debug)
memcpy(&old, addr, sizeof(old));
*addr = map->to;
if (*check) {
fast_csum(check,
&map->from, &map->to, addr - begin);
}
if (debug)
printk(KERN_DEBUG "bsalg: mapped %pI4 to %pI4\n",
&old, addr);
}
}
static unsigned char snmp_trap_decode(struct asn1_ctx *ctx,
struct snmp_v1_trap *trap,
const struct oct1_map *map,
__sum16 *check)
{
unsigned int cls, con, tag, len;
unsigned char *end;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_OJI)
return 0;
if (!asn1_oid_decode(ctx, end, &trap->id, &trap->id_len))
return 0;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
goto err_id_free;
if (!((cls == ASN1_APL && con == ASN1_PRI && tag == SNMP_IPA) ||
(cls == ASN1_UNI && con == ASN1_PRI && tag == ASN1_OTS)))
goto err_id_free;
if (!asn1_octets_decode(ctx, end, (unsigned char **)&trap->ip_address, &len))
goto err_id_free;
if (len != 4)
goto err_addr_free;
mangle_address(ctx->begin, ctx->pointer - 4, map, check);
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
goto err_addr_free;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_INT)
goto err_addr_free;
if (!asn1_uint_decode(ctx, end, &trap->general))
goto err_addr_free;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
goto err_addr_free;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_INT)
goto err_addr_free;
if (!asn1_uint_decode(ctx, end, &trap->specific))
goto err_addr_free;
if (!asn1_header_decode(ctx, &end, &cls, &con, &tag))
goto err_addr_free;
if (!((cls == ASN1_APL && con == ASN1_PRI && tag == SNMP_TIT) ||
(cls == ASN1_UNI && con == ASN1_PRI && tag == ASN1_INT)))
goto err_addr_free;
if (!asn1_ulong_decode(ctx, end, &trap->time))
goto err_addr_free;
return 1;
err_addr_free:
kfree((unsigned long *)trap->ip_address);
err_id_free:
kfree(trap->id);
return 0;
}
static void hex_dump(const unsigned char *buf, size_t len)
{
size_t i;
for (i = 0; i < len; i++) {
if (i && !(i % 16))
printk("\n");
printk("%02x ", *(buf + i));
}
printk("\n");
}
static int snmp_parse_mangle(unsigned char *msg,
u_int16_t len,
const struct oct1_map *map,
__sum16 *check)
{
unsigned char *eoc, *end;
unsigned int cls, con, tag, vers, pdutype;
struct asn1_ctx ctx;
struct asn1_octstr comm;
struct snmp_object *obj;
if (debug > 1)
hex_dump(msg, len);
asn1_open(&ctx, msg, len);
if (!asn1_header_decode(&ctx, &eoc, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SEQ)
return 0;
if (!asn1_header_decode(&ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_INT)
return 0;
if (!asn1_uint_decode (&ctx, end, &vers))
return 0;
if (debug > 1)
printk(KERN_DEBUG "bsalg: snmp version: %u\n", vers + 1);
if (vers > 1)
return 1;
if (!asn1_header_decode (&ctx, &end, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_OTS)
return 0;
if (!asn1_octets_decode(&ctx, end, &comm.data, &comm.len))
return 0;
if (debug > 1) {
unsigned int i;
printk(KERN_DEBUG "bsalg: community: ");
for (i = 0; i < comm.len; i++)
printk("%c", comm.data[i]);
printk("\n");
}
kfree(comm.data);
if (!asn1_header_decode(&ctx, &eoc, &cls, &con, &pdutype))
return 0;
if (cls != ASN1_CTX || con != ASN1_CON)
return 0;
if (debug > 1) {
static const unsigned char *const pdus[] = {
[SNMP_PDU_GET] = "get",
[SNMP_PDU_NEXT] = "get-next",
[SNMP_PDU_RESPONSE] = "response",
[SNMP_PDU_SET] = "set",
[SNMP_PDU_TRAP1] = "trapv1",
[SNMP_PDU_BULK] = "bulk",
[SNMP_PDU_INFORM] = "inform",
[SNMP_PDU_TRAP2] = "trapv2"
};
if (pdutype > SNMP_PDU_TRAP2)
printk(KERN_DEBUG "bsalg: bad pdu type %u\n", pdutype);
else
printk(KERN_DEBUG "bsalg: pdu: %s\n", pdus[pdutype]);
}
if (pdutype != SNMP_PDU_RESPONSE &&
pdutype != SNMP_PDU_TRAP1 && pdutype != SNMP_PDU_TRAP2)
return 1;
if (pdutype == SNMP_PDU_TRAP1) {
struct snmp_v1_trap trap;
unsigned char ret = snmp_trap_decode(&ctx, &trap, map, check);
if (ret) {
kfree(trap.id);
kfree((unsigned long *)trap.ip_address);
} else
return ret;
} else {
struct snmp_request req;
if (!snmp_request_decode(&ctx, &req))
return 0;
if (debug > 1)
printk(KERN_DEBUG "bsalg: request: id=0x%lx error_status=%u "
"error_index=%u\n", req.id, req.error_status,
req.error_index);
}
if (!asn1_header_decode(&ctx, &eoc, &cls, &con, &tag))
return 0;
if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SEQ)
return 0;
while (!asn1_eoc_decode(&ctx, eoc)) {
unsigned int i;
if (!snmp_object_decode(&ctx, &obj)) {
if (obj) {
kfree(obj->id);
kfree(obj);
}
return 0;
}
if (debug > 1) {
printk(KERN_DEBUG "bsalg: object: ");
for (i = 0; i < obj->id_len; i++) {
if (i > 0)
printk(".");
printk("%lu", obj->id[i]);
}
printk(": type=%u\n", obj->type);
}
if (obj->type == SNMP_IPADDR)
mangle_address(ctx.begin, ctx.pointer - 4 , map, check);
kfree(obj->id);
kfree(obj);
}
if (!asn1_eoc_decode(&ctx, eoc))
return 0;
return 1;
}
static int snmp_translate(struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
struct sk_buff *skb)
{
struct iphdr *iph = ip_hdr(skb);
struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl);
u_int16_t udplen = ntohs(udph->len);
u_int16_t paylen = udplen - sizeof(struct udphdr);
int dir = CTINFO2DIR(ctinfo);
struct oct1_map map;
if (dir == IP_CT_DIR_ORIGINAL) {
map.from = NOCT1(&ct->tuplehash[dir].tuple.src.u3.ip);
map.to = NOCT1(&ct->tuplehash[!dir].tuple.dst.u3.ip);
} else {
map.from = NOCT1(&ct->tuplehash[dir].tuple.src.u3.ip);
map.to = NOCT1(&ct->tuplehash[!dir].tuple.dst.u3.ip);
}
if (map.from == map.to)
return NF_ACCEPT;
if (!snmp_parse_mangle((unsigned char *)udph + sizeof(struct udphdr),
paylen, &map, &udph->check)) {
if (net_ratelimit())
printk(KERN_WARNING "bsalg: parser failed\n");
return NF_DROP;
}
return NF_ACCEPT;
}
static int help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo)
{
int dir = CTINFO2DIR(ctinfo);
unsigned int ret;
const struct iphdr *iph = ip_hdr(skb);
const struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl);
if (udph->source == htons(SNMP_PORT) && dir != IP_CT_DIR_REPLY)
return NF_ACCEPT;
if (udph->dest == htons(SNMP_TRAP_PORT) && dir != IP_CT_DIR_ORIGINAL)
return NF_ACCEPT;
if (!(ct->status & IPS_NAT_MASK))
return NF_ACCEPT;
if (ntohs(udph->len) != skb->len - (iph->ihl << 2)) {
if (net_ratelimit())
printk(KERN_WARNING "SNMP: dropping malformed packet src=%pI4 dst=%pI4\n",
&iph->saddr, &iph->daddr);
return NF_DROP;
}
if (!skb_make_writable(skb, skb->len))
return NF_DROP;
spin_lock_bh(&snmp_lock);
ret = snmp_translate(ct, ctinfo, skb);
spin_unlock_bh(&snmp_lock);
return ret;
}
static const struct nf_conntrack_expect_policy snmp_exp_policy = {
.max_expected = 0,
.timeout = 180,
};
static struct nf_conntrack_helper snmp_helper __read_mostly = {
.me = THIS_MODULE,
.help = help,
.expect_policy = &snmp_exp_policy,
.name = "snmp",
.tuple.src.l3num = AF_INET,
.tuple.src.u.udp.port = cpu_to_be16(SNMP_PORT),
.tuple.dst.protonum = IPPROTO_UDP,
};
static struct nf_conntrack_helper snmp_trap_helper __read_mostly = {
.me = THIS_MODULE,
.help = help,
.expect_policy = &snmp_exp_policy,
.name = "snmp_trap",
.tuple.src.l3num = AF_INET,
.tuple.src.u.udp.port = cpu_to_be16(SNMP_TRAP_PORT),
.tuple.dst.protonum = IPPROTO_UDP,
};
static int __init nf_nat_snmp_basic_init(void)
{
int ret = 0;
BUG_ON(nf_nat_snmp_hook != NULL);
RCU_INIT_POINTER(nf_nat_snmp_hook, help);
ret = nf_conntrack_helper_register(&snmp_trap_helper);
if (ret < 0) {
nf_conntrack_helper_unregister(&snmp_helper);
return ret;
}
return ret;
}
static void __exit nf_nat_snmp_basic_fini(void)
{
RCU_INIT_POINTER(nf_nat_snmp_hook, NULL);
nf_conntrack_helper_unregister(&snmp_trap_helper);
}
module_init(nf_nat_snmp_basic_init);
module_exit(nf_nat_snmp_basic_fini);
module_param(debug, int, 0600);
| gpl-2.0 |
k5t4j5/kernel_htc_hybrid | arch/arm/mach-pxa/palmz72.c | 34 | 7940 | /*
* Hardware definitions for Palm Zire72
*
* Authors:
* Vladimir "Farcaller" Pouzanov <farcaller@gmail.com>
* Sergey Lapin <slapin@ossfans.org>
* Alex Osborne <bobofdoom@gmail.com>
* Jan Herman <2hp@seznam.cz>
*
* Rewrite for mainline:
* Marek Vasut <marek.vasut@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* (find more info at www.hackndev.com)
*
*/
#include <linux/platform_device.h>
#include <linux/syscore_ops.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/pda_power.h>
#include <linux/pwm_backlight.h>
#include <linux/gpio.h>
#include <linux/wm97xx.h>
#include <linux/power_supply.h>
#include <linux/usb/gpio_vbus.h>
#include <linux/i2c-gpio.h>
#include <asm/mach-types.h>
#include <asm/suspend.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/pxa27x.h>
#include <mach/audio.h>
#include <mach/palmz72.h>
#include <mach/mmc.h>
#include <mach/pxafb.h>
#include <mach/irda.h>
#include <plat/pxa27x_keypad.h>
#include <mach/udc.h>
#include <mach/palmasoc.h>
#include <mach/palm27x.h>
#include <mach/pm.h>
#include <mach/camera.h>
#include <media/soc_camera.h>
#include "generic.h"
#include "devices.h"
static unsigned long palmz72_pin_config[] __initdata = {
GPIO32_MMC_CLK,
GPIO92_MMC_DAT_0,
GPIO109_MMC_DAT_1,
GPIO110_MMC_DAT_2,
GPIO111_MMC_DAT_3,
GPIO112_MMC_CMD,
GPIO14_GPIO,
GPIO115_GPIO,
GPIO98_GPIO,
GPIO28_AC97_BITCLK,
GPIO29_AC97_SDATA_IN_0,
GPIO30_AC97_SDATA_OUT,
GPIO31_AC97_SYNC,
GPIO89_AC97_SYSCLK,
GPIO113_AC97_nRESET,
GPIO49_GPIO,
GPIO46_FICP_RXD,
GPIO47_FICP_TXD,
GPIO16_PWM0_OUT,
GPIO15_GPIO,
GPIO95_GPIO,
GPIO100_KP_MKIN_0 | WAKEUP_ON_LEVEL_HIGH,
GPIO101_KP_MKIN_1 | WAKEUP_ON_LEVEL_HIGH,
GPIO102_KP_MKIN_2 | WAKEUP_ON_LEVEL_HIGH,
GPIO97_KP_MKIN_3 | WAKEUP_ON_LEVEL_HIGH,
GPIO103_KP_MKOUT_0,
GPIO104_KP_MKOUT_1,
GPIO105_KP_MKOUT_2,
GPIOxx_LCD_TFT_16BPP,
GPIO20_GPIO,
GPIO21_GPIO,
GPIO22_GPIO,
GPIO96_GPIO,
GPIO81_CIF_DD_0,
GPIO48_CIF_DD_5,
GPIO50_CIF_DD_3,
GPIO51_CIF_DD_2,
GPIO52_CIF_DD_4,
GPIO53_CIF_MCLK,
GPIO54_CIF_PCLK,
GPIO55_CIF_DD_1,
GPIO84_CIF_FV,
GPIO85_CIF_LV,
GPIO93_CIF_DD_6,
GPIO108_CIF_DD_7,
GPIO56_GPIO,
GPIO57_GPIO,
GPIO91_GPIO,
GPIO117_GPIO,
GPIO118_GPIO,
GPIO0_GPIO | WAKEUP_ON_LEVEL_HIGH,
GPIO88_GPIO,
GPIO27_GPIO,
};
#if defined(CONFIG_KEYBOARD_PXA27x) || defined(CONFIG_KEYBOARD_PXA27x_MODULE)
static unsigned int palmz72_matrix_keys[] = {
KEY(0, 0, KEY_POWER),
KEY(0, 1, KEY_F1),
KEY(0, 2, KEY_ENTER),
KEY(1, 0, KEY_F2),
KEY(1, 1, KEY_F3),
KEY(1, 2, KEY_F4),
KEY(2, 0, KEY_UP),
KEY(2, 2, KEY_DOWN),
KEY(3, 0, KEY_RIGHT),
KEY(3, 2, KEY_LEFT),
};
static struct pxa27x_keypad_platform_data palmz72_keypad_platform_data = {
.matrix_key_rows = 4,
.matrix_key_cols = 3,
.matrix_key_map = palmz72_matrix_keys,
.matrix_key_map_size = ARRAY_SIZE(palmz72_matrix_keys),
.debounce_interval = 30,
};
static void __init palmz72_kpc_init(void)
{
pxa_set_keypad_info(&palmz72_keypad_platform_data);
}
#else
static inline void palmz72_kpc_init(void) {}
#endif
#if defined(CONFIG_LEDS_GPIO) || defined(CONFIG_LEDS_GPIO_MODULE)
static struct gpio_led gpio_leds[] = {
{
.name = "palmz72:green:led",
.default_trigger = "none",
.gpio = GPIO_NR_PALMZ72_LED_GREEN,
},
};
static struct gpio_led_platform_data gpio_led_info = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct platform_device palmz72_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &gpio_led_info,
}
};
static void __init palmz72_leds_init(void)
{
platform_device_register(&palmz72_leds);
}
#else
static inline void palmz72_leds_init(void) {}
#endif
#ifdef CONFIG_PM
#define PALMZ72_SAVE_DWORD ((unsigned long *)0xc0000050)
static struct palmz72_resume_info palmz72_resume_info = {
.magic0 = 0xb4e6,
.magic1 = 1,
.arm_control = 0,
.aux_control = 0,
.ttb = 0,
.domain_access = 0,
.process_id = 0,
};
static unsigned long store_ptr;
static int palmz72_pm_suspend(void)
{
palmz72_resume_info.resume_addr = (u32) cpu_resume;
store_ptr = *PALMZ72_SAVE_DWORD;
PSPR = virt_to_phys(&palmz72_resume_info);
return 0;
}
static void palmz72_pm_resume(void)
{
*PALMZ72_SAVE_DWORD = store_ptr;
}
static struct syscore_ops palmz72_pm_syscore_ops = {
.suspend = palmz72_pm_suspend,
.resume = palmz72_pm_resume,
};
static int __init palmz72_pm_init(void)
{
if (machine_is_palmz72()) {
register_syscore_ops(&palmz72_pm_syscore_ops);
return 0;
}
return -ENODEV;
}
device_initcall(palmz72_pm_init);
#endif
#if defined(CONFIG_SOC_CAMERA_OV9640) || \
defined(CONFIG_SOC_CAMERA_OV9640_MODULE)
static struct pxacamera_platform_data palmz72_pxacamera_platform_data = {
.flags = PXA_CAMERA_MASTER | PXA_CAMERA_DATAWIDTH_8 |
PXA_CAMERA_PCLK_EN | PXA_CAMERA_MCLK_EN,
.mclk_10khz = 2600,
};
static struct i2c_board_info palmz72_i2c_device[] = {
{
I2C_BOARD_INFO("ov9640", 0x30),
}
};
static int palmz72_camera_power(struct device *dev, int power)
{
gpio_set_value(GPIO_NR_PALMZ72_CAM_PWDN, !power);
mdelay(50);
return 0;
}
static int palmz72_camera_reset(struct device *dev)
{
gpio_set_value(GPIO_NR_PALMZ72_CAM_RESET, 1);
mdelay(50);
gpio_set_value(GPIO_NR_PALMZ72_CAM_RESET, 0);
mdelay(50);
return 0;
}
static struct soc_camera_link palmz72_iclink = {
.bus_id = 0,
.board_info = &palmz72_i2c_device[0],
.i2c_adapter_id = 0,
.module_name = "ov96xx",
.power = &palmz72_camera_power,
.reset = &palmz72_camera_reset,
.flags = SOCAM_DATAWIDTH_8,
};
static struct i2c_gpio_platform_data palmz72_i2c_bus_data = {
.sda_pin = 118,
.scl_pin = 117,
.udelay = 10,
.timeout = 100,
};
static struct platform_device palmz72_i2c_bus_device = {
.name = "i2c-gpio",
.id = 0,
.dev = {
.platform_data = &palmz72_i2c_bus_data,
}
};
static struct platform_device palmz72_camera = {
.name = "soc-camera-pdrv",
.id = -1,
.dev = {
.platform_data = &palmz72_iclink,
},
};
static struct gpio palmz72_camera_gpios[] = {
{ GPIO_NR_PALMZ72_CAM_POWER, GPIOF_INIT_HIGH,"Camera DVDD" },
{ GPIO_NR_PALMZ72_CAM_RESET, GPIOF_INIT_LOW, "Camera RESET" },
{ GPIO_NR_PALMZ72_CAM_PWDN, GPIOF_INIT_LOW, "Camera PWDN" },
};
static inline void __init palmz72_cam_gpio_init(void)
{
int ret;
ret = gpio_request_array(ARRAY_AND_SIZE(palmz72_camera_gpios));
if (!ret)
gpio_free_array(ARRAY_AND_SIZE(palmz72_camera_gpios));
else
printk(KERN_ERR "Camera GPIO init failed!\n");
return;
}
static void __init palmz72_camera_init(void)
{
palmz72_cam_gpio_init();
pxa_set_camera_info(&palmz72_pxacamera_platform_data);
platform_device_register(&palmz72_i2c_bus_device);
platform_device_register(&palmz72_camera);
}
#else
static inline void palmz72_camera_init(void) {}
#endif
static void __init palmz72_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(palmz72_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
palm27x_mmc_init(GPIO_NR_PALMZ72_SD_DETECT_N, GPIO_NR_PALMZ72_SD_RO,
GPIO_NR_PALMZ72_SD_POWER_N, 1);
palm27x_lcd_init(-1, &palm_320x320_lcd_mode);
palm27x_udc_init(GPIO_NR_PALMZ72_USB_DETECT_N,
GPIO_NR_PALMZ72_USB_PULLUP, 0);
palm27x_irda_init(GPIO_NR_PALMZ72_IR_DISABLE);
palm27x_ac97_init(PALMZ72_BAT_MIN_VOLTAGE, PALMZ72_BAT_MAX_VOLTAGE,
-1, 113);
palm27x_pwm_init(-1, -1);
palm27x_power_init(-1, -1);
palm27x_pmic_init();
palmz72_kpc_init();
palmz72_leds_init();
palmz72_camera_init();
}
MACHINE_START(PALMZ72, "Palm Zire72")
.atag_offset = 0x100,
.map_io = pxa27x_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.timer = &pxa_timer,
.init_machine = palmz72_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
AODP/android_kernel_asus_moorefield | drivers/external_drivers/camera/drivers/media/i2c/m10mo_fw_type2.c | 34 | 13269 | /*
* Copyright (c) 2014 Intel Corporation. All Rights Reserved.
*
* Partially based on m-5mols kernel driver,
* Copyright (C) 2011 Samsung Electronics Co., Ltd.
*
* Partially based on jc_v4l2 kernel driver from http://opensource.samsung.com
* Copyright (c) 2011, 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 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/atomisp_platform.h>
#include <media/m10mo_atomisp.h>
#include <linux/module.h>
#include "m10mo.h"
static const uint32_t m10mo_md_effective_size[] = {
M10MO_METADATA_WIDTH,
M10MO_METADATA_WIDTH,
M10MO_METADATA_WIDTH,
M10MO_METADATA_WIDTH
};
int m10mo_set_burst_mode_fw_type2(struct v4l2_subdev *sd, unsigned int val)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
switch (val) {
case EXT_ISP_BURST_CAPTURE_CTRL_START:
dev->capture_mode = M10MO_CAPTURE_MODE_ZSL_BURST;
break;
case EXT_ISP_BURST_CAPTURE_CTRL_STOP:
dev->capture_mode = M10MO_CAPTURE_MODE_ZSL_NORMAL;
break;
default:
return -EINVAL;
}
return 0;
}
static int m10mo_set_monitor_mode(struct v4l2_subdev *sd)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
u32 val;
int mode = M10MO_GET_RESOLUTION_MODE(dev->fw_type);
dev_info(&client->dev, "%s mode: %d Width: %d, height: %d, cmd: 0x%x\n",
__func__, dev->cmd, dev->curr_res_table[dev->fmt_idx].width,
dev->curr_res_table[dev->fmt_idx].height,
dev->curr_res_table[dev->fmt_idx].command);
/* Check if m10mo already streaming @ required resolution */
ret = m10mo_readb(sd, CATEGORY_PARAM, PARAM_MON_SIZE, &val);
if (ret)
goto out;
/* If mode is monitor mode and size same, do not configure again*/
if (dev->cmd == M10MO_MONITOR_MODE &&
val == dev->curr_res_table[dev->fmt_idx].command)
return 0;
/*Change to Monitor Size (e,g. VGA) */
ret = m10mo_writeb(sd, CATEGORY_PARAM, PARAM_MON_SIZE,
dev->curr_res_table[dev->fmt_idx].command);
if (ret)
goto out;
if (mode == M10MO_RESOLUTION_MODE_0) {
/* TODO: FPS setting must be changed */
ret = m10mo_writeb(sd, CATEGORY_PARAM, PARAM_MON_FPS, 0x02);
if (ret)
goto out;
ret = m10mo_writeb(sd, CATEGORY_PARAM, 0x67, 0x00);
if (ret)
goto out;
}
if (dev->run_mode == CI_MODE_VIDEO)
ret = m10mo_writeb(sd, CATEGORY_PARAM,
MONITOR_TYPE, MONITOR_VIDEO);
else
ret = m10mo_writeb(sd, CATEGORY_PARAM,
MONITOR_TYPE, MONITOR_PREVIEW);
/* Enable metadata */
ret = m10mo_writeb(sd, CATEGORY_PARAM, MON_METADATA_SUPPORT_CTRL,
MON_METADATA_SUPPORT_CTRL_EN);
if (ret)
goto out;
ret = m10mo_writeb(sd, CATEGORY_PARAM, MPO_FORMAT_META, 1);
if (ret)
goto out;
/* Enable interrupt signal */
ret = m10mo_writeb(sd, CATEGORY_SYSTEM, SYSTEM_INT_ENABLE, 0x01);
if (ret)
goto out;
/* Go to Monitor mode and output YUV Data */
ret = m10mo_request_cmd_effect(sd, M10MO_MONITOR_MODE, NULL);
if (ret)
goto out;
return 0;
out:
dev_err(&client->dev, "Streaming failed %d\n", ret);
return ret;
}
static int m10mo_set_burst_capture(struct v4l2_subdev *sd)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
const struct m10mo_resolution *capture_res;
// int mode = M10MO_GET_RESOLUTION_MODE(dev->fw_type);
int idx;
int ret;
dev_info(&client->dev, "%s mode: %d width: %d, height: %d, cmd: 0x%x\n",
__func__, dev->cmd, dev->curr_res_table[dev->fmt_idx].width,
dev->curr_res_table[dev->fmt_idx].height,
dev->curr_res_table[dev->fmt_idx].command);
/* Exit from normal monitor mode. */
ret = m10mo_request_cmd_effect(sd, M10MO_PARAMETER_MODE_REQUEST_CMD, NULL);
if (ret)
return ret;
ret = m10mo_wait_mode_change(sd, M10MO_PARAMETER_MODE_REQUEST_CMD, M10MO_INIT_TIMEOUT);
if (ret)
return ret;
/* Configure burst capture resolution.
* Map burst capture size to monitor size. Burst capture uses
* monitor parameters.
*/
capture_res = resolutions[M10MO_MODE_CAPTURE_INDEX];
idx = get_resolution_index(
resolutions[M10MO_MODE_CAPTURE_INDEX],
resolutions_sizes[M10MO_MODE_CAPTURE_INDEX],
capture_res->width, capture_res->height);
if (idx == -1) {
dev_err(&client->dev, "Unsupported burst capture size %dx%d\n",
capture_res->width, capture_res->height);
return -EINVAL;
}
ret = m10mo_writeb(sd, CATEGORY_PARAM, PARAM_MON_SIZE,
resolutions[M10MO_MODE_PREVIEW_INDEX][idx]
.command);
if (ret)
return ret;
/* Start burst capture. */
ret = m10mo_request_cmd_effect(sd, M10MO_BURST_CAPTURE_MODE, NULL);
return ret;
}
static int m10mo_set_still_capture_fw_type2(struct v4l2_subdev *sd)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
// int mode = M10MO_GET_RESOLUTION_MODE(dev->fw_type);
int ret;
dev_info(&client->dev, "%s mode: %d width: %d, height: %d, cmd: 0x%x\n",
__func__, dev->cmd, dev->curr_res_table[dev->fmt_idx].width,
dev->curr_res_table[dev->fmt_idx].height,
dev->curr_res_table[dev->fmt_idx].command);
/* Setting before switching to capture mode */
ret = m10mo_writeb(sd, CATEGORY_CAPTURE_PARAM, CAPP_MAIN_IMAGE_SIZE,
resolutions[M10MO_MODE_CAPTURE_INDEX][dev->capture_res_idx].command);
if (ret)
goto out;
ret = m10mo_writeb(sd, CATEGORY_CAPTURE_CTRL, CAPC_MODE, 0);/* Single Capture*/
if (ret)
goto out;
ret = m10mo_writeb(sd, CATEGORY_SYSTEM, SYSTEM_INT_ENABLE, 0x08);
if (ret)
goto out;
/* Set capture mode */
ret = m10mo_request_cmd_effect(sd, M10MO_SINGLE_CAPTURE_MODE, NULL);
out:
return ret;
}
int m10mo_set_run_mode_fw_type2(struct v4l2_subdev *sd)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
int ret;
/*
* Handle RAW capture mode separately irrespective of the run mode
* being configured. Start the RAW capture right away.
*/
if (dev->capture_mode == M10MO_CAPTURE_MODE_ZSL_RAW) {
/*
* As RAW capture is done from a command line tool, we are not
* restarting the preview after the RAW capture. So it is ok
* to reset the RAW capture mode here because the next RAW
* capture has to start from the Set format onwards.
*/
dev->capture_mode = M10MO_CAPTURE_MODE_ZSL_NORMAL;
return m10mo_set_zsl_raw_capture(sd);
}
switch (dev->run_mode) {
case CI_MODE_STILL_CAPTURE:
ret = m10mo_set_still_capture_fw_type2(sd);
break;
default:
/* Start still capture if M10MO is already in monitor mode. */
if (dev->cmd == M10MO_MONITOR_MODE) {
if (dev->capture_mode ==
M10MO_CAPTURE_MODE_ZSL_BURST)
ret = m10mo_set_burst_capture(sd);
else
ret = m10mo_set_still_capture_fw_type2(sd);
} else {
ret = m10mo_set_monitor_mode(sd);
}
}
return ret;
}
static int __m10mo_monitor_mode_set(struct v4l2_subdev *sd)
{
int ret;
ret = m10mo_request_cmd_effect(sd, M10MO_MONITOR_MODE, NULL);
if (ret)
return ret;
ret = m10mo_wait_mode_change(sd, M10MO_MONITOR_MODE,
M10MO_INIT_TIMEOUT);
if (ret > 0)
ret = 0;
return ret;
}
int m10mo_streamoff_fw_type2(struct v4l2_subdev *sd)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
int ret = 0;
if (dev->cmd == M10MO_SINGLE_CAPTURE_MODE) {
/* Exit capture mode and back to monitor mode */
ret = m10mo_writeb(sd, CATEGORY_SYSTEM, SYSTEM_INT_ENABLE, 0x01);
if (ret)
goto out;
ret = __m10mo_monitor_mode_set(sd);
if (ret)
return ret;
} else if (dev->cmd == M10MO_BURST_CAPTURE_MODE) {
/* Exit burst capture mode. */
ret = __m10mo_param_mode_set(sd);
if (ret)
goto out;
/* Set monitor type as Preview. */
ret = m10mo_writeb(sd, CATEGORY_PARAM,
MONITOR_TYPE, MONITOR_PREVIEW);
if (ret)
goto out;
/* Restart monitor mode. */
ret = m10mo_writeb(sd, CATEGORY_SYSTEM, SYSTEM_INT_ENABLE, 0x01);
if (ret)
return ret;
ret = __m10mo_monitor_mode_set(sd);
}
out:
return ret;
}
int m10mo_single_capture_process_fw_type2(struct v4l2_subdev *sd)
{
int ret;
/* Select frame */
ret = m10mo_writeb(sd, CATEGORY_CAPTURE_CTRL,
CAPC_SEL_FRAME_MAIN, 0x01);
if (ret)
return ret;
/* Start image transfer */
ret = m10mo_writeb(sd, CATEGORY_CAPTURE_CTRL,
CAPC_TRANSFER_START, 0x01);
return ret;
}
int __m10mo_try_mbus_fmt_fw_type2(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *fmt, bool update_fmt)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct atomisp_input_stream_info *stream_info =
(struct atomisp_input_stream_info *)fmt->reserved;
const struct m10mo_resolution *res;
int entries, idx;
// int mode = M10MO_GET_RESOLUTION_MODE(dev->fw_type);
/* Set mbus format to 0x8001(YUV420) */
fmt->code = 0x8001;
/* In ZSL case, capture table needs to be handled separately */
if (stream_info->stream == ATOMISP_INPUT_STREAM_CAPTURE &&
(dev->run_mode == CI_MODE_PREVIEW ||
dev->run_mode == CI_MODE_VIDEO ||
dev->run_mode == CI_MODE_CONTINUOUS)) {
res = resolutions[M10MO_MODE_CAPTURE_INDEX];
entries =
resolutions_sizes[M10MO_MODE_CAPTURE_INDEX];
} else {
res = dev->curr_res_table;
entries = dev->entries_curr_table;
}
/* check if the given resolutions are spported */
idx = get_resolution_index(res, entries, fmt->width, fmt->height);
if (idx < 0) {
dev_err(&client->dev, "%s unsupported resolution: %dx%d\n",
__func__, fmt->width, fmt->height);
return -EINVAL;
}
/* If the caller wants to get updated fmt values based on the search */
if (update_fmt) {
if (fmt->code == V4L2_MBUS_FMT_JPEG_1X8) {
fmt->width = dev->mipi_params.jpeg_width;
fmt->height = dev->mipi_params.jpeg_height;
} else if (fmt->code == V4L2_MBUS_FMT_CUSTOM_M10MO_RAW) {
fmt->width = dev->mipi_params.raw_width;
fmt->height = dev->mipi_params.raw_height;
} else {
fmt->width = res[idx].width;
fmt->height = res[idx].height;
}
}
return idx;
}
int __m10mo_set_mbus_fmt_fw_type2(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *fmt)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct atomisp_input_stream_info *stream_info =
(struct atomisp_input_stream_info *)fmt->reserved;
struct camera_mipi_info *mipi_info = v4l2_get_subdev_hostdata(sd);
int mode = M10MO_GET_RESOLUTION_MODE(dev->fw_type);
int index;
mutex_lock(&dev->input_lock);
index = dev->fw_ops->try_mbus_fmt(sd, fmt, false);
if (index < 0) {
mutex_unlock(&dev->input_lock);
return -EINVAL;
}
dev->format.code = fmt->code;
dev->fmt_idx = index;
if (stream_info->stream == ATOMISP_INPUT_STREAM_CAPTURE) {
/* Save the index for selecting the capture resolution */
dev->capture_res_idx = dev->fmt_idx;
}
/* For FW_TYPE_2, preview/video images are output from VC0
* and capture images are output from VC1.
*/
if (stream_info->stream == ATOMISP_INPUT_STREAM_CAPTURE)
stream_info->ch_id = 1;
else
stream_info->ch_id = 0;
mipi_info->metadata_format = M10MO_METADATA_FORMAT;
mipi_info->metadata_width = M10MO_METADATA_WIDTH;
mipi_info->metadata_height = M10MO_METADATA_HEIGHT;
mipi_info->metadata_effective_width = m10mo_md_effective_size;
dev_dbg(&client->dev,
"%s index prev/cap: %d/%d width: %d, height: %d, code; 0x%x\n",
__func__, dev->fmt_idx, dev->capture_res_idx, fmt->width,
fmt->height, dev->format.code);
/* Make the fixed width and height for JPEG and RAW formats */
if (dev->format.code == V4L2_MBUS_FMT_JPEG_1X8) {
/* The m10mo can only run JPEG in 30fps or lower */
dev->fps = M10MO_NORMAL_FPS;
fmt->width = dev->mipi_params.jpeg_width;
fmt->height = dev->mipi_params.jpeg_height;
} else if (dev->format.code == V4L2_MBUS_FMT_CUSTOM_M10MO_RAW) {
fmt->width = dev->mipi_params.raw_width;
fmt->height = dev->mipi_params.raw_height;
}
/* Update the stream info. Atomisp uses this for configuring mipi */
__m10mo_update_stream_info(sd, fmt);
/*
* Handle raw capture mode separately. Update the capture mode to RAW
* capture now. So that the next streamon call will start RAW capture.
*/
if (mode == M10MO_RESOLUTION_MODE_1 &&
dev->format.code == V4L2_MBUS_FMT_CUSTOM_M10MO_RAW) {
dev_dbg(&client->dev, "%s RAW capture mode\n", __func__);
dev->capture_mode = M10MO_CAPTURE_MODE_ZSL_RAW;
dev->capture_res_idx = dev->fmt_idx;
dev->fmt_idx = 0;
}
mutex_unlock(&dev->input_lock);
return 0;
}
int m10mo_test_pattern_fw_type2(struct v4l2_subdev *sd, u8 val)
{
struct m10mo_device *dev = to_m10mo_sensor(sd);
return m10mo_writeb(&dev->sd, CATEGORY_TEST,
TEST_PATTERN_SENSOR, val ? 2 : 0);
}
const struct m10mo_fw_ops fw_type2_ops = {
.set_run_mode = m10mo_set_run_mode_fw_type2,
.set_burst_mode = m10mo_set_burst_mode_fw_type2,
.stream_off = m10mo_streamoff_fw_type2,
.single_capture_process = m10mo_single_capture_process_fw_type2,
.try_mbus_fmt = __m10mo_try_mbus_fmt_fw_type2,
.set_mbus_fmt = __m10mo_set_mbus_fmt_fw_type2,
.test_pattern = m10mo_test_pattern_fw_type2,
};
| gpl-2.0 |
lonelydra/furnace_kernel_htc_m8 | drivers/net/wireless/wl12xx/main.c | 34 | 125514 |
/*
* This file is part of wl1271
*
* Copyright (C) 2008-2010 Nokia Corporation
*
* Contact: Luciano Coelho <luciano.coelho@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/module.h>
#include <linux/firmware.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/crc32.h>
#include <linux/etherdevice.h>
#include <linux/vmalloc.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/wl12xx.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include "wl12xx.h"
#include "debug.h"
#include "wl12xx_80211.h"
#include "reg.h"
#include "io.h"
#include "event.h"
#include "tx.h"
#include "rx.h"
#include "ps.h"
#include "init.h"
#include "debugfs.h"
#include "cmd.h"
#include "boot.h"
#include "testmode.h"
#include "scan.h"
#define WL1271_BOOT_RETRIES 3
static struct conf_drv_settings default_conf = {
.sg = {
.params = {
[CONF_SG_ACL_BT_MASTER_MIN_BR] = 10,
[CONF_SG_ACL_BT_MASTER_MAX_BR] = 180,
[CONF_SG_ACL_BT_SLAVE_MIN_BR] = 10,
[CONF_SG_ACL_BT_SLAVE_MAX_BR] = 180,
[CONF_SG_ACL_BT_MASTER_MIN_EDR] = 10,
[CONF_SG_ACL_BT_MASTER_MAX_EDR] = 80,
[CONF_SG_ACL_BT_SLAVE_MIN_EDR] = 10,
[CONF_SG_ACL_BT_SLAVE_MAX_EDR] = 80,
[CONF_SG_ACL_WLAN_PS_MASTER_BR] = 8,
[CONF_SG_ACL_WLAN_PS_SLAVE_BR] = 8,
[CONF_SG_ACL_WLAN_PS_MASTER_EDR] = 20,
[CONF_SG_ACL_WLAN_PS_SLAVE_EDR] = 20,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_BR] = 20,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_BR] = 35,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_BR] = 16,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_BR] = 35,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_EDR] = 32,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_EDR] = 50,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_EDR] = 28,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_EDR] = 50,
[CONF_SG_ACL_ACTIVE_SCAN_WLAN_BR] = 10,
[CONF_SG_ACL_ACTIVE_SCAN_WLAN_EDR] = 20,
[CONF_SG_ACL_PASSIVE_SCAN_BT_BR] = 75,
[CONF_SG_ACL_PASSIVE_SCAN_WLAN_BR] = 15,
[CONF_SG_ACL_PASSIVE_SCAN_BT_EDR] = 27,
[CONF_SG_ACL_PASSIVE_SCAN_WLAN_EDR] = 17,
[CONF_SG_AUTO_SCAN_PROBE_REQ] = 170,
[CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_HV3] = 50,
[CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_A2DP] = 100,
[CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_BR] = 800,
[CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_EDR] = 200,
[CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_HV3] = 200,
[CONF_SG_CONSECUTIVE_HV3_IN_PASSIVE_SCAN] = 0,
[CONF_SG_BCN_HV3_COLLISION_THRESH_IN_PASSIVE_SCAN] = 0,
[CONF_SG_TX_RX_PROTECTION_BWIDTH_IN_PASSIVE_SCAN] = 0,
[CONF_SG_STA_FORCE_PS_IN_BT_SCO] = 1,
[CONF_SG_ANTENNA_CONFIGURATION] = 0,
[CONF_SG_BEACON_MISS_PERCENT] = 60,
[CONF_SG_DHCP_TIME] = 5000,
[CONF_SG_RXT] = 1200,
[CONF_SG_TXT] = 1000,
[CONF_SG_ADAPTIVE_RXT_TXT] = 1,
[CONF_SG_GENERAL_USAGE_BIT_MAP] = 3,
[CONF_SG_HV3_MAX_SERVED] = 6,
[CONF_SG_PS_POLL_TIMEOUT] = 10,
[CONF_SG_UPSD_TIMEOUT] = 10,
[CONF_SG_CONSECUTIVE_CTS_THRESHOLD] = 2,
[CONF_SG_STA_RX_WINDOW_AFTER_DTIM] = 5,
[CONF_SG_STA_CONNECTION_PROTECTION_TIME] = 30,
[CONF_AP_BEACON_MISS_TX] = 3,
[CONF_AP_RX_WINDOW_AFTER_BEACON] = 10,
[CONF_AP_BEACON_WINDOW_INTERVAL] = 2,
[CONF_AP_CONNECTION_PROTECTION_TIME] = 0,
[CONF_AP_BT_ACL_VAL_BT_SERVE_TIME] = 25,
[CONF_AP_BT_ACL_VAL_WL_SERVE_TIME] = 25,
[CONF_SG_CTS_DILUTED_BAD_RX_PACKETS_TH] = 0,
[CONF_SG_CTS_CHOP_IN_DUAL_ANT_SCO_MASTER] = 0,
},
.state = CONF_SG_PROTECTIVE,
},
.rx = {
.rx_msdu_life_time = 512000,
.packet_detection_threshold = 0,
.ps_poll_timeout = 15,
.upsd_timeout = 15,
.rts_threshold = IEEE80211_MAX_RTS_THRESHOLD,
.rx_cca_threshold = 0,
.irq_blk_threshold = 0xFFFF,
.irq_pkt_threshold = 0,
.irq_timeout = 600,
.queue_type = CONF_RX_QUEUE_TYPE_LOW_PRIORITY,
},
.tx = {
.tx_energy_detection = 0,
.sta_rc_conf = {
.enabled_rates = 0,
.short_retry_limit = 10,
.long_retry_limit = 10,
.aflags = 0,
},
.ac_conf_count = 4,
.ac_conf = {
[CONF_TX_AC_BE] = {
.ac = CONF_TX_AC_BE,
.cw_min = 15,
.cw_max = 63,
.aifsn = 3,
.tx_op_limit = 0,
},
[CONF_TX_AC_BK] = {
.ac = CONF_TX_AC_BK,
.cw_min = 15,
.cw_max = 63,
.aifsn = 7,
.tx_op_limit = 0,
},
[CONF_TX_AC_VI] = {
.ac = CONF_TX_AC_VI,
.cw_min = 15,
.cw_max = 63,
.aifsn = CONF_TX_AIFS_PIFS,
.tx_op_limit = 3008,
},
[CONF_TX_AC_VO] = {
.ac = CONF_TX_AC_VO,
.cw_min = 15,
.cw_max = 63,
.aifsn = CONF_TX_AIFS_PIFS,
.tx_op_limit = 1504,
},
},
.max_tx_retries = 100,
.ap_aging_period = 300,
.tid_conf_count = 4,
.tid_conf = {
[CONF_TX_AC_BE] = {
.queue_id = CONF_TX_AC_BE,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_BE,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_BK] = {
.queue_id = CONF_TX_AC_BK,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_BK,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_VI] = {
.queue_id = CONF_TX_AC_VI,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_VI,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_VO] = {
.queue_id = CONF_TX_AC_VO,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_VO,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
},
.frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD,
.tx_compl_timeout = 700,
.tx_compl_threshold = 4,
.basic_rate = CONF_HW_BIT_RATE_1MBPS,
.basic_rate_5 = CONF_HW_BIT_RATE_6MBPS,
.tmpl_short_retry_limit = 10,
.tmpl_long_retry_limit = 10,
.tx_watchdog_timeout = 5000,
},
.conn = {
.wake_up_event = CONF_WAKE_UP_EVENT_DTIM,
.listen_interval = 1,
.suspend_wake_up_event = CONF_WAKE_UP_EVENT_N_DTIM,
.suspend_listen_interval = 3,
.bcn_filt_mode = CONF_BCN_FILT_MODE_ENABLED,
.bcn_filt_ie_count = 2,
.bcn_filt_ie = {
[0] = {
.ie = WLAN_EID_CHANNEL_SWITCH,
.rule = CONF_BCN_RULE_PASS_ON_APPEARANCE,
},
[1] = {
.ie = WLAN_EID_HT_INFORMATION,
.rule = CONF_BCN_RULE_PASS_ON_CHANGE,
},
},
.synch_fail_thold = 10,
.bss_lose_timeout = 100,
.beacon_rx_timeout = 10000,
.broadcast_timeout = 20000,
.rx_broadcast_in_ps = 1,
.ps_poll_threshold = 10,
.bet_enable = CONF_BET_MODE_ENABLE,
.bet_max_consecutive = 50,
.psm_entry_retries = 8,
.psm_exit_retries = 16,
.psm_entry_nullfunc_retries = 3,
.dynamic_ps_timeout = 200,
.forced_ps = false,
.keep_alive_interval = 55000,
.max_listen_interval = 20,
},
.itrim = {
.enable = false,
.timeout = 50000,
},
.pm_config = {
.host_clk_settling_time = 5000,
.host_fast_wakeup_support = false
},
.roam_trigger = {
.trigger_pacing = 1,
.avg_weight_rssi_beacon = 20,
.avg_weight_rssi_data = 10,
.avg_weight_snr_beacon = 20,
.avg_weight_snr_data = 10,
},
.scan = {
.min_dwell_time_active = 7500,
.max_dwell_time_active = 30000,
.min_dwell_time_passive = 100000,
.max_dwell_time_passive = 100000,
.num_probe_reqs = 2,
.split_scan_timeout = 50000,
},
.sched_scan = {
.min_dwell_time_active = 30,
.max_dwell_time_active = 60,
.dwell_time_passive = 100,
.dwell_time_dfs = 150,
.num_probe_reqs = 2,
.rssi_threshold = -90,
.snr_threshold = 0,
},
.rf = {
.tx_per_channel_power_compensation_2 = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
.tx_per_channel_power_compensation_5 = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
},
.ht = {
.rx_ba_win_size = 8,
.tx_ba_win_size = 64,
.inactivity_timeout = 10000,
.tx_ba_tid_bitmap = CONF_TX_BA_ENABLED_TID_BITMAP,
},
.mem_wl127x = {
.num_stations = 1,
.ssid_profiles = 1,
.rx_block_num = 70,
.tx_min_block_num = 40,
.dynamic_memory = 1,
.min_req_tx_blocks = 100,
.min_req_rx_blocks = 22,
.tx_min = 27,
},
.mem_wl128x = {
.num_stations = 1,
.ssid_profiles = 1,
.rx_block_num = 40,
.tx_min_block_num = 40,
.dynamic_memory = 1,
.min_req_tx_blocks = 45,
.min_req_rx_blocks = 22,
.tx_min = 27,
},
.fm_coex = {
.enable = true,
.swallow_period = 5,
.n_divider_fref_set_1 = 0xff,
.n_divider_fref_set_2 = 12,
.m_divider_fref_set_1 = 148,
.m_divider_fref_set_2 = 0xffff,
.coex_pll_stabilization_time = 0xffffffff,
.ldo_stabilization_time = 0xffff,
.fm_disturbed_band_margin = 0xff,
.swallow_clk_diff = 0xff,
},
.rx_streaming = {
.duration = 150,
.queues = 0x1,
.interval = 20,
.always = 0,
},
.fwlog = {
.mode = WL12XX_FWLOG_ON_DEMAND,
.mem_blocks = 2,
.severity = 0,
.timestamp = WL12XX_FWLOG_TIMESTAMP_DISABLED,
.output = WL12XX_FWLOG_OUTPUT_HOST,
.threshold = 0,
},
.hci_io_ds = HCI_IO_DS_6MA,
.rate = {
.rate_retry_score = 32000,
.per_add = 8192,
.per_th1 = 2048,
.per_th2 = 4096,
.max_per = 8100,
.inverse_curiosity_factor = 5,
.tx_fail_low_th = 4,
.tx_fail_high_th = 10,
.per_alpha_shift = 4,
.per_add_shift = 13,
.per_beta1_shift = 10,
.per_beta2_shift = 8,
.rate_check_up = 2,
.rate_check_down = 12,
.rate_retry_policy = {
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00,
},
},
.hangover = {
.recover_time = 0,
.hangover_period = 20,
.dynamic_mode = 1,
.early_termination_mode = 1,
.max_period = 20,
.min_period = 1,
.increase_delta = 1,
.decrease_delta = 2,
.quiet_time = 4,
.increase_time = 1,
.window_size = 16,
},
};
static char *fwlog_param;
static bool bug_on_recovery;
static void __wl1271_op_remove_interface(struct wl1271 *wl,
struct ieee80211_vif *vif,
bool reset_tx_queues);
static void wl1271_op_stop(struct ieee80211_hw *hw);
static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif);
static int wl12xx_set_authorized(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret;
if (WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS))
return -EINVAL;
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
return 0;
if (test_and_set_bit(WLVIF_FLAG_STA_STATE_SENT, &wlvif->flags))
return 0;
ret = wl12xx_cmd_set_peer_state(wl, wlvif->sta.hlid);
if (ret < 0)
return ret;
wl12xx_croc(wl, wlvif->role_id);
wl1271_info("Association completed.");
return 0;
}
static int wl1271_reg_notify(struct wiphy *wiphy,
struct regulatory_request *request)
{
struct ieee80211_supported_band *band;
struct ieee80211_channel *ch;
int i;
band = wiphy->bands[IEEE80211_BAND_5GHZ];
for (i = 0; i < band->n_channels; i++) {
ch = &band->channels[i];
if (ch->flags & IEEE80211_CHAN_DISABLED)
continue;
if (ch->flags & IEEE80211_CHAN_RADAR)
ch->flags |= IEEE80211_CHAN_NO_IBSS |
IEEE80211_CHAN_PASSIVE_SCAN;
}
return 0;
}
static int wl1271_set_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool enable)
{
int ret = 0;
ret = wl1271_acx_ps_rx_streaming(wl, wlvif, enable);
if (ret < 0)
goto out;
if (enable)
set_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags);
else
clear_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags);
out:
return ret;
}
int wl1271_recalc_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int ret = 0;
int period = wl->conf.rx_streaming.interval;
if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags))
goto out;
if (period &&
test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) &&
(wl->conf.rx_streaming.always ||
test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags)))
ret = wl1271_set_rx_streaming(wl, wlvif, true);
else {
ret = wl1271_set_rx_streaming(wl, wlvif, false);
del_timer_sync(&wlvif->rx_streaming_timer);
}
out:
return ret;
}
static void wl1271_rx_streaming_enable_work(struct work_struct *work)
{
int ret;
struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif,
rx_streaming_enable_work);
struct wl1271 *wl = wlvif->wl;
mutex_lock(&wl->mutex);
if (test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags) ||
!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) ||
(!wl->conf.rx_streaming.always &&
!test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags)))
goto out;
if (!wl->conf.rx_streaming.interval)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_set_rx_streaming(wl, wlvif, true);
if (ret < 0)
goto out_sleep;
mod_timer(&wlvif->rx_streaming_timer,
jiffies + msecs_to_jiffies(wl->conf.rx_streaming.duration));
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1271_rx_streaming_disable_work(struct work_struct *work)
{
int ret;
struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif,
rx_streaming_disable_work);
struct wl1271 *wl = wlvif->wl;
mutex_lock(&wl->mutex);
if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_set_rx_streaming(wl, wlvif, false);
if (ret)
goto out_sleep;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1271_rx_streaming_timer(unsigned long data)
{
struct wl12xx_vif *wlvif = (struct wl12xx_vif *)data;
struct wl1271 *wl = wlvif->wl;
ieee80211_queue_work(wl->hw, &wlvif->rx_streaming_disable_work);
}
void wl12xx_rearm_tx_watchdog_locked(struct wl1271 *wl)
{
if (wl->tx_allocated_blocks == 0)
return;
cancel_delayed_work(&wl->tx_watchdog_work);
ieee80211_queue_delayed_work(wl->hw, &wl->tx_watchdog_work,
msecs_to_jiffies(wl->conf.tx.tx_watchdog_timeout));
}
static void wl12xx_tx_watchdog_work(struct work_struct *work)
{
struct delayed_work *dwork;
struct wl1271 *wl;
dwork = container_of(work, struct delayed_work, work);
wl = container_of(dwork, struct wl1271, tx_watchdog_work);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
if (unlikely(wl->tx_allocated_blocks == 0))
goto out;
if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to ROC",
wl->conf.tx.tx_watchdog_timeout);
wl12xx_rearm_tx_watchdog_locked(wl);
goto out;
}
if (wl->scan.state != WL1271_SCAN_STATE_IDLE) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to scan",
wl->conf.tx.tx_watchdog_timeout);
wl12xx_rearm_tx_watchdog_locked(wl);
goto out;
}
if (wl->active_sta_count) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms. AP has "
" %d stations",
wl->conf.tx.tx_watchdog_timeout,
wl->active_sta_count);
wl12xx_rearm_tx_watchdog_locked(wl);
goto out;
}
wl1271_error("Tx stuck (in FW) for %d ms. Starting recovery",
wl->conf.tx.tx_watchdog_timeout);
wl12xx_queue_recovery_work(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1271_conf_init(struct wl1271 *wl)
{
memcpy(&wl->conf, &default_conf, sizeof(default_conf));
if (fwlog_param) {
if (!strcmp(fwlog_param, "continuous")) {
wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS;
} else if (!strcmp(fwlog_param, "ondemand")) {
wl->conf.fwlog.mode = WL12XX_FWLOG_ON_DEMAND;
} else if (!strcmp(fwlog_param, "dbgpins")) {
wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS;
wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_DBG_PINS;
} else if (!strcmp(fwlog_param, "disable")) {
wl->conf.fwlog.mem_blocks = 0;
wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_NONE;
} else {
wl1271_error("Unknown fwlog parameter %s", fwlog_param);
}
}
}
static int wl1271_plt_init(struct wl1271 *wl)
{
int ret;
if (wl->chip.id == CHIP_ID_1283_PG20)
ret = wl128x_cmd_general_parms(wl);
else
ret = wl1271_cmd_general_parms(wl);
if (ret < 0)
return ret;
if (wl->chip.id == CHIP_ID_1283_PG20)
ret = wl128x_cmd_radio_parms(wl);
else
ret = wl1271_cmd_radio_parms(wl);
if (ret < 0)
return ret;
if (wl->chip.id != CHIP_ID_1283_PG20) {
ret = wl1271_cmd_ext_radio_parms(wl);
if (ret < 0)
return ret;
}
ret = wl1271_chip_specific_init(wl);
if (ret < 0)
return ret;
ret = wl1271_acx_init_mem_config(wl);
if (ret < 0)
return ret;
ret = wl12xx_acx_mem_cfg(wl);
if (ret < 0)
goto out_free_memmap;
ret = wl1271_cmd_data_path(wl, 1);
if (ret < 0)
goto out_free_memmap;
ret = wl1271_acx_sleep_auth(wl, WL1271_PSM_CAM);
if (ret < 0)
goto out_free_memmap;
ret = wl1271_acx_pm_config(wl);
if (ret < 0)
goto out_free_memmap;
return 0;
out_free_memmap:
kfree(wl->target_mem_map);
wl->target_mem_map = NULL;
return ret;
}
static void wl12xx_irq_ps_regulate_link(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
u8 hlid, u8 tx_pkts)
{
bool fw_ps, single_sta;
fw_ps = test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map);
single_sta = (wl->active_sta_count == 1);
if (!fw_ps || tx_pkts < WL1271_PS_STA_MAX_PACKETS)
wl12xx_ps_link_end(wl, wlvif, hlid);
else if (!single_sta && fw_ps && tx_pkts >= WL1271_PS_STA_MAX_PACKETS)
wl12xx_ps_link_start(wl, wlvif, hlid, true);
}
static void wl12xx_irq_update_links_status(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct wl12xx_fw_status *status)
{
struct wl1271_link *lnk;
u32 cur_fw_ps_map;
u8 hlid, cnt;
cur_fw_ps_map = le32_to_cpu(status->link_ps_bitmap);
if (wl->ap_fw_ps_map != cur_fw_ps_map) {
wl1271_debug(DEBUG_PSM,
"link ps prev 0x%x cur 0x%x changed 0x%x",
wl->ap_fw_ps_map, cur_fw_ps_map,
wl->ap_fw_ps_map ^ cur_fw_ps_map);
wl->ap_fw_ps_map = cur_fw_ps_map;
}
for_each_set_bit(hlid, wlvif->ap.sta_hlid_map, WL12XX_MAX_LINKS) {
lnk = &wl->links[hlid];
cnt = status->tx_lnk_free_pkts[hlid] - lnk->prev_freed_pkts;
lnk->prev_freed_pkts = status->tx_lnk_free_pkts[hlid];
lnk->allocated_pkts -= cnt;
wl12xx_irq_ps_regulate_link(wl, wlvif, hlid,
lnk->allocated_pkts);
}
}
static void wl12xx_fw_status(struct wl1271 *wl,
struct wl12xx_fw_status *status)
{
struct wl12xx_vif *wlvif;
struct timespec ts;
u32 old_tx_blk_count = wl->tx_blocks_available;
int avail, freed_blocks;
int i;
wl1271_raw_read(wl, FW_STATUS_ADDR, status, sizeof(*status), false);
wl1271_debug(DEBUG_IRQ, "intr: 0x%x (fw_rx_counter = %d, "
"drv_rx_counter = %d, tx_results_counter = %d)",
status->intr,
status->fw_rx_counter,
status->drv_rx_counter,
status->tx_results_counter);
for (i = 0; i < NUM_TX_QUEUES; i++) {
wl->tx_allocated_pkts[i] -=
(status->tx_released_pkts[i] -
wl->tx_pkts_freed[i]) & 0xff;
wl->tx_pkts_freed[i] = status->tx_released_pkts[i];
}
if (likely(wl->tx_blocks_freed <=
le32_to_cpu(status->total_released_blks)))
freed_blocks = le32_to_cpu(status->total_released_blks) -
wl->tx_blocks_freed;
else
freed_blocks = 0x100000000LL - wl->tx_blocks_freed +
le32_to_cpu(status->total_released_blks);
wl->tx_blocks_freed = le32_to_cpu(status->total_released_blks);
wl->tx_allocated_blocks -= freed_blocks;
if (freed_blocks) {
if (wl->tx_allocated_blocks)
wl12xx_rearm_tx_watchdog_locked(wl);
else
cancel_delayed_work(&wl->tx_watchdog_work);
}
avail = le32_to_cpu(status->tx_total) - wl->tx_allocated_blocks;
wl->tx_blocks_available = max((int)wl->tx_blocks_available,
avail);
if (wl->tx_blocks_available > old_tx_blk_count)
clear_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags);
wl12xx_for_each_wlvif_ap(wl, wlvif) {
wl12xx_irq_update_links_status(wl, wlvif, status);
}
getnstimeofday(&ts);
wl->time_offset = (timespec_to_ns(&ts) >> 10) -
(s64)le32_to_cpu(status->fw_localtime);
}
static void wl1271_flush_deferred_work(struct wl1271 *wl)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(&wl->deferred_rx_queue)))
ieee80211_rx_ni(wl->hw, skb);
while ((skb = skb_dequeue(&wl->deferred_tx_queue)))
ieee80211_tx_status_ni(wl->hw, skb);
}
static void wl1271_netstack_work(struct work_struct *work)
{
struct wl1271 *wl =
container_of(work, struct wl1271, netstack_work);
do {
wl1271_flush_deferred_work(wl);
} while (skb_queue_len(&wl->deferred_rx_queue));
}
#define WL1271_IRQ_MAX_LOOPS 256
static irqreturn_t wl1271_irq(int irq, void *cookie)
{
int ret;
u32 intr;
int loopcount = WL1271_IRQ_MAX_LOOPS;
struct wl1271 *wl = (struct wl1271 *)cookie;
bool done = false;
unsigned int defer_count;
unsigned long flags;
set_bit(WL1271_FLAG_TX_PENDING, &wl->flags);
cancel_work_sync(&wl->tx_work);
if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ)
loopcount = 1;
mutex_lock(&wl->mutex);
wl1271_debug(DEBUG_IRQ, "IRQ work");
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
while (!done && loopcount--) {
clear_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags);
smp_mb__after_clear_bit();
wl12xx_fw_status(wl, wl->fw_status);
intr = le32_to_cpu(wl->fw_status->intr);
intr &= WL1271_INTR_MASK;
if (!intr) {
done = true;
continue;
}
if (unlikely(intr & WL1271_ACX_INTR_WATCHDOG)) {
wl1271_error("watchdog interrupt received! "
"starting recovery.");
wl12xx_queue_recovery_work(wl);
goto out;
}
if (likely(intr & WL1271_ACX_INTR_DATA)) {
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_DATA");
wl12xx_rx(wl, wl->fw_status);
spin_lock_irqsave(&wl->wl_lock, flags);
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) &&
wl1271_tx_total_queue_count(wl) > 0) {
spin_unlock_irqrestore(&wl->wl_lock, flags);
wl1271_tx_work_locked(wl);
} else {
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
if (wl->fw_status->tx_results_counter !=
(wl->tx_results_count & 0xff))
wl1271_tx_complete(wl);
defer_count = skb_queue_len(&wl->deferred_tx_queue) +
skb_queue_len(&wl->deferred_rx_queue);
if (defer_count > WL1271_DEFERRED_QUEUE_LIMIT)
wl1271_flush_deferred_work(wl);
}
if (intr & WL1271_ACX_INTR_EVENT_A) {
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_A");
wl1271_event_handle(wl, 0);
}
if (intr & WL1271_ACX_INTR_EVENT_B) {
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_B");
wl1271_event_handle(wl, 1);
}
if (intr & WL1271_ACX_INTR_INIT_COMPLETE)
wl1271_debug(DEBUG_IRQ,
"WL1271_ACX_INTR_INIT_COMPLETE");
if (intr & WL1271_ACX_INTR_HW_AVAILABLE)
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_HW_AVAILABLE");
}
wl1271_ps_elp_sleep(wl);
out:
spin_lock_irqsave(&wl->wl_lock, flags);
clear_bit(WL1271_FLAG_TX_PENDING, &wl->flags);
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) &&
wl1271_tx_total_queue_count(wl) > 0)
ieee80211_queue_work(wl->hw, &wl->tx_work);
spin_unlock_irqrestore(&wl->wl_lock, flags);
mutex_unlock(&wl->mutex);
return IRQ_HANDLED;
}
struct vif_counter_data {
u8 counter;
struct ieee80211_vif *cur_vif;
bool cur_vif_running;
};
static void wl12xx_vif_count_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct vif_counter_data *counter = data;
counter->counter++;
if (counter->cur_vif == vif)
counter->cur_vif_running = true;
}
static void wl12xx_get_vif_count(struct ieee80211_hw *hw,
struct ieee80211_vif *cur_vif,
struct vif_counter_data *data)
{
memset(data, 0, sizeof(*data));
data->cur_vif = cur_vif;
ieee80211_iterate_active_interfaces(hw,
wl12xx_vif_count_iter, data);
}
static int wl12xx_fetch_firmware(struct wl1271 *wl, bool plt)
{
const struct firmware *fw;
const char *fw_name;
enum wl12xx_fw_type fw_type;
int ret;
if (plt) {
fw_type = WL12XX_FW_TYPE_PLT;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = WL128X_PLT_FW_NAME;
else
fw_name = WL127X_PLT_FW_NAME;
} else {
if (wl->last_vif_count > 1) {
fw_type = WL12XX_FW_TYPE_MULTI;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = WL128X_FW_NAME_MULTI;
else
fw_name = WL127X_FW_NAME_MULTI;
} else {
fw_type = WL12XX_FW_TYPE_NORMAL;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = WL128X_FW_NAME_SINGLE;
else
fw_name = WL127X_FW_NAME_SINGLE;
}
}
if (wl->fw_type == fw_type)
return 0;
wl1271_debug(DEBUG_BOOT, "booting firmware %s", fw_name);
ret = request_firmware(&fw, fw_name, wl->dev);
if (ret < 0) {
wl1271_error("could not get firmware %s: %d", fw_name, ret);
return ret;
}
if (fw->size % 4) {
wl1271_error("firmware size is not multiple of 32 bits: %zu",
fw->size);
ret = -EILSEQ;
goto out;
}
vfree(wl->fw);
wl->fw_type = WL12XX_FW_TYPE_NONE;
wl->fw_len = fw->size;
wl->fw = vmalloc(wl->fw_len);
if (!wl->fw) {
wl1271_error("could not allocate memory for the firmware");
ret = -ENOMEM;
goto out;
}
memcpy(wl->fw, fw->data, wl->fw_len);
ret = 0;
wl->fw_type = fw_type;
out:
release_firmware(fw);
return ret;
}
static int wl1271_fetch_nvs(struct wl1271 *wl)
{
const struct firmware *fw;
int ret;
ret = request_firmware(&fw, WL12XX_NVS_NAME, wl->dev);
if (ret < 0) {
wl1271_error("could not get nvs file %s: %d", WL12XX_NVS_NAME,
ret);
return ret;
}
wl->nvs = kmemdup(fw->data, fw->size, GFP_KERNEL);
if (!wl->nvs) {
wl1271_error("could not allocate memory for the nvs file");
ret = -ENOMEM;
goto out;
}
wl->nvs_len = fw->size;
out:
release_firmware(fw);
return ret;
}
void wl12xx_queue_recovery_work(struct wl1271 *wl)
{
if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags))
ieee80211_queue_work(wl->hw, &wl->recovery_work);
}
size_t wl12xx_copy_fwlog(struct wl1271 *wl, u8 *memblock, size_t maxlen)
{
size_t len = 0;
while (len < maxlen) {
if (memblock[len] == 0)
break;
if (len + memblock[len] + 1 > maxlen)
break;
len += memblock[len] + 1;
}
len = min(len, (size_t)(PAGE_SIZE - wl->fwlog_size));
memcpy(wl->fwlog + wl->fwlog_size, memblock, len);
wl->fwlog_size += len;
return len;
}
static void wl12xx_read_fwlog_panic(struct wl1271 *wl)
{
u32 addr;
u32 first_addr;
u8 *block;
if ((wl->quirks & WL12XX_QUIRK_FWLOG_NOT_IMPLEMENTED) ||
(wl->conf.fwlog.mode != WL12XX_FWLOG_ON_DEMAND) ||
(wl->conf.fwlog.mem_blocks == 0))
return;
wl1271_info("Reading FW panic log");
block = kmalloc(WL12XX_HW_BLOCK_SIZE, GFP_KERNEL);
if (!block)
return;
if (!wl1271_ps_elp_wakeup(wl))
wl12xx_cmd_stop_fwlog(wl);
wl12xx_fw_status(wl, wl->fw_status);
first_addr = le32_to_cpu(wl->fw_status->log_start_addr);
if (!first_addr)
goto out;
addr = first_addr;
do {
memset(block, 0, WL12XX_HW_BLOCK_SIZE);
wl1271_read_hwaddr(wl, addr, block, WL12XX_HW_BLOCK_SIZE,
false);
addr = le32_to_cpup((__le32 *)block);
if (!wl12xx_copy_fwlog(wl, block + sizeof(addr),
WL12XX_HW_BLOCK_SIZE - sizeof(addr)))
break;
} while (addr && (addr != first_addr));
wake_up_interruptible(&wl->fwlog_waitq);
out:
kfree(block);
}
static void wl1271_recovery_work(struct work_struct *work)
{
struct wl1271 *wl =
container_of(work, struct wl1271, recovery_work);
struct wl12xx_vif *wlvif;
struct ieee80211_vif *vif;
mutex_lock(&wl->mutex);
if (wl->state != WL1271_STATE_ON || wl->plt)
goto out_unlock;
set_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags);
wl12xx_read_fwlog_panic(wl);
wl1271_info("Hardware recovery in progress. FW ver: %s pc: 0x%x",
wl->chip.fw_ver_str, wl1271_read32(wl, SCR_PAD4));
BUG_ON(bug_on_recovery &&
!test_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags));
wl12xx_for_each_wlvif(wl, wlvif) {
if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) ||
test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags))
wlvif->tx_security_seq +=
WL1271_TX_SQN_POST_RECOVERY_PADDING;
}
ieee80211_stop_queues(wl->hw);
if (wl->sched_scanning) {
ieee80211_sched_scan_stopped(wl->hw);
wl->sched_scanning = false;
}
while (!list_empty(&wl->wlvif_list)) {
wlvif = list_first_entry(&wl->wlvif_list,
struct wl12xx_vif, list);
vif = wl12xx_wlvif_to_vif(wlvif);
__wl1271_op_remove_interface(wl, vif, false);
}
mutex_unlock(&wl->mutex);
wl1271_op_stop(wl->hw);
clear_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags);
ieee80211_restart_hw(wl->hw);
ieee80211_wake_queues(wl->hw);
return;
out_unlock:
mutex_unlock(&wl->mutex);
}
static void wl1271_fw_wakeup(struct wl1271 *wl)
{
u32 elp_reg;
elp_reg = ELPCTRL_WAKE_UP;
wl1271_raw_write32(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, elp_reg);
}
static int wl1271_setup(struct wl1271 *wl)
{
wl->fw_status = kmalloc(sizeof(*wl->fw_status), GFP_KERNEL);
if (!wl->fw_status)
return -ENOMEM;
wl->tx_res_if = kmalloc(sizeof(*wl->tx_res_if), GFP_KERNEL);
if (!wl->tx_res_if) {
kfree(wl->fw_status);
return -ENOMEM;
}
return 0;
}
static int wl12xx_set_power_on(struct wl1271 *wl)
{
int ret;
msleep(WL1271_PRE_POWER_ON_SLEEP);
ret = wl1271_power_on(wl);
if (ret < 0)
goto out;
msleep(WL1271_POWER_ON_SLEEP);
wl1271_io_reset(wl);
wl1271_io_init(wl);
wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]);
wl1271_fw_wakeup(wl);
out:
return ret;
}
static int wl12xx_chip_wakeup(struct wl1271 *wl, bool plt)
{
int ret = 0;
ret = wl12xx_set_power_on(wl);
if (ret < 0)
goto out;
if (!wl1271_set_block_size(wl))
wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT;
switch (wl->chip.id) {
case CHIP_ID_1271_PG10:
wl1271_warning("chip id 0x%x (1271 PG10) support is obsolete",
wl->chip.id);
ret = wl1271_setup(wl);
if (ret < 0)
goto out;
wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT;
break;
case CHIP_ID_1271_PG20:
wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1271 PG20)",
wl->chip.id);
ret = wl1271_setup(wl);
if (ret < 0)
goto out;
wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT;
break;
case CHIP_ID_1283_PG20:
wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1283 PG20)",
wl->chip.id);
ret = wl1271_setup(wl);
if (ret < 0)
goto out;
break;
case CHIP_ID_1283_PG10:
default:
wl1271_warning("unsupported chip id: 0x%x", wl->chip.id);
ret = -ENODEV;
goto out;
}
ret = wl12xx_fetch_firmware(wl, plt);
if (ret < 0)
goto out;
if (wl->nvs == NULL) {
ret = wl1271_fetch_nvs(wl);
if (ret < 0)
goto out;
}
out:
return ret;
}
int wl1271_plt_start(struct wl1271 *wl)
{
int retries = WL1271_BOOT_RETRIES;
struct wiphy *wiphy = wl->hw->wiphy;
int ret;
mutex_lock(&wl->mutex);
wl1271_notice("power up");
if (wl->state != WL1271_STATE_OFF) {
wl1271_error("cannot go into PLT state because not "
"in off state: %d", wl->state);
ret = -EBUSY;
goto out;
}
while (retries) {
retries--;
ret = wl12xx_chip_wakeup(wl, true);
if (ret < 0)
goto power_off;
ret = wl1271_boot(wl);
if (ret < 0)
goto power_off;
ret = wl1271_plt_init(wl);
if (ret < 0)
goto irq_disable;
wl->plt = true;
wl->state = WL1271_STATE_ON;
wl1271_notice("firmware booted in PLT mode (%s)",
wl->chip.fw_ver_str);
wiphy->hw_version = wl->chip.id;
strncpy(wiphy->fw_version, wl->chip.fw_ver_str,
sizeof(wiphy->fw_version));
goto out;
irq_disable:
mutex_unlock(&wl->mutex);
wl1271_disable_interrupts(wl);
wl1271_flush_deferred_work(wl);
cancel_work_sync(&wl->netstack_work);
mutex_lock(&wl->mutex);
power_off:
wl1271_power_off(wl);
}
wl1271_error("firmware boot in PLT mode failed despite %d retries",
WL1271_BOOT_RETRIES);
out:
mutex_unlock(&wl->mutex);
return ret;
}
int wl1271_plt_stop(struct wl1271 *wl)
{
int ret = 0;
wl1271_notice("power down");
wl1271_disable_interrupts(wl);
mutex_lock(&wl->mutex);
if (!wl->plt) {
mutex_unlock(&wl->mutex);
wl1271_enable_interrupts(wl);
wl1271_error("cannot power down because not in PLT "
"state: %d", wl->state);
ret = -EBUSY;
goto out;
}
mutex_unlock(&wl->mutex);
wl1271_flush_deferred_work(wl);
cancel_work_sync(&wl->netstack_work);
cancel_work_sync(&wl->recovery_work);
cancel_delayed_work_sync(&wl->elp_work);
cancel_delayed_work_sync(&wl->tx_watchdog_work);
mutex_lock(&wl->mutex);
wl1271_power_off(wl);
wl->flags = 0;
wl->state = WL1271_STATE_OFF;
wl->plt = false;
wl->rx_counter = 0;
mutex_unlock(&wl->mutex);
out:
return ret;
}
static void wl1271_op_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct wl1271 *wl = hw->priv;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_vif *vif = info->control.vif;
struct wl12xx_vif *wlvif = NULL;
unsigned long flags;
int q, mapping;
u8 hlid;
if (vif)
wlvif = wl12xx_vif_to_data(vif);
mapping = skb_get_queue_mapping(skb);
q = wl1271_tx_get_queue(mapping);
hlid = wl12xx_tx_get_hlid(wl, wlvif, skb);
spin_lock_irqsave(&wl->wl_lock, flags);
if (hlid == WL12XX_INVALID_LINK_ID ||
(wlvif && !test_bit(hlid, wlvif->links_map))) {
wl1271_debug(DEBUG_TX, "DROP skb hlid %d q %d", hlid, q);
ieee80211_free_txskb(hw, skb);
goto out;
}
wl1271_debug(DEBUG_TX, "queue skb hlid %d q %d len %d",
hlid, q, skb->len);
skb_queue_tail(&wl->links[hlid].tx_queue[q], skb);
wl->tx_queue_count[q]++;
if (wl->tx_queue_count[q] >= WL1271_TX_QUEUE_HIGH_WATERMARK) {
wl1271_debug(DEBUG_TX, "op_tx: stopping queues for q %d", q);
ieee80211_stop_queue(wl->hw, mapping);
set_bit(q, &wl->stopped_queues_map);
}
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) &&
!test_bit(WL1271_FLAG_TX_PENDING, &wl->flags))
ieee80211_queue_work(wl->hw, &wl->tx_work);
out:
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
int wl1271_tx_dummy_packet(struct wl1271 *wl)
{
unsigned long flags;
int q;
if (test_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags))
return 0;
q = wl1271_tx_get_queue(skb_get_queue_mapping(wl->dummy_packet));
spin_lock_irqsave(&wl->wl_lock, flags);
set_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags);
wl->tx_queue_count[q]++;
spin_unlock_irqrestore(&wl->wl_lock, flags);
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags))
wl1271_tx_work_locked(wl);
return 0;
}
#define TOTAL_TX_DUMMY_PACKET_SIZE (ALIGN(1400, 512))
static struct sk_buff *wl12xx_alloc_dummy_packet(struct wl1271 *wl)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr *hdr;
unsigned int dummy_packet_size;
dummy_packet_size = TOTAL_TX_DUMMY_PACKET_SIZE -
sizeof(struct wl1271_tx_hw_descr) - sizeof(*hdr);
skb = dev_alloc_skb(TOTAL_TX_DUMMY_PACKET_SIZE);
if (!skb) {
wl1271_warning("Failed to allocate a dummy packet skb");
return NULL;
}
skb_reserve(skb, sizeof(struct wl1271_tx_hw_descr));
hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr));
memset(hdr, 0, sizeof(*hdr));
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC |
IEEE80211_FCTL_TODS);
memset(skb_put(skb, dummy_packet_size), 0, dummy_packet_size);
skb->priority = WL1271_TID_MGMT;
skb_set_queue_mapping(skb, 0);
memset(IEEE80211_SKB_CB(skb), 0, sizeof(struct ieee80211_tx_info));
return skb;
}
#ifdef CONFIG_PM
static int wl1271_configure_suspend_sta(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
mutex_lock(&wl->mutex);
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
goto out_unlock;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
ret = wl1271_acx_wake_up_conditions(wl, wlvif,
wl->conf.conn.suspend_wake_up_event,
wl->conf.conn.suspend_listen_interval);
if (ret < 0)
wl1271_error("suspend: set wake up conditions failed: %d", ret);
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_configure_suspend_ap(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
mutex_lock(&wl->mutex);
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags))
goto out_unlock;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
ret = wl1271_acx_beacon_filter_opt(wl, wlvif, true);
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_configure_suspend(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
if (wlvif->bss_type == BSS_TYPE_STA_BSS)
return wl1271_configure_suspend_sta(wl, wlvif);
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
return wl1271_configure_suspend_ap(wl, wlvif);
return 0;
}
static void wl1271_configure_resume(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS;
bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS;
if ((!is_ap) && (!is_sta))
return;
mutex_lock(&wl->mutex);
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (is_sta) {
ret = wl1271_acx_wake_up_conditions(wl, wlvif,
wl->conf.conn.wake_up_event,
wl->conf.conn.listen_interval);
if (ret < 0)
wl1271_error("resume: wake up conditions failed: %d",
ret);
} else if (is_ap) {
ret = wl1271_acx_beacon_filter_opt(wl, wlvif, false);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_op_suspend(struct ieee80211_hw *hw,
struct cfg80211_wowlan *wow)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 suspend wow=%d", !!wow);
WARN_ON(!wow || !wow->any);
wl1271_tx_flush(wl);
wl->wow_enabled = true;
wl12xx_for_each_wlvif(wl, wlvif) {
ret = wl1271_configure_suspend(wl, wlvif);
if (ret < 0) {
wl1271_warning("couldn't prepare device to suspend");
return ret;
}
}
wl1271_debug(DEBUG_MAC80211, "flushing remaining works");
wl1271_disable_interrupts(wl);
set_bit(WL1271_FLAG_SUSPENDED, &wl->flags);
wl1271_enable_interrupts(wl);
flush_work(&wl->tx_work);
flush_delayed_work(&wl->elp_work);
return 0;
}
static int wl1271_op_resume(struct ieee80211_hw *hw)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
unsigned long flags;
bool run_irq_work = false;
wl1271_debug(DEBUG_MAC80211, "mac80211 resume wow=%d",
wl->wow_enabled);
WARN_ON(!wl->wow_enabled);
spin_lock_irqsave(&wl->wl_lock, flags);
clear_bit(WL1271_FLAG_SUSPENDED, &wl->flags);
if (test_and_clear_bit(WL1271_FLAG_PENDING_WORK, &wl->flags))
run_irq_work = true;
spin_unlock_irqrestore(&wl->wl_lock, flags);
if (run_irq_work) {
wl1271_debug(DEBUG_MAC80211,
"run postponed irq_work directly");
wl1271_irq(0, wl);
wl1271_enable_interrupts(wl);
}
wl12xx_for_each_wlvif(wl, wlvif) {
wl1271_configure_resume(wl, wlvif);
}
wl->wow_enabled = false;
return 0;
}
#endif
static int wl1271_op_start(struct ieee80211_hw *hw)
{
wl1271_debug(DEBUG_MAC80211, "mac80211 start");
return 0;
}
static void wl1271_op_stop(struct ieee80211_hw *hw)
{
struct wl1271 *wl = hw->priv;
int i;
wl1271_debug(DEBUG_MAC80211, "mac80211 stop");
wl1271_disable_interrupts(wl);
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
mutex_unlock(&wl->mutex);
wl1271_enable_interrupts(wl);
return;
}
wl->state = WL1271_STATE_OFF;
mutex_unlock(&wl->mutex);
wl1271_flush_deferred_work(wl);
cancel_delayed_work_sync(&wl->scan_complete_work);
cancel_work_sync(&wl->netstack_work);
cancel_work_sync(&wl->tx_work);
cancel_delayed_work_sync(&wl->elp_work);
cancel_delayed_work_sync(&wl->tx_watchdog_work);
wl12xx_tx_reset(wl, true);
mutex_lock(&wl->mutex);
wl1271_power_off(wl);
wl->band = IEEE80211_BAND_2GHZ;
wl->rx_counter = 0;
wl->power_level = WL1271_DEFAULT_POWER_LEVEL;
wl->tx_blocks_available = 0;
wl->tx_allocated_blocks = 0;
wl->tx_results_count = 0;
wl->tx_packets_count = 0;
wl->time_offset = 0;
wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
wl->ap_fw_ps_map = 0;
wl->ap_ps_map = 0;
wl->sched_scanning = false;
memset(wl->roles_map, 0, sizeof(wl->roles_map));
memset(wl->links_map, 0, sizeof(wl->links_map));
memset(wl->roc_map, 0, sizeof(wl->roc_map));
wl->active_sta_count = 0;
__set_bit(WL12XX_SYSTEM_HLID, wl->links_map);
wl->flags = 0;
wl->tx_blocks_freed = 0;
for (i = 0; i < NUM_TX_QUEUES; i++) {
wl->tx_pkts_freed[i] = 0;
wl->tx_allocated_pkts[i] = 0;
}
wl1271_debugfs_reset(wl);
kfree(wl->fw_status);
wl->fw_status = NULL;
kfree(wl->tx_res_if);
wl->tx_res_if = NULL;
kfree(wl->target_mem_map);
wl->target_mem_map = NULL;
mutex_unlock(&wl->mutex);
}
static int wl12xx_allocate_rate_policy(struct wl1271 *wl, u8 *idx)
{
u8 policy = find_first_zero_bit(wl->rate_policies_map,
WL12XX_MAX_RATE_POLICIES);
if (policy >= WL12XX_MAX_RATE_POLICIES)
return -EBUSY;
__set_bit(policy, wl->rate_policies_map);
*idx = policy;
return 0;
}
static void wl12xx_free_rate_policy(struct wl1271 *wl, u8 *idx)
{
if (WARN_ON(*idx >= WL12XX_MAX_RATE_POLICIES))
return;
__clear_bit(*idx, wl->rate_policies_map);
*idx = WL12XX_MAX_RATE_POLICIES;
}
static u8 wl12xx_get_role_type(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
switch (wlvif->bss_type) {
case BSS_TYPE_AP_BSS:
if (wlvif->p2p)
return WL1271_ROLE_P2P_GO;
else
return WL1271_ROLE_AP;
case BSS_TYPE_STA_BSS:
if (wlvif->p2p)
return WL1271_ROLE_P2P_CL;
else
return WL1271_ROLE_STA;
case BSS_TYPE_IBSS:
return WL1271_ROLE_IBSS;
default:
wl1271_error("invalid bss_type: %d", wlvif->bss_type);
}
return WL12XX_INVALID_ROLE_TYPE;
}
static int wl12xx_init_vif_data(struct wl1271 *wl, struct ieee80211_vif *vif)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int i;
memset(wlvif, 0, offsetof(struct wl12xx_vif, persistent));
switch (ieee80211_vif_type_p2p(vif)) {
case NL80211_IFTYPE_P2P_CLIENT:
wlvif->p2p = 1;
case NL80211_IFTYPE_STATION:
wlvif->bss_type = BSS_TYPE_STA_BSS;
break;
case NL80211_IFTYPE_ADHOC:
wlvif->bss_type = BSS_TYPE_IBSS;
break;
case NL80211_IFTYPE_P2P_GO:
wlvif->p2p = 1;
case NL80211_IFTYPE_AP:
wlvif->bss_type = BSS_TYPE_AP_BSS;
break;
default:
wlvif->bss_type = MAX_BSS_TYPE;
return -EOPNOTSUPP;
}
wlvif->role_id = WL12XX_INVALID_ROLE_ID;
wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID;
wlvif->dev_hlid = WL12XX_INVALID_LINK_ID;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
wlvif->sta.hlid = WL12XX_INVALID_LINK_ID;
wl12xx_allocate_rate_policy(wl, &wlvif->sta.basic_rate_idx);
wl12xx_allocate_rate_policy(wl, &wlvif->sta.ap_rate_idx);
wl12xx_allocate_rate_policy(wl, &wlvif->sta.p2p_rate_idx);
} else {
wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID;
wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID;
wl12xx_allocate_rate_policy(wl, &wlvif->ap.mgmt_rate_idx);
wl12xx_allocate_rate_policy(wl, &wlvif->ap.bcast_rate_idx);
for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++)
wl12xx_allocate_rate_policy(wl,
&wlvif->ap.ucast_rate_idx[i]);
}
wlvif->bitrate_masks[IEEE80211_BAND_2GHZ] = wl->conf.tx.basic_rate;
wlvif->bitrate_masks[IEEE80211_BAND_5GHZ] = wl->conf.tx.basic_rate_5;
wlvif->basic_rate_set = CONF_TX_RATE_MASK_BASIC;
wlvif->basic_rate = CONF_TX_RATE_MASK_BASIC;
wlvif->rate_set = CONF_TX_RATE_MASK_BASIC;
wlvif->beacon_int = WL1271_DEFAULT_BEACON_INT;
wlvif->band = wl->band;
wlvif->channel = wl->channel;
wlvif->power_level = wl->power_level;
INIT_WORK(&wlvif->rx_streaming_enable_work,
wl1271_rx_streaming_enable_work);
INIT_WORK(&wlvif->rx_streaming_disable_work,
wl1271_rx_streaming_disable_work);
INIT_LIST_HEAD(&wlvif->list);
setup_timer(&wlvif->rx_streaming_timer, wl1271_rx_streaming_timer,
(unsigned long) wlvif);
return 0;
}
static bool wl12xx_init_fw(struct wl1271 *wl)
{
int retries = WL1271_BOOT_RETRIES;
bool booted = false;
struct wiphy *wiphy = wl->hw->wiphy;
int ret;
while (retries) {
retries--;
ret = wl12xx_chip_wakeup(wl, false);
if (ret < 0)
goto power_off;
ret = wl1271_boot(wl);
if (ret < 0)
goto power_off;
ret = wl1271_hw_init(wl);
if (ret < 0)
goto irq_disable;
booted = true;
break;
irq_disable:
mutex_unlock(&wl->mutex);
wl1271_disable_interrupts(wl);
wl1271_flush_deferred_work(wl);
cancel_work_sync(&wl->netstack_work);
mutex_lock(&wl->mutex);
power_off:
wl1271_power_off(wl);
}
if (!booted) {
wl1271_error("firmware boot failed despite %d retries",
WL1271_BOOT_RETRIES);
goto out;
}
wl1271_info("firmware booted (%s)", wl->chip.fw_ver_str);
wiphy->hw_version = wl->chip.id;
strncpy(wiphy->fw_version, wl->chip.fw_ver_str,
sizeof(wiphy->fw_version));
if (!wl->enable_11a)
wiphy->bands[IEEE80211_BAND_5GHZ]->n_channels = 0;
wl1271_debug(DEBUG_MAC80211, "11a is %ssupported",
wl->enable_11a ? "" : "not ");
wl->state = WL1271_STATE_ON;
out:
return booted;
}
static bool wl12xx_dev_role_started(struct wl12xx_vif *wlvif)
{
return wlvif->dev_hlid != WL12XX_INVALID_LINK_ID;
}
static bool wl12xx_need_fw_change(struct wl1271 *wl,
struct vif_counter_data vif_counter_data,
bool add)
{
enum wl12xx_fw_type current_fw = wl->fw_type;
u8 vif_count = vif_counter_data.counter;
if (test_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags))
return false;
if (add && !vif_counter_data.cur_vif_running)
vif_count++;
wl->last_vif_count = vif_count;
if (wl->state == WL1271_STATE_OFF)
return false;
if (vif_count > 1 && current_fw == WL12XX_FW_TYPE_NORMAL)
return true;
if (vif_count <= 1 && current_fw == WL12XX_FW_TYPE_MULTI)
return true;
return false;
}
static void wl12xx_force_active_psm(struct wl1271 *wl)
{
struct wl12xx_vif *wlvif;
wl12xx_for_each_wlvif_sta(wl, wlvif) {
wl1271_ps_set_mode(wl, wlvif, STATION_POWER_SAVE_MODE);
}
}
static int wl1271_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct vif_counter_data vif_count;
int ret = 0;
u8 role_type;
bool booted = false;
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER |
IEEE80211_VIF_SUPPORTS_CQM_RSSI;
wl1271_debug(DEBUG_MAC80211, "mac80211 add interface type %d mac %pM",
ieee80211_vif_type_p2p(vif), vif->addr);
wl12xx_get_vif_count(hw, vif, &vif_count);
mutex_lock(&wl->mutex);
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
if (test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags) ||
test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) {
ret = -EBUSY;
goto out;
}
ret = wl12xx_init_vif_data(wl, vif);
if (ret < 0)
goto out;
wlvif->wl = wl;
role_type = wl12xx_get_role_type(wl, wlvif);
if (role_type == WL12XX_INVALID_ROLE_TYPE) {
ret = -EINVAL;
goto out;
}
if (wl12xx_need_fw_change(wl, vif_count, true)) {
wl12xx_force_active_psm(wl);
set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags);
mutex_unlock(&wl->mutex);
wl1271_recovery_work(&wl->recovery_work);
return 0;
}
if (wl->state == WL1271_STATE_OFF) {
memcpy(wl->addresses[0].addr, vif->addr, ETH_ALEN);
booted = wl12xx_init_fw(wl);
if (!booted) {
ret = -EINVAL;
goto out;
}
}
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
ret = wl12xx_cmd_role_enable(wl, vif->addr,
WL1271_ROLE_DEVICE,
&wlvif->dev_role_id);
if (ret < 0)
goto out;
}
ret = wl12xx_cmd_role_enable(wl, vif->addr,
role_type, &wlvif->role_id);
if (ret < 0)
goto out;
ret = wl1271_init_vif_specific(wl, vif);
if (ret < 0)
goto out;
list_add(&wlvif->list, &wl->wlvif_list);
set_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags);
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
wl->ap_count++;
else
wl->sta_count++;
out:
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static void __wl1271_op_remove_interface(struct wl1271 *wl,
struct ieee80211_vif *vif,
bool reset_tx_queues)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int i, ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 remove interface");
if (!test_and_clear_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))
return;
if (wl->state != WL1271_STATE_ON)
return;
wl1271_info("down");
if (wl->scan.state != WL1271_SCAN_STATE_IDLE &&
wl->scan_vif == vif) {
wl12xx_rearm_tx_watchdog_locked(wl);
wl->scan.state = WL1271_SCAN_STATE_IDLE;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan_vif = NULL;
wl->scan.req = NULL;
ieee80211_scan_completed(wl->hw, true);
}
if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags)) {
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto deinit;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
if (wl12xx_dev_role_started(wlvif))
wl12xx_stop_dev(wl, wlvif);
ret = wl12xx_cmd_role_disable(wl, &wlvif->dev_role_id);
if (ret < 0)
goto deinit;
}
ret = wl12xx_cmd_role_disable(wl, &wlvif->role_id);
if (ret < 0)
goto deinit;
wl1271_ps_elp_sleep(wl);
}
deinit:
wlvif->dev_hlid = WL12XX_INVALID_LINK_ID;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
wlvif->sta.hlid = WL12XX_INVALID_LINK_ID;
wl12xx_free_rate_policy(wl, &wlvif->sta.basic_rate_idx);
wl12xx_free_rate_policy(wl, &wlvif->sta.ap_rate_idx);
wl12xx_free_rate_policy(wl, &wlvif->sta.p2p_rate_idx);
} else {
wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID;
wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID;
wl12xx_free_rate_policy(wl, &wlvif->ap.mgmt_rate_idx);
wl12xx_free_rate_policy(wl, &wlvif->ap.bcast_rate_idx);
for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++)
wl12xx_free_rate_policy(wl,
&wlvif->ap.ucast_rate_idx[i]);
}
wl12xx_tx_reset_wlvif(wl, wlvif);
wl1271_free_ap_keys(wl, wlvif);
if (wl->last_wlvif == wlvif)
wl->last_wlvif = NULL;
list_del(&wlvif->list);
memset(wlvif->ap.sta_hlid_map, 0, sizeof(wlvif->ap.sta_hlid_map));
wlvif->role_id = WL12XX_INVALID_ROLE_ID;
wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID;
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
wl->ap_count--;
else
wl->sta_count--;
mutex_unlock(&wl->mutex);
del_timer_sync(&wlvif->rx_streaming_timer);
cancel_work_sync(&wlvif->rx_streaming_enable_work);
cancel_work_sync(&wlvif->rx_streaming_disable_work);
mutex_lock(&wl->mutex);
}
static void wl1271_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct wl12xx_vif *iter;
struct vif_counter_data vif_count;
bool cancel_recovery = true;
wl12xx_get_vif_count(hw, vif, &vif_count);
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF ||
!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))
goto out;
wl12xx_for_each_wlvif(wl, iter) {
if (iter != wlvif)
continue;
__wl1271_op_remove_interface(wl, vif, true);
break;
}
WARN_ON(iter != wlvif);
if (wl12xx_need_fw_change(wl, vif_count, false)) {
wl12xx_force_active_psm(wl);
set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags);
wl12xx_queue_recovery_work(wl);
cancel_recovery = false;
}
out:
mutex_unlock(&wl->mutex);
if (cancel_recovery)
cancel_work_sync(&wl->recovery_work);
}
static int wl12xx_op_change_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype new_type, bool p2p)
{
struct wl1271 *wl = hw->priv;
int ret;
set_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags);
wl1271_op_remove_interface(hw, vif);
vif->type = new_type;
vif->p2p = p2p;
ret = wl1271_op_add_interface(hw, vif);
clear_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags);
return ret;
}
static int wl1271_join(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool set_assoc)
{
int ret;
bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS);
if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
wl1271_info("JOIN while associated.");
wlvif->encryption_type = KEY_NONE;
if (set_assoc)
set_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags);
if (is_ibss)
ret = wl12xx_cmd_role_start_ibss(wl, wlvif);
else
ret = wl12xx_cmd_role_start_sta(wl, wlvif);
if (ret < 0)
goto out;
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
goto out;
ret = wl1271_acx_keep_alive_mode(wl, wlvif, true);
if (ret < 0)
goto out;
ret = wl1271_acx_aid(wl, wlvif, wlvif->aid);
if (ret < 0)
goto out;
ret = wl12xx_cmd_build_klv_null_data(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_acx_keep_alive_config(wl, wlvif,
CMD_TEMPL_KLV_IDX_NULL_DATA,
ACX_KEEP_ALIVE_TPL_VALID);
if (ret < 0)
goto out;
out:
return ret;
}
static int wl1271_unjoin(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int ret;
if (test_and_clear_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags)) {
struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif);
wl12xx_cmd_stop_channel_switch(wl);
ieee80211_chswitch_done(vif, false);
}
ret = wl12xx_cmd_role_stop_sta(wl, wlvif);
if (ret < 0)
goto out;
wlvif->tx_security_last_seq_lsb = 0;
wlvif->tx_security_seq = 0;
out:
return ret;
}
static void wl1271_set_band_rate(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
wlvif->basic_rate_set = wlvif->bitrate_masks[wlvif->band];
wlvif->rate_set = wlvif->basic_rate_set;
}
static int wl1271_sta_handle_idle(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool idle)
{
int ret;
bool cur_idle = !test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags);
if (idle == cur_idle)
return 0;
if (idle) {
if (wl12xx_dev_role_started(wlvif)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
goto out;
}
wlvif->rate_set =
wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_acx_keep_alive_config(
wl, wlvif, CMD_TEMPL_KLV_IDX_NULL_DATA,
ACX_KEEP_ALIVE_TPL_INVALID);
if (ret < 0)
goto out;
clear_bit(WLVIF_FLAG_IN_USE, &wlvif->flags);
} else {
if (wl->sched_scanning) {
wl1271_scan_sched_scan_stop(wl);
ieee80211_sched_scan_stopped(wl->hw);
}
ret = wl12xx_start_dev(wl, wlvif);
if (ret < 0)
goto out;
set_bit(WLVIF_FLAG_IN_USE, &wlvif->flags);
}
out:
return ret;
}
static int wl12xx_config_vif(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct ieee80211_conf *conf, u32 changed)
{
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
int channel, ret;
channel = ieee80211_frequency_to_channel(conf->channel->center_freq);
if (changed & IEEE80211_CONF_CHANGE_CHANNEL &&
((wlvif->band != conf->channel->band) ||
(wlvif->channel != channel))) {
wl1271_tx_work_locked(wl);
wlvif->band = conf->channel->band;
wlvif->channel = channel;
if (!is_ap) {
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
wl1271_set_band_rate(wl, wlvif);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
wl1271_warning("rate policy for channel "
"failed %d", ret);
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED,
&wlvif->flags) &&
wl12xx_dev_role_started(wlvif) &&
!(conf->flags & IEEE80211_CONF_IDLE)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
return ret;
ret = wl12xx_start_dev(wl, wlvif);
if (ret < 0)
return ret;
}
}
}
if ((changed & IEEE80211_CONF_CHANGE_PS) && !is_ap) {
if ((conf->flags & IEEE80211_CONF_PS) &&
test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) &&
!test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) {
int ps_mode;
char *ps_mode_str;
if (wl->conf.conn.forced_ps) {
ps_mode = STATION_POWER_SAVE_MODE;
ps_mode_str = "forced";
} else {
ps_mode = STATION_AUTO_PS_MODE;
ps_mode_str = "auto";
}
wl1271_debug(DEBUG_PSM, "%s ps enabled", ps_mode_str);
ret = wl1271_ps_set_mode(wl, wlvif, ps_mode);
if (ret < 0)
wl1271_warning("enter %s ps failed %d",
ps_mode_str, ret);
} else if (!(conf->flags & IEEE80211_CONF_PS) &&
test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) {
wl1271_debug(DEBUG_PSM, "auto ps disabled");
ret = wl1271_ps_set_mode(wl, wlvif,
STATION_ACTIVE_MODE);
if (ret < 0)
wl1271_warning("exit auto ps failed %d", ret);
}
}
if (conf->power_level != wlvif->power_level) {
ret = wl1271_acx_tx_power(wl, wlvif, conf->power_level);
if (ret < 0)
return ret;
wlvif->power_level = conf->power_level;
}
return 0;
}
static int wl1271_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
struct ieee80211_conf *conf = &hw->conf;
int channel, ret = 0;
channel = ieee80211_frequency_to_channel(conf->channel->center_freq);
wl1271_debug(DEBUG_MAC80211, "mac80211 config ch %d psm %s power %d %s"
" changed 0x%x",
channel,
conf->flags & IEEE80211_CONF_PS ? "on" : "off",
conf->power_level,
conf->flags & IEEE80211_CONF_IDLE ? "idle" : "in use",
changed);
if ((changed & IEEE80211_CONF_CHANGE_IDLE) &&
(conf->flags & IEEE80211_CONF_IDLE))
wl1271_tx_flush(wl);
mutex_lock(&wl->mutex);
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
wl->band = conf->channel->band;
wl->channel = channel;
}
if (changed & IEEE80211_CONF_CHANGE_POWER)
wl->power_level = conf->power_level;
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl12xx_for_each_wlvif(wl, wlvif) {
ret = wl12xx_config_vif(wl, wlvif, conf, changed);
if (ret < 0)
goto out_sleep;
}
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
struct wl1271_filter_params {
bool enabled;
int mc_list_length;
u8 mc_list[ACX_MC_ADDRESS_GROUP_MAX][ETH_ALEN];
};
static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw,
struct netdev_hw_addr_list *mc_list)
{
struct wl1271_filter_params *fp;
struct netdev_hw_addr *ha;
struct wl1271 *wl = hw->priv;
if (unlikely(wl->state == WL1271_STATE_OFF))
return 0;
fp = kzalloc(sizeof(*fp), GFP_ATOMIC);
if (!fp) {
wl1271_error("Out of memory setting filters.");
return 0;
}
fp->mc_list_length = 0;
if (netdev_hw_addr_list_count(mc_list) > ACX_MC_ADDRESS_GROUP_MAX) {
fp->enabled = false;
} else {
fp->enabled = true;
netdev_hw_addr_list_for_each(ha, mc_list) {
memcpy(fp->mc_list[fp->mc_list_length],
ha->addr, ETH_ALEN);
fp->mc_list_length++;
}
}
return (u64)(unsigned long)fp;
}
#define WL1271_SUPPORTED_FILTERS (FIF_PROMISC_IN_BSS | \
FIF_ALLMULTI | \
FIF_FCSFAIL | \
FIF_BCN_PRBRESP_PROMISC | \
FIF_CONTROL | \
FIF_OTHER_BSS)
static void wl1271_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed,
unsigned int *total, u64 multicast)
{
struct wl1271_filter_params *fp = (void *)(unsigned long)multicast;
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 configure filter changed %x"
" total %x", changed, *total);
mutex_lock(&wl->mutex);
*total &= WL1271_SUPPORTED_FILTERS;
changed &= WL1271_SUPPORTED_FILTERS;
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl12xx_for_each_wlvif(wl, wlvif) {
if (wlvif->bss_type != BSS_TYPE_AP_BSS) {
if (*total & FIF_ALLMULTI)
ret = wl1271_acx_group_address_tbl(wl, wlvif,
false,
NULL, 0);
else if (fp)
ret = wl1271_acx_group_address_tbl(wl, wlvif,
fp->enabled,
fp->mc_list,
fp->mc_list_length);
if (ret < 0)
goto out_sleep;
}
}
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
kfree(fp);
}
static int wl1271_record_ap_key(struct wl1271 *wl, struct wl12xx_vif *wlvif,
u8 id, u8 key_type, u8 key_size,
const u8 *key, u8 hlid, u32 tx_seq_32,
u16 tx_seq_16)
{
struct wl1271_ap_key *ap_key;
int i;
wl1271_debug(DEBUG_CRYPT, "record ap key id %d", (int)id);
if (key_size > MAX_KEY_SIZE)
return -EINVAL;
for (i = 0; i < MAX_NUM_KEYS; i++) {
if (wlvif->ap.recorded_keys[i] == NULL)
break;
if (wlvif->ap.recorded_keys[i]->id == id) {
wl1271_warning("trying to record key replacement");
return -EINVAL;
}
}
if (i == MAX_NUM_KEYS)
return -EBUSY;
ap_key = kzalloc(sizeof(*ap_key), GFP_KERNEL);
if (!ap_key)
return -ENOMEM;
ap_key->id = id;
ap_key->key_type = key_type;
ap_key->key_size = key_size;
memcpy(ap_key->key, key, key_size);
ap_key->hlid = hlid;
ap_key->tx_seq_32 = tx_seq_32;
ap_key->tx_seq_16 = tx_seq_16;
wlvif->ap.recorded_keys[i] = ap_key;
return 0;
}
static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int i;
for (i = 0; i < MAX_NUM_KEYS; i++) {
kfree(wlvif->ap.recorded_keys[i]);
wlvif->ap.recorded_keys[i] = NULL;
}
}
static int wl1271_ap_init_hwenc(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int i, ret = 0;
struct wl1271_ap_key *key;
bool wep_key_added = false;
for (i = 0; i < MAX_NUM_KEYS; i++) {
u8 hlid;
if (wlvif->ap.recorded_keys[i] == NULL)
break;
key = wlvif->ap.recorded_keys[i];
hlid = key->hlid;
if (hlid == WL12XX_INVALID_LINK_ID)
hlid = wlvif->ap.bcast_hlid;
ret = wl1271_cmd_set_ap_key(wl, wlvif, KEY_ADD_OR_REPLACE,
key->id, key->key_type,
key->key_size, key->key,
hlid, key->tx_seq_32,
key->tx_seq_16);
if (ret < 0)
goto out;
if (key->key_type == KEY_WEP)
wep_key_added = true;
}
if (wep_key_added) {
ret = wl12xx_cmd_set_default_wep_key(wl, wlvif->default_key,
wlvif->ap.bcast_hlid);
if (ret < 0)
goto out;
}
out:
wl1271_free_ap_keys(wl, wlvif);
return ret;
}
static int wl1271_set_key(struct wl1271 *wl, struct wl12xx_vif *wlvif,
u16 action, u8 id, u8 key_type,
u8 key_size, const u8 *key, u32 tx_seq_32,
u16 tx_seq_16, struct ieee80211_sta *sta)
{
int ret;
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
if (is_ap) {
struct wl1271_station *wl_sta;
u8 hlid;
if (sta) {
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
} else {
hlid = wlvif->ap.bcast_hlid;
}
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) {
if (action != KEY_ADD_OR_REPLACE)
return 0;
ret = wl1271_record_ap_key(wl, wlvif, id,
key_type, key_size,
key, hlid, tx_seq_32,
tx_seq_16);
} else {
ret = wl1271_cmd_set_ap_key(wl, wlvif, action,
id, key_type, key_size,
key, hlid, tx_seq_32,
tx_seq_16);
}
if (ret < 0)
return ret;
} else {
const u8 *addr;
static const u8 bcast_addr[ETH_ALEN] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
if (key_type == KEY_GEM) {
if (action == KEY_ADD_OR_REPLACE)
wl->tx_spare_blocks = 2;
else if (action == KEY_REMOVE)
wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
}
addr = sta ? sta->addr : bcast_addr;
if (is_zero_ether_addr(addr)) {
return -EOPNOTSUPP;
}
if (action == KEY_REMOVE && !is_broadcast_ether_addr(addr))
return 0;
if (action == KEY_REMOVE &&
wlvif->sta.hlid == WL12XX_INVALID_LINK_ID)
return 0;
ret = wl1271_cmd_set_sta_key(wl, wlvif, action,
id, key_type, key_size,
key, addr, tx_seq_32,
tx_seq_16);
if (ret < 0)
return ret;
if (key_type == KEY_WEP) {
ret = wl12xx_cmd_set_default_wep_key(wl,
wlvif->default_key,
wlvif->sta.hlid);
if (ret < 0)
return ret;
}
}
return 0;
}
static int wl1271_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct ieee80211_key_conf *key_conf)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
u32 tx_seq_32 = 0;
u16 tx_seq_16 = 0;
u8 key_type;
wl1271_debug(DEBUG_MAC80211, "mac80211 set key");
wl1271_debug(DEBUG_CRYPT, "CMD: 0x%x sta: %p", cmd, sta);
wl1271_debug(DEBUG_CRYPT, "Key: algo:0x%x, id:%d, len:%d flags 0x%x",
key_conf->cipher, key_conf->keyidx,
key_conf->keylen, key_conf->flags);
wl1271_dump(DEBUG_CRYPT, "KEY: ", key_conf->key, key_conf->keylen);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out_unlock;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
switch (key_conf->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
key_type = KEY_WEP;
key_conf->hw_key_idx = key_conf->keyidx;
break;
case WLAN_CIPHER_SUITE_TKIP:
key_type = KEY_TKIP;
key_conf->hw_key_idx = key_conf->keyidx;
tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq);
tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq);
break;
case WLAN_CIPHER_SUITE_CCMP:
key_type = KEY_AES;
key_conf->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE;
tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq);
tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq);
break;
case WL1271_CIPHER_SUITE_GEM:
key_type = KEY_GEM;
tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq);
tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq);
break;
default:
wl1271_error("Unknown key algo 0x%x", key_conf->cipher);
ret = -EOPNOTSUPP;
goto out_sleep;
}
switch (cmd) {
case SET_KEY:
ret = wl1271_set_key(wl, wlvif, KEY_ADD_OR_REPLACE,
key_conf->keyidx, key_type,
key_conf->keylen, key_conf->key,
tx_seq_32, tx_seq_16, sta);
if (ret < 0) {
wl1271_error("Could not add or replace key");
goto out_sleep;
}
if (wlvif->bss_type == BSS_TYPE_STA_BSS &&
(sta || key_type == KEY_WEP) &&
wlvif->encryption_type != key_type) {
wlvif->encryption_type = key_type;
ret = wl1271_cmd_build_arp_rsp(wl, wlvif);
if (ret < 0) {
wl1271_warning("build arp rsp failed: %d", ret);
goto out_sleep;
}
}
break;
case DISABLE_KEY:
ret = wl1271_set_key(wl, wlvif, KEY_REMOVE,
key_conf->keyidx, key_type,
key_conf->keylen, key_conf->key,
0, 0, sta);
if (ret < 0) {
wl1271_error("Could not remove key");
goto out_sleep;
}
break;
default:
wl1271_error("Unsupported key cmd 0x%x", cmd);
ret = -EOPNOTSUPP;
break;
}
out_sleep:
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_op_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_scan_request *req)
{
struct wl1271 *wl = hw->priv;
int ret;
u8 *ssid = NULL;
size_t len = 0;
wl1271_debug(DEBUG_MAC80211, "mac80211 hw scan");
if (req->n_ssids) {
ssid = req->ssids[0].ssid;
len = req->ssids[0].ssid_len;
}
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) {
ret = -EBUSY;
goto out_sleep;
}
ret = wl1271_scan(hw->priv, vif, ssid, len, req);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1271_op_cancel_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 cancel hw scan");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF)
goto out;
if (wl->scan.state == WL1271_SCAN_STATE_IDLE)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (wl->scan.state != WL1271_SCAN_STATE_DONE) {
ret = wl1271_scan_stop(wl);
if (ret < 0)
goto out_sleep;
}
wl12xx_rearm_tx_watchdog_locked(wl);
wl->scan.state = WL1271_SCAN_STATE_IDLE;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan_vif = NULL;
wl->scan.req = NULL;
ieee80211_scan_completed(wl->hw, true);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
cancel_delayed_work_sync(&wl->scan_complete_work);
}
static int wl1271_op_sched_scan_start(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_sched_scan_request *req,
struct ieee80211_sched_scan_ies *ies)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_start");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_scan_sched_scan_config(wl, wlvif, req, ies);
if (ret < 0)
goto out_sleep;
ret = wl1271_scan_sched_scan_start(wl, wlvif);
if (ret < 0)
goto out_sleep;
wl->sched_scanning = true;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1271_op_sched_scan_stop(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
int ret;
wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_stop");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_scan_sched_scan_stop(wl);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_op_set_frag_threshold(struct ieee80211_hw *hw, u32 value)
{
struct wl1271 *wl = hw->priv;
int ret = 0;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_acx_frag_threshold(wl, value);
if (ret < 0)
wl1271_warning("wl1271_op_set_frag_threshold failed: %d", ret);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_op_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret = 0;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl12xx_for_each_wlvif(wl, wlvif) {
ret = wl1271_acx_rts_threshold(wl, wlvif, value);
if (ret < 0)
wl1271_warning("set rts threshold failed: %d", ret);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_ssid_set(struct ieee80211_vif *vif, struct sk_buff *skb,
int offset)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
u8 ssid_len;
const u8 *ptr = cfg80211_find_ie(WLAN_EID_SSID, skb->data + offset,
skb->len - offset);
if (!ptr) {
wl1271_error("No SSID in IEs!");
return -ENOENT;
}
ssid_len = ptr[1];
if (ssid_len > IEEE80211_MAX_SSID_LEN) {
wl1271_error("SSID is too long!");
return -EINVAL;
}
wlvif->ssid_len = ssid_len;
memcpy(wlvif->ssid, ptr+2, ssid_len);
return 0;
}
static void wl12xx_remove_ie(struct sk_buff *skb, u8 eid, int ieoffset)
{
int len;
const u8 *next, *end = skb->data + skb->len;
u8 *ie = (u8 *)cfg80211_find_ie(eid, skb->data + ieoffset,
skb->len - ieoffset);
if (!ie)
return;
len = ie[1] + 2;
next = ie + len;
memmove(ie, next, end - next);
skb_trim(skb, skb->len - len);
}
static void wl12xx_remove_vendor_ie(struct sk_buff *skb,
unsigned int oui, u8 oui_type,
int ieoffset)
{
int len;
const u8 *next, *end = skb->data + skb->len;
u8 *ie = (u8 *)cfg80211_find_vendor_ie(oui, oui_type,
skb->data + ieoffset,
skb->len - ieoffset);
if (!ie)
return;
len = ie[1] + 2;
next = ie + len;
memmove(ie, next, end - next);
skb_trim(skb, skb->len - len);
}
static int wl1271_ap_set_probe_resp_tmpl(struct wl1271 *wl, u32 rates,
struct ieee80211_vif *vif)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct sk_buff *skb;
int ret;
skb = ieee80211_proberesp_get(wl->hw, vif);
if (!skb)
return -EOPNOTSUPP;
ret = wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_AP_PROBE_RESPONSE,
skb->data,
skb->len, 0,
rates);
dev_kfree_skb(skb);
return ret;
}
static int wl1271_ap_set_probe_resp_tmpl_legacy(struct wl1271 *wl,
struct ieee80211_vif *vif,
u8 *probe_rsp_data,
size_t probe_rsp_len,
u32 rates)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct ieee80211_bss_conf *bss_conf = &vif->bss_conf;
u8 probe_rsp_templ[WL1271_CMD_TEMPL_MAX_SIZE];
int ssid_ie_offset, ie_offset, templ_len;
const u8 *ptr;
if (wlvif->ssid_len > 0)
return wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_AP_PROBE_RESPONSE,
probe_rsp_data,
probe_rsp_len, 0,
rates);
if (probe_rsp_len + bss_conf->ssid_len > WL1271_CMD_TEMPL_MAX_SIZE) {
wl1271_error("probe_rsp template too big");
return -EINVAL;
}
ie_offset = offsetof(struct ieee80211_mgmt, u.probe_resp.variable);
ptr = cfg80211_find_ie(WLAN_EID_SSID, probe_rsp_data + ie_offset,
probe_rsp_len - ie_offset);
if (!ptr) {
wl1271_error("No SSID in beacon!");
return -EINVAL;
}
ssid_ie_offset = ptr - probe_rsp_data;
ptr += (ptr[1] + 2);
memcpy(probe_rsp_templ, probe_rsp_data, ssid_ie_offset);
probe_rsp_templ[ssid_ie_offset] = WLAN_EID_SSID;
probe_rsp_templ[ssid_ie_offset + 1] = bss_conf->ssid_len;
memcpy(probe_rsp_templ + ssid_ie_offset + 2,
bss_conf->ssid, bss_conf->ssid_len);
templ_len = ssid_ie_offset + 2 + bss_conf->ssid_len;
memcpy(probe_rsp_templ + ssid_ie_offset + 2 + bss_conf->ssid_len,
ptr, probe_rsp_len - (ptr - probe_rsp_data));
templ_len += probe_rsp_len - (ptr - probe_rsp_data);
return wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_AP_PROBE_RESPONSE,
probe_rsp_templ,
templ_len, 0,
rates);
}
static int wl1271_bss_erp_info_changed(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret = 0;
if (changed & BSS_CHANGED_ERP_SLOT) {
if (bss_conf->use_short_slot)
ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_SHORT);
else
ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_LONG);
if (ret < 0) {
wl1271_warning("Set slot time failed %d", ret);
goto out;
}
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
if (bss_conf->use_short_preamble)
wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_SHORT);
else
wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_LONG);
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
if (bss_conf->use_cts_prot)
ret = wl1271_acx_cts_protect(wl, wlvif,
CTSPROTECT_ENABLE);
else
ret = wl1271_acx_cts_protect(wl, wlvif,
CTSPROTECT_DISABLE);
if (ret < 0) {
wl1271_warning("Set ctsprotect failed %d", ret);
goto out;
}
}
out:
return ret;
}
static int wl1271_bss_beacon_info_changed(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
int ret = 0;
if ((changed & BSS_CHANGED_BEACON_INT)) {
wl1271_debug(DEBUG_MASTER, "beacon interval updated: %d",
bss_conf->beacon_int);
wlvif->beacon_int = bss_conf->beacon_int;
}
if ((changed & BSS_CHANGED_AP_PROBE_RESP) && is_ap) {
u32 rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
if (!wl1271_ap_set_probe_resp_tmpl(wl, rate, vif)) {
wl1271_debug(DEBUG_AP, "probe response updated");
set_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags);
}
}
if ((changed & BSS_CHANGED_BEACON)) {
struct ieee80211_hdr *hdr;
u32 min_rate;
int ieoffset = offsetof(struct ieee80211_mgmt,
u.beacon.variable);
struct sk_buff *beacon = ieee80211_beacon_get(wl->hw, vif);
u16 tmpl_id;
if (!beacon) {
ret = -EINVAL;
goto out;
}
wl1271_debug(DEBUG_MASTER, "beacon updated");
ret = wl1271_ssid_set(vif, beacon, ieoffset);
if (ret < 0) {
dev_kfree_skb(beacon);
goto out;
}
min_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
tmpl_id = is_ap ? CMD_TEMPL_AP_BEACON :
CMD_TEMPL_BEACON;
ret = wl1271_cmd_template_set(wl, wlvif->role_id, tmpl_id,
beacon->data,
beacon->len, 0,
min_rate);
if (ret < 0) {
dev_kfree_skb(beacon);
goto out;
}
if (test_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags))
goto end_bcn;
wl12xx_remove_ie(beacon, WLAN_EID_TIM, ieoffset);
wl12xx_remove_vendor_ie(beacon, WLAN_OUI_WFA,
WLAN_OUI_TYPE_WFA_P2P, ieoffset);
hdr = (struct ieee80211_hdr *) beacon->data;
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_PROBE_RESP);
if (is_ap)
ret = wl1271_ap_set_probe_resp_tmpl_legacy(wl, vif,
beacon->data,
beacon->len,
min_rate);
else
ret = wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_PROBE_RESPONSE,
beacon->data,
beacon->len, 0,
min_rate);
end_bcn:
dev_kfree_skb(beacon);
if (ret < 0)
goto out;
}
out:
if (ret != 0)
wl1271_error("beacon info change failed: %d", ret);
return ret;
}
static void wl1271_bss_info_changed_ap(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret = 0;
if ((changed & BSS_CHANGED_BASIC_RATES)) {
u32 rates = bss_conf->basic_rates;
wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates,
wlvif->band);
wlvif->basic_rate = wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
ret = wl1271_init_ap_rates(wl, wlvif);
if (ret < 0) {
wl1271_error("AP rate policy change failed %d", ret);
goto out;
}
ret = wl1271_ap_init_templates(wl, vif);
if (ret < 0)
goto out;
}
ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
if ((changed & BSS_CHANGED_BEACON_ENABLED)) {
if (bss_conf->enable_beacon) {
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) {
ret = wl12xx_cmd_role_start_ap(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_ap_init_hwenc(wl, wlvif);
if (ret < 0)
goto out;
set_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags);
wl1271_debug(DEBUG_AP, "started AP");
}
} else {
if (test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) {
ret = wl12xx_cmd_role_stop_ap(wl, wlvif);
if (ret < 0)
goto out;
clear_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags);
clear_bit(WLVIF_FLAG_AP_PROBE_RESP_SET,
&wlvif->flags);
wl1271_debug(DEBUG_AP, "stopped AP");
}
}
}
ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
if ((changed & BSS_CHANGED_HT) &&
(bss_conf->channel_type != NL80211_CHAN_NO_HT)) {
ret = wl1271_acx_set_ht_information(wl, wlvif,
bss_conf->ht_operation_mode);
if (ret < 0) {
wl1271_warning("Set ht information failed %d", ret);
goto out;
}
}
out:
return;
}
static void wl1271_bss_info_changed_sta(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
bool do_join = false, set_assoc = false;
bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS);
bool ibss_joined = false;
u32 sta_rate_set = 0;
int ret;
struct ieee80211_sta *sta;
bool sta_exists = false;
struct ieee80211_sta_ht_cap sta_ht_cap;
if (is_ibss) {
ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf,
changed);
if (ret < 0)
goto out;
}
if (changed & BSS_CHANGED_IBSS) {
if (bss_conf->ibss_joined) {
set_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags);
ibss_joined = true;
} else {
if (test_and_clear_bit(WLVIF_FLAG_IBSS_JOINED,
&wlvif->flags))
wl1271_unjoin(wl, wlvif);
}
}
if ((changed & BSS_CHANGED_BEACON_INT) && ibss_joined)
do_join = true;
if ((changed & BSS_CHANGED_BEACON) && ibss_joined)
do_join = true;
if ((changed & BSS_CHANGED_BEACON_ENABLED) && ibss_joined) {
wl1271_debug(DEBUG_ADHOC, "ad-hoc beaconing: %s",
bss_conf->enable_beacon ? "enabled" : "disabled");
do_join = true;
}
if (changed & BSS_CHANGED_IDLE && !is_ibss) {
ret = wl1271_sta_handle_idle(wl, wlvif, bss_conf->idle);
if (ret < 0)
wl1271_warning("idle mode change failed %d", ret);
}
if ((changed & BSS_CHANGED_CQM)) {
bool enable = false;
if (bss_conf->cqm_rssi_thold)
enable = true;
ret = wl1271_acx_rssi_snr_trigger(wl, wlvif, enable,
bss_conf->cqm_rssi_thold,
bss_conf->cqm_rssi_hyst);
if (ret < 0)
goto out;
wlvif->rssi_thold = bss_conf->cqm_rssi_thold;
}
if (changed & BSS_CHANGED_BSSID &&
(is_ibss || bss_conf->assoc))
if (!is_zero_ether_addr(bss_conf->bssid)) {
ret = wl12xx_cmd_build_null_data(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_build_qos_null_data(wl, vif);
if (ret < 0)
goto out;
do_join = true;
}
if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_HT)) {
rcu_read_lock();
sta = ieee80211_find_sta(vif, bss_conf->bssid);
if (!sta)
goto sta_not_found;
sta_rate_set = sta->supp_rates[wl->hw->conf.channel->band];
if (sta->ht_cap.ht_supported)
sta_rate_set |=
(sta->ht_cap.mcs.rx_mask[0] << HW_HT_RATES_OFFSET);
sta_ht_cap = sta->ht_cap;
sta_exists = true;
sta_not_found:
rcu_read_unlock();
}
if ((changed & BSS_CHANGED_ASSOC)) {
if (bss_conf->assoc) {
u32 rates;
int ieoffset;
wlvif->aid = bss_conf->aid;
wlvif->beacon_int = bss_conf->beacon_int;
set_assoc = true;
rates = bss_conf->basic_rates;
wlvif->basic_rate_set =
wl1271_tx_enabled_rates_get(wl, rates,
wlvif->band);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
if (sta_rate_set)
wlvif->rate_set =
wl1271_tx_enabled_rates_get(wl,
sta_rate_set,
wlvif->band);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_cmd_build_ps_poll(wl, wlvif, wlvif->aid);
if (ret < 0)
goto out;
dev_kfree_skb(wlvif->probereq);
wlvif->probereq = wl1271_cmd_build_ap_probe_req(wl,
wlvif,
NULL);
ieoffset = offsetof(struct ieee80211_mgmt,
u.probe_req.variable);
wl1271_ssid_set(vif, wlvif->probereq, ieoffset);
ret = wl1271_acx_conn_monit_params(wl, wlvif, true);
if (ret < 0)
goto out;
} else {
bool was_assoc =
!!test_and_clear_bit(WLVIF_FLAG_STA_ASSOCIATED,
&wlvif->flags);
bool was_ifup =
!!test_and_clear_bit(WLVIF_FLAG_STA_STATE_SENT,
&wlvif->flags);
wlvif->aid = 0;
dev_kfree_skb(wlvif->probereq);
wlvif->probereq = NULL;
wl1271_set_band_rate(wl, wlvif);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_acx_conn_monit_params(wl, wlvif, false);
ret = wl1271_acx_keep_alive_mode(wl, wlvif, false);
if (ret < 0)
goto out;
if (was_assoc) {
if (!was_ifup) {
ret = wl12xx_croc(wl, wlvif->role_id);
if (ret < 0)
goto out;
}
if (test_bit(wlvif->dev_role_id, wl->roc_map)) {
ret = wl12xx_croc(wl,
wlvif->dev_role_id);
if (ret < 0)
goto out;
}
wl1271_unjoin(wl, wlvif);
if (!bss_conf->idle)
wl12xx_start_dev(wl, wlvif);
}
}
}
if (changed & BSS_CHANGED_IBSS) {
wl1271_debug(DEBUG_ADHOC, "ibss_joined: %d",
bss_conf->ibss_joined);
if (bss_conf->ibss_joined) {
u32 rates = bss_conf->basic_rates;
wlvif->basic_rate_set =
wl1271_tx_enabled_rates_get(wl, rates,
wlvif->band);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
wlvif->rate_set = CONF_TX_IBSS_DEFAULT_RATES;
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
}
}
ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
if (do_join) {
ret = wl1271_join(wl, wlvif, set_assoc);
if (ret < 0) {
wl1271_warning("cmd join failed %d", ret);
goto out;
}
if (!is_ibss) {
ret = wl12xx_roc(wl, wlvif, wlvif->role_id);
if (ret < 0)
goto out;
if (test_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags))
wl12xx_set_authorized(wl, wlvif);
}
if (wl12xx_dev_role_started(wlvif)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
goto out;
}
}
if (sta_exists) {
if ((changed & BSS_CHANGED_HT) &&
(bss_conf->channel_type != NL80211_CHAN_NO_HT)) {
ret = wl1271_acx_set_ht_capabilities(wl,
&sta_ht_cap,
true,
wlvif->sta.hlid);
if (ret < 0) {
wl1271_warning("Set ht cap true failed %d",
ret);
goto out;
}
}
else if (changed & BSS_CHANGED_ASSOC) {
ret = wl1271_acx_set_ht_capabilities(wl,
&sta_ht_cap,
false,
wlvif->sta.hlid);
if (ret < 0) {
wl1271_warning("Set ht cap false failed %d",
ret);
goto out;
}
}
}
if ((changed & BSS_CHANGED_HT) &&
(bss_conf->channel_type != NL80211_CHAN_NO_HT)) {
ret = wl1271_acx_set_ht_information(wl, wlvif,
bss_conf->ht_operation_mode);
if (ret < 0) {
wl1271_warning("Set ht information failed %d", ret);
goto out;
}
}
if ((changed & BSS_CHANGED_ARP_FILTER) ||
(!is_ibss && (changed & BSS_CHANGED_QOS))) {
__be32 addr = bss_conf->arp_addr_list[0];
wlvif->sta.qos = bss_conf->qos;
WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS);
if (bss_conf->arp_addr_cnt == 1 &&
bss_conf->arp_filter_enabled) {
wlvif->ip_addr = addr;
ret = wl1271_cmd_build_arp_rsp(wl, wlvif);
if (ret < 0) {
wl1271_warning("build arp rsp failed: %d", ret);
goto out;
}
ret = wl1271_acx_arp_ip_filter(wl, wlvif,
(ACX_ARP_FILTER_ARP_FILTERING |
ACX_ARP_FILTER_AUTO_ARP),
addr);
} else {
wlvif->ip_addr = 0;
ret = wl1271_acx_arp_ip_filter(wl, wlvif, 0, addr);
}
if (ret < 0)
goto out;
}
out:
return;
}
static void wl1271_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 bss info changed 0x%x",
(int)changed);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
if (unlikely(!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (is_ap)
wl1271_bss_info_changed_ap(wl, vif, bss_conf, changed);
else
wl1271_bss_info_changed_sta(wl, vif, bss_conf, changed);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_op_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
u8 ps_scheme;
int ret = 0;
mutex_lock(&wl->mutex);
wl1271_debug(DEBUG_MAC80211, "mac80211 conf tx %d", queue);
if (params->uapsd)
ps_scheme = CONF_PS_SCHEME_UPSD_TRIGGER;
else
ps_scheme = CONF_PS_SCHEME_LEGACY;
if (!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_acx_ac_cfg(wl, wlvif, wl1271_tx_get_queue(queue),
params->cw_min, params->cw_max,
params->aifs, params->txop << 5);
if (ret < 0)
goto out_sleep;
ret = wl1271_acx_tid_cfg(wl, wlvif, wl1271_tx_get_queue(queue),
CONF_CHANNEL_TYPE_EDCF,
wl1271_tx_get_queue(queue),
ps_scheme, CONF_ACK_POLICY_LEGACY,
0, 0);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static u64 wl1271_op_get_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
u64 mactime = ULLONG_MAX;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 get tsf");
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl12xx_acx_tsf_info(wl, wlvif, &mactime);
if (ret < 0)
goto out_sleep;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return mactime;
}
static int wl1271_op_get_survey(struct ieee80211_hw *hw, int idx,
struct survey_info *survey)
{
struct wl1271 *wl = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
if (idx != 0)
return -ENOENT;
survey->channel = conf->channel;
survey->filled = SURVEY_INFO_NOISE_DBM;
survey->noise = wl->noise;
return 0;
}
static int wl1271_allocate_sta(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta)
{
struct wl1271_station *wl_sta;
int ret;
if (wl->active_sta_count >= AP_MAX_STATIONS) {
wl1271_warning("could not allocate HLID - too much stations");
return -EBUSY;
}
wl_sta = (struct wl1271_station *)sta->drv_priv;
ret = wl12xx_allocate_link(wl, wlvif, &wl_sta->hlid);
if (ret < 0) {
wl1271_warning("could not allocate HLID - too many links");
return -EBUSY;
}
set_bit(wl_sta->hlid, wlvif->ap.sta_hlid_map);
memcpy(wl->links[wl_sta->hlid].addr, sta->addr, ETH_ALEN);
wl->active_sta_count++;
return 0;
}
void wl1271_free_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid)
{
if (!test_bit(hlid, wlvif->ap.sta_hlid_map))
return;
clear_bit(hlid, wlvif->ap.sta_hlid_map);
memset(wl->links[hlid].addr, 0, ETH_ALEN);
wl->links[hlid].ba_bitmap = 0;
__clear_bit(hlid, &wl->ap_ps_map);
__clear_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map);
wl12xx_free_link(wl, wlvif, &hlid);
wl->active_sta_count--;
if (wl->active_sta_count == 0)
wl12xx_rearm_tx_watchdog_locked(wl);
}
static int wl12xx_sta_add(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta)
{
struct wl1271_station *wl_sta;
int ret = 0;
u8 hlid;
wl1271_debug(DEBUG_MAC80211, "mac80211 add sta %d", (int)sta->aid);
ret = wl1271_allocate_sta(wl, wlvif, sta);
if (ret < 0)
return ret;
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
ret = wl12xx_cmd_add_peer(wl, wlvif, sta, hlid);
if (ret < 0)
wl1271_free_sta(wl, wlvif, hlid);
return ret;
}
static int wl12xx_sta_remove(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta)
{
struct wl1271_station *wl_sta;
int ret = 0, id;
wl1271_debug(DEBUG_MAC80211, "mac80211 remove sta %d", (int)sta->aid);
wl_sta = (struct wl1271_station *)sta->drv_priv;
id = wl_sta->hlid;
if (WARN_ON(!test_bit(id, wlvif->ap.sta_hlid_map)))
return -EINVAL;
ret = wl12xx_cmd_remove_peer(wl, wl_sta->hlid);
if (ret < 0)
return ret;
wl1271_free_sta(wl, wlvif, wl_sta->hlid);
return ret;
}
static int wl12xx_update_sta_state(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta,
enum ieee80211_sta_state old_state,
enum ieee80211_sta_state new_state)
{
struct wl1271_station *wl_sta;
u8 hlid;
bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS;
bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS;
int ret;
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
if (is_ap &&
old_state == IEEE80211_STA_NOTEXIST &&
new_state == IEEE80211_STA_NONE)
return wl12xx_sta_add(wl, wlvif, sta);
if (is_ap &&
old_state == IEEE80211_STA_NONE &&
new_state == IEEE80211_STA_NOTEXIST) {
wl12xx_sta_remove(wl, wlvif, sta);
return 0;
}
if (is_ap &&
new_state == IEEE80211_STA_AUTHORIZED) {
ret = wl12xx_cmd_set_peer_state(wl, hlid);
if (ret < 0)
return ret;
ret = wl1271_acx_set_ht_capabilities(wl, &sta->ht_cap, true,
hlid);
return ret;
}
if (is_sta &&
new_state == IEEE80211_STA_AUTHORIZED) {
set_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags);
return wl12xx_set_authorized(wl, wlvif);
}
if (is_sta &&
old_state == IEEE80211_STA_AUTHORIZED &&
new_state == IEEE80211_STA_ASSOC) {
clear_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags);
return 0;
}
return 0;
}
static int wl12xx_op_sta_state(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
enum ieee80211_sta_state old_state,
enum ieee80211_sta_state new_state)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 sta %d state=%d->%d",
sta->aid, old_state, new_state);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EBUSY;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl12xx_update_sta_state(wl, wlvif, sta, old_state, new_state);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
if (new_state < old_state)
return 0;
return ret;
}
static int wl1271_op_ampdu_action(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid, u16 *ssn,
u8 buf_size)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
u8 hlid, *ba_bitmap;
wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu action %d tid %d", action,
tid);
if (WARN_ON(tid > 0xFF))
return -ENOTSUPP;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out;
}
if (wlvif->bss_type == BSS_TYPE_STA_BSS) {
hlid = wlvif->sta.hlid;
ba_bitmap = &wlvif->sta.ba_rx_bitmap;
} else if (wlvif->bss_type == BSS_TYPE_AP_BSS) {
struct wl1271_station *wl_sta;
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
ba_bitmap = &wl->links[hlid].ba_bitmap;
} else {
ret = -EINVAL;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu: Rx tid %d action %d",
tid, action);
switch (action) {
case IEEE80211_AMPDU_RX_START:
if (!wlvif->ba_support || !wlvif->ba_allowed) {
ret = -ENOTSUPP;
break;
}
if (wl->ba_rx_session_count >= RX_BA_MAX_SESSIONS) {
ret = -EBUSY;
wl1271_error("exceeded max RX BA sessions");
break;
}
if (*ba_bitmap & BIT(tid)) {
ret = -EINVAL;
wl1271_error("cannot enable RX BA session on active "
"tid: %d", tid);
break;
}
ret = wl12xx_acx_set_ba_receiver_session(wl, tid, *ssn, true,
hlid);
if (!ret) {
*ba_bitmap |= BIT(tid);
wl->ba_rx_session_count++;
}
break;
case IEEE80211_AMPDU_RX_STOP:
if (!(*ba_bitmap & BIT(tid))) {
ret = -EINVAL;
wl1271_error("no active RX BA session on tid: %d",
tid);
break;
}
ret = wl12xx_acx_set_ba_receiver_session(wl, tid, 0, false,
hlid);
if (!ret) {
*ba_bitmap &= ~BIT(tid);
wl->ba_rx_session_count--;
}
break;
case IEEE80211_AMPDU_TX_START:
case IEEE80211_AMPDU_TX_STOP:
case IEEE80211_AMPDU_TX_OPERATIONAL:
ret = -EINVAL;
break;
default:
wl1271_error("Incorrect ampdu action id=%x\n", action);
ret = -EINVAL;
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl12xx_set_bitrate_mask(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const struct cfg80211_bitrate_mask *mask)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct wl1271 *wl = hw->priv;
int i, ret = 0;
wl1271_debug(DEBUG_MAC80211, "mac80211 set_bitrate_mask 0x%x 0x%x",
mask->control[NL80211_BAND_2GHZ].legacy,
mask->control[NL80211_BAND_5GHZ].legacy);
mutex_lock(&wl->mutex);
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
wlvif->bitrate_masks[i] =
wl1271_tx_enabled_rates_get(wl,
mask->control[i].legacy,
i);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
if (wlvif->bss_type == BSS_TYPE_STA_BSS &&
!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) {
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_set_band_rate(wl, wlvif);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
wl1271_ps_elp_sleep(wl);
}
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl12xx_op_channel_switch(struct ieee80211_hw *hw,
struct ieee80211_channel_switch *ch_switch)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 channel switch");
wl1271_tx_flush(wl);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
wl12xx_for_each_wlvif_sta(wl, wlvif) {
struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif);
ieee80211_chswitch_done(vif, false);
}
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl12xx_for_each_wlvif_sta(wl, wlvif) {
ret = wl12xx_cmd_channel_switch(wl, wlvif, ch_switch);
if (!ret)
set_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static bool wl1271_tx_frames_pending(struct ieee80211_hw *hw)
{
struct wl1271 *wl = hw->priv;
bool ret = false;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = (wl1271_tx_total_queue_count(wl) > 0) || (wl->tx_frames_cnt > 0);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static struct ieee80211_rate wl1271_rates[] = {
{ .bitrate = 10,
.hw_value = CONF_HW_BIT_RATE_1MBPS,
.hw_value_short = CONF_HW_BIT_RATE_1MBPS, },
{ .bitrate = 20,
.hw_value = CONF_HW_BIT_RATE_2MBPS,
.hw_value_short = CONF_HW_BIT_RATE_2MBPS,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55,
.hw_value = CONF_HW_BIT_RATE_5_5MBPS,
.hw_value_short = CONF_HW_BIT_RATE_5_5MBPS,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110,
.hw_value = CONF_HW_BIT_RATE_11MBPS,
.hw_value_short = CONF_HW_BIT_RATE_11MBPS,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60,
.hw_value = CONF_HW_BIT_RATE_6MBPS,
.hw_value_short = CONF_HW_BIT_RATE_6MBPS, },
{ .bitrate = 90,
.hw_value = CONF_HW_BIT_RATE_9MBPS,
.hw_value_short = CONF_HW_BIT_RATE_9MBPS, },
{ .bitrate = 120,
.hw_value = CONF_HW_BIT_RATE_12MBPS,
.hw_value_short = CONF_HW_BIT_RATE_12MBPS, },
{ .bitrate = 180,
.hw_value = CONF_HW_BIT_RATE_18MBPS,
.hw_value_short = CONF_HW_BIT_RATE_18MBPS, },
{ .bitrate = 240,
.hw_value = CONF_HW_BIT_RATE_24MBPS,
.hw_value_short = CONF_HW_BIT_RATE_24MBPS, },
{ .bitrate = 360,
.hw_value = CONF_HW_BIT_RATE_36MBPS,
.hw_value_short = CONF_HW_BIT_RATE_36MBPS, },
{ .bitrate = 480,
.hw_value = CONF_HW_BIT_RATE_48MBPS,
.hw_value_short = CONF_HW_BIT_RATE_48MBPS, },
{ .bitrate = 540,
.hw_value = CONF_HW_BIT_RATE_54MBPS,
.hw_value_short = CONF_HW_BIT_RATE_54MBPS, },
};
static struct ieee80211_channel wl1271_channels[] = {
{ .hw_value = 1, .center_freq = 2412, .max_power = 25 },
{ .hw_value = 2, .center_freq = 2417, .max_power = 25 },
{ .hw_value = 3, .center_freq = 2422, .max_power = 25 },
{ .hw_value = 4, .center_freq = 2427, .max_power = 25 },
{ .hw_value = 5, .center_freq = 2432, .max_power = 25 },
{ .hw_value = 6, .center_freq = 2437, .max_power = 25 },
{ .hw_value = 7, .center_freq = 2442, .max_power = 25 },
{ .hw_value = 8, .center_freq = 2447, .max_power = 25 },
{ .hw_value = 9, .center_freq = 2452, .max_power = 25 },
{ .hw_value = 10, .center_freq = 2457, .max_power = 25 },
{ .hw_value = 11, .center_freq = 2462, .max_power = 25 },
{ .hw_value = 12, .center_freq = 2467, .max_power = 25 },
{ .hw_value = 13, .center_freq = 2472, .max_power = 25 },
{ .hw_value = 14, .center_freq = 2484, .max_power = 25 },
};
static const u8 wl1271_rate_to_idx_2ghz[] = {
7,
7,
6,
5,
4,
3,
2,
1,
0,
11,
10,
9,
8,
CONF_HW_RXTX_RATE_UNSUPPORTED,
7,
6,
3,
5,
4,
2,
1,
0
};
#define HW_RX_HIGHEST_RATE 72
#define WL12XX_HT_CAP { \
.cap = IEEE80211_HT_CAP_GRN_FLD | IEEE80211_HT_CAP_SGI_20 | \
(1 << IEEE80211_HT_CAP_RX_STBC_SHIFT), \
.ht_supported = true, \
.ampdu_factor = IEEE80211_HT_MAX_AMPDU_8K, \
.ampdu_density = IEEE80211_HT_MPDU_DENSITY_8, \
.mcs = { \
.rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, \
.rx_highest = cpu_to_le16(HW_RX_HIGHEST_RATE), \
.tx_params = IEEE80211_HT_MCS_TX_DEFINED, \
}, \
}
static struct ieee80211_supported_band wl1271_band_2ghz = {
.channels = wl1271_channels,
.n_channels = ARRAY_SIZE(wl1271_channels),
.bitrates = wl1271_rates,
.n_bitrates = ARRAY_SIZE(wl1271_rates),
.ht_cap = WL12XX_HT_CAP,
};
static struct ieee80211_rate wl1271_rates_5ghz[] = {
{ .bitrate = 60,
.hw_value = CONF_HW_BIT_RATE_6MBPS,
.hw_value_short = CONF_HW_BIT_RATE_6MBPS, },
{ .bitrate = 90,
.hw_value = CONF_HW_BIT_RATE_9MBPS,
.hw_value_short = CONF_HW_BIT_RATE_9MBPS, },
{ .bitrate = 120,
.hw_value = CONF_HW_BIT_RATE_12MBPS,
.hw_value_short = CONF_HW_BIT_RATE_12MBPS, },
{ .bitrate = 180,
.hw_value = CONF_HW_BIT_RATE_18MBPS,
.hw_value_short = CONF_HW_BIT_RATE_18MBPS, },
{ .bitrate = 240,
.hw_value = CONF_HW_BIT_RATE_24MBPS,
.hw_value_short = CONF_HW_BIT_RATE_24MBPS, },
{ .bitrate = 360,
.hw_value = CONF_HW_BIT_RATE_36MBPS,
.hw_value_short = CONF_HW_BIT_RATE_36MBPS, },
{ .bitrate = 480,
.hw_value = CONF_HW_BIT_RATE_48MBPS,
.hw_value_short = CONF_HW_BIT_RATE_48MBPS, },
{ .bitrate = 540,
.hw_value = CONF_HW_BIT_RATE_54MBPS,
.hw_value_short = CONF_HW_BIT_RATE_54MBPS, },
};
static struct ieee80211_channel wl1271_channels_5ghz[] = {
{ .hw_value = 7, .center_freq = 5035, .max_power = 25 },
{ .hw_value = 8, .center_freq = 5040, .max_power = 25 },
{ .hw_value = 9, .center_freq = 5045, .max_power = 25 },
{ .hw_value = 11, .center_freq = 5055, .max_power = 25 },
{ .hw_value = 12, .center_freq = 5060, .max_power = 25 },
{ .hw_value = 16, .center_freq = 5080, .max_power = 25 },
{ .hw_value = 34, .center_freq = 5170, .max_power = 25 },
{ .hw_value = 36, .center_freq = 5180, .max_power = 25 },
{ .hw_value = 38, .center_freq = 5190, .max_power = 25 },
{ .hw_value = 40, .center_freq = 5200, .max_power = 25 },
{ .hw_value = 42, .center_freq = 5210, .max_power = 25 },
{ .hw_value = 44, .center_freq = 5220, .max_power = 25 },
{ .hw_value = 46, .center_freq = 5230, .max_power = 25 },
{ .hw_value = 48, .center_freq = 5240, .max_power = 25 },
{ .hw_value = 52, .center_freq = 5260, .max_power = 25 },
{ .hw_value = 56, .center_freq = 5280, .max_power = 25 },
{ .hw_value = 60, .center_freq = 5300, .max_power = 25 },
{ .hw_value = 64, .center_freq = 5320, .max_power = 25 },
{ .hw_value = 100, .center_freq = 5500, .max_power = 25 },
{ .hw_value = 104, .center_freq = 5520, .max_power = 25 },
{ .hw_value = 108, .center_freq = 5540, .max_power = 25 },
{ .hw_value = 112, .center_freq = 5560, .max_power = 25 },
{ .hw_value = 116, .center_freq = 5580, .max_power = 25 },
{ .hw_value = 120, .center_freq = 5600, .max_power = 25 },
{ .hw_value = 124, .center_freq = 5620, .max_power = 25 },
{ .hw_value = 128, .center_freq = 5640, .max_power = 25 },
{ .hw_value = 132, .center_freq = 5660, .max_power = 25 },
{ .hw_value = 136, .center_freq = 5680, .max_power = 25 },
{ .hw_value = 140, .center_freq = 5700, .max_power = 25 },
{ .hw_value = 149, .center_freq = 5745, .max_power = 25 },
{ .hw_value = 153, .center_freq = 5765, .max_power = 25 },
{ .hw_value = 157, .center_freq = 5785, .max_power = 25 },
{ .hw_value = 161, .center_freq = 5805, .max_power = 25 },
{ .hw_value = 165, .center_freq = 5825, .max_power = 25 },
};
static const u8 wl1271_rate_to_idx_5ghz[] = {
7,
7,
6,
5,
4,
3,
2,
1,
0,
7,
6,
5,
4,
CONF_HW_RXTX_RATE_UNSUPPORTED,
3,
2,
CONF_HW_RXTX_RATE_UNSUPPORTED,
1,
0,
CONF_HW_RXTX_RATE_UNSUPPORTED,
CONF_HW_RXTX_RATE_UNSUPPORTED,
CONF_HW_RXTX_RATE_UNSUPPORTED
};
static struct ieee80211_supported_band wl1271_band_5ghz = {
.channels = wl1271_channels_5ghz,
.n_channels = ARRAY_SIZE(wl1271_channels_5ghz),
.bitrates = wl1271_rates_5ghz,
.n_bitrates = ARRAY_SIZE(wl1271_rates_5ghz),
.ht_cap = WL12XX_HT_CAP,
};
static const u8 *wl1271_band_rate_to_idx[] = {
[IEEE80211_BAND_2GHZ] = wl1271_rate_to_idx_2ghz,
[IEEE80211_BAND_5GHZ] = wl1271_rate_to_idx_5ghz
};
static const struct ieee80211_ops wl1271_ops = {
.start = wl1271_op_start,
.stop = wl1271_op_stop,
.add_interface = wl1271_op_add_interface,
.remove_interface = wl1271_op_remove_interface,
.change_interface = wl12xx_op_change_interface,
#ifdef CONFIG_PM
.suspend = wl1271_op_suspend,
.resume = wl1271_op_resume,
#endif
.config = wl1271_op_config,
.prepare_multicast = wl1271_op_prepare_multicast,
.configure_filter = wl1271_op_configure_filter,
.tx = wl1271_op_tx,
.set_key = wl1271_op_set_key,
.hw_scan = wl1271_op_hw_scan,
.cancel_hw_scan = wl1271_op_cancel_hw_scan,
.sched_scan_start = wl1271_op_sched_scan_start,
.sched_scan_stop = wl1271_op_sched_scan_stop,
.bss_info_changed = wl1271_op_bss_info_changed,
.set_frag_threshold = wl1271_op_set_frag_threshold,
.set_rts_threshold = wl1271_op_set_rts_threshold,
.conf_tx = wl1271_op_conf_tx,
.get_tsf = wl1271_op_get_tsf,
.get_survey = wl1271_op_get_survey,
.sta_state = wl12xx_op_sta_state,
.ampdu_action = wl1271_op_ampdu_action,
.tx_frames_pending = wl1271_tx_frames_pending,
.set_bitrate_mask = wl12xx_set_bitrate_mask,
.channel_switch = wl12xx_op_channel_switch,
CFG80211_TESTMODE_CMD(wl1271_tm_cmd)
};
u8 wl1271_rate_to_idx(int rate, enum ieee80211_band band)
{
u8 idx;
BUG_ON(band >= sizeof(wl1271_band_rate_to_idx)/sizeof(u8 *));
if (unlikely(rate >= CONF_HW_RXTX_RATE_MAX)) {
wl1271_error("Illegal RX rate from HW: %d", rate);
return 0;
}
idx = wl1271_band_rate_to_idx[band][rate];
if (unlikely(idx == CONF_HW_RXTX_RATE_UNSUPPORTED)) {
wl1271_error("Unsupported RX rate from HW: %d", rate);
return 0;
}
return idx;
}
static ssize_t wl1271_sysfs_show_bt_coex_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct wl1271 *wl = dev_get_drvdata(dev);
ssize_t len;
len = PAGE_SIZE;
mutex_lock(&wl->mutex);
len = snprintf(buf, len, "%d\n\n0 - off\n1 - on\n",
wl->sg_enabled);
mutex_unlock(&wl->mutex);
return len;
}
static ssize_t wl1271_sysfs_store_bt_coex_state(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct wl1271 *wl = dev_get_drvdata(dev);
unsigned long res;
int ret;
ret = kstrtoul(buf, 10, &res);
if (ret < 0) {
wl1271_warning("incorrect value written to bt_coex_mode");
return count;
}
mutex_lock(&wl->mutex);
res = !!res;
if (res == wl->sg_enabled)
goto out;
wl->sg_enabled = res;
if (wl->state == WL1271_STATE_OFF)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_acx_sg_enable(wl, wl->sg_enabled);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return count;
}
static DEVICE_ATTR(bt_coex_state, S_IRUGO | S_IWUSR,
wl1271_sysfs_show_bt_coex_state,
wl1271_sysfs_store_bt_coex_state);
static ssize_t wl1271_sysfs_show_hw_pg_ver(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct wl1271 *wl = dev_get_drvdata(dev);
ssize_t len;
len = PAGE_SIZE;
mutex_lock(&wl->mutex);
if (wl->hw_pg_ver >= 0)
len = snprintf(buf, len, "%d\n", wl->hw_pg_ver);
else
len = snprintf(buf, len, "n/a\n");
mutex_unlock(&wl->mutex);
return len;
}
static DEVICE_ATTR(hw_pg_ver, S_IRUGO,
wl1271_sysfs_show_hw_pg_ver, NULL);
static ssize_t wl1271_sysfs_read_fwlog(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buffer, loff_t pos, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct wl1271 *wl = dev_get_drvdata(dev);
ssize_t len;
int ret;
ret = mutex_lock_interruptible(&wl->mutex);
if (ret < 0)
return -ERESTARTSYS;
while (wl->fwlog_size == 0) {
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(&wl->fwlog_waitq,
&wait,
TASK_INTERRUPTIBLE);
if (wl->fwlog_size != 0) {
finish_wait(&wl->fwlog_waitq, &wait);
break;
}
mutex_unlock(&wl->mutex);
schedule();
finish_wait(&wl->fwlog_waitq, &wait);
if (signal_pending(current))
return -ERESTARTSYS;
ret = mutex_lock_interruptible(&wl->mutex);
if (ret < 0)
return -ERESTARTSYS;
}
if (wl->fwlog_size < 0) {
mutex_unlock(&wl->mutex);
return 0;
}
len = min(count, (size_t)wl->fwlog_size);
wl->fwlog_size -= len;
memcpy(buffer, wl->fwlog, len);
memmove(wl->fwlog, wl->fwlog + len, wl->fwlog_size);
mutex_unlock(&wl->mutex);
return len;
}
static struct bin_attribute fwlog_attr = {
.attr = {.name = "fwlog", .mode = S_IRUSR},
.read = wl1271_sysfs_read_fwlog,
};
static bool wl12xx_mac_in_fuse(struct wl1271 *wl)
{
bool supported = false;
u8 major, minor;
if (wl->chip.id == CHIP_ID_1283_PG20) {
major = WL128X_PG_GET_MAJOR(wl->hw_pg_ver);
minor = WL128X_PG_GET_MINOR(wl->hw_pg_ver);
if (major > 2 || (major == 2 && minor >= 1))
supported = true;
} else {
major = WL127X_PG_GET_MAJOR(wl->hw_pg_ver);
minor = WL127X_PG_GET_MINOR(wl->hw_pg_ver);
if (major == 3 && minor >= 1)
supported = true;
}
wl1271_debug(DEBUG_PROBE,
"PG Ver major = %d minor = %d, MAC %s present",
major, minor, supported ? "is" : "is not");
return supported;
}
static void wl12xx_derive_mac_addresses(struct wl1271 *wl,
u32 oui, u32 nic, int n)
{
int i;
wl1271_debug(DEBUG_PROBE, "base address: oui %06x nic %06x, n %d",
oui, nic, n);
if (nic + n - 1 > 0xffffff)
wl1271_warning("NIC part of the MAC address wraps around!");
for (i = 0; i < n; i++) {
wl->addresses[i].addr[0] = (u8)(oui >> 16);
wl->addresses[i].addr[1] = (u8)(oui >> 8);
wl->addresses[i].addr[2] = (u8) oui;
wl->addresses[i].addr[3] = (u8)(nic >> 16);
wl->addresses[i].addr[4] = (u8)(nic >> 8);
wl->addresses[i].addr[5] = (u8) nic;
nic++;
}
wl->hw->wiphy->n_addresses = n;
wl->hw->wiphy->addresses = wl->addresses;
}
static void wl12xx_get_fuse_mac(struct wl1271 *wl)
{
u32 mac1, mac2;
wl1271_set_partition(wl, &wl12xx_part_table[PART_DRPW]);
mac1 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_1);
mac2 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_2);
wl->fuse_oui_addr = ((mac2 & 0xffff) << 8) +
((mac1 & 0xff000000) >> 24);
wl->fuse_nic_addr = mac1 & 0xffffff;
wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]);
}
static int wl12xx_get_hw_info(struct wl1271 *wl)
{
int ret;
u32 die_info;
ret = wl12xx_set_power_on(wl);
if (ret < 0)
goto out;
wl->chip.id = wl1271_read32(wl, CHIP_ID_B);
if (wl->chip.id == CHIP_ID_1283_PG20)
die_info = wl1271_top_reg_read(wl, WL128X_REG_FUSE_DATA_2_1);
else
die_info = wl1271_top_reg_read(wl, WL127X_REG_FUSE_DATA_2_1);
wl->hw_pg_ver = (s8) (die_info & PG_VER_MASK) >> PG_VER_OFFSET;
if (!wl12xx_mac_in_fuse(wl)) {
wl->fuse_oui_addr = 0;
wl->fuse_nic_addr = 0;
} else {
wl12xx_get_fuse_mac(wl);
}
wl1271_power_off(wl);
out:
return ret;
}
static int wl1271_register_hw(struct wl1271 *wl)
{
int ret;
u32 oui_addr = 0, nic_addr = 0;
if (wl->mac80211_registered)
return 0;
ret = wl12xx_get_hw_info(wl);
if (ret < 0) {
wl1271_error("couldn't get hw info");
goto out;
}
ret = wl1271_fetch_nvs(wl);
if (ret == 0) {
u8 *nvs_ptr = (u8 *)wl->nvs;
oui_addr =
(nvs_ptr[11] << 16) + (nvs_ptr[10] << 8) + nvs_ptr[6];
nic_addr =
(nvs_ptr[5] << 16) + (nvs_ptr[4] << 8) + nvs_ptr[3];
}
if (oui_addr == 0 && nic_addr == 0) {
oui_addr = wl->fuse_oui_addr;
nic_addr = wl->fuse_nic_addr + 1;
}
wl12xx_derive_mac_addresses(wl, oui_addr, nic_addr, 2);
ret = ieee80211_register_hw(wl->hw);
if (ret < 0) {
wl1271_error("unable to register mac80211 hw: %d", ret);
goto out;
}
wl->mac80211_registered = true;
wl1271_debugfs_init(wl);
wl1271_notice("loaded");
out:
return ret;
}
static void wl1271_unregister_hw(struct wl1271 *wl)
{
if (wl->plt)
wl1271_plt_stop(wl);
ieee80211_unregister_hw(wl->hw);
wl->mac80211_registered = false;
}
static int wl1271_init_ieee80211(struct wl1271 *wl)
{
static const u32 cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
WL1271_CIPHER_SUITE_GEM,
};
wl->hw->extra_tx_headroom = WL1271_EXTRA_SPACE_TKIP +
sizeof(struct wl1271_tx_hw_descr);
wl->hw->channel_change_time = 10000;
wl->hw->max_listen_interval = wl->conf.conn.max_listen_interval;
wl->hw->flags = IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_SUPPORTS_DYNAMIC_PS |
IEEE80211_HW_SUPPORTS_UAPSD |
IEEE80211_HW_HAS_RATE_CONTROL |
IEEE80211_HW_CONNECTION_MONITOR |
IEEE80211_HW_REPORTS_TX_ACK_STATUS |
IEEE80211_HW_SPECTRUM_MGMT |
IEEE80211_HW_AP_LINK_PS |
IEEE80211_HW_AMPDU_AGGREGATION |
IEEE80211_HW_TX_AMPDU_SETUP_IN_HW |
IEEE80211_HW_SCAN_WHILE_IDLE;
wl->hw->wiphy->cipher_suites = cipher_suites;
wl->hw->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites);
wl->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_CLIENT) | BIT(NL80211_IFTYPE_P2P_GO);
wl->hw->wiphy->max_scan_ssids = 1;
wl->hw->wiphy->max_sched_scan_ssids = 16;
wl->hw->wiphy->max_match_sets = 16;
wl->hw->wiphy->max_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE -
sizeof(struct ieee80211_header);
wl->hw->wiphy->max_sched_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE -
sizeof(struct ieee80211_header);
wl->hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD;
BUILD_BUG_ON(ARRAY_SIZE(wl1271_channels) +
ARRAY_SIZE(wl1271_channels_5ghz) >
WL1271_MAX_CHANNELS);
memcpy(&wl->bands[IEEE80211_BAND_2GHZ], &wl1271_band_2ghz,
sizeof(wl1271_band_2ghz));
memcpy(&wl->bands[IEEE80211_BAND_5GHZ], &wl1271_band_5ghz,
sizeof(wl1271_band_5ghz));
wl->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
&wl->bands[IEEE80211_BAND_2GHZ];
wl->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
&wl->bands[IEEE80211_BAND_5GHZ];
wl->hw->queues = 4;
wl->hw->max_rates = 1;
wl->hw->wiphy->reg_notifier = wl1271_reg_notify;
wl->hw->wiphy->flags |= WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD;
wl->hw->wiphy->probe_resp_offload =
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS |
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2 |
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P;
SET_IEEE80211_DEV(wl->hw, wl->dev);
wl->hw->sta_data_size = sizeof(struct wl1271_station);
wl->hw->vif_data_size = sizeof(struct wl12xx_vif);
wl->hw->max_rx_aggregation_subframes = 8;
return 0;
}
#define WL1271_DEFAULT_CHANNEL 0
static struct ieee80211_hw *wl1271_alloc_hw(void)
{
struct ieee80211_hw *hw;
struct wl1271 *wl;
int i, j, ret;
unsigned int order;
BUILD_BUG_ON(AP_MAX_STATIONS > WL12XX_MAX_LINKS);
hw = ieee80211_alloc_hw(sizeof(*wl), &wl1271_ops);
if (!hw) {
wl1271_error("could not alloc ieee80211_hw");
ret = -ENOMEM;
goto err_hw_alloc;
}
wl = hw->priv;
memset(wl, 0, sizeof(*wl));
INIT_LIST_HEAD(&wl->wlvif_list);
wl->hw = hw;
for (i = 0; i < NUM_TX_QUEUES; i++)
for (j = 0; j < WL12XX_MAX_LINKS; j++)
skb_queue_head_init(&wl->links[j].tx_queue[i]);
skb_queue_head_init(&wl->deferred_rx_queue);
skb_queue_head_init(&wl->deferred_tx_queue);
INIT_DELAYED_WORK(&wl->elp_work, wl1271_elp_work);
INIT_WORK(&wl->netstack_work, wl1271_netstack_work);
INIT_WORK(&wl->tx_work, wl1271_tx_work);
INIT_WORK(&wl->recovery_work, wl1271_recovery_work);
INIT_DELAYED_WORK(&wl->scan_complete_work, wl1271_scan_complete_work);
INIT_DELAYED_WORK(&wl->tx_watchdog_work, wl12xx_tx_watchdog_work);
wl->freezable_wq = create_freezable_workqueue("wl12xx_wq");
if (!wl->freezable_wq) {
ret = -ENOMEM;
goto err_hw;
}
wl->channel = WL1271_DEFAULT_CHANNEL;
wl->rx_counter = 0;
wl->power_level = WL1271_DEFAULT_POWER_LEVEL;
wl->band = IEEE80211_BAND_2GHZ;
wl->flags = 0;
wl->sg_enabled = true;
wl->hw_pg_ver = -1;
wl->ap_ps_map = 0;
wl->ap_fw_ps_map = 0;
wl->quirks = 0;
wl->platform_quirks = 0;
wl->sched_scanning = false;
wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
wl->system_hlid = WL12XX_SYSTEM_HLID;
wl->active_sta_count = 0;
wl->fwlog_size = 0;
init_waitqueue_head(&wl->fwlog_waitq);
__set_bit(WL12XX_SYSTEM_HLID, wl->links_map);
memset(wl->tx_frames_map, 0, sizeof(wl->tx_frames_map));
for (i = 0; i < ACX_TX_DESCRIPTORS; i++)
wl->tx_frames[i] = NULL;
spin_lock_init(&wl->wl_lock);
wl->state = WL1271_STATE_OFF;
wl->fw_type = WL12XX_FW_TYPE_NONE;
mutex_init(&wl->mutex);
wl1271_conf_init(wl);
order = get_order(WL1271_AGGR_BUFFER_SIZE);
wl->aggr_buf = (u8 *)__get_free_pages(GFP_KERNEL, order);
if (!wl->aggr_buf) {
ret = -ENOMEM;
goto err_wq;
}
wl->dummy_packet = wl12xx_alloc_dummy_packet(wl);
if (!wl->dummy_packet) {
ret = -ENOMEM;
goto err_aggr;
}
wl->fwlog = (u8 *)get_zeroed_page(GFP_KERNEL);
if (!wl->fwlog) {
ret = -ENOMEM;
goto err_dummy_packet;
}
return hw;
err_dummy_packet:
dev_kfree_skb(wl->dummy_packet);
err_aggr:
free_pages((unsigned long)wl->aggr_buf, order);
err_wq:
destroy_workqueue(wl->freezable_wq);
err_hw:
wl1271_debugfs_exit(wl);
ieee80211_free_hw(hw);
err_hw_alloc:
return ERR_PTR(ret);
}
static int wl1271_free_hw(struct wl1271 *wl)
{
mutex_lock(&wl->mutex);
wl->fwlog_size = -1;
wake_up_interruptible_all(&wl->fwlog_waitq);
mutex_unlock(&wl->mutex);
device_remove_bin_file(wl->dev, &fwlog_attr);
device_remove_file(wl->dev, &dev_attr_hw_pg_ver);
device_remove_file(wl->dev, &dev_attr_bt_coex_state);
free_page((unsigned long)wl->fwlog);
dev_kfree_skb(wl->dummy_packet);
free_pages((unsigned long)wl->aggr_buf,
get_order(WL1271_AGGR_BUFFER_SIZE));
wl1271_debugfs_exit(wl);
vfree(wl->fw);
wl->fw = NULL;
wl->fw_type = WL12XX_FW_TYPE_NONE;
kfree(wl->nvs);
wl->nvs = NULL;
kfree(wl->fw_status);
kfree(wl->tx_res_if);
destroy_workqueue(wl->freezable_wq);
ieee80211_free_hw(wl->hw);
return 0;
}
static irqreturn_t wl12xx_hardirq(int irq, void *cookie)
{
struct wl1271 *wl = cookie;
unsigned long flags;
wl1271_debug(DEBUG_IRQ, "IRQ");
spin_lock_irqsave(&wl->wl_lock, flags);
set_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags);
if (wl->elp_compl) {
complete(wl->elp_compl);
wl->elp_compl = NULL;
}
if (test_bit(WL1271_FLAG_SUSPENDED, &wl->flags)) {
set_bit(WL1271_FLAG_PENDING_WORK, &wl->flags);
wl1271_debug(DEBUG_IRQ, "should not enqueue work");
disable_irq_nosync(wl->irq);
pm_wakeup_event(wl->dev, 0);
spin_unlock_irqrestore(&wl->wl_lock, flags);
return IRQ_HANDLED;
}
spin_unlock_irqrestore(&wl->wl_lock, flags);
return IRQ_WAKE_THREAD;
}
static int __devinit wl12xx_probe(struct platform_device *pdev)
{
struct wl12xx_platform_data *pdata = pdev->dev.platform_data;
struct ieee80211_hw *hw;
struct wl1271 *wl;
unsigned long irqflags;
int ret = -ENODEV;
hw = wl1271_alloc_hw();
if (IS_ERR(hw)) {
wl1271_error("can't allocate hw");
ret = PTR_ERR(hw);
goto out;
}
wl = hw->priv;
wl->irq = platform_get_irq(pdev, 0);
wl->ref_clock = pdata->board_ref_clock;
wl->tcxo_clock = pdata->board_tcxo_clock;
wl->platform_quirks = pdata->platform_quirks;
wl->set_power = pdata->set_power;
wl->dev = &pdev->dev;
wl->if_ops = pdata->ops;
platform_set_drvdata(pdev, wl);
if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ)
irqflags = IRQF_TRIGGER_RISING;
else
irqflags = IRQF_TRIGGER_HIGH | IRQF_ONESHOT;
ret = request_threaded_irq(wl->irq, wl12xx_hardirq, wl1271_irq,
irqflags,
pdev->name, wl);
if (ret < 0) {
wl1271_error("request_irq() failed: %d", ret);
goto out_free_hw;
}
ret = enable_irq_wake(wl->irq);
if (!ret) {
wl->irq_wake_enabled = true;
device_init_wakeup(wl->dev, 1);
if (pdata->pwr_in_suspend)
hw->wiphy->wowlan.flags = WIPHY_WOWLAN_ANY;
}
disable_irq(wl->irq);
ret = wl1271_init_ieee80211(wl);
if (ret)
goto out_irq;
ret = wl1271_register_hw(wl);
if (ret)
goto out_irq;
ret = device_create_file(wl->dev, &dev_attr_bt_coex_state);
if (ret < 0) {
wl1271_error("failed to create sysfs file bt_coex_state");
goto out_irq;
}
ret = device_create_file(wl->dev, &dev_attr_hw_pg_ver);
if (ret < 0) {
wl1271_error("failed to create sysfs file hw_pg_ver");
goto out_bt_coex_state;
}
ret = device_create_bin_file(wl->dev, &fwlog_attr);
if (ret < 0) {
wl1271_error("failed to create sysfs file fwlog");
goto out_hw_pg_ver;
}
return 0;
out_hw_pg_ver:
device_remove_file(wl->dev, &dev_attr_hw_pg_ver);
out_bt_coex_state:
device_remove_file(wl->dev, &dev_attr_bt_coex_state);
out_irq:
free_irq(wl->irq, wl);
out_free_hw:
wl1271_free_hw(wl);
out:
return ret;
}
static int __devexit wl12xx_remove(struct platform_device *pdev)
{
struct wl1271 *wl = platform_get_drvdata(pdev);
if (wl->irq_wake_enabled) {
device_init_wakeup(wl->dev, 0);
disable_irq_wake(wl->irq);
}
wl1271_unregister_hw(wl);
free_irq(wl->irq, wl);
wl1271_free_hw(wl);
return 0;
}
static const struct platform_device_id wl12xx_id_table[] __devinitconst = {
{ "wl12xx", 0 },
{ }
};
MODULE_DEVICE_TABLE(platform, wl12xx_id_table);
static struct platform_driver wl12xx_driver = {
.probe = wl12xx_probe,
.remove = __devexit_p(wl12xx_remove),
.id_table = wl12xx_id_table,
.driver = {
.name = "wl12xx_driver",
.owner = THIS_MODULE,
}
};
static int __init wl12xx_init(void)
{
return platform_driver_register(&wl12xx_driver);
}
module_init(wl12xx_init);
static void __exit wl12xx_exit(void)
{
platform_driver_unregister(&wl12xx_driver);
}
module_exit(wl12xx_exit);
u32 wl12xx_debug_level = DEBUG_NONE;
EXPORT_SYMBOL_GPL(wl12xx_debug_level);
module_param_named(debug_level, wl12xx_debug_level, uint, S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(debug_level, "wl12xx debugging level");
module_param_named(fwlog, fwlog_param, charp, 0);
MODULE_PARM_DESC(fwlog,
"FW logger options: continuous, ondemand, dbgpins or disable");
module_param(bug_on_recovery, bool, S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(bug_on_recovery, "BUG() on fw recovery");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Luciano Coelho <coelho@ti.com>");
MODULE_AUTHOR("Juuso Oikarinen <juuso.oikarinen@nokia.com>");
| gpl-2.0 |
marcoxx626/M8_Kernel_Sense | drivers/scsi/aic7xxx_old.c | 34 | 252662 | /*+M*************************************************************************
* Adaptec AIC7xxx device driver for Linux.
*
* Copyright (c) 1994 John Aycock
* The University of Calgary Department of Computer Science.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Sources include the Adaptec 1740 driver (aha1740.c), the Ultrastor 24F
* driver (ultrastor.c), various Linux kernel source, the Adaptec EISA
* config file (!adp7771.cfg), the Adaptec AHA-2740A Series User's Guide,
* the Linux Kernel Hacker's Guide, Writing a SCSI Device Driver for Linux,
* the Adaptec 1542 driver (aha1542.c), the Adaptec EISA overlay file
* (adp7770.ovl), the Adaptec AHA-2740 Series Technical Reference Manual,
* the Adaptec AIC-7770 Data Book, the ANSI SCSI specification, the
* ANSI SCSI-2 specification (draft 10c), ...
*
* --------------------------------------------------------------------------
*
* Modifications by Daniel M. Eischen (deischen@iworks.InterWorks.org):
*
* Substantially modified to include support for wide and twin bus
* adapters, DMAing of SCBs, tagged queueing, IRQ sharing, bug fixes,
* SCB paging, and other rework of the code.
*
* Parts of this driver were also based on the FreeBSD driver by
* Justin T. Gibbs. His copyright follows:
*
* --------------------------------------------------------------------------
* Copyright (c) 1994-1997 Justin Gibbs.
* 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, immediately at the beginning of the file.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Where this Software is combined with software released under the terms of
* the GNU General Public License ("GPL") and the terms of the GPL would require the
* combined work to also be released under the terms of the GPL, the terms
* and conditions of this License will apply in addition to those of the
* GPL with the exception of any terms or conditions of this License that
* conflict with, or are expressly prohibited by, the GPL.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: aic7xxx.c,v 1.119 1997/06/27 19:39:18 gibbs Exp $
*---------------------------------------------------------------------------
*
* Thanks also go to (in alphabetical order) the following:
*
* Rory Bolt - Sequencer bug fixes
* Jay Estabrook - Initial DEC Alpha support
* Doug Ledford - Much needed abort/reset bug fixes
* Kai Makisara - DMAing of SCBs
*
* A Boot time option was also added for not resetting the scsi bus.
*
* Form: aic7xxx=extended
* aic7xxx=no_reset
* aic7xxx=ultra
* aic7xxx=irq_trigger:[0,1] # 0 edge, 1 level
* aic7xxx=verbose
*
* Daniel M. Eischen, deischen@iworks.InterWorks.org, 1/23/97
*
* $Id: aic7xxx.c,v 4.1 1997/06/12 08:23:42 deang Exp $
*-M*************************************************************************/
/*+M**************************************************************************
*
* Further driver modifications made by Doug Ledford <dledford@redhat.com>
*
* Copyright (c) 1997-1999 Doug Ledford
*
* These changes are released under the same licensing terms as the FreeBSD
* driver written by Justin Gibbs. Please see his Copyright notice above
* for the exact terms and conditions covering my changes as well as the
* warranty statement.
*
* Modifications made to the aic7xxx.c,v 4.1 driver from Dan Eischen include
* but are not limited to:
*
* 1: Import of the latest FreeBSD sequencer code for this driver
* 2: Modification of kernel code to accommodate different sequencer semantics
* 3: Extensive changes throughout kernel portion of driver to improve
* abort/reset processing and error hanndling
* 4: Other work contributed by various people on the Internet
* 5: Changes to printk information and verbosity selection code
* 6: General reliability related changes, especially in IRQ management
* 7: Modifications to the default probe/attach order for supported cards
* 8: SMP friendliness has been improved
*
* Overall, this driver represents a significant departure from the official
* aic7xxx driver released by Dan Eischen in two ways. First, in the code
* itself. A diff between the two version of the driver is now a several
* thousand line diff. Second, in approach to solving the same problem. The
* problem is importing the FreeBSD aic7xxx driver code to linux can be a
* difficult and time consuming process, that also can be error prone. Dan
* Eischen's official driver uses the approach that the linux and FreeBSD
* drivers should be as identical as possible. To that end, his next version
* of this driver will be using a mid-layer code library that he is developing
* to moderate communications between the linux mid-level SCSI code and the
* low level FreeBSD driver. He intends to be able to essentially drop the
* FreeBSD driver into the linux kernel with only a few minor tweaks to some
* include files and the like and get things working, making for fast easy
* imports of the FreeBSD code into linux.
*
* I disagree with Dan's approach. Not that I don't think his way of doing
* things would be nice, easy to maintain, and create a more uniform driver
* between FreeBSD and Linux. I have no objection to those issues. My
* disagreement is on the needed functionality. There simply are certain
* things that are done differently in FreeBSD than linux that will cause
* problems for this driver regardless of any middle ware Dan implements.
* The biggest example of this at the moment is interrupt semantics. Linux
* doesn't provide the same protection techniques as FreeBSD does, nor can
* they be easily implemented in any middle ware code since they would truly
* belong in the kernel proper and would effect all drivers. For the time
* being, I see issues such as these as major stumbling blocks to the
* reliability of code based upon such middle ware. Therefore, I choose to
* use a different approach to importing the FreeBSD code that doesn't
* involve any middle ware type code. My approach is to import the sequencer
* code from FreeBSD wholesale. Then, to only make changes in the kernel
* portion of the driver as they are needed for the new sequencer semantics.
* In this way, the portion of the driver that speaks to the rest of the
* linux kernel is fairly static and can be changed/modified to solve
* any problems one might encounter without concern for the FreeBSD driver.
*
* Note: If time and experience should prove me wrong that the middle ware
* code Dan writes is reliable in its operation, then I'll retract my above
* statements. But, for those that don't know, I'm from Missouri (in the US)
* and our state motto is "The Show-Me State". Well, before I will put
* faith into it, you'll have to show me that it works :)
*
*_M*************************************************************************/
#define AIC7XXX_STRICT_PCI_SETUP
#include <linux/module.h>
#include <stdarg.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/byteorder.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/proc_fs.h>
#include <linux/blkdev.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "aic7xxx_old/aic7xxx.h"
#include "aic7xxx_old/sequencer.h"
#include "aic7xxx_old/scsi_message.h"
#include "aic7xxx_old/aic7xxx_reg.h"
#include <scsi/scsicam.h>
#include <linux/stat.h>
#include <linux/slab.h>
#define AIC7XXX_C_VERSION "5.2.6"
#define ALL_TARGETS -1
#define ALL_CHANNELS -1
#define ALL_LUNS -1
#define MAX_TARGETS 16
#define MAX_LUNS 8
#ifndef TRUE
# define TRUE 1
#endif
#ifndef FALSE
# define FALSE 0
#endif
#if defined(__powerpc__) || defined(__i386__) || defined(__x86_64__)
# define MMAPIO
#endif
#define AIC7XXX_CMDS_PER_DEVICE 32
typedef struct
{
unsigned char tag_commands[16];
} adapter_tag_info_t;
#define DEFAULT_TAG_COMMANDS {0, 0, 0, 0, 0, 0, 0, 0,\
0, 0, 0, 0, 0, 0, 0, 0}
static adapter_tag_info_t aic7xxx_tag_info[] =
{
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS},
{DEFAULT_TAG_COMMANDS}
};
static const char *board_names[] = {
"AIC-7xxx Unknown",
"Adaptec AIC-7810 Hardware RAID Controller",
"Adaptec AIC-7770 SCSI host adapter",
"Adaptec AHA-274X SCSI host adapter",
"Adaptec AHA-284X SCSI host adapter",
"Adaptec AIC-7850 SCSI host adapter",
"Adaptec AIC-7855 SCSI host adapter",
"Adaptec AIC-7860 Ultra SCSI host adapter",
"Adaptec AHA-2940A Ultra SCSI host adapter",
"Adaptec AIC-7870 SCSI host adapter",
"Adaptec AHA-294X SCSI host adapter",
"Adaptec AHA-394X SCSI host adapter",
"Adaptec AHA-398X SCSI host adapter",
"Adaptec AHA-2944 SCSI host adapter",
"Adaptec AIC-7880 Ultra SCSI host adapter",
"Adaptec AHA-294X Ultra SCSI host adapter",
"Adaptec AHA-394X Ultra SCSI host adapter",
"Adaptec AHA-398X Ultra SCSI host adapter",
"Adaptec AHA-2944 Ultra SCSI host adapter",
"Adaptec AHA-2940UW Pro Ultra SCSI host adapter",
"Adaptec AIC-7895 Ultra SCSI host adapter",
"Adaptec AIC-7890/1 Ultra2 SCSI host adapter",
"Adaptec AHA-293X Ultra2 SCSI host adapter",
"Adaptec AHA-294X Ultra2 SCSI host adapter",
"Adaptec AIC-7896/7 Ultra2 SCSI host adapter",
"Adaptec AHA-394X Ultra2 SCSI host adapter",
"Adaptec AHA-395X Ultra2 SCSI host adapter",
"Adaptec PCMCIA SCSI controller",
"Adaptec AIC-7892 Ultra 160/m SCSI host adapter",
"Adaptec AIC-7899 Ultra 160/m SCSI host adapter",
};
#define DID_UNDERFLOW DID_ERROR
#define DID_RETRY_COMMAND DID_ERROR
#define HSCSIID 0x07
#define SCSI_RESET 0x040
#define MINSLOT 1
#define MAXSLOT 15
#define SLOTBASE(x) ((x) << 12)
#define BASE_TO_SLOT(x) ((x) >> 12)
#define AHC_HID0 0x80
#define AHC_HID1 0x81
#define AHC_HID2 0x82
#define AHC_HID3 0x83
#define MINREG 0xC00
#define MAXREG 0xCFF
#define INTDEF 0x5C
#define CLASS_PROGIF_REVID 0x08
#define DEVREVID 0x000000FFul
#define PROGINFC 0x0000FF00ul
#define SUBCLASS 0x00FF0000ul
#define BASECLASS 0xFF000000ul
#define CSIZE_LATTIME 0x0C
#define CACHESIZE 0x0000003Ful
#define LATTIME 0x0000FF00ul
#define DEVCONFIG 0x40
#define SCBSIZE32 0x00010000ul
#define MPORTMODE 0x00000400ul
#define RAMPSM 0x00000200ul
#define RAMPSM_ULTRA2 0x00000004
#define VOLSENSE 0x00000100ul
#define SCBRAMSEL 0x00000080ul
#define SCBRAMSEL_ULTRA2 0x00000008
#define MRDCEN 0x00000040ul
#define EXTSCBTIME 0x00000020ul
#define EXTSCBPEN 0x00000010ul
#define BERREN 0x00000008ul
#define DACEN 0x00000004ul
#define STPWLEVEL 0x00000002ul
#define DIFACTNEGEN 0x00000001ul
#define SCAMCTL 0x1a
#define CCSCBBADDR 0xf0
typedef enum {C46 = 6, C56_66 = 8} seeprom_chip_type;
struct seeprom_config {
#define CFXFER 0x0007
#define CFSYNCH 0x0008
#define CFDISC 0x0010
#define CFWIDEB 0x0020
#define CFSYNCHISULTRA 0x0040
#define CFNEWULTRAFORMAT 0x0080
#define CFSTART 0x0100
#define CFINCBIOS 0x0200
#define CFRNFOUND 0x0400
#define CFMULTILUN 0x0800
#define CFWBCACHEYES 0x4000
#define CFWBCACHENC 0xc000
unsigned short device_flags[16];
#define CFSUPREM 0x0001
#define CFSUPREMB 0x0002
#define CFBIOSEN 0x0004
#define CFSM2DRV 0x0010
#define CF284XEXTEND 0x0020
#define CFEXTEND 0x0080
unsigned short bios_control;
#define CFAUTOTERM 0x0001
#define CFULTRAEN 0x0002
#define CF284XSELTO 0x0003
#define CF284XFIFO 0x000C
#define CFSTERM 0x0004
#define CFWSTERM 0x0008
#define CFSPARITY 0x0010
#define CF284XSTERM 0x0020
#define CFRESETB 0x0040
#define CFBPRIMARY 0x0100
#define CFSEAUTOTERM 0x0400
#define CFLVDSTERM 0x0800
unsigned short adapter_control;
#define CFSCSIID 0x000F
#define CFBRTIME 0xFF00
unsigned short brtime_id;
#define CFMAXTARG 0x00FF
unsigned short max_targets;
unsigned short res_1[11];
unsigned short checksum;
};
#define SELBUS_MASK 0x0a
#define SELNARROW 0x00
#define SELBUSB 0x08
#define SINGLE_BUS 0x00
#define SCB_TARGET(scb) \
(((scb)->hscb->target_channel_lun & TID) >> 4)
#define SCB_LUN(scb) \
((scb)->hscb->target_channel_lun & LID)
#define SCB_IS_SCSIBUS_B(scb) \
(((scb)->hscb->target_channel_lun & SELBUSB) != 0)
#define aic7xxx_error(cmd) ((cmd)->SCp.Status)
#define aic7xxx_status(cmd) ((cmd)->SCp.sent_command)
#define aic7xxx_position(cmd) ((cmd)->SCp.have_data_in)
#define aic7xxx_mapping(cmd) ((cmd)->SCp.phase)
#define AIC_DEV(cmd) ((struct aic_dev_data *)(cmd)->device->hostdata)
static struct aic7xxx_host *first_aic7xxx = NULL;
struct hw_scatterlist {
unsigned int address;
unsigned int length;
};
#define AIC7XXX_MAX_SG 128
#define AIC7XXX_MAXSCB 255
struct aic7xxx_hwscb {
unsigned char control;
unsigned char target_channel_lun;
unsigned char target_status;
unsigned char SG_segment_count;
unsigned int SG_list_pointer;
unsigned char residual_SG_segment_count;
unsigned char residual_data_count[3];
unsigned int data_pointer;
unsigned int data_count;
unsigned int SCSI_cmd_pointer;
unsigned char SCSI_cmd_length;
unsigned char tag;
#define SCB_PIO_TRANSFER_SIZE 26
unsigned char next;
unsigned char prev;
unsigned int pad;
};
typedef enum {
SCB_FREE = 0x0000,
SCB_DTR_SCB = 0x0001,
SCB_WAITINGQ = 0x0002,
SCB_ACTIVE = 0x0004,
SCB_SENSE = 0x0008,
SCB_ABORT = 0x0010,
SCB_DEVICE_RESET = 0x0020,
SCB_RESET = 0x0040,
SCB_RECOVERY_SCB = 0x0080,
SCB_MSGOUT_PPR = 0x0100,
SCB_MSGOUT_SENT = 0x0200,
SCB_MSGOUT_SDTR = 0x0400,
SCB_MSGOUT_WDTR = 0x0800,
SCB_MSGOUT_BITS = SCB_MSGOUT_PPR |
SCB_MSGOUT_SENT |
SCB_MSGOUT_SDTR |
SCB_MSGOUT_WDTR,
SCB_QUEUED_ABORT = 0x1000,
SCB_QUEUED_FOR_DONE = 0x2000,
SCB_WAS_BUSY = 0x4000,
SCB_QUEUE_FULL = 0x8000
} scb_flag_type;
typedef enum {
AHC_FNONE = 0x00000000,
AHC_PAGESCBS = 0x00000001,
AHC_CHANNEL_B_PRIMARY = 0x00000002,
AHC_USEDEFAULTS = 0x00000004,
AHC_INDIRECT_PAGING = 0x00000008,
AHC_CHNLB = 0x00000020,
AHC_CHNLC = 0x00000040,
AHC_EXTEND_TRANS_A = 0x00000100,
AHC_EXTEND_TRANS_B = 0x00000200,
AHC_TERM_ENB_A = 0x00000400,
AHC_TERM_ENB_SE_LOW = 0x00000400,
AHC_TERM_ENB_B = 0x00000800,
AHC_TERM_ENB_SE_HIGH = 0x00000800,
AHC_HANDLING_REQINITS = 0x00001000,
AHC_TARGETMODE = 0x00002000,
AHC_NEWEEPROM_FMT = 0x00004000,
AHC_MOTHERBOARD = 0x00020000,
AHC_NO_STPWEN = 0x00040000,
AHC_RESET_DELAY = 0x00080000,
AHC_A_SCANNED = 0x00100000,
AHC_B_SCANNED = 0x00200000,
AHC_MULTI_CHANNEL = 0x00400000,
AHC_BIOS_ENABLED = 0x00800000,
AHC_SEEPROM_FOUND = 0x01000000,
AHC_TERM_ENB_LVD = 0x02000000,
AHC_ABORT_PENDING = 0x04000000,
AHC_RESET_PENDING = 0x08000000,
#define AHC_IN_ISR_BIT 28
AHC_IN_ISR = 0x10000000,
AHC_IN_ABORT = 0x20000000,
AHC_IN_RESET = 0x40000000,
AHC_EXTERNAL_SRAM = 0x80000000
} ahc_flag_type;
typedef enum {
AHC_NONE = 0x0000,
AHC_CHIPID_MASK = 0x00ff,
AHC_AIC7770 = 0x0001,
AHC_AIC7850 = 0x0002,
AHC_AIC7860 = 0x0003,
AHC_AIC7870 = 0x0004,
AHC_AIC7880 = 0x0005,
AHC_AIC7890 = 0x0006,
AHC_AIC7895 = 0x0007,
AHC_AIC7896 = 0x0008,
AHC_AIC7892 = 0x0009,
AHC_AIC7899 = 0x000a,
AHC_VL = 0x0100,
AHC_EISA = 0x0200,
AHC_PCI = 0x0400,
} ahc_chip;
typedef enum {
AHC_FENONE = 0x0000,
AHC_ULTRA = 0x0001,
AHC_ULTRA2 = 0x0002,
AHC_WIDE = 0x0004,
AHC_TWIN = 0x0008,
AHC_MORE_SRAM = 0x0010,
AHC_CMD_CHAN = 0x0020,
AHC_QUEUE_REGS = 0x0040,
AHC_SG_PRELOAD = 0x0080,
AHC_SPIOCAP = 0x0100,
AHC_ULTRA3 = 0x0200,
AHC_NEW_AUTOTERM = 0x0400,
AHC_AIC7770_FE = AHC_FENONE,
AHC_AIC7850_FE = AHC_SPIOCAP,
AHC_AIC7860_FE = AHC_ULTRA|AHC_SPIOCAP,
AHC_AIC7870_FE = AHC_FENONE,
AHC_AIC7880_FE = AHC_ULTRA,
AHC_AIC7890_FE = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA2|
AHC_QUEUE_REGS|AHC_SG_PRELOAD|AHC_NEW_AUTOTERM,
AHC_AIC7895_FE = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA,
AHC_AIC7896_FE = AHC_AIC7890_FE,
AHC_AIC7892_FE = AHC_AIC7890_FE|AHC_ULTRA3,
AHC_AIC7899_FE = AHC_AIC7890_FE|AHC_ULTRA3,
} ahc_feature;
#define SCB_DMA_ADDR(scb, addr) ((unsigned long)(addr) + (scb)->scb_dma->dma_offset)
struct aic7xxx_scb_dma {
unsigned long dma_offset;
dma_addr_t dma_address;
unsigned int dma_len;
};
typedef enum {
AHC_BUG_NONE = 0x0000,
AHC_BUG_TMODE_WIDEODD = 0x0001,
AHC_BUG_AUTOFLUSH = 0x0002,
AHC_BUG_CACHETHEN = 0x0004,
AHC_BUG_CACHETHEN_DIS = 0x0008,
AHC_BUG_PCI_2_1_RETRY = 0x0010,
AHC_BUG_PCI_MWI = 0x0020,
AHC_BUG_SCBCHAN_UPLOAD = 0x0040,
} ahc_bugs;
struct aic7xxx_scb {
struct aic7xxx_hwscb *hscb;
struct scsi_cmnd *cmd;
struct aic7xxx_scb *q_next;
volatile scb_flag_type flags;
struct hw_scatterlist *sg_list;
unsigned char tag_action;
unsigned char sg_count;
unsigned char *sense_cmd;
unsigned char *cmnd;
unsigned int sg_length;
void *kmalloc_ptr;
struct aic7xxx_scb_dma *scb_dma;
};
typedef struct {
struct aic7xxx_scb *head;
struct aic7xxx_scb *tail;
} scb_queue_type;
static struct {
unsigned char errno;
const char *errmesg;
} hard_error[] = {
{ ILLHADDR, "Illegal Host Access" },
{ ILLSADDR, "Illegal Sequencer Address referenced" },
{ ILLOPCODE, "Illegal Opcode in sequencer program" },
{ SQPARERR, "Sequencer Ram Parity Error" },
{ DPARERR, "Data-Path Ram Parity Error" },
{ MPARERR, "Scratch Ram/SCB Array Ram Parity Error" },
{ PCIERRSTAT,"PCI Error detected" },
{ CIOPARERR, "CIOBUS Parity Error" }
};
static unsigned char
generic_sense[] = { REQUEST_SENSE, 0, 0, 0, 255, 0 };
typedef struct {
scb_queue_type free_scbs;
struct aic7xxx_scb *scb_array[AIC7XXX_MAXSCB];
struct aic7xxx_hwscb *hscbs;
unsigned char numscbs;
unsigned char maxhscbs;
unsigned char maxscbs;
dma_addr_t hscbs_dma;
unsigned int hscbs_dma_len;
void *hscb_kmalloc_ptr;
} scb_data_type;
struct target_cmd {
unsigned char mesg_bytes[4];
unsigned char command[28];
};
#define AHC_TRANS_CUR 0x0001
#define AHC_TRANS_ACTIVE 0x0002
#define AHC_TRANS_GOAL 0x0004
#define AHC_TRANS_USER 0x0008
#define AHC_TRANS_QUITE 0x0010
typedef struct {
unsigned char width;
unsigned char period;
unsigned char offset;
unsigned char options;
} transinfo_type;
struct aic_dev_data {
volatile scb_queue_type delayed_scbs;
volatile unsigned short temp_q_depth;
unsigned short max_q_depth;
volatile unsigned char active_cmds;
long w_total;
long r_total;
long barrier_total;
long ordered_total;
long w_bins[6];
long r_bins[6];
transinfo_type cur;
transinfo_type goal;
#define BUS_DEVICE_RESET_PENDING 0x01
#define DEVICE_RESET_DELAY 0x02
#define DEVICE_PRINT_DTR 0x04
#define DEVICE_WAS_BUSY 0x08
#define DEVICE_DTR_SCANNED 0x10
#define DEVICE_SCSI_3 0x20
volatile unsigned char flags;
unsigned needppr:1;
unsigned needppr_copy:1;
unsigned needsdtr:1;
unsigned needsdtr_copy:1;
unsigned needwdtr:1;
unsigned needwdtr_copy:1;
unsigned dtr_pending:1;
struct scsi_device *SDptr;
struct list_head list;
};
struct aic7xxx_host {
/*
* We are grouping things here....first, items that get either read or
* written with nearly every interrupt
*/
volatile long flags;
ahc_feature features;
unsigned long base;
volatile unsigned char __iomem *maddr;
unsigned long isr_count;
unsigned long spurious_int;
scb_data_type *scb_data;
struct aic7xxx_cmd_queue {
struct scsi_cmnd *head;
struct scsi_cmnd *tail;
} completeq;
/*
* Things read/written on nearly every entry into aic7xxx_queue()
*/
volatile scb_queue_type waiting_scbs;
unsigned char unpause;
unsigned char pause;
volatile unsigned char qoutfifonext;
volatile unsigned char activescbs;
volatile unsigned char max_activescbs;
volatile unsigned char qinfifonext;
volatile unsigned char *untagged_scbs;
volatile unsigned char *qoutfifo;
volatile unsigned char *qinfifo;
unsigned char dev_last_queue_full[MAX_TARGETS];
unsigned char dev_last_queue_full_count[MAX_TARGETS];
unsigned short ultraenb;
unsigned short discenable;
transinfo_type user[MAX_TARGETS];
unsigned char msg_buf[13];
unsigned char msg_type;
#define MSG_TYPE_NONE 0x00
#define MSG_TYPE_INITIATOR_MSGOUT 0x01
#define MSG_TYPE_INITIATOR_MSGIN 0x02
unsigned char msg_len;
unsigned char msg_index;
unsigned int irq;
int instance;
int scsi_id;
int scsi_id_b;
unsigned int bios_address;
int board_name_index;
unsigned short bios_control;
unsigned short adapter_control;
struct pci_dev *pdev;
unsigned char pci_bus;
unsigned char pci_device_fn;
struct seeprom_config sc;
unsigned short sc_type;
unsigned short sc_size;
struct aic7xxx_host *next;
struct Scsi_Host *host;
struct list_head aic_devs;
int host_no;
unsigned long mbase;
ahc_chip chip;
ahc_bugs bugs;
dma_addr_t fifo_dma;
};
#define AHC_SYNCRATE_ULTRA3 0
#define AHC_SYNCRATE_ULTRA2 1
#define AHC_SYNCRATE_ULTRA 3
#define AHC_SYNCRATE_FAST 6
#define AHC_SYNCRATE_CRC 0x40
#define AHC_SYNCRATE_SE 0x10
static struct aic7xxx_syncrate {
#define ULTRA_SXFR 0x100
int sxfr_ultra2;
int sxfr;
unsigned char period;
const char *rate[2];
} aic7xxx_syncrates[] = {
{ 0x42, 0x000, 9, {"80.0", "160.0"} },
{ 0x13, 0x000, 10, {"40.0", "80.0"} },
{ 0x14, 0x000, 11, {"33.0", "66.6"} },
{ 0x15, 0x100, 12, {"20.0", "40.0"} },
{ 0x16, 0x110, 15, {"16.0", "32.0"} },
{ 0x17, 0x120, 18, {"13.4", "26.8"} },
{ 0x18, 0x000, 25, {"10.0", "20.0"} },
{ 0x19, 0x010, 31, {"8.0", "16.0"} },
{ 0x1a, 0x020, 37, {"6.67", "13.3"} },
{ 0x1b, 0x030, 43, {"5.7", "11.4"} },
{ 0x10, 0x040, 50, {"5.0", "10.0"} },
{ 0x00, 0x050, 56, {"4.4", "8.8" } },
{ 0x00, 0x060, 62, {"4.0", "8.0" } },
{ 0x00, 0x070, 68, {"3.6", "7.2" } },
{ 0x00, 0x000, 0, {NULL, NULL} },
};
#define CTL_OF_SCB(scb) (((scb->hscb)->target_channel_lun >> 3) & 0x1), \
(((scb->hscb)->target_channel_lun >> 4) & 0xf), \
((scb->hscb)->target_channel_lun & 0x07)
#define CTL_OF_CMD(cmd) ((cmd->device->channel) & 0x01), \
((cmd->device->id) & 0x0f), \
((cmd->device->lun) & 0x07)
#define TARGET_INDEX(cmd) ((cmd)->device->id | ((cmd)->device->channel << 3))
#define WARN_LEAD KERN_WARNING "(scsi%d:%d:%d:%d) "
#define INFO_LEAD KERN_INFO "(scsi%d:%d:%d:%d) "
static unsigned int aic7xxx_default_queue_depth = AIC7XXX_CMDS_PER_DEVICE;
static unsigned int aic7xxx_no_reset = 0;
static int aic7xxx_reverse_scan = 0;
static unsigned int aic7xxx_extended = 0;
static int aic7xxx_irq_trigger = -1;
static int aic7xxx_override_term = -1;
static int aic7xxx_stpwlev = -1;
static int aic7xxx_panic_on_abort = 0;
static int aic7xxx_pci_parity = 0;
static int aic7xxx_dump_card = 0;
static int aic7xxx_dump_sequencer = 0;
static int aic7xxx_no_probe = 0;
static int aic7xxx_scbram = 0;
static int aic7xxx_seltime = 0x10;
#ifdef MODULE
static char * aic7xxx = NULL;
module_param(aic7xxx, charp, 0);
#endif
#define VERBOSE_NORMAL 0x0000
#define VERBOSE_NEGOTIATION 0x0001
#define VERBOSE_SEQINT 0x0002
#define VERBOSE_SCSIINT 0x0004
#define VERBOSE_PROBE 0x0008
#define VERBOSE_PROBE2 0x0010
#define VERBOSE_NEGOTIATION2 0x0020
#define VERBOSE_MINOR_ERROR 0x0040
#define VERBOSE_TRACING 0x0080
#define VERBOSE_ABORT 0x0f00
#define VERBOSE_ABORT_MID 0x0100
#define VERBOSE_ABORT_FIND 0x0200
#define VERBOSE_ABORT_PROCESS 0x0400
#define VERBOSE_ABORT_RETURN 0x0800
#define VERBOSE_RESET 0xf000
#define VERBOSE_RESET_MID 0x1000
#define VERBOSE_RESET_FIND 0x2000
#define VERBOSE_RESET_PROCESS 0x4000
#define VERBOSE_RESET_RETURN 0x8000
static int aic7xxx_verbose = VERBOSE_NORMAL | VERBOSE_NEGOTIATION |
VERBOSE_PROBE;
static int aic7xxx_release(struct Scsi_Host *host);
static void aic7xxx_set_syncrate(struct aic7xxx_host *p,
struct aic7xxx_syncrate *syncrate, int target, int channel,
unsigned int period, unsigned int offset, unsigned char options,
unsigned int type, struct aic_dev_data *aic_dev);
static void aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel,
int lun, unsigned int width, unsigned int type,
struct aic_dev_data *aic_dev);
static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd);
static void aic7xxx_print_card(struct aic7xxx_host *p);
static void aic7xxx_print_scratch_ram(struct aic7xxx_host *p);
static void aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded);
#ifdef AIC7XXX_VERBOSE_DEBUGGING
static void aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer);
#endif
static unsigned char
aic_inb(struct aic7xxx_host *p, long port)
{
#ifdef MMAPIO
unsigned char x;
if(p->maddr)
{
x = readb(p->maddr + port);
}
else
{
x = inb(p->base + port);
}
return(x);
#else
return(inb(p->base + port));
#endif
}
static void
aic_outb(struct aic7xxx_host *p, unsigned char val, long port)
{
#ifdef MMAPIO
if(p->maddr)
{
writeb(val, p->maddr + port);
mb();
readb(p->maddr + HCNTRL);
}
else
{
outb(val, p->base + port);
mb();
}
#else
outb(val, p->base + port);
mb();
#endif
}
static int
aic7xxx_setup(char *s)
{
int i, n;
char *p;
char *end;
static struct {
const char *name;
unsigned int *flag;
} options[] = {
{ "extended", &aic7xxx_extended },
{ "no_reset", &aic7xxx_no_reset },
{ "irq_trigger", &aic7xxx_irq_trigger },
{ "verbose", &aic7xxx_verbose },
{ "reverse_scan",&aic7xxx_reverse_scan },
{ "override_term", &aic7xxx_override_term },
{ "stpwlev", &aic7xxx_stpwlev },
{ "no_probe", &aic7xxx_no_probe },
{ "panic_on_abort", &aic7xxx_panic_on_abort },
{ "pci_parity", &aic7xxx_pci_parity },
{ "dump_card", &aic7xxx_dump_card },
{ "dump_sequencer", &aic7xxx_dump_sequencer },
{ "default_queue_depth", &aic7xxx_default_queue_depth },
{ "scbram", &aic7xxx_scbram },
{ "seltime", &aic7xxx_seltime },
{ "tag_info", NULL }
};
end = strchr(s, '\0');
while ((p = strsep(&s, ",.")) != NULL)
{
for (i = 0; i < ARRAY_SIZE(options); i++)
{
n = strlen(options[i].name);
if (!strncmp(options[i].name, p, n))
{
if (!strncmp(p, "tag_info", n))
{
if (p[n] == ':')
{
char *base;
char *tok, *tok_end, *tok_end2;
char tok_list[] = { '.', ',', '{', '}', '\0' };
int i, instance = -1, device = -1;
unsigned char done = FALSE;
base = p;
tok = base + n + 1;
tok_end = strchr(tok, '\0');
if (tok_end < end)
*tok_end = ',';
while(!done)
{
switch(*tok)
{
case '{':
if (instance == -1)
instance = 0;
else if (device == -1)
device = 0;
tok++;
break;
case '}':
if (device != -1)
device = -1;
else if (instance != -1)
instance = -1;
tok++;
break;
case ',':
case '.':
if (instance == -1)
done = TRUE;
else if (device >= 0)
device++;
else if (instance >= 0)
instance++;
if ( (device >= MAX_TARGETS) ||
(instance >= ARRAY_SIZE(aic7xxx_tag_info)) )
done = TRUE;
tok++;
if (!done)
{
base = tok;
}
break;
case '\0':
done = TRUE;
break;
default:
done = TRUE;
tok_end = strchr(tok, '\0');
for(i=0; tok_list[i]; i++)
{
tok_end2 = strchr(tok, tok_list[i]);
if ( (tok_end2) && (tok_end2 < tok_end) )
{
tok_end = tok_end2;
done = FALSE;
}
}
if ( (instance >= 0) && (device >= 0) &&
(instance < ARRAY_SIZE(aic7xxx_tag_info)) &&
(device < MAX_TARGETS) )
aic7xxx_tag_info[instance].tag_commands[device] =
simple_strtoul(tok, NULL, 0) & 0xff;
tok = tok_end;
break;
}
}
while((p != base) && (p != NULL))
p = strsep(&s, ",.");
}
}
else if (p[n] == ':')
{
*(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
if(!strncmp(p, "seltime", n))
{
*(options[i].flag) = (*(options[i].flag) % 4) << 3;
}
}
else if (!strncmp(p, "verbose", n))
{
*(options[i].flag) = 0xff29;
}
else
{
*(options[i].flag) = ~(*(options[i].flag));
if(!strncmp(p, "seltime", n))
{
*(options[i].flag) = (*(options[i].flag) % 4) << 3;
}
}
}
}
}
return 1;
}
__setup("aic7xxx=", aic7xxx_setup);
static void
pause_sequencer(struct aic7xxx_host *p)
{
aic_outb(p, p->pause, HCNTRL);
while ((aic_inb(p, HCNTRL) & PAUSE) == 0)
{
;
}
if(p->features & AHC_ULTRA2)
{
aic_inb(p, CCSCBCTL);
}
}
static void
unpause_sequencer(struct aic7xxx_host *p, int unpause_always)
{
if (unpause_always ||
( !(aic_inb(p, INTSTAT) & (SCSIINT | SEQINT | BRKADRINT)) &&
!(p->flags & AHC_HANDLING_REQINITS) ) )
{
aic_outb(p, p->unpause, HCNTRL);
}
}
static void
restart_sequencer(struct aic7xxx_host *p)
{
aic_outb(p, 0, SEQADDR0);
aic_outb(p, 0, SEQADDR1);
aic_outb(p, FASTMODE, SEQCTL);
}
#include "aic7xxx_old/aic7xxx_seq.c"
static int
aic7xxx_check_patch(struct aic7xxx_host *p,
struct sequencer_patch **start_patch, int start_instr, int *skip_addr)
{
struct sequencer_patch *cur_patch;
struct sequencer_patch *last_patch;
int num_patches;
num_patches = ARRAY_SIZE(sequencer_patches);
last_patch = &sequencer_patches[num_patches];
cur_patch = *start_patch;
while ((cur_patch < last_patch) && (start_instr == cur_patch->begin))
{
if (cur_patch->patch_func(p) == 0)
{
*skip_addr = start_instr + cur_patch->skip_instr;
cur_patch += cur_patch->skip_patch;
}
else
{
cur_patch++;
}
}
*start_patch = cur_patch;
if (start_instr < *skip_addr)
return (0);
return(1);
}
static void
aic7xxx_download_instr(struct aic7xxx_host *p, int instrptr,
unsigned char *dconsts)
{
union ins_formats instr;
struct ins_format1 *fmt1_ins;
struct ins_format3 *fmt3_ins;
unsigned char opcode;
instr = *(union ins_formats*) &seqprog[instrptr * 4];
instr.integer = le32_to_cpu(instr.integer);
fmt1_ins = &instr.format1;
fmt3_ins = NULL;
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:
{
struct sequencer_patch *cur_patch;
int address_offset;
unsigned int address;
int skip_addr;
int i;
fmt3_ins = &instr.format3;
address_offset = 0;
address = fmt3_ins->address;
cur_patch = sequencer_patches;
skip_addr = 0;
for (i = 0; i < address;)
{
aic7xxx_check_patch(p, &cur_patch, i, &skip_addr);
if (skip_addr > i)
{
int end_addr;
end_addr = min_t(int, address, skip_addr);
address_offset += end_addr - i;
i = skip_addr;
}
else
{
i++;
}
}
address -= address_offset;
fmt3_ins->address = address;
}
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;
case AIC_OP_ROL:
if ((p->features & AHC_ULTRA2) != 0)
{
int i, count;
for ( i=0, count=0; i < 31; i++)
{
unsigned int mask;
mask = 0x01 << i;
if ((instr.integer & mask) != 0)
count++;
}
if (!(count & 0x01))
instr.format1.parity = 1;
}
else
{
if (fmt3_ins != NULL)
{
instr.integer = fmt3_ins->immediate |
(fmt3_ins->source << 8) |
(fmt3_ins->address << 16) |
(fmt3_ins->opcode << 25);
}
else
{
instr.integer = fmt1_ins->immediate |
(fmt1_ins->source << 8) |
(fmt1_ins->destination << 16) |
(fmt1_ins->ret << 24) |
(fmt1_ins->opcode << 25);
}
}
aic_outb(p, (instr.integer & 0xff), SEQRAM);
aic_outb(p, ((instr.integer >> 8) & 0xff), SEQRAM);
aic_outb(p, ((instr.integer >> 16) & 0xff), SEQRAM);
aic_outb(p, ((instr.integer >> 24) & 0xff), SEQRAM);
udelay(10);
break;
default:
panic("aic7xxx: Unknown opcode encountered in sequencer program.");
break;
}
}
static void
aic7xxx_loadseq(struct aic7xxx_host *p)
{
struct sequencer_patch *cur_patch;
int i;
int downloaded;
int skip_addr;
unsigned char download_consts[4] = {0, 0, 0, 0};
if (aic7xxx_verbose & VERBOSE_PROBE)
{
printk(KERN_INFO "(scsi%d) Downloading sequencer code...", p->host_no);
}
#if 0
download_consts[TMODE_NUMCMDS] = p->num_targetcmds;
#endif
download_consts[TMODE_NUMCMDS] = 0;
cur_patch = &sequencer_patches[0];
downloaded = 0;
skip_addr = 0;
aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
aic_outb(p, 0, SEQADDR0);
aic_outb(p, 0, SEQADDR1);
for (i = 0; i < sizeof(seqprog) / 4; i++)
{
if (aic7xxx_check_patch(p, &cur_patch, i, &skip_addr) == 0)
{
continue;
}
aic7xxx_download_instr(p, i, &download_consts[0]);
downloaded++;
}
aic_outb(p, 0, SEQADDR0);
aic_outb(p, 0, SEQADDR1);
aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
unpause_sequencer(p, TRUE);
mdelay(1);
pause_sequencer(p);
aic_outb(p, FASTMODE, SEQCTL);
if (aic7xxx_verbose & VERBOSE_PROBE)
{
printk(" %d instructions downloaded\n", downloaded);
}
if (aic7xxx_dump_sequencer)
aic7xxx_print_sequencer(p, downloaded);
}
static void
aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded)
{
int i, k, temp;
aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
aic_outb(p, 0, SEQADDR0);
aic_outb(p, 0, SEQADDR1);
k = 0;
for (i=0; i < downloaded; i++)
{
if ( k == 0 )
printk("%03x: ", i);
temp = aic_inb(p, SEQRAM);
temp |= (aic_inb(p, SEQRAM) << 8);
temp |= (aic_inb(p, SEQRAM) << 16);
temp |= (aic_inb(p, SEQRAM) << 24);
printk("%08x", temp);
if ( ++k == 8 )
{
printk("\n");
k = 0;
}
else
printk(" ");
}
aic_outb(p, 0, SEQADDR0);
aic_outb(p, 0, SEQADDR1);
aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
unpause_sequencer(p, TRUE);
mdelay(1);
pause_sequencer(p);
aic_outb(p, FASTMODE, SEQCTL);
printk("\n");
}
static const char *
aic7xxx_info(struct Scsi_Host *dooh)
{
static char buffer[256];
char *bp;
struct aic7xxx_host *p;
bp = &buffer[0];
p = (struct aic7xxx_host *)dooh->hostdata;
memset(bp, 0, sizeof(buffer));
strcpy(bp, "Adaptec AHA274x/284x/294x (EISA/VLB/PCI-Fast SCSI) ");
strcat(bp, AIC7XXX_C_VERSION);
strcat(bp, "/");
strcat(bp, AIC7XXX_H_VERSION);
strcat(bp, "\n");
strcat(bp, " <");
strcat(bp, board_names[p->board_name_index]);
strcat(bp, ">");
return(bp);
}
static struct aic7xxx_syncrate *
aic7xxx_find_syncrate(struct aic7xxx_host *p, unsigned int *period,
unsigned int maxsync, unsigned char *options)
{
struct aic7xxx_syncrate *syncrate;
int done = FALSE;
switch(*options)
{
case MSG_EXT_PPR_OPTION_DT_CRC:
case MSG_EXT_PPR_OPTION_DT_UNITS:
if(!(p->features & AHC_ULTRA3))
{
*options = 0;
maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
}
break;
case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
if(!(p->features & AHC_ULTRA3))
{
*options = 0;
maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
}
else
{
switch(*options)
{
case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
*options = MSG_EXT_PPR_OPTION_DT_CRC;
break;
case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
*options = MSG_EXT_PPR_OPTION_DT_UNITS;
break;
}
}
break;
default:
*options = 0;
maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
break;
}
syncrate = &aic7xxx_syncrates[maxsync];
while ( (syncrate->rate[0] != NULL) &&
(!(p->features & AHC_ULTRA2) || syncrate->sxfr_ultra2) )
{
if (*period <= syncrate->period)
{
switch(*options)
{
case MSG_EXT_PPR_OPTION_DT_CRC:
case MSG_EXT_PPR_OPTION_DT_UNITS:
if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
{
done = TRUE;
*options = 0;
*period = syncrate->period;
}
else
{
done = TRUE;
if(syncrate == &aic7xxx_syncrates[maxsync])
{
*period = syncrate->period;
}
}
break;
default:
if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
{
done = TRUE;
if(syncrate == &aic7xxx_syncrates[maxsync])
{
*period = syncrate->period;
}
}
break;
}
if(done)
{
break;
}
}
syncrate++;
}
if ( (*period == 0) || (syncrate->rate[0] == NULL) ||
((p->features & AHC_ULTRA2) && (syncrate->sxfr_ultra2 == 0)) )
{
*options = 0;
*period = 255;
syncrate = NULL;
}
return (syncrate);
}
static unsigned int
aic7xxx_find_period(struct aic7xxx_host *p, unsigned int scsirate,
unsigned int maxsync)
{
struct aic7xxx_syncrate *syncrate;
if (p->features & AHC_ULTRA2)
{
scsirate &= SXFR_ULTRA2;
}
else
{
scsirate &= SXFR;
}
syncrate = &aic7xxx_syncrates[maxsync];
while (syncrate->rate[0] != NULL)
{
if (p->features & AHC_ULTRA2)
{
if (syncrate->sxfr_ultra2 == 0)
break;
else if (scsirate == syncrate->sxfr_ultra2)
return (syncrate->period);
else if (scsirate == (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC))
return (syncrate->period);
}
else if (scsirate == (syncrate->sxfr & ~ULTRA_SXFR))
{
return (syncrate->period);
}
syncrate++;
}
return (0);
}
static void
aic7xxx_validate_offset(struct aic7xxx_host *p,
struct aic7xxx_syncrate *syncrate, unsigned int *offset, int wide)
{
unsigned int maxoffset;
if (syncrate == NULL)
{
maxoffset = 0;
}
else if (p->features & AHC_ULTRA2)
{
maxoffset = MAX_OFFSET_ULTRA2;
}
else
{
if (wide)
maxoffset = MAX_OFFSET_16BIT;
else
maxoffset = MAX_OFFSET_8BIT;
}
*offset = min(*offset, maxoffset);
}
static void
aic7xxx_set_syncrate(struct aic7xxx_host *p, struct aic7xxx_syncrate *syncrate,
int target, int channel, unsigned int period, unsigned int offset,
unsigned char options, unsigned int type, struct aic_dev_data *aic_dev)
{
unsigned char tindex;
unsigned short target_mask;
unsigned char lun, old_options;
unsigned int old_period, old_offset;
tindex = target | (channel << 3);
target_mask = 0x01 << tindex;
lun = aic_inb(p, SCB_TCL) & 0x07;
if (syncrate == NULL)
{
period = 0;
offset = 0;
}
old_period = aic_dev->cur.period;
old_offset = aic_dev->cur.offset;
old_options = aic_dev->cur.options;
if (type & AHC_TRANS_CUR)
{
unsigned int scsirate;
scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
if (p->features & AHC_ULTRA2)
{
scsirate &= ~SXFR_ULTRA2;
if (syncrate != NULL)
{
switch(options)
{
case MSG_EXT_PPR_OPTION_DT_UNITS:
scsirate |= (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC);
break;
default:
scsirate |= syncrate->sxfr_ultra2;
break;
}
}
if (type & AHC_TRANS_ACTIVE)
{
aic_outb(p, offset, SCSIOFFSET);
}
aic_outb(p, offset, TARG_OFFSET + tindex);
}
else
{
scsirate &= ~(SXFR|SOFS);
p->ultraenb &= ~target_mask;
if (syncrate != NULL)
{
if (syncrate->sxfr & ULTRA_SXFR)
{
p->ultraenb |= target_mask;
}
scsirate |= (syncrate->sxfr & SXFR);
scsirate |= (offset & SOFS);
}
if (type & AHC_TRANS_ACTIVE)
{
unsigned char sxfrctl0;
sxfrctl0 = aic_inb(p, SXFRCTL0);
sxfrctl0 &= ~FAST20;
if (p->ultraenb & target_mask)
sxfrctl0 |= FAST20;
aic_outb(p, sxfrctl0, SXFRCTL0);
}
aic_outb(p, p->ultraenb & 0xff, ULTRA_ENB);
aic_outb(p, (p->ultraenb >> 8) & 0xff, ULTRA_ENB + 1 );
}
if (type & AHC_TRANS_ACTIVE)
{
aic_outb(p, scsirate, SCSIRATE);
}
aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
aic_dev->cur.period = period;
aic_dev->cur.offset = offset;
aic_dev->cur.options = options;
if ( !(type & AHC_TRANS_QUITE) &&
(aic7xxx_verbose & VERBOSE_NEGOTIATION) &&
(aic_dev->flags & DEVICE_PRINT_DTR) )
{
if (offset)
{
int rate_mod = (scsirate & WIDEXFER) ? 1 : 0;
printk(INFO_LEAD "Synchronous at %s Mbyte/sec, "
"offset %d.\n", p->host_no, channel, target, lun,
syncrate->rate[rate_mod], offset);
}
else
{
printk(INFO_LEAD "Using asynchronous transfers.\n",
p->host_no, channel, target, lun);
}
aic_dev->flags &= ~DEVICE_PRINT_DTR;
}
}
if (type & AHC_TRANS_GOAL)
{
aic_dev->goal.period = period;
aic_dev->goal.offset = offset;
aic_dev->goal.options = options;
}
if (type & AHC_TRANS_USER)
{
p->user[tindex].period = period;
p->user[tindex].offset = offset;
p->user[tindex].options = options;
}
}
static void
aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel, int lun,
unsigned int width, unsigned int type, struct aic_dev_data *aic_dev)
{
unsigned char tindex;
unsigned short target_mask;
unsigned int old_width;
tindex = target | (channel << 3);
target_mask = 1 << tindex;
old_width = aic_dev->cur.width;
if (type & AHC_TRANS_CUR)
{
unsigned char scsirate;
scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
scsirate &= ~WIDEXFER;
if (width == MSG_EXT_WDTR_BUS_16_BIT)
scsirate |= WIDEXFER;
aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
if (type & AHC_TRANS_ACTIVE)
aic_outb(p, scsirate, SCSIRATE);
aic_dev->cur.width = width;
if ( !(type & AHC_TRANS_QUITE) &&
(aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
(aic_dev->flags & DEVICE_PRINT_DTR) )
{
printk(INFO_LEAD "Using %s transfers\n", p->host_no, channel, target,
lun, (scsirate & WIDEXFER) ? "Wide(16bit)" : "Narrow(8bit)" );
}
}
if (type & AHC_TRANS_GOAL)
aic_dev->goal.width = width;
if (type & AHC_TRANS_USER)
p->user[tindex].width = width;
if (aic_dev->goal.offset)
{
if (p->features & AHC_ULTRA2)
{
aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
}
else if (width == MSG_EXT_WDTR_BUS_16_BIT)
{
aic_dev->goal.offset = MAX_OFFSET_16BIT;
}
else
{
aic_dev->goal.offset = MAX_OFFSET_8BIT;
}
}
}
static void
scbq_init(volatile scb_queue_type *queue)
{
queue->head = NULL;
queue->tail = NULL;
}
static inline void
scbq_insert_head(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
{
scb->q_next = queue->head;
queue->head = scb;
if (queue->tail == NULL)
queue->tail = queue->head;
}
static inline struct aic7xxx_scb *
scbq_remove_head(volatile scb_queue_type *queue)
{
struct aic7xxx_scb * scbp;
scbp = queue->head;
if (queue->head != NULL)
queue->head = queue->head->q_next;
if (queue->head == NULL)
queue->tail = NULL;
return(scbp);
}
static inline void
scbq_remove(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
{
if (queue->head == scb)
{
scbq_remove_head(queue);
}
else
{
struct aic7xxx_scb *curscb = queue->head;
while ((curscb != NULL) && (curscb->q_next != scb))
{
curscb = curscb->q_next;
}
if (curscb != NULL)
{
curscb->q_next = scb->q_next;
if (scb->q_next == NULL)
{
queue->tail = curscb;
}
}
}
}
static inline void
scbq_insert_tail(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
{
scb->q_next = NULL;
if (queue->tail != NULL)
queue->tail->q_next = scb;
queue->tail = scb;
if (queue->head == NULL)
queue->head = queue->tail;
}
static int
aic7xxx_match_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
int target, int channel, int lun, unsigned char tag)
{
int targ = (scb->hscb->target_channel_lun >> 4) & 0x0F;
int chan = (scb->hscb->target_channel_lun >> 3) & 0x01;
int slun = scb->hscb->target_channel_lun & 0x07;
int match;
match = ((chan == channel) || (channel == ALL_CHANNELS));
if (match != 0)
match = ((targ == target) || (target == ALL_TARGETS));
if (match != 0)
match = ((lun == slun) || (lun == ALL_LUNS));
if (match != 0)
match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
return (match);
}
static void
aic7xxx_add_curscb_to_free_list(struct aic7xxx_host *p)
{
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic_outb(p, 0, SCB_CONTROL);
aic_outb(p, aic_inb(p, FREE_SCBH), SCB_NEXT);
aic_outb(p, aic_inb(p, SCBPTR), FREE_SCBH);
}
static unsigned char
aic7xxx_rem_scb_from_disc_list(struct aic7xxx_host *p, unsigned char scbptr,
unsigned char prev)
{
unsigned char next;
aic_outb(p, scbptr, SCBPTR);
next = aic_inb(p, SCB_NEXT);
aic7xxx_add_curscb_to_free_list(p);
if (prev != SCB_LIST_NULL)
{
aic_outb(p, prev, SCBPTR);
aic_outb(p, next, SCB_NEXT);
}
else
{
aic_outb(p, next, DISCONNECTED_SCBH);
}
return next;
}
static inline void
aic7xxx_busy_target(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
p->untagged_scbs[scb->hscb->target_channel_lun] = scb->hscb->tag;
}
static inline unsigned char
aic7xxx_index_busy_target(struct aic7xxx_host *p, unsigned char tcl,
int unbusy)
{
unsigned char busy_scbid;
busy_scbid = p->untagged_scbs[tcl];
if (unbusy)
{
p->untagged_scbs[tcl] = SCB_LIST_NULL;
}
return (busy_scbid);
}
static unsigned char
aic7xxx_find_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
unsigned char saved_scbptr;
unsigned char curindex;
saved_scbptr = aic_inb(p, SCBPTR);
curindex = 0;
for (curindex = 0; curindex < p->scb_data->maxhscbs; curindex++)
{
aic_outb(p, curindex, SCBPTR);
if (aic_inb(p, SCB_TAG) == scb->hscb->tag)
{
break;
}
}
aic_outb(p, saved_scbptr, SCBPTR);
if (curindex >= p->scb_data->maxhscbs)
{
curindex = SCB_LIST_NULL;
}
return (curindex);
}
static int
aic7xxx_allocate_scb(struct aic7xxx_host *p)
{
struct aic7xxx_scb *scbp = NULL;
int scb_size = (sizeof (struct hw_scatterlist) * AIC7XXX_MAX_SG) + 12 + 6;
int i;
int step = PAGE_SIZE / 1024;
unsigned long scb_count = 0;
struct hw_scatterlist *hsgp;
struct aic7xxx_scb *scb_ap;
struct aic7xxx_scb_dma *scb_dma;
unsigned char *bufs;
if (p->scb_data->numscbs < p->scb_data->maxscbs)
{
for ( i=step;; i *= 2 )
{
if ( (scb_size * (i-1)) >= ( (PAGE_SIZE * (i/step)) - 64 ) )
{
i /= 2;
break;
}
}
scb_count = min( (i-1), p->scb_data->maxscbs - p->scb_data->numscbs);
scb_ap = kmalloc(sizeof (struct aic7xxx_scb) * scb_count
+ sizeof(struct aic7xxx_scb_dma), GFP_ATOMIC);
if (scb_ap == NULL)
return(0);
scb_dma = (struct aic7xxx_scb_dma *)&scb_ap[scb_count];
hsgp = (struct hw_scatterlist *)
pci_alloc_consistent(p->pdev, scb_size * scb_count,
&scb_dma->dma_address);
if (hsgp == NULL)
{
kfree(scb_ap);
return(0);
}
bufs = (unsigned char *)&hsgp[scb_count * AIC7XXX_MAX_SG];
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
{
if (p->scb_data->numscbs == 0)
printk(INFO_LEAD "Allocating initial %ld SCB structures.\n",
p->host_no, -1, -1, -1, scb_count);
else
printk(INFO_LEAD "Allocating %ld additional SCB structures.\n",
p->host_no, -1, -1, -1, scb_count);
}
#endif
memset(scb_ap, 0, sizeof (struct aic7xxx_scb) * scb_count);
scb_dma->dma_offset = (unsigned long)scb_dma->dma_address
- (unsigned long)hsgp;
scb_dma->dma_len = scb_size * scb_count;
for (i=0; i < scb_count; i++)
{
scbp = &scb_ap[i];
scbp->hscb = &p->scb_data->hscbs[p->scb_data->numscbs];
scbp->sg_list = &hsgp[i * AIC7XXX_MAX_SG];
scbp->sense_cmd = bufs;
scbp->cmnd = bufs + 6;
bufs += 12 + 6;
scbp->scb_dma = scb_dma;
memset(scbp->hscb, 0, sizeof(struct aic7xxx_hwscb));
scbp->hscb->tag = p->scb_data->numscbs;
p->scb_data->scb_array[p->scb_data->numscbs++] = scbp;
scbq_insert_tail(&p->scb_data->free_scbs, scbp);
}
scbp->kmalloc_ptr = scb_ap;
}
return(scb_count);
}
static void
aic7xxx_queue_cmd_complete(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
{
aic7xxx_position(cmd) = SCB_LIST_NULL;
cmd->host_scribble = (char *)p->completeq.head;
p->completeq.head = cmd;
}
static void aic7xxx_done_cmds_complete(struct aic7xxx_host *p)
{
struct scsi_cmnd *cmd;
while (p->completeq.head != NULL) {
cmd = p->completeq.head;
p->completeq.head = (struct scsi_cmnd *) cmd->host_scribble;
cmd->host_scribble = NULL;
cmd->scsi_done(cmd);
}
}
static void
aic7xxx_free_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
scb->flags = SCB_FREE;
scb->cmd = NULL;
scb->sg_count = 0;
scb->sg_length = 0;
scb->tag_action = 0;
scb->hscb->control = 0;
scb->hscb->target_status = 0;
scb->hscb->target_channel_lun = SCB_LIST_NULL;
scbq_insert_head(&p->scb_data->free_scbs, scb);
}
static void
aic7xxx_done(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
struct scsi_cmnd *cmd = scb->cmd;
struct aic_dev_data *aic_dev = cmd->device->hostdata;
int tindex = TARGET_INDEX(cmd);
struct aic7xxx_scb *scbp;
unsigned char queue_depth;
scsi_dma_unmap(cmd);
if (scb->flags & SCB_SENSE)
{
pci_unmap_single(p->pdev,
le32_to_cpu(scb->sg_list[0].address),
SCSI_SENSE_BUFFERSIZE,
PCI_DMA_FROMDEVICE);
}
if (scb->flags & SCB_RECOVERY_SCB)
{
p->flags &= ~AHC_ABORT_PENDING;
}
if (scb->flags & (SCB_RESET|SCB_ABORT))
{
cmd->result |= (DID_RESET << 16);
}
if ((scb->flags & SCB_MSGOUT_BITS) != 0)
{
unsigned short mask;
int message_error = FALSE;
mask = 0x01 << tindex;
if ((scb->flags & SCB_SENSE) &&
((scb->cmd->sense_buffer[12] == 0x43) ||
(scb->cmd->sense_buffer[12] == 0x49)))
{
message_error = TRUE;
}
if (scb->flags & SCB_MSGOUT_WDTR)
{
if (message_error)
{
if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
(aic_dev->flags & DEVICE_PRINT_DTR) )
{
printk(INFO_LEAD "Device failed to complete Wide Negotiation "
"processing and\n", p->host_no, CTL_OF_SCB(scb));
printk(INFO_LEAD "returned a sense error code for invalid message, "
"disabling future\n", p->host_no, CTL_OF_SCB(scb));
printk(INFO_LEAD "Wide negotiation to this device.\n", p->host_no,
CTL_OF_SCB(scb));
}
aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
}
}
if (scb->flags & SCB_MSGOUT_SDTR)
{
if (message_error)
{
if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
(aic_dev->flags & DEVICE_PRINT_DTR) )
{
printk(INFO_LEAD "Device failed to complete Sync Negotiation "
"processing and\n", p->host_no, CTL_OF_SCB(scb));
printk(INFO_LEAD "returned a sense error code for invalid message, "
"disabling future\n", p->host_no, CTL_OF_SCB(scb));
printk(INFO_LEAD "Sync negotiation to this device.\n", p->host_no,
CTL_OF_SCB(scb));
aic_dev->flags &= ~DEVICE_PRINT_DTR;
}
aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
}
}
if (scb->flags & SCB_MSGOUT_PPR)
{
if(message_error)
{
if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
(aic_dev->flags & DEVICE_PRINT_DTR) )
{
printk(INFO_LEAD "Device failed to complete Parallel Protocol "
"Request processing and\n", p->host_no, CTL_OF_SCB(scb));
printk(INFO_LEAD "returned a sense error code for invalid message, "
"disabling future\n", p->host_no, CTL_OF_SCB(scb));
printk(INFO_LEAD "Parallel Protocol Request negotiation to this "
"device.\n", p->host_no, CTL_OF_SCB(scb));
}
aic_dev->needppr = aic_dev->needppr_copy = 0;
aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
}
}
}
queue_depth = aic_dev->temp_q_depth;
if (queue_depth >= aic_dev->active_cmds)
{
scbp = scbq_remove_head(&aic_dev->delayed_scbs);
if (scbp)
{
if (queue_depth == 1)
{
scbq_insert_head(&p->waiting_scbs, scbp);
}
else
{
scbq_insert_tail(&p->waiting_scbs, scbp);
}
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
printk(INFO_LEAD "Moving SCB from delayed to waiting queue.\n",
p->host_no, CTL_OF_SCB(scbp));
#endif
if (queue_depth > aic_dev->active_cmds)
{
scbp = scbq_remove_head(&aic_dev->delayed_scbs);
if (scbp)
scbq_insert_tail(&p->waiting_scbs, scbp);
}
}
}
if (!(scb->tag_action))
{
aic7xxx_index_busy_target(p, scb->hscb->target_channel_lun,
TRUE);
if (cmd->device->simple_tags)
{
aic_dev->temp_q_depth = aic_dev->max_q_depth;
}
}
if(scb->flags & SCB_DTR_SCB)
{
aic_dev->dtr_pending = 0;
}
aic_dev->active_cmds--;
p->activescbs--;
if ((scb->sg_length >= 512) && (((cmd->result >> 16) & 0xf) == DID_OK))
{
long *ptr;
int x, i;
if (rq_data_dir(cmd->request) == WRITE)
{
aic_dev->w_total++;
ptr = aic_dev->w_bins;
}
else
{
aic_dev->r_total++;
ptr = aic_dev->r_bins;
}
x = scb->sg_length;
x >>= 10;
for(i=0; i<6; i++)
{
x >>= 2;
if(!x) {
ptr[i]++;
break;
}
}
if(i == 6 && x)
ptr[5]++;
}
aic7xxx_free_scb(p, scb);
aic7xxx_queue_cmd_complete(p, cmd);
}
static void
aic7xxx_run_done_queue(struct aic7xxx_host *p, int complete)
{
struct aic7xxx_scb *scb;
int i, found = 0;
for (i = 0; i < p->scb_data->numscbs; i++)
{
scb = p->scb_data->scb_array[i];
if (scb->flags & SCB_QUEUED_FOR_DONE)
{
if (scb->flags & SCB_QUEUE_FULL)
{
scb->cmd->result = QUEUE_FULL << 1;
}
else
{
if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
printk(INFO_LEAD "Aborting scb %d\n",
p->host_no, CTL_OF_SCB(scb), scb->hscb->tag);
scb->hscb->residual_SG_segment_count = 0;
scb->hscb->residual_data_count[0] = 0;
scb->hscb->residual_data_count[1] = 0;
scb->hscb->residual_data_count[2] = 0;
}
found++;
aic7xxx_done(p, scb);
}
}
if (aic7xxx_verbose & (VERBOSE_ABORT_RETURN | VERBOSE_RESET_RETURN))
{
printk(INFO_LEAD "%d commands found and queued for "
"completion.\n", p->host_no, -1, -1, -1, found);
}
if (complete)
{
aic7xxx_done_cmds_complete(p);
}
}
static unsigned char
aic7xxx_abort_waiting_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
unsigned char scbpos, unsigned char prev)
{
unsigned char curscb, next;
curscb = aic_inb(p, SCBPTR);
aic_outb(p, scbpos, SCBPTR);
next = aic_inb(p, SCB_NEXT);
aic7xxx_add_curscb_to_free_list(p);
if (prev == SCB_LIST_NULL)
{
aic_outb(p, next, WAITING_SCBH);
}
else
{
aic_outb(p, prev, SCBPTR);
aic_outb(p, next, SCB_NEXT);
}
aic_outb(p, curscb, SCBPTR);
return (next);
}
static int
aic7xxx_search_qinfifo(struct aic7xxx_host *p, int target, int channel,
int lun, unsigned char tag, int flags, int requeue,
volatile scb_queue_type *queue)
{
int found;
unsigned char qinpos, qintail;
struct aic7xxx_scb *scbp;
found = 0;
qinpos = aic_inb(p, QINPOS);
qintail = p->qinfifonext;
p->qinfifonext = qinpos;
while (qinpos != qintail)
{
scbp = p->scb_data->scb_array[p->qinfifo[qinpos++]];
if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
{
if (requeue && (queue != NULL))
{
if (scbp->flags & SCB_WAITINGQ)
{
scbq_remove(queue, scbp);
scbq_remove(&p->waiting_scbs, scbp);
scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
AIC_DEV(scbp->cmd)->active_cmds++;
p->activescbs++;
}
scbq_insert_tail(queue, scbp);
AIC_DEV(scbp->cmd)->active_cmds--;
p->activescbs--;
scbp->flags |= SCB_WAITINGQ;
if ( !(scbp->tag_action & TAG_ENB) )
{
aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
TRUE);
}
}
else if (requeue)
{
p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
}
else
{
scbp->flags = flags | (scbp->flags & SCB_RECOVERY_SCB);
if (aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
FALSE) == scbp->hscb->tag)
{
aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
TRUE);
}
}
found++;
}
else
{
p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
}
}
qinpos = p->qinfifonext;
while(qinpos != qintail)
{
p->qinfifo[qinpos++] = SCB_LIST_NULL;
}
if (p->features & AHC_QUEUE_REGS)
aic_outb(p, p->qinfifonext, HNSCB_QOFF);
else
aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
return (found);
}
static int
aic7xxx_scb_on_qoutfifo(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
int i=0;
while(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] != SCB_LIST_NULL)
{
if(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] == scb->hscb->tag)
return TRUE;
else
i++;
}
return FALSE;
}
static void
aic7xxx_reset_device(struct aic7xxx_host *p, int target, int channel,
int lun, unsigned char tag)
{
struct aic7xxx_scb *scbp, *prev_scbp;
struct scsi_device *sd;
unsigned char active_scb, tcl, scb_tag;
int i = 0, init_lists = FALSE;
struct aic_dev_data *aic_dev;
active_scb = aic_inb(p, SCBPTR);
scb_tag = aic_inb(p, SCB_TAG);
if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
{
printk(INFO_LEAD "Reset device, hardware_scb %d,\n",
p->host_no, channel, target, lun, active_scb);
printk(INFO_LEAD "Current scb %d, SEQADDR 0x%x, LASTPHASE "
"0x%x\n",
p->host_no, channel, target, lun, scb_tag,
aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
aic_inb(p, LASTPHASE));
printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
p->host_no, channel, target, lun,
(p->features & AHC_ULTRA2) ? aic_inb(p, SG_CACHEPTR) : 0,
aic_inb(p, SG_COUNT), aic_inb(p, SCSISIGI));
printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
p->host_no, channel, target, lun, aic_inb(p, SSTAT0),
aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
}
list_for_each_entry(aic_dev, &p->aic_devs, list)
{
if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
printk(INFO_LEAD "processing aic_dev %p\n", p->host_no, channel, target,
lun, aic_dev);
sd = aic_dev->SDptr;
if((target != ALL_TARGETS && target != sd->id) ||
(channel != ALL_CHANNELS && channel != sd->channel))
continue;
if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
printk(INFO_LEAD "Cleaning up status information "
"and delayed_scbs.\n", p->host_no, sd->channel, sd->id, sd->lun);
aic_dev->flags &= ~BUS_DEVICE_RESET_PENDING;
if ( tag == SCB_LIST_NULL )
{
aic_dev->dtr_pending = 0;
aic_dev->needppr = aic_dev->needppr_copy;
aic_dev->needsdtr = aic_dev->needsdtr_copy;
aic_dev->needwdtr = aic_dev->needwdtr_copy;
aic_dev->flags = DEVICE_PRINT_DTR;
aic_dev->temp_q_depth = aic_dev->max_q_depth;
}
tcl = (sd->id << 4) | (sd->channel << 3) | sd->lun;
if ( (aic7xxx_index_busy_target(p, tcl, FALSE) == tag) ||
(tag == SCB_LIST_NULL) )
aic7xxx_index_busy_target(p, tcl, TRUE);
prev_scbp = NULL;
scbp = aic_dev->delayed_scbs.head;
while (scbp != NULL)
{
prev_scbp = scbp;
scbp = scbp->q_next;
if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
{
scbq_remove(&aic_dev->delayed_scbs, prev_scbp);
if (prev_scbp->flags & SCB_WAITINGQ)
{
aic_dev->active_cmds++;
p->activescbs++;
}
prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
}
}
}
if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
printk(INFO_LEAD "Cleaning QINFIFO.\n", p->host_no, channel, target, lun );
aic7xxx_search_qinfifo(p, target, channel, lun, tag,
SCB_RESET | SCB_QUEUED_FOR_DONE, FALSE, NULL);
if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
printk(INFO_LEAD "Cleaning waiting_scbs.\n", p->host_no, channel,
target, lun );
{
struct aic7xxx_scb *scbp, *prev_scbp;
prev_scbp = NULL;
scbp = p->waiting_scbs.head;
while (scbp != NULL)
{
prev_scbp = scbp;
scbp = scbp->q_next;
if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
{
scbq_remove(&p->waiting_scbs, prev_scbp);
if (prev_scbp->flags & SCB_WAITINGQ)
{
AIC_DEV(prev_scbp->cmd)->active_cmds++;
p->activescbs++;
}
prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
}
}
}
if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
printk(INFO_LEAD "Cleaning waiting for selection "
"list.\n", p->host_no, channel, target, lun);
{
unsigned char next, prev, scb_index;
next = aic_inb(p, WAITING_SCBH);
prev = SCB_LIST_NULL;
while (next != SCB_LIST_NULL)
{
aic_outb(p, next, SCBPTR);
scb_index = aic_inb(p, SCB_TAG);
if (scb_index >= p->scb_data->numscbs)
{
printk(WARN_LEAD "Waiting List inconsistency; SCB index=%d, "
"numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
p->scb_data->numscbs);
next = aic_inb(p, SCB_NEXT);
aic7xxx_add_curscb_to_free_list(p);
}
else
{
scbp = p->scb_data->scb_array[scb_index];
if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
{
next = aic7xxx_abort_waiting_scb(p, scbp, next, prev);
if (scbp->flags & SCB_WAITINGQ)
{
AIC_DEV(scbp->cmd)->active_cmds++;
p->activescbs++;
}
scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
if (prev == SCB_LIST_NULL)
{
aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
aic_outb(p, CLRSELTIMEO, CLRSINT1);
}
}
else
{
prev = next;
next = aic_inb(p, SCB_NEXT);
}
}
}
}
if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
printk(INFO_LEAD "Cleaning disconnected scbs "
"list.\n", p->host_no, channel, target, lun);
if (p->flags & AHC_PAGESCBS)
{
unsigned char next, prev, scb_index;
next = aic_inb(p, DISCONNECTED_SCBH);
prev = SCB_LIST_NULL;
while (next != SCB_LIST_NULL)
{
aic_outb(p, next, SCBPTR);
scb_index = aic_inb(p, SCB_TAG);
if (scb_index > p->scb_data->numscbs)
{
printk(WARN_LEAD "Disconnected List inconsistency; SCB index=%d, "
"numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
p->scb_data->numscbs);
next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
}
else
{
scbp = p->scb_data->scb_array[scb_index];
if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
{
next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
if (scbp->flags & SCB_WAITINGQ)
{
AIC_DEV(scbp->cmd)->active_cmds++;
p->activescbs++;
}
scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
scbp->hscb->control = 0;
}
else
{
prev = next;
next = aic_inb(p, SCB_NEXT);
}
}
}
}
if (p->flags & AHC_PAGESCBS)
{
unsigned char next;
next = aic_inb(p, FREE_SCBH);
while (next != SCB_LIST_NULL)
{
aic_outb(p, next, SCBPTR);
if (aic_inb(p, SCB_TAG) < p->scb_data->numscbs)
{
printk(WARN_LEAD "Free list inconsistency!.\n", p->host_no, channel,
target, lun);
init_lists = TRUE;
next = SCB_LIST_NULL;
}
else
{
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic_outb(p, 0, SCB_CONTROL);
next = aic_inb(p, SCB_NEXT);
}
}
}
if (init_lists)
{
aic_outb(p, SCB_LIST_NULL, FREE_SCBH);
aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
}
for (i = p->scb_data->maxhscbs - 1; i >= 0; i--)
{
unsigned char scbid;
aic_outb(p, i, SCBPTR);
if (init_lists)
{
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
aic_outb(p, 0, SCB_CONTROL);
aic7xxx_add_curscb_to_free_list(p);
}
else
{
scbid = aic_inb(p, SCB_TAG);
if (scbid < p->scb_data->numscbs)
{
scbp = p->scb_data->scb_array[scbid];
if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
{
aic_outb(p, 0, SCB_CONTROL);
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic7xxx_add_curscb_to_free_list(p);
}
}
}
}
for (i = 0; i < p->scb_data->numscbs; i++)
{
scbp = p->scb_data->scb_array[i];
if ((scbp->flags & SCB_ACTIVE) &&
aic7xxx_match_scb(p, scbp, target, channel, lun, tag) &&
!aic7xxx_scb_on_qoutfifo(p, scbp))
{
if (scbp->flags & SCB_WAITINGQ)
{
scbq_remove(&p->waiting_scbs, scbp);
scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
AIC_DEV(scbp->cmd)->active_cmds++;
p->activescbs++;
}
scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
}
}
aic_outb(p, active_scb, SCBPTR);
}
static void
aic7xxx_clear_intstat(struct aic7xxx_host *p)
{
aic_outb(p, CLRSELDO | CLRSELDI | CLRSELINGO, CLRSINT0);
aic_outb(p, CLRSELTIMEO | CLRATNO | CLRSCSIRSTI | CLRBUSFREE | CLRSCSIPERR |
CLRPHASECHG | CLRREQINIT, CLRSINT1);
aic_outb(p, CLRSCSIINT | CLRSEQINT | CLRBRKADRINT | CLRPARERR, CLRINT);
}
static void
aic7xxx_reset_current_bus(struct aic7xxx_host *p)
{
aic_outb(p, aic_inb(p, SIMODE1) & ~ENSCSIRST, SIMODE1);
aic_outb(p, aic_inb(p, SCSISEQ) | SCSIRSTO, SCSISEQ);
while ( (aic_inb(p, SCSISEQ) & SCSIRSTO) == 0)
mdelay(5);
if (p->features & AHC_ULTRA2)
mdelay(250);
else
mdelay(50);
aic_outb(p, 0, SCSISEQ);
mdelay(10);
aic7xxx_clear_intstat(p);
aic_outb(p, aic_inb(p, SIMODE1) | ENSCSIRST, SIMODE1);
}
static void
aic7xxx_reset_channel(struct aic7xxx_host *p, int channel, int initiate_reset)
{
unsigned long offset_min, offset_max;
unsigned char sblkctl;
int cur_channel;
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Reset channel called, %s initiate reset.\n",
p->host_no, channel, -1, -1, (initiate_reset==TRUE) ? "will" : "won't" );
if (channel == 1)
{
offset_min = 8;
offset_max = 16;
}
else
{
if (p->features & AHC_TWIN)
{
offset_min = 0;
offset_max = 8;
}
else
{
offset_min = 0;
if (p->features & AHC_WIDE)
{
offset_max = 16;
}
else
{
offset_max = 8;
}
}
}
while (offset_min < offset_max)
{
aic_outb(p, 0, TARG_SCSIRATE + offset_min);
if (p->features & AHC_ULTRA2)
{
aic_outb(p, 0, TARG_OFFSET + offset_min);
}
offset_min++;
}
sblkctl = aic_inb(p, SBLKCTL);
if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
cur_channel = (sblkctl & SELBUSB) >> 3;
else
cur_channel = 0;
if ( (cur_channel != channel) && (p->features & AHC_TWIN) )
{
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Stealthily resetting idle channel.\n", p->host_no,
channel, -1, -1);
aic_outb(p, sblkctl ^ SELBUSB, SBLKCTL);
aic_outb(p, aic_inb(p, SIMODE1) & ~ENBUSFREE, SIMODE1);
if (initiate_reset)
{
aic7xxx_reset_current_bus(p);
}
aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
aic7xxx_clear_intstat(p);
aic_outb(p, sblkctl, SBLKCTL);
}
else
{
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Resetting currently active channel.\n", p->host_no,
channel, -1, -1);
aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
SIMODE1);
p->flags &= ~AHC_HANDLING_REQINITS;
p->msg_type = MSG_TYPE_NONE;
p->msg_len = 0;
if (initiate_reset)
{
aic7xxx_reset_current_bus(p);
}
aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
aic7xxx_clear_intstat(p);
}
if (aic7xxx_verbose & VERBOSE_RESET_RETURN)
printk(INFO_LEAD "Channel reset\n", p->host_no, channel, -1, -1);
aic7xxx_reset_device(p, ALL_TARGETS, channel, ALL_LUNS, SCB_LIST_NULL);
if ( !(p->features & AHC_TWIN) )
{
restart_sequencer(p);
}
return;
}
static void
aic7xxx_run_waiting_queues(struct aic7xxx_host *p)
{
struct aic7xxx_scb *scb;
struct aic_dev_data *aic_dev;
int sent;
if (p->waiting_scbs.head == NULL)
return;
sent = 0;
while ((scb = scbq_remove_head(&p->waiting_scbs)) != NULL)
{
aic_dev = scb->cmd->device->hostdata;
if ( !scb->tag_action )
{
aic_dev->temp_q_depth = 1;
}
if ( aic_dev->active_cmds >= aic_dev->temp_q_depth)
{
scbq_insert_tail(&aic_dev->delayed_scbs, scb);
}
else
{
scb->flags &= ~SCB_WAITINGQ;
aic_dev->active_cmds++;
p->activescbs++;
if ( !(scb->tag_action) )
{
aic7xxx_busy_target(p, scb);
}
p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
sent++;
}
}
if (sent)
{
if (p->features & AHC_QUEUE_REGS)
aic_outb(p, p->qinfifonext, HNSCB_QOFF);
else
{
pause_sequencer(p);
aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
unpause_sequencer(p, FALSE);
}
if (p->activescbs > p->max_activescbs)
p->max_activescbs = p->activescbs;
}
}
#ifdef CONFIG_PCI
#define DPE 0x80
#define SSE 0x40
#define RMA 0x20
#define RTA 0x10
#define STA 0x08
#define DPR 0x01
static void
aic7xxx_pci_intr(struct aic7xxx_host *p)
{
unsigned char status1;
pci_read_config_byte(p->pdev, PCI_STATUS + 1, &status1);
if ( (status1 & DPE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
printk(WARN_LEAD "Data Parity Error during PCI address or PCI write"
"phase.\n", p->host_no, -1, -1, -1);
if ( (status1 & SSE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
printk(WARN_LEAD "Signal System Error Detected\n", p->host_no,
-1, -1, -1);
if ( (status1 & RMA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
printk(WARN_LEAD "Received a PCI Master Abort\n", p->host_no,
-1, -1, -1);
if ( (status1 & RTA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
printk(WARN_LEAD "Received a PCI Target Abort\n", p->host_no,
-1, -1, -1);
if ( (status1 & STA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
printk(WARN_LEAD "Signaled a PCI Target Abort\n", p->host_no,
-1, -1, -1);
if ( (status1 & DPR) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
printk(WARN_LEAD "Data Parity Error has been reported via PCI pin "
"PERR#\n", p->host_no, -1, -1, -1);
pci_write_config_byte(p->pdev, PCI_STATUS + 1, status1);
if (status1 & (DPR|RMA|RTA))
aic_outb(p, CLRPARERR, CLRINT);
if ( (aic7xxx_panic_on_abort) && (p->spurious_int > 500) )
aic7xxx_panic_abort(p, NULL);
}
#endif
static void
aic7xxx_construct_ppr(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
p->msg_buf[p->msg_index++] = MSG_EXTENDED;
p->msg_buf[p->msg_index++] = MSG_EXT_PPR_LEN;
p->msg_buf[p->msg_index++] = MSG_EXT_PPR;
p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.period;
p->msg_buf[p->msg_index++] = 0;
p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.offset;
p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.width;
p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.options;
p->msg_len += 8;
}
static void
aic7xxx_construct_sdtr(struct aic7xxx_host *p, unsigned char period,
unsigned char offset)
{
p->msg_buf[p->msg_index++] = MSG_EXTENDED;
p->msg_buf[p->msg_index++] = MSG_EXT_SDTR_LEN;
p->msg_buf[p->msg_index++] = MSG_EXT_SDTR;
p->msg_buf[p->msg_index++] = period;
p->msg_buf[p->msg_index++] = offset;
p->msg_len += 5;
}
static void
aic7xxx_construct_wdtr(struct aic7xxx_host *p, unsigned char bus_width)
{
p->msg_buf[p->msg_index++] = MSG_EXTENDED;
p->msg_buf[p->msg_index++] = MSG_EXT_WDTR_LEN;
p->msg_buf[p->msg_index++] = MSG_EXT_WDTR;
p->msg_buf[p->msg_index++] = bus_width;
p->msg_len += 4;
}
static void
aic7xxx_calculate_residual (struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
struct aic7xxx_hwscb *hscb;
struct scsi_cmnd *cmd;
int actual, i;
cmd = scb->cmd;
hscb = scb->hscb;
if (((scb->hscb->control & DISCONNECTED) == 0) &&
(scb->flags & SCB_SENSE) == 0)
{
actual = scb->sg_length;
for (i=1; i < hscb->residual_SG_segment_count; i++)
{
actual -= scb->sg_list[scb->sg_count - i].length;
}
actual -= (hscb->residual_data_count[2] << 16) |
(hscb->residual_data_count[1] << 8) |
hscb->residual_data_count[0];
if (actual < cmd->underflow)
{
if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
{
printk(INFO_LEAD "Underflow - Wanted %u, %s %u, residual SG "
"count %d.\n", p->host_no, CTL_OF_SCB(scb), cmd->underflow,
(rq_data_dir(cmd->request) == WRITE) ? "wrote" : "read", actual,
hscb->residual_SG_segment_count);
printk(INFO_LEAD "status 0x%x.\n", p->host_no, CTL_OF_SCB(scb),
hscb->target_status);
}
scsi_set_resid(cmd, scb->sg_length - actual);
aic7xxx_status(cmd) = hscb->target_status;
}
}
hscb->residual_data_count[2] = 0;
hscb->residual_data_count[1] = 0;
hscb->residual_data_count[0] = 0;
hscb->residual_SG_segment_count = 0;
}
static void
aic7xxx_handle_device_reset(struct aic7xxx_host *p, int target, int channel)
{
unsigned char tindex = target;
tindex |= ((channel & 0x01) << 3);
aic_outb(p, 0, TARG_SCSIRATE + tindex);
if (p->features & AHC_ULTRA2)
aic_outb(p, 0, TARG_OFFSET + tindex);
aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Bus Device Reset delivered.\n", p->host_no, channel,
target, -1);
aic7xxx_run_done_queue(p, TRUE);
}
static void
aic7xxx_handle_seqint(struct aic7xxx_host *p, unsigned char intstat)
{
struct aic7xxx_scb *scb;
struct aic_dev_data *aic_dev;
unsigned short target_mask;
unsigned char target, lun, tindex;
unsigned char queue_flag = FALSE;
char channel;
int result;
target = ((aic_inb(p, SAVED_TCL) >> 4) & 0x0f);
if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
else
channel = 0;
tindex = target + (channel << 3);
lun = aic_inb(p, SAVED_TCL) & 0x07;
target_mask = (0x01 << tindex);
aic_outb(p, CLRSEQINT, CLRINT);
switch (intstat & SEQINT_MASK)
{
case NO_MATCH:
{
aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
SCSISEQ);
printk(WARN_LEAD "No active SCB for reconnecting target - Issuing "
"BUS DEVICE RESET.\n", p->host_no, channel, target, lun);
printk(WARN_LEAD " SAVED_TCL=0x%x, ARG_1=0x%x, SEQADDR=0x%x\n",
p->host_no, channel, target, lun,
aic_inb(p, SAVED_TCL), aic_inb(p, ARG_1),
(aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
if (aic7xxx_panic_on_abort)
aic7xxx_panic_abort(p, NULL);
}
break;
case SEND_REJECT:
{
if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
printk(INFO_LEAD "Rejecting unknown message (0x%x) received from "
"target, SEQ_FLAGS=0x%x\n", p->host_no, channel, target, lun,
aic_inb(p, ACCUM), aic_inb(p, SEQ_FLAGS));
}
break;
case NO_IDENT:
{
if (aic7xxx_verbose & (VERBOSE_SEQINT | VERBOSE_RESET_MID))
printk(INFO_LEAD "Target did not send an IDENTIFY message; "
"LASTPHASE 0x%x, SAVED_TCL 0x%x\n", p->host_no, channel, target,
lun, aic_inb(p, LASTPHASE), aic_inb(p, SAVED_TCL));
aic7xxx_reset_channel(p, channel, TRUE);
aic7xxx_run_done_queue(p, TRUE);
}
break;
case BAD_PHASE:
if (aic_inb(p, LASTPHASE) == P_BUSFREE)
{
if (aic7xxx_verbose & VERBOSE_SEQINT)
printk(INFO_LEAD "Missed busfree.\n", p->host_no, channel,
target, lun);
restart_sequencer(p);
}
else
{
if (aic7xxx_verbose & VERBOSE_SEQINT)
printk(INFO_LEAD "Unknown scsi bus phase, continuing\n", p->host_no,
channel, target, lun);
}
break;
case EXTENDED_MSG:
{
p->msg_type = MSG_TYPE_INITIATOR_MSGIN;
p->msg_len = 0;
p->msg_index = 0;
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
printk(INFO_LEAD "Enabling REQINITs for MSG_IN\n", p->host_no,
channel, target, lun);
#endif
p->flags |= AHC_HANDLING_REQINITS;
aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
return;
}
case REJECT_MSG:
{
unsigned char scb_index;
unsigned char last_msg;
scb_index = aic_inb(p, SCB_TAG);
scb = p->scb_data->scb_array[scb_index];
aic_dev = AIC_DEV(scb->cmd);
last_msg = aic_inb(p, LAST_MSG);
if ( (last_msg == MSG_IDENTIFYFLAG) &&
(scb->tag_action) &&
!(scb->flags & SCB_MSGOUT_BITS) )
{
if (scb->tag_action == MSG_ORDERED_Q_TAG)
{
scsi_adjust_queue_depth(scb->cmd->device, MSG_SIMPLE_TAG,
scb->cmd->device->queue_depth);
scb->tag_action = MSG_SIMPLE_Q_TAG;
scb->hscb->control &= ~SCB_TAG_TYPE;
scb->hscb->control |= MSG_SIMPLE_Q_TAG;
aic_outb(p, scb->hscb->control, SCB_CONTROL);
aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
}
else if (scb->tag_action == MSG_SIMPLE_Q_TAG)
{
unsigned char i;
struct aic7xxx_scb *scbp;
int old_verbose;
scsi_adjust_queue_depth(scb->cmd->device, 0 ,
p->host->cmd_per_lun);
aic_dev->max_q_depth = aic_dev->temp_q_depth = 1;
scb->tag_action = 0;
scb->hscb->control &= ~(TAG_ENB | SCB_TAG_TYPE);
aic_outb(p, scb->hscb->control, SCB_CONTROL);
old_verbose = aic7xxx_verbose;
aic7xxx_verbose &= ~(VERBOSE_RESET|VERBOSE_ABORT);
for (i=0; i < p->scb_data->numscbs; i++)
{
scbp = p->scb_data->scb_array[i];
if ((scbp->flags & SCB_ACTIVE) && (scbp != scb))
{
if (aic7xxx_match_scb(p, scbp, target, channel, lun, i))
{
aic7xxx_reset_device(p, target, channel, lun, i);
}
}
}
aic7xxx_run_done_queue(p, TRUE);
aic7xxx_verbose = old_verbose;
aic7xxx_busy_target(p, scb);
printk(INFO_LEAD "Device is refusing tagged commands, using "
"untagged I/O.\n", p->host_no, channel, target, lun);
aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
}
}
else if (scb->flags & SCB_MSGOUT_PPR)
{
aic_dev->needppr = aic_dev->needppr_copy = 0;
aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
(AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE), aic_dev);
aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
aic_dev);
aic_dev->goal.options = aic_dev->dtr_pending = 0;
scb->flags &= ~SCB_MSGOUT_BITS;
if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Device is rejecting PPR messages, falling "
"back.\n", p->host_no, channel, target, lun);
}
if ( aic_dev->goal.width )
{
aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
aic_dev->dtr_pending = 1;
scb->flags |= SCB_MSGOUT_WDTR;
}
if ( aic_dev->goal.offset )
{
aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
if( !aic_dev->dtr_pending )
{
aic_dev->dtr_pending = 1;
scb->flags |= SCB_MSGOUT_SDTR;
}
}
if ( aic_dev->dtr_pending )
{
aic_outb(p, HOST_MSG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
}
}
else if (scb->flags & SCB_MSGOUT_WDTR)
{
aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
scb->flags &= ~SCB_MSGOUT_BITS;
aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
(AHC_TRANS_ACTIVE|AHC_TRANS_GOAL|AHC_TRANS_CUR), aic_dev);
aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
aic_dev);
if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Device is rejecting WDTR messages, using "
"narrow transfers.\n", p->host_no, channel, target, lun);
}
aic_dev->needsdtr = aic_dev->needsdtr_copy;
}
else if (scb->flags & SCB_MSGOUT_SDTR)
{
aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
scb->flags &= ~SCB_MSGOUT_BITS;
aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
(AHC_TRANS_CUR|AHC_TRANS_ACTIVE|AHC_TRANS_GOAL), aic_dev);
if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Device is rejecting SDTR messages, using "
"async transfers.\n", p->host_no, channel, target, lun);
}
}
else if (aic7xxx_verbose & VERBOSE_SEQINT)
{
printk(INFO_LEAD "Received MESSAGE_REJECT for unknown cause. "
"Ignoring.\n", p->host_no, channel, target, lun);
}
}
break;
case BAD_STATUS:
{
unsigned char scb_index;
struct aic7xxx_hwscb *hscb;
struct scsi_cmnd *cmd;
aic_outb(p, 0, RETURN_1);
scb_index = aic_inb(p, SCB_TAG);
if (scb_index > p->scb_data->numscbs)
{
printk(WARN_LEAD "Invalid SCB during SEQINT 0x%02x, SCB_TAG %d.\n",
p->host_no, channel, target, lun, intstat, scb_index);
break;
}
scb = p->scb_data->scb_array[scb_index];
hscb = scb->hscb;
if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
{
printk(WARN_LEAD "Invalid SCB during SEQINT 0x%x, scb %d, flags 0x%x,"
" cmd 0x%lx.\n", p->host_no, channel, target, lun, intstat,
scb_index, scb->flags, (unsigned long) scb->cmd);
}
else
{
cmd = scb->cmd;
aic_dev = AIC_DEV(scb->cmd);
hscb->target_status = aic_inb(p, SCB_TARGET_STATUS);
aic7xxx_status(cmd) = hscb->target_status;
cmd->result = hscb->target_status;
switch (status_byte(hscb->target_status))
{
case GOOD:
if (aic7xxx_verbose & VERBOSE_SEQINT)
printk(INFO_LEAD "Interrupted for status of GOOD???\n",
p->host_no, CTL_OF_SCB(scb));
break;
case COMMAND_TERMINATED:
case CHECK_CONDITION:
if ( !(scb->flags & SCB_SENSE) )
{
memcpy(scb->sense_cmd, &generic_sense[0],
sizeof(generic_sense));
scb->sense_cmd[1] = (cmd->device->lun << 5);
scb->sense_cmd[4] = SCSI_SENSE_BUFFERSIZE;
scb->sg_list[0].length =
cpu_to_le32(SCSI_SENSE_BUFFERSIZE);
scb->sg_list[0].address =
cpu_to_le32(pci_map_single(p->pdev, cmd->sense_buffer,
SCSI_SENSE_BUFFERSIZE,
PCI_DMA_FROMDEVICE));
hscb->control = 0;
hscb->target_status = 0;
hscb->SG_list_pointer =
cpu_to_le32(SCB_DMA_ADDR(scb, scb->sg_list));
hscb->SCSI_cmd_pointer =
cpu_to_le32(SCB_DMA_ADDR(scb, scb->sense_cmd));
hscb->data_count = scb->sg_list[0].length;
hscb->data_pointer = scb->sg_list[0].address;
hscb->SCSI_cmd_length = COMMAND_SIZE(scb->sense_cmd[0]);
hscb->residual_SG_segment_count = 0;
hscb->residual_data_count[0] = 0;
hscb->residual_data_count[1] = 0;
hscb->residual_data_count[2] = 0;
scb->sg_count = hscb->SG_segment_count = 1;
scb->sg_length = SCSI_SENSE_BUFFERSIZE;
scb->tag_action = 0;
scb->flags |= SCB_SENSE;
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
if (scb->flags & SCB_MSGOUT_BITS)
printk(INFO_LEAD "Requesting SENSE with %s\n", p->host_no,
CTL_OF_SCB(scb), (scb->flags & SCB_MSGOUT_SDTR) ?
"SDTR" : "WDTR");
else
printk(INFO_LEAD "Requesting SENSE, no MSG\n", p->host_no,
CTL_OF_SCB(scb));
}
#endif
aic7xxx_busy_target(p, scb);
aic_outb(p, SEND_SENSE, RETURN_1);
aic7xxx_error(cmd) = DID_OK;
break;
}
printk(INFO_LEAD "CHECK_CONDITION on REQUEST_SENSE, returning "
"an error.\n", p->host_no, CTL_OF_SCB(scb));
aic7xxx_error(cmd) = DID_ERROR;
scb->flags &= ~SCB_SENSE;
break;
case QUEUE_FULL:
queue_flag = TRUE;
case BUSY:
{
struct aic7xxx_scb *next_scbp, *prev_scbp;
unsigned char active_hscb, next_hscb, prev_hscb, scb_index;
next_scbp = p->waiting_scbs.head;
while ( next_scbp != NULL )
{
prev_scbp = next_scbp;
next_scbp = next_scbp->q_next;
if ( aic7xxx_match_scb(p, prev_scbp, target, channel, lun,
SCB_LIST_NULL) )
{
scbq_remove(&p->waiting_scbs, prev_scbp);
scb->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
p->activescbs++;
aic_dev->active_cmds++;
}
}
aic7xxx_search_qinfifo(p, target, channel, lun,
SCB_LIST_NULL, SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL,
FALSE, NULL);
next_scbp = NULL;
active_hscb = aic_inb(p, SCBPTR);
prev_hscb = next_hscb = scb_index = SCB_LIST_NULL;
next_hscb = aic_inb(p, WAITING_SCBH);
while (next_hscb != SCB_LIST_NULL)
{
aic_outb(p, next_hscb, SCBPTR);
scb_index = aic_inb(p, SCB_TAG);
if (scb_index < p->scb_data->numscbs)
{
next_scbp = p->scb_data->scb_array[scb_index];
if (aic7xxx_match_scb(p, next_scbp, target, channel, lun,
SCB_LIST_NULL) )
{
next_scbp->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
next_hscb = aic_inb(p, SCB_NEXT);
aic_outb(p, 0, SCB_CONTROL);
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic7xxx_add_curscb_to_free_list(p);
if (prev_hscb == SCB_LIST_NULL)
{
aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
aic_outb(p, CLRSELTIMEO, CLRSINT1);
aic_outb(p, next_hscb, WAITING_SCBH);
}
else
{
aic_outb(p, prev_hscb, SCBPTR);
aic_outb(p, next_hscb, SCB_NEXT);
}
}
else
{
prev_hscb = next_hscb;
next_hscb = aic_inb(p, SCB_NEXT);
}
}
}
aic_outb(p, active_hscb, SCBPTR);
aic7xxx_run_done_queue(p, FALSE);
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if( (aic7xxx_verbose & VERBOSE_MINOR_ERROR) ||
(aic7xxx_verbose > 0xffff) )
{
if (queue_flag)
printk(INFO_LEAD "Queue full received; queue depth %d, "
"active %d\n", p->host_no, CTL_OF_SCB(scb),
aic_dev->max_q_depth, aic_dev->active_cmds);
else
printk(INFO_LEAD "Target busy\n", p->host_no, CTL_OF_SCB(scb));
}
#endif
if (queue_flag)
{
int diff;
result = scsi_track_queue_full(cmd->device,
aic_dev->active_cmds);
if ( result < 0 )
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
printk(INFO_LEAD "Tagged Command Queueing disabled.\n",
p->host_no, CTL_OF_SCB(scb));
diff = aic_dev->max_q_depth - p->host->cmd_per_lun;
aic_dev->temp_q_depth = 1;
aic_dev->max_q_depth = 1;
}
else if ( result > 0 )
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
printk(INFO_LEAD "Queue depth reduced to %d\n", p->host_no,
CTL_OF_SCB(scb), result);
diff = aic_dev->max_q_depth - result;
aic_dev->max_q_depth = result;
if(aic_dev->temp_q_depth > result)
aic_dev->temp_q_depth = result;
}
}
break;
}
default:
if (aic7xxx_verbose & VERBOSE_SEQINT)
printk(INFO_LEAD "Unexpected target status 0x%x.\n", p->host_no,
CTL_OF_SCB(scb), scb->hscb->target_status);
if (!aic7xxx_error(cmd))
{
aic7xxx_error(cmd) = DID_RETRY_COMMAND;
}
break;
}
}
}
break;
case AWAITING_MSG:
{
unsigned char scb_index, msg_out;
scb_index = aic_inb(p, SCB_TAG);
msg_out = aic_inb(p, MSG_OUT);
scb = p->scb_data->scb_array[scb_index];
aic_dev = AIC_DEV(scb->cmd);
p->msg_index = p->msg_len = 0;
if ( !(scb->flags & SCB_DEVICE_RESET) &&
(msg_out == MSG_IDENTIFYFLAG) &&
(scb->hscb->control & TAG_ENB) )
{
p->msg_buf[p->msg_index++] = scb->tag_action;
p->msg_buf[p->msg_index++] = scb->hscb->tag;
p->msg_len += 2;
}
if (scb->flags & SCB_DEVICE_RESET)
{
p->msg_buf[p->msg_index++] = MSG_BUS_DEV_RESET;
p->msg_len++;
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Bus device reset mailed.\n",
p->host_no, CTL_OF_SCB(scb));
}
else if (scb->flags & SCB_ABORT)
{
if (scb->tag_action)
{
p->msg_buf[p->msg_index++] = MSG_ABORT_TAG;
}
else
{
p->msg_buf[p->msg_index++] = MSG_ABORT;
}
p->msg_len++;
if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
printk(INFO_LEAD "Abort message mailed.\n", p->host_no,
CTL_OF_SCB(scb));
}
else if (scb->flags & SCB_MSGOUT_PPR)
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Sending PPR (%d/%d/%d/%d) message.\n",
p->host_no, CTL_OF_SCB(scb),
aic_dev->goal.period,
aic_dev->goal.offset,
aic_dev->goal.width,
aic_dev->goal.options);
}
aic7xxx_construct_ppr(p, scb);
}
else if (scb->flags & SCB_MSGOUT_WDTR)
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Sending WDTR message.\n", p->host_no,
CTL_OF_SCB(scb));
}
aic7xxx_construct_wdtr(p, aic_dev->goal.width);
}
else if (scb->flags & SCB_MSGOUT_SDTR)
{
unsigned int max_sync, period;
unsigned char options = 0;
if (p->features & AHC_ULTRA2)
{
if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
!(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
{
max_sync = AHC_SYNCRATE_ULTRA2;
}
else
{
max_sync = AHC_SYNCRATE_ULTRA;
}
}
else if (p->features & AHC_ULTRA)
{
max_sync = AHC_SYNCRATE_ULTRA;
}
else
{
max_sync = AHC_SYNCRATE_FAST;
}
period = aic_dev->goal.period;
aic7xxx_find_syncrate(p, &period, max_sync, &options);
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Sending SDTR %d/%d message.\n", p->host_no,
CTL_OF_SCB(scb), period,
aic_dev->goal.offset);
}
aic7xxx_construct_sdtr(p, period, aic_dev->goal.offset);
}
else
{
panic("aic7xxx: AWAITING_MSG for an SCB that does "
"not have a waiting message.\n");
}
scb->flags |= SCB_MSGOUT_SENT;
p->msg_index = 0;
p->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
p->flags |= AHC_HANDLING_REQINITS;
aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
return;
}
break;
case DATA_OVERRUN:
{
unsigned char scb_index = aic_inb(p, SCB_TAG);
unsigned char lastphase = aic_inb(p, LASTPHASE);
unsigned int i;
scb = (p->scb_data->scb_array[scb_index]);
if ( !(scb->flags & SCB_SENSE) )
{
printk(WARN_LEAD "Data overrun detected in %s phase, tag %d;\n",
p->host_no, CTL_OF_SCB(scb),
(lastphase == P_DATAIN) ? "Data-In" : "Data-Out", scb->hscb->tag);
printk(KERN_WARNING " %s seen Data Phase. Length=%d, NumSGs=%d.\n",
(aic_inb(p, SEQ_FLAGS) & DPHASE) ? "Have" : "Haven't",
scb->sg_length, scb->sg_count);
printk(KERN_WARNING " Raw SCSI Command: 0x");
for (i = 0; i < scb->hscb->SCSI_cmd_length; i++)
{
printk("%02x ", scb->cmd->cmnd[i]);
}
printk("\n");
if(aic7xxx_verbose > 0xffff)
{
for (i = 0; i < scb->sg_count; i++)
{
printk(KERN_WARNING " sg[%d] - Addr 0x%x : Length %d\n",
i,
le32_to_cpu(scb->sg_list[i].address),
le32_to_cpu(scb->sg_list[i].length) );
}
}
aic7xxx_error(scb->cmd) = DID_ERROR;
}
else
printk(INFO_LEAD "Data Overrun during SEND_SENSE operation.\n",
p->host_no, CTL_OF_SCB(scb));
}
break;
case WIDE_RESIDUE:
{
unsigned char resid_sgcnt, index;
unsigned char scb_index = aic_inb(p, SCB_TAG);
unsigned int cur_addr, resid_dcnt;
unsigned int native_addr, native_length, sg_addr;
int i;
if(scb_index > p->scb_data->numscbs)
{
printk(WARN_LEAD "invalid scb_index during WIDE_RESIDUE.\n",
p->host_no, -1, -1, -1);
break;
}
scb = p->scb_data->scb_array[scb_index];
if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
{
printk(WARN_LEAD "invalid scb during WIDE_RESIDUE flags:0x%x "
"scb->cmd:0x%lx\n", p->host_no, CTL_OF_SCB(scb),
scb->flags, (unsigned long)scb->cmd);
break;
}
if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
printk(INFO_LEAD "Got WIDE_RESIDUE message, patching up data "
"pointer.\n", p->host_no, CTL_OF_SCB(scb));
cur_addr = aic_inb(p, SHADDR) | (aic_inb(p, SHADDR + 1) << 8) |
(aic_inb(p, SHADDR + 2) << 16) | (aic_inb(p, SHADDR + 3) << 24);
sg_addr = aic_inb(p, SG_COUNT + 1) | (aic_inb(p, SG_COUNT + 2) << 8) |
(aic_inb(p, SG_COUNT + 3) << 16) | (aic_inb(p, SG_COUNT + 4) << 24);
resid_sgcnt = aic_inb(p, SCB_RESID_SGCNT);
resid_dcnt = aic_inb(p, SCB_RESID_DCNT) |
(aic_inb(p, SCB_RESID_DCNT + 1) << 8) |
(aic_inb(p, SCB_RESID_DCNT + 2) << 16);
index = scb->sg_count - ((resid_sgcnt) ? resid_sgcnt : 1);
native_addr = le32_to_cpu(scb->sg_list[index].address);
native_length = le32_to_cpu(scb->sg_list[index].length);
if(resid_dcnt == native_length)
{
if(index == 0)
{
break;
}
resid_dcnt = 1;
resid_sgcnt += 1;
native_addr = le32_to_cpu(scb->sg_list[index - 1].address);
native_length = le32_to_cpu(scb->sg_list[index - 1].length);
cur_addr = native_addr + (native_length - 1);
sg_addr -= sizeof(struct hw_scatterlist);
}
else
{
resid_dcnt += 1;
cur_addr -= 1;
}
aic_outb(p, resid_sgcnt, SG_COUNT);
aic_outb(p, resid_sgcnt, SCB_RESID_SGCNT);
aic_outb(p, sg_addr & 0xff, SG_COUNT + 1);
aic_outb(p, (sg_addr >> 8) & 0xff, SG_COUNT + 2);
aic_outb(p, (sg_addr >> 16) & 0xff, SG_COUNT + 3);
aic_outb(p, (sg_addr >> 24) & 0xff, SG_COUNT + 4);
aic_outb(p, resid_dcnt & 0xff, SCB_RESID_DCNT);
aic_outb(p, (resid_dcnt >> 8) & 0xff, SCB_RESID_DCNT + 1);
aic_outb(p, (resid_dcnt >> 16) & 0xff, SCB_RESID_DCNT + 2);
if(p->features & AHC_ULTRA2)
{
aic_outb(p, resid_dcnt & 0xff, HCNT);
aic_outb(p, (resid_dcnt >> 8) & 0xff, HCNT + 1);
aic_outb(p, (resid_dcnt >> 16) & 0xff, HCNT + 2);
aic_outb(p, cur_addr & 0xff, HADDR);
aic_outb(p, (cur_addr >> 8) & 0xff, HADDR + 1);
aic_outb(p, (cur_addr >> 16) & 0xff, HADDR + 2);
aic_outb(p, (cur_addr >> 24) & 0xff, HADDR + 3);
aic_outb(p, aic_inb(p, DMAPARAMS) | PRELOADEN, DFCNTRL);
udelay(1);
aic_outb(p, aic_inb(p, DMAPARAMS) & ~(SCSIEN|HDMAEN), DFCNTRL);
i=0;
while(((aic_inb(p, DFCNTRL) & (SCSIEN|HDMAEN)) != 0) && (i++ < 1000))
{
udelay(1);
}
}
else
{
aic_outb(p, cur_addr & 0xff, SHADDR);
aic_outb(p, (cur_addr >> 8) & 0xff, SHADDR + 1);
aic_outb(p, (cur_addr >> 16) & 0xff, SHADDR + 2);
aic_outb(p, (cur_addr >> 24) & 0xff, SHADDR + 3);
}
}
break;
case SEQ_SG_FIXUP:
{
unsigned char scb_index, tmp;
int sg_addr, sg_length;
scb_index = aic_inb(p, SCB_TAG);
if(scb_index > p->scb_data->numscbs)
{
printk(WARN_LEAD "invalid scb_index during SEQ_SG_FIXUP.\n",
p->host_no, -1, -1, -1);
printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
"0x%x\n", p->host_no, -1, -1, -1,
aic_inb(p, SCSISIGI),
aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
p->host_no, -1, -1, -1, aic_inb(p, SG_CACHEPTR),
aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
break;
}
scb = p->scb_data->scb_array[scb_index];
if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
{
printk(WARN_LEAD "invalid scb during SEQ_SG_FIXUP flags:0x%x "
"scb->cmd:0x%p\n", p->host_no, CTL_OF_SCB(scb),
scb->flags, scb->cmd);
printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
"0x%x\n", p->host_no, CTL_OF_SCB(scb),
aic_inb(p, SCSISIGI),
aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
p->host_no, CTL_OF_SCB(scb), aic_inb(p, SG_CACHEPTR),
aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
break;
}
if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
printk(INFO_LEAD "Fixing up SG address for sequencer.\n", p->host_no,
CTL_OF_SCB(scb));
tmp = aic_inb(p, SG_NEXT);
tmp += SG_SIZEOF;
aic_outb(p, tmp, SG_NEXT);
if( tmp < SG_SIZEOF )
aic_outb(p, aic_inb(p, SG_NEXT + 1) + 1, SG_NEXT + 1);
tmp = aic_inb(p, SG_COUNT) - 1;
aic_outb(p, tmp, SG_COUNT);
sg_addr = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].address);
sg_length = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].length);
aic_outb(p, sg_addr & 0xff, HADDR);
aic_outb(p, (sg_addr >> 8) & 0xff, HADDR + 1);
aic_outb(p, (sg_addr >> 16) & 0xff, HADDR + 2);
aic_outb(p, (sg_addr >> 24) & 0xff, HADDR + 3);
aic_outb(p, sg_length & 0xff, HCNT);
aic_outb(p, (sg_length >> 8) & 0xff, HCNT + 1);
aic_outb(p, (sg_length >> 16) & 0xff, HCNT + 2);
aic_outb(p, (tmp << 2) | ((tmp == 1) ? LAST_SEG : 0), SG_CACHEPTR);
aic_outb(p, aic_inb(p, DMAPARAMS), DFCNTRL);
while(aic_inb(p, SSTAT0) & SDONE) udelay(1);
while(aic_inb(p, DFCNTRL) & (HDMAEN|SCSIEN)) aic_outb(p, 0, DFCNTRL);
}
break;
#ifdef AIC7XXX_NOT_YET
case TRACEPOINT2:
{
printk(INFO_LEAD "Tracepoint #2 reached.\n", p->host_no,
channel, target, lun);
}
break;
case MSG_BUFFER_BUSY:
printk("aic7xxx: Message buffer busy.\n");
break;
case MSGIN_PHASEMIS:
printk("aic7xxx: Message-in phasemis.\n");
break;
#endif
default:
printk(WARN_LEAD "Unknown SEQINT, INTSTAT 0x%x, SCSISIGI 0x%x.\n",
p->host_no, channel, target, lun, intstat,
aic_inb(p, SCSISIGI));
break;
}
unpause_sequencer(p, TRUE);
}
static int
aic7xxx_parse_msg(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
int reject, reply, done;
unsigned char target_scsirate, tindex;
unsigned short target_mask;
unsigned char target, channel, lun;
unsigned char bus_width, new_bus_width;
unsigned char trans_options, new_trans_options;
unsigned int period, new_period, offset, new_offset, maxsync;
struct aic7xxx_syncrate *syncrate;
struct aic_dev_data *aic_dev;
target = scb->cmd->device->id;
channel = scb->cmd->device->channel;
lun = scb->cmd->device->lun;
reply = reject = done = FALSE;
tindex = TARGET_INDEX(scb->cmd);
aic_dev = AIC_DEV(scb->cmd);
target_scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
target_mask = (0x01 << tindex);
if (p->msg_buf[0] != MSG_EXTENDED)
{
reject = TRUE;
}
if (p->features & AHC_ULTRA2)
{
if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
!(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
{
if (p->features & AHC_ULTRA3)
maxsync = AHC_SYNCRATE_ULTRA3;
else
maxsync = AHC_SYNCRATE_ULTRA2;
}
else
{
maxsync = AHC_SYNCRATE_ULTRA;
}
}
else if (p->features & AHC_ULTRA)
{
maxsync = AHC_SYNCRATE_ULTRA;
}
else
{
maxsync = AHC_SYNCRATE_FAST;
}
if ( !reject && (p->msg_len > 2) )
{
switch(p->msg_buf[2])
{
case MSG_EXT_SDTR:
{
if (p->msg_buf[1] != MSG_EXT_SDTR_LEN)
{
reject = TRUE;
break;
}
if (p->msg_len < (MSG_EXT_SDTR_LEN + 2))
{
break;
}
period = new_period = p->msg_buf[3];
offset = new_offset = p->msg_buf[4];
trans_options = new_trans_options = 0;
bus_width = new_bus_width = target_scsirate & WIDEXFER;
if(maxsync == AHC_SYNCRATE_ULTRA3)
maxsync = AHC_SYNCRATE_ULTRA2;
if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR)) !=
(SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR) )
{
if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
{
aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
aic_dev->goal.options = 0;
if(p->user[tindex].offset)
{
aic_dev->needsdtr_copy = 1;
aic_dev->goal.period = max_t(unsigned char, 10,p->user[tindex].period);
if(p->features & AHC_ULTRA2)
{
aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
}
else
{
aic_dev->goal.offset = MAX_OFFSET_8BIT;
}
}
else
{
aic_dev->needsdtr_copy = 0;
aic_dev->goal.period = 255;
aic_dev->goal.offset = 0;
}
aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
}
else if (aic_dev->needsdtr_copy == 0)
{
reject = TRUE;
break;
}
reply = TRUE;
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Received pre-emptive SDTR message from "
"target.\n", p->host_no, CTL_OF_SCB(scb));
}
new_period = max_t(unsigned int, period, aic_dev->goal.period);
new_offset = min_t(unsigned int, offset, aic_dev->goal.offset);
}
syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
&trans_options);
aic7xxx_validate_offset(p, syncrate, &new_offset, bus_width);
if ((new_offset == 0) && (new_offset != offset))
{
aic_dev->needsdtr_copy = 0;
reply = TRUE;
}
if(reply)
{
aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
new_offset, trans_options,
AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
aic_dev);
scb->flags &= ~SCB_MSGOUT_BITS;
scb->flags |= SCB_MSGOUT_SDTR;
aic_outb(p, HOST_MSG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
}
else
{
aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
new_offset, trans_options,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
aic_dev->needsdtr = 0;
}
done = TRUE;
break;
}
case MSG_EXT_WDTR:
{
if (p->msg_buf[1] != MSG_EXT_WDTR_LEN)
{
reject = TRUE;
break;
}
if (p->msg_len < (MSG_EXT_WDTR_LEN + 2))
{
break;
}
bus_width = new_bus_width = p->msg_buf[3];
if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR)) ==
(SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR) )
{
switch(bus_width)
{
default:
{
reject = TRUE;
if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
((aic_dev->flags & DEVICE_PRINT_DTR) ||
(aic7xxx_verbose > 0xffff)) )
{
printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
}
}
case MSG_EXT_WDTR_BUS_8_BIT:
{
aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
aic_dev->needwdtr_copy &= ~target_mask;
break;
}
case MSG_EXT_WDTR_BUS_16_BIT:
{
break;
}
}
aic_dev->needwdtr = 0;
aic7xxx_set_width(p, target, channel, lun, new_bus_width,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
}
else
{
if ( !(aic_dev->flags & DEVICE_DTR_SCANNED) )
{
if( (p->features & AHC_WIDE) && p->user[tindex].width )
{
aic_dev->goal.width = MSG_EXT_WDTR_BUS_16_BIT;
aic_dev->needwdtr_copy = 1;
}
aic_dev->goal.options = 0;
if(p->user[tindex].offset)
{
aic_dev->needsdtr_copy = 1;
aic_dev->goal.period = max_t(unsigned char, 10, p->user[tindex].period);
if(p->features & AHC_ULTRA2)
{
aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
}
else if( aic_dev->goal.width )
{
aic_dev->goal.offset = MAX_OFFSET_16BIT;
}
else
{
aic_dev->goal.offset = MAX_OFFSET_8BIT;
}
} else {
aic_dev->needsdtr_copy = 0;
aic_dev->goal.period = 255;
aic_dev->goal.offset = 0;
}
aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
}
else if (aic_dev->needwdtr_copy == 0)
{
reject = TRUE;
break;
}
reply = TRUE;
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Received pre-emptive WDTR message from "
"target.\n", p->host_no, CTL_OF_SCB(scb));
}
switch(bus_width)
{
case MSG_EXT_WDTR_BUS_16_BIT:
{
if ( (p->features & AHC_WIDE) &&
(aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) )
{
new_bus_width = MSG_EXT_WDTR_BUS_16_BIT;
break;
}
}
default:
case MSG_EXT_WDTR_BUS_8_BIT:
{
aic_dev->needwdtr_copy = 0;
new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
break;
}
}
scb->flags &= ~SCB_MSGOUT_BITS;
scb->flags |= SCB_MSGOUT_WDTR;
aic_dev->needwdtr = 0;
if(aic_dev->dtr_pending == 0)
{
aic_dev->dtr_pending = 1;
scb->flags |= SCB_DTR_SCB;
}
aic_outb(p, HOST_MSG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
aic7xxx_set_width(p, target, channel, lun, new_bus_width,
AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
aic_dev);
}
aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
aic_dev);
aic_dev->needsdtr = aic_dev->needsdtr_copy;
done = TRUE;
break;
}
case MSG_EXT_PPR:
{
if (p->msg_buf[1] != MSG_EXT_PPR_LEN)
{
reject = TRUE;
break;
}
if (p->msg_len < (MSG_EXT_PPR_LEN + 2))
{
break;
}
period = new_period = p->msg_buf[3];
offset = new_offset = p->msg_buf[5];
bus_width = new_bus_width = p->msg_buf[6];
trans_options = new_trans_options = p->msg_buf[7] & 0xf;
if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Parsing PPR message (%d/%d/%d/%d)\n",
p->host_no, CTL_OF_SCB(scb), period, offset, bus_width,
trans_options);
}
if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR)) !=
(SCB_MSGOUT_SENT|SCB_MSGOUT_PPR) )
{
if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
{
aic_dev->needppr = aic_dev->needppr_copy = 1;
aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
aic_dev->flags |= DEVICE_SCSI_3;
aic_dev->goal.width = p->user[tindex].width;
if(p->user[tindex].offset)
{
aic_dev->goal.period = p->user[tindex].period;
aic_dev->goal.options = p->user[tindex].options;
if(p->features & AHC_ULTRA2)
{
aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
}
else if( aic_dev->goal.width &&
(bus_width == MSG_EXT_WDTR_BUS_16_BIT) &&
p->features & AHC_WIDE )
{
aic_dev->goal.offset = MAX_OFFSET_16BIT;
}
else
{
aic_dev->goal.offset = MAX_OFFSET_8BIT;
}
}
else
{
aic_dev->goal.period = 255;
aic_dev->goal.offset = 0;
aic_dev->goal.options = 0;
}
aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
}
else if (aic_dev->needppr_copy == 0)
{
reject = TRUE;
break;
}
reply = TRUE;
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Received pre-emptive PPR message from "
"target.\n", p->host_no, CTL_OF_SCB(scb));
}
}
switch(bus_width)
{
case MSG_EXT_WDTR_BUS_16_BIT:
{
if ( (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) &&
p->features & AHC_WIDE)
{
break;
}
}
default:
{
if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
((aic_dev->flags & DEVICE_PRINT_DTR) ||
(aic7xxx_verbose > 0xffff)) )
{
reply = TRUE;
printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
}
}
case MSG_EXT_WDTR_BUS_8_BIT:
{
new_trans_options = 0;
new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
break;
}
}
if(reply)
{
aic7xxx_set_width(p, target, channel, lun, new_bus_width,
AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
aic_dev);
syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
&new_trans_options);
aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
new_offset, new_trans_options,
AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
aic_dev);
}
else
{
aic7xxx_set_width(p, target, channel, lun, new_bus_width,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
&new_trans_options);
aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
new_offset, new_trans_options,
AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
}
if(new_trans_options == 0)
{
aic_dev->needppr = aic_dev->needppr_copy = 0;
if(new_offset)
{
aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
}
if (new_bus_width)
{
aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
}
}
if((new_offset == 0) && (offset != 0))
{
reply = TRUE;
}
if(reply)
{
scb->flags &= ~SCB_MSGOUT_BITS;
scb->flags |= SCB_MSGOUT_PPR;
aic_outb(p, HOST_MSG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
}
else
{
aic_dev->needppr = 0;
}
done = TRUE;
break;
}
default:
{
reject = TRUE;
break;
}
}
}
if (!reply && reject)
{
aic_outb(p, MSG_MESSAGE_REJECT, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
done = TRUE;
}
return(done);
}
static void
aic7xxx_handle_reqinit(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
{
unsigned char lastbyte;
unsigned char phasemis;
int done = FALSE;
switch(p->msg_type)
{
case MSG_TYPE_INITIATOR_MSGOUT:
{
if (p->msg_len == 0)
panic("aic7xxx: REQINIT with no active message!\n");
lastbyte = (p->msg_index == (p->msg_len - 1));
phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK) != P_MESGOUT;
if (lastbyte || phasemis)
{
p->msg_len = 0;
p->msg_type = MSG_TYPE_NONE;
aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
aic_outb(p, CLRSCSIINT, CLRINT);
p->flags &= ~AHC_HANDLING_REQINITS;
if (phasemis == 0)
{
aic_outb(p, p->msg_buf[p->msg_index], SINDEX);
aic_outb(p, 0, RETURN_1);
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
printk(INFO_LEAD "Completed sending of REQINIT message.\n",
p->host_no, CTL_OF_SCB(scb));
#endif
}
else
{
aic_outb(p, MSGOUT_PHASEMIS, RETURN_1);
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
printk(INFO_LEAD "PHASEMIS while sending REQINIT message.\n",
p->host_no, CTL_OF_SCB(scb));
#endif
}
unpause_sequencer(p, TRUE);
}
else
{
aic_outb(p, CLRREQINIT, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
aic_outb(p, p->msg_buf[p->msg_index++], SCSIDATL);
}
break;
}
case MSG_TYPE_INITIATOR_MSGIN:
{
phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK ) != P_MESGIN;
if (phasemis == 0)
{
p->msg_len++;
p->msg_buf[p->msg_index] = aic_inb(p, SCSIBUSL);
done = aic7xxx_parse_msg(p, scb);
aic_outb(p, CLRREQINIT, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
aic_inb(p, SCSIDATL);
p->msg_index++;
}
if (phasemis || done)
{
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
{
if (phasemis)
printk(INFO_LEAD "PHASEMIS while receiving REQINIT message.\n",
p->host_no, CTL_OF_SCB(scb));
else
printk(INFO_LEAD "Completed receipt of REQINIT message.\n",
p->host_no, CTL_OF_SCB(scb));
}
#endif
p->msg_len = 0;
p->msg_type = MSG_TYPE_NONE;
aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
aic_outb(p, CLRSCSIINT, CLRINT);
p->flags &= ~AHC_HANDLING_REQINITS;
unpause_sequencer(p, TRUE);
}
break;
}
default:
{
panic("aic7xxx: Unknown REQINIT message type.\n");
break;
}
}
}
static void
aic7xxx_handle_scsiint(struct aic7xxx_host *p, unsigned char intstat)
{
unsigned char scb_index;
unsigned char status;
struct aic7xxx_scb *scb;
struct aic_dev_data *aic_dev;
scb_index = aic_inb(p, SCB_TAG);
status = aic_inb(p, SSTAT1);
if (scb_index < p->scb_data->numscbs)
{
scb = p->scb_data->scb_array[scb_index];
if ((scb->flags & SCB_ACTIVE) == 0)
{
scb = NULL;
}
}
else
{
scb = NULL;
}
if ((status & SCSIRSTI) != 0)
{
int channel;
if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
else
channel = 0;
if (aic7xxx_verbose & VERBOSE_RESET)
printk(WARN_LEAD "Someone else reset the channel!!\n",
p->host_no, channel, -1, -1);
if (aic7xxx_panic_on_abort)
aic7xxx_panic_abort(p, NULL);
aic7xxx_reset_channel(p, channel, FALSE);
aic7xxx_run_done_queue(p, TRUE);
scb = NULL;
}
else if ( ((status & BUSFREE) != 0) && ((status & SELTO) == 0) )
{
unsigned char lastphase = aic_inb(p, LASTPHASE);
unsigned char saved_tcl = aic_inb(p, SAVED_TCL);
unsigned char target = (saved_tcl >> 4) & 0x0F;
int channel;
int printerror = TRUE;
if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
else
channel = 0;
aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
SCSISEQ);
if (lastphase == P_MESGOUT)
{
unsigned char message;
message = aic_inb(p, SINDEX);
if ((message == MSG_ABORT) || (message == MSG_ABORT_TAG))
{
if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
printk(INFO_LEAD "SCB %d abort delivered.\n", p->host_no,
CTL_OF_SCB(scb), scb->hscb->tag);
aic7xxx_reset_device(p, target, channel, ALL_LUNS,
(message == MSG_ABORT) ? SCB_LIST_NULL : scb->hscb->tag );
aic7xxx_run_done_queue(p, TRUE);
scb = NULL;
printerror = 0;
}
else if (message == MSG_BUS_DEV_RESET)
{
aic7xxx_handle_device_reset(p, target, channel);
scb = NULL;
printerror = 0;
}
}
if ( (scb != NULL) && (scb->flags & SCB_DTR_SCB) )
{
printerror = 0;
aic7xxx_reset_device(p, target, channel, ALL_LUNS, scb->hscb->tag);
aic7xxx_run_done_queue(p, TRUE);
scb = NULL;
}
if (printerror != 0)
{
if (scb != NULL)
{
unsigned char tag;
if ((scb->hscb->control & TAG_ENB) != 0)
{
tag = scb->hscb->tag;
}
else
{
tag = SCB_LIST_NULL;
}
aic7xxx_reset_device(p, target, channel, ALL_LUNS, tag);
aic7xxx_run_done_queue(p, TRUE);
}
else
{
aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
aic7xxx_run_done_queue(p, TRUE);
}
printk(INFO_LEAD "Unexpected busfree, LASTPHASE = 0x%x, "
"SEQADDR = 0x%x\n", p->host_no, channel, target, -1, lastphase,
(aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
scb = NULL;
}
aic_outb(p, MSG_NOOP, MSG_OUT);
aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
SIMODE1);
p->flags &= ~AHC_HANDLING_REQINITS;
aic_outb(p, CLRBUSFREE, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
restart_sequencer(p);
unpause_sequencer(p, TRUE);
}
else if ((status & SELTO) != 0)
{
unsigned char scbptr;
unsigned char nextscb;
struct scsi_cmnd *cmd;
scbptr = aic_inb(p, WAITING_SCBH);
if (scbptr > p->scb_data->maxhscbs)
{
printk(INFO_LEAD "Invalid WAITING_SCBH value %d, improvising.\n",
p->host_no, -1, -1, -1, scbptr);
if (p->scb_data->maxhscbs > 4)
scbptr &= (p->scb_data->maxhscbs - 1);
else
scbptr &= 0x03;
}
aic_outb(p, scbptr, SCBPTR);
scb_index = aic_inb(p, SCB_TAG);
scb = NULL;
if (scb_index < p->scb_data->numscbs)
{
scb = p->scb_data->scb_array[scb_index];
if ((scb->flags & SCB_ACTIVE) == 0)
{
scb = NULL;
}
}
if (scb == NULL)
{
printk(WARN_LEAD "Referenced SCB %d not valid during SELTO.\n",
p->host_no, -1, -1, -1, scb_index);
printk(KERN_WARNING " SCSISEQ = 0x%x SEQADDR = 0x%x SSTAT0 = 0x%x "
"SSTAT1 = 0x%x\n", aic_inb(p, SCSISEQ),
aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
if (aic7xxx_panic_on_abort)
aic7xxx_panic_abort(p, NULL);
}
else
{
cmd = scb->cmd;
cmd->result = (DID_TIME_OUT << 16);
aic_outb(p, 0, SCB_CONTROL);
aic_outb(p, MSG_NOOP, MSG_OUT);
nextscb = aic_inb(p, SCB_NEXT);
aic_outb(p, nextscb, WAITING_SCBH);
aic7xxx_add_curscb_to_free_list(p);
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
printk(INFO_LEAD "Selection Timeout.\n", p->host_no, CTL_OF_SCB(scb));
#endif
if (scb->flags & SCB_QUEUED_ABORT)
{
cmd->result = 0;
scb = NULL;
}
}
aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
if( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
aic_outb(p, 0, SCSIBUSL);
udelay(301);
aic_outb(p, CLRSELINGO, CLRSINT0);
aic_outb(p, aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
p->flags &= ~AHC_HANDLING_REQINITS;
aic_outb(p, CLRSELTIMEO | CLRBUSFREE, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
restart_sequencer(p);
unpause_sequencer(p, TRUE);
}
else if (scb == NULL)
{
printk(WARN_LEAD "aic7xxx_isr - referenced scb not valid "
"during scsiint 0x%x scb(%d)\n"
" SIMODE0 0x%x, SIMODE1 0x%x, SSTAT0 0x%x, SEQADDR 0x%x\n",
p->host_no, -1, -1, -1, status, scb_index, aic_inb(p, SIMODE0),
aic_inb(p, SIMODE1), aic_inb(p, SSTAT0),
(aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
aic_outb(p, status, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
unpause_sequencer(p, TRUE);
scb = NULL;
}
else if (status & SCSIPERR)
{
char *phase;
struct scsi_cmnd *cmd;
unsigned char mesg_out = MSG_NOOP;
unsigned char lastphase = aic_inb(p, LASTPHASE);
unsigned char sstat2 = aic_inb(p, SSTAT2);
cmd = scb->cmd;
switch (lastphase)
{
case P_DATAOUT:
phase = "Data-Out";
break;
case P_DATAIN:
phase = "Data-In";
mesg_out = MSG_INITIATOR_DET_ERR;
break;
case P_COMMAND:
phase = "Command";
break;
case P_MESGOUT:
phase = "Message-Out";
break;
case P_STATUS:
phase = "Status";
mesg_out = MSG_INITIATOR_DET_ERR;
break;
case P_MESGIN:
phase = "Message-In";
mesg_out = MSG_PARITY_ERROR;
break;
default:
phase = "unknown";
break;
}
if( (p->features & AHC_ULTRA3) &&
(aic_inb(p, SCSIRATE) & AHC_SYNCRATE_CRC) &&
(lastphase == P_DATAIN) )
{
printk(WARN_LEAD "CRC error during %s phase.\n",
p->host_no, CTL_OF_SCB(scb), phase);
if(sstat2 & CRCVALERR)
{
printk(WARN_LEAD " CRC error in intermediate CRC packet.\n",
p->host_no, CTL_OF_SCB(scb));
}
if(sstat2 & CRCENDERR)
{
printk(WARN_LEAD " CRC error in ending CRC packet.\n",
p->host_no, CTL_OF_SCB(scb));
}
if(sstat2 & CRCREQERR)
{
printk(WARN_LEAD " Target incorrectly requested a CRC packet.\n",
p->host_no, CTL_OF_SCB(scb));
}
if(sstat2 & DUAL_EDGE_ERROR)
{
printk(WARN_LEAD " Dual Edge transmission error.\n",
p->host_no, CTL_OF_SCB(scb));
}
}
else if( (lastphase == P_MESGOUT) &&
(scb->flags & SCB_MSGOUT_PPR) )
{
aic_dev = AIC_DEV(scb->cmd);
aic_dev->needppr = aic_dev->needppr_copy = 0;
aic7xxx_set_width(p, scb->cmd->device->id, scb->cmd->device->channel, scb->cmd->device->lun,
MSG_EXT_WDTR_BUS_8_BIT,
(AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE),
aic_dev);
aic7xxx_set_syncrate(p, NULL, scb->cmd->device->id, scb->cmd->device->channel, 0, 0,
0, AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
aic_dev);
aic_dev->goal.options = 0;
scb->flags &= ~SCB_MSGOUT_BITS;
if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "parity error during PPR message, reverting "
"to WDTR/SDTR\n", p->host_no, CTL_OF_SCB(scb));
}
if ( aic_dev->goal.width )
{
aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
}
if ( aic_dev->goal.offset )
{
if( aic_dev->goal.period <= 9 )
{
aic_dev->goal.period = 10;
}
aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
}
scb = NULL;
}
if (mesg_out != MSG_NOOP)
{
aic_outb(p, mesg_out, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
scb = NULL;
}
aic_outb(p, CLRSCSIPERR, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
unpause_sequencer(p, TRUE);
}
else if ( (status & REQINIT) &&
(p->flags & AHC_HANDLING_REQINITS) )
{
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic7xxx_verbose > 0xffff)
printk(INFO_LEAD "Handling REQINIT, SSTAT1=0x%x.\n", p->host_no,
CTL_OF_SCB(scb), aic_inb(p, SSTAT1));
#endif
aic7xxx_handle_reqinit(p, scb);
return;
}
else
{
if (aic7xxx_verbose & VERBOSE_SCSIINT)
printk(INFO_LEAD "Unknown SCSIINT status, SSTAT1(0x%x).\n",
p->host_no, -1, -1, -1, status);
aic_outb(p, status, CLRSINT1);
aic_outb(p, CLRSCSIINT, CLRINT);
unpause_sequencer(p, TRUE);
scb = NULL;
}
if (scb != NULL)
{
aic7xxx_done(p, scb);
}
}
#ifdef AIC7XXX_VERBOSE_DEBUGGING
static void
aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer)
{
unsigned char saved_scbptr, free_scbh, dis_scbh, wait_scbh, temp;
int i, bogus, lost;
static unsigned char scb_status[AIC7XXX_MAXSCB];
#define SCB_NO_LIST 0
#define SCB_FREE_LIST 1
#define SCB_WAITING_LIST 2
#define SCB_DISCONNECTED_LIST 4
#define SCB_CURRENTLY_ACTIVE 8
bogus = FALSE;
memset(&scb_status[0], 0, sizeof(scb_status));
pause_sequencer(p);
saved_scbptr = aic_inb(p, SCBPTR);
if (saved_scbptr >= p->scb_data->maxhscbs)
{
printk("Bogus SCBPTR %d\n", saved_scbptr);
bogus = TRUE;
}
scb_status[saved_scbptr] = SCB_CURRENTLY_ACTIVE;
free_scbh = aic_inb(p, FREE_SCBH);
if ( (free_scbh != SCB_LIST_NULL) &&
(free_scbh >= p->scb_data->maxhscbs) )
{
printk("Bogus FREE_SCBH %d\n", free_scbh);
bogus = TRUE;
}
else
{
temp = free_scbh;
while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
{
if(scb_status[temp] & 0x07)
{
printk("HSCB %d on multiple lists, status 0x%02x", temp,
scb_status[temp] | SCB_FREE_LIST);
bogus = TRUE;
}
scb_status[temp] |= SCB_FREE_LIST;
aic_outb(p, temp, SCBPTR);
temp = aic_inb(p, SCB_NEXT);
}
}
dis_scbh = aic_inb(p, DISCONNECTED_SCBH);
if ( (dis_scbh != SCB_LIST_NULL) &&
(dis_scbh >= p->scb_data->maxhscbs) )
{
printk("Bogus DISCONNECTED_SCBH %d\n", dis_scbh);
bogus = TRUE;
}
else
{
temp = dis_scbh;
while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
{
if(scb_status[temp] & 0x07)
{
printk("HSCB %d on multiple lists, status 0x%02x", temp,
scb_status[temp] | SCB_DISCONNECTED_LIST);
bogus = TRUE;
}
scb_status[temp] |= SCB_DISCONNECTED_LIST;
aic_outb(p, temp, SCBPTR);
temp = aic_inb(p, SCB_NEXT);
}
}
wait_scbh = aic_inb(p, WAITING_SCBH);
if ( (wait_scbh != SCB_LIST_NULL) &&
(wait_scbh >= p->scb_data->maxhscbs) )
{
printk("Bogus WAITING_SCBH %d\n", wait_scbh);
bogus = TRUE;
}
else
{
temp = wait_scbh;
while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
{
if(scb_status[temp] & 0x07)
{
printk("HSCB %d on multiple lists, status 0x%02x", temp,
scb_status[temp] | SCB_WAITING_LIST);
bogus = TRUE;
}
scb_status[temp] |= SCB_WAITING_LIST;
aic_outb(p, temp, SCBPTR);
temp = aic_inb(p, SCB_NEXT);
}
}
lost=0;
for(i=0; i < p->scb_data->maxhscbs; i++)
{
aic_outb(p, i, SCBPTR);
temp = aic_inb(p, SCB_NEXT);
if ( ((temp != SCB_LIST_NULL) &&
(temp >= p->scb_data->maxhscbs)) )
{
printk("HSCB %d bad, SCB_NEXT invalid(%d).\n", i, temp);
bogus = TRUE;
}
if ( temp == i )
{
printk("HSCB %d bad, SCB_NEXT points to self.\n", i);
bogus = TRUE;
}
if (scb_status[i] == 0)
lost++;
if (lost > 1)
{
printk("Too many lost scbs.\n");
bogus=TRUE;
}
}
aic_outb(p, saved_scbptr, SCBPTR);
unpause_sequencer(p, FALSE);
if (bogus)
{
printk("Bogus parameters found in card SCB array structures.\n");
printk("%s\n", buffer);
aic7xxx_panic_abort(p, NULL);
}
return;
}
#endif
static void
aic7xxx_handle_command_completion_intr(struct aic7xxx_host *p)
{
struct aic7xxx_scb *scb = NULL;
struct aic_dev_data *aic_dev;
struct scsi_cmnd *cmd;
unsigned char scb_index, tindex;
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) )
printk(INFO_LEAD "Command Complete Int.\n", p->host_no, -1, -1, -1);
#endif
aic_outb(p, CLRCMDINT, CLRINT);
aic_inb(p, INTSTAT);
while (p->qoutfifo[p->qoutfifonext] != SCB_LIST_NULL)
{
scb_index = p->qoutfifo[p->qoutfifonext];
p->qoutfifo[p->qoutfifonext++] = SCB_LIST_NULL;
if ( scb_index >= p->scb_data->numscbs )
{
printk(WARN_LEAD "CMDCMPLT with invalid SCB index %d\n", p->host_no,
-1, -1, -1, scb_index);
continue;
}
scb = p->scb_data->scb_array[scb_index];
if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
{
printk(WARN_LEAD "CMDCMPLT without command for SCB %d, SCB flags "
"0x%x, cmd 0x%lx\n", p->host_no, -1, -1, -1, scb_index, scb->flags,
(unsigned long) scb->cmd);
continue;
}
tindex = TARGET_INDEX(scb->cmd);
aic_dev = AIC_DEV(scb->cmd);
if (scb->flags & SCB_QUEUED_ABORT)
{
pause_sequencer(p);
if ( ((aic_inb(p, LASTPHASE) & PHASE_MASK) != P_BUSFREE) &&
(aic_inb(p, SCB_TAG) == scb->hscb->tag) )
{
unpause_sequencer(p, FALSE);
continue;
}
aic7xxx_reset_device(p, scb->cmd->device->id, scb->cmd->device->channel,
scb->cmd->device->lun, scb->hscb->tag);
scb->flags &= ~(SCB_QUEUED_FOR_DONE | SCB_RESET | SCB_ABORT |
SCB_QUEUED_ABORT);
unpause_sequencer(p, FALSE);
}
else if (scb->flags & SCB_ABORT)
{
scb->flags &= ~(SCB_ABORT|SCB_RESET);
}
else if (scb->flags & SCB_SENSE)
{
char *buffer = &scb->cmd->sense_buffer[0];
if (buffer[12] == 0x47 || buffer[12] == 0x54)
{
aic_dev->needppr = aic_dev->needppr_copy;
aic_dev->needsdtr = aic_dev->needsdtr_copy;
aic_dev->needwdtr = aic_dev->needwdtr_copy;
}
}
cmd = scb->cmd;
if (scb->hscb->residual_SG_segment_count != 0)
{
aic7xxx_calculate_residual(p, scb);
}
cmd->result |= (aic7xxx_error(cmd) << 16);
aic7xxx_done(p, scb);
}
}
static void
aic7xxx_isr(void *dev_id)
{
struct aic7xxx_host *p;
unsigned char intstat;
p = dev_id;
if (!((intstat = aic_inb(p, INTSTAT)) & INT_PEND))
{
#ifdef CONFIG_PCI
if ( (p->chip & AHC_PCI) && (p->spurious_int > 500) &&
!(p->flags & AHC_HANDLING_REQINITS) )
{
if ( aic_inb(p, ERROR) & PCIERRSTAT )
{
aic7xxx_pci_intr(p);
}
p->spurious_int = 0;
}
else if ( !(p->flags & AHC_HANDLING_REQINITS) )
{
p->spurious_int++;
}
#endif
return;
}
p->spurious_int = 0;
p->isr_count++;
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
(aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
aic7xxx_check_scbs(p, "Bogus settings at start of interrupt.");
#endif
if (intstat & CMDCMPLT)
{
aic7xxx_handle_command_completion_intr(p);
}
if (intstat & BRKADRINT)
{
int i;
unsigned char errno = aic_inb(p, ERROR);
printk(KERN_ERR "(scsi%d) BRKADRINT error(0x%x):\n", p->host_no, errno);
for (i = 0; i < ARRAY_SIZE(hard_error); i++)
{
if (errno & hard_error[i].errno)
{
printk(KERN_ERR " %s\n", hard_error[i].errmesg);
}
}
printk(KERN_ERR "(scsi%d) SEQADDR=0x%x\n", p->host_no,
(((aic_inb(p, SEQADDR1) << 8) & 0x100) | aic_inb(p, SEQADDR0)));
if (aic7xxx_panic_on_abort)
aic7xxx_panic_abort(p, NULL);
#ifdef CONFIG_PCI
if (errno & PCIERRSTAT)
aic7xxx_pci_intr(p);
#endif
if (errno & (SQPARERR | ILLOPCODE | ILLSADDR))
{
panic("aic7xxx: unrecoverable BRKADRINT.\n");
}
if (errno & ILLHADDR)
{
printk(KERN_ERR "(scsi%d) BUG! Driver accessed chip without first "
"pausing controller!\n", p->host_no);
}
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (errno & DPARERR)
{
if (aic_inb(p, DMAPARAMS) & DIRECTION)
printk("(scsi%d) while DMAing SCB from host to card.\n", p->host_no);
else
printk("(scsi%d) while DMAing SCB from card to host.\n", p->host_no);
}
#endif
aic_outb(p, CLRPARERR | CLRBRKADRINT, CLRINT);
unpause_sequencer(p, FALSE);
}
if (intstat & SEQINT)
{
if(p->features & AHC_ULTRA2)
{
aic_inb(p, CCSCBCTL);
}
aic7xxx_handle_seqint(p, intstat);
}
if (intstat & SCSIINT)
{
aic7xxx_handle_scsiint(p, intstat);
}
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
(aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
aic7xxx_check_scbs(p, "Bogus settings at end of interrupt.");
#endif
}
static irqreturn_t
do_aic7xxx_isr(int irq, void *dev_id)
{
unsigned long cpu_flags;
struct aic7xxx_host *p;
p = dev_id;
if(!p)
return IRQ_NONE;
spin_lock_irqsave(p->host->host_lock, cpu_flags);
p->flags |= AHC_IN_ISR;
do
{
aic7xxx_isr(dev_id);
} while ( (aic_inb(p, INTSTAT) & INT_PEND) );
aic7xxx_done_cmds_complete(p);
aic7xxx_run_waiting_queues(p);
p->flags &= ~AHC_IN_ISR;
spin_unlock_irqrestore(p->host->host_lock, cpu_flags);
return IRQ_HANDLED;
}
static void
aic7xxx_init_transinfo(struct aic7xxx_host *p, struct aic_dev_data *aic_dev)
{
struct scsi_device *sdpnt = aic_dev->SDptr;
unsigned char tindex;
tindex = sdpnt->id | (sdpnt->channel << 3);
if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
{
aic_dev->flags |= DEVICE_DTR_SCANNED;
if ( sdpnt->wdtr && (p->features & AHC_WIDE) )
{
aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
aic_dev->goal.width = p->user[tindex].width;
}
else
{
aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
pause_sequencer(p);
aic7xxx_set_width(p, sdpnt->id, sdpnt->channel, sdpnt->lun,
MSG_EXT_WDTR_BUS_8_BIT, (AHC_TRANS_ACTIVE |
AHC_TRANS_GOAL |
AHC_TRANS_CUR), aic_dev );
unpause_sequencer(p, FALSE);
}
if ( sdpnt->sdtr && p->user[tindex].offset )
{
aic_dev->goal.period = p->user[tindex].period;
aic_dev->goal.options = p->user[tindex].options;
if (p->features & AHC_ULTRA2)
aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
else if (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT)
aic_dev->goal.offset = MAX_OFFSET_16BIT;
else
aic_dev->goal.offset = MAX_OFFSET_8BIT;
if ( sdpnt->ppr && p->user[tindex].period <= 9 &&
p->user[tindex].options )
{
aic_dev->needppr = aic_dev->needppr_copy = 1;
aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
aic_dev->flags |= DEVICE_SCSI_3;
}
else
{
aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
aic_dev->goal.period = max_t(unsigned char, 10, aic_dev->goal.period);
aic_dev->goal.options = 0;
}
}
else
{
aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
aic_dev->goal.period = 255;
aic_dev->goal.offset = 0;
aic_dev->goal.options = 0;
}
aic_dev->flags |= DEVICE_PRINT_DTR;
}
}
static int
aic7xxx_slave_alloc(struct scsi_device *SDptr)
{
struct aic7xxx_host *p = (struct aic7xxx_host *)SDptr->host->hostdata;
struct aic_dev_data *aic_dev;
aic_dev = kmalloc(sizeof(struct aic_dev_data), GFP_KERNEL);
if(!aic_dev)
return 1;
if (!(p->flags & AHC_A_SCANNED) && (SDptr->channel == 0))
{
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(INFO_LEAD "Scanning channel for devices.\n",
p->host_no, 0, -1, -1);
p->flags |= AHC_A_SCANNED;
}
else
{
if (!(p->flags & AHC_B_SCANNED) && (SDptr->channel == 1))
{
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(INFO_LEAD "Scanning channel for devices.\n",
p->host_no, 1, -1, -1);
p->flags |= AHC_B_SCANNED;
}
}
memset(aic_dev, 0, sizeof(struct aic_dev_data));
SDptr->hostdata = aic_dev;
aic_dev->SDptr = SDptr;
aic_dev->max_q_depth = 1;
aic_dev->temp_q_depth = 1;
scbq_init(&aic_dev->delayed_scbs);
INIT_LIST_HEAD(&aic_dev->list);
list_add_tail(&aic_dev->list, &p->aic_devs);
return 0;
}
static void
aic7xxx_device_queue_depth(struct aic7xxx_host *p, struct scsi_device *device)
{
int tag_enabled = FALSE;
struct aic_dev_data *aic_dev = device->hostdata;
unsigned char tindex;
tindex = device->id | (device->channel << 3);
if (device->simple_tags)
return;
if (device->tagged_supported)
{
tag_enabled = TRUE;
if (!(p->discenable & (1 << tindex)))
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
printk(INFO_LEAD "Disconnection disabled, unable to "
"enable tagged queueing.\n",
p->host_no, device->channel, device->id, device->lun);
tag_enabled = FALSE;
}
else
{
if (p->instance >= ARRAY_SIZE(aic7xxx_tag_info))
{
static int print_warning = TRUE;
if(print_warning)
{
printk(KERN_INFO "aic7xxx: WARNING, insufficient tag_info instances for"
" installed controllers.\n");
printk(KERN_INFO "aic7xxx: Please update the aic7xxx_tag_info array in"
" the aic7xxx.c source file.\n");
print_warning = FALSE;
}
aic_dev->max_q_depth = aic_dev->temp_q_depth =
aic7xxx_default_queue_depth;
}
else
{
if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 255)
{
tag_enabled = FALSE;
}
else if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 0)
{
aic_dev->max_q_depth = aic_dev->temp_q_depth =
aic7xxx_default_queue_depth;
}
else
{
aic_dev->max_q_depth = aic_dev->temp_q_depth =
aic7xxx_tag_info[p->instance].tag_commands[tindex];
}
}
}
}
if (tag_enabled)
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Tagged queuing enabled, queue depth %d.\n",
p->host_no, device->channel, device->id,
device->lun, aic_dev->max_q_depth);
}
scsi_adjust_queue_depth(device, MSG_ORDERED_TAG, aic_dev->max_q_depth);
}
else
{
if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
{
printk(INFO_LEAD "Tagged queuing disabled, queue depth %d.\n",
p->host_no, device->channel, device->id,
device->lun, device->host->cmd_per_lun);
}
scsi_adjust_queue_depth(device, 0, device->host->cmd_per_lun);
}
return;
}
static void
aic7xxx_slave_destroy(struct scsi_device *SDptr)
{
struct aic_dev_data *aic_dev = SDptr->hostdata;
list_del(&aic_dev->list);
SDptr->hostdata = NULL;
kfree(aic_dev);
return;
}
static int
aic7xxx_slave_configure(struct scsi_device *SDptr)
{
struct aic7xxx_host *p = (struct aic7xxx_host *) SDptr->host->hostdata;
struct aic_dev_data *aic_dev;
int scbnum;
aic_dev = (struct aic_dev_data *)SDptr->hostdata;
aic7xxx_init_transinfo(p, aic_dev);
aic7xxx_device_queue_depth(p, SDptr);
if(list_empty(&aic_dev->list))
list_add_tail(&aic_dev->list, &p->aic_devs);
scbnum = 0;
list_for_each_entry(aic_dev, &p->aic_devs, list) {
scbnum += aic_dev->max_q_depth;
}
while (scbnum > p->scb_data->numscbs)
{
if ( aic7xxx_allocate_scb(p) == 0 )
break;
}
return(0);
}
#if defined(__i386__) || defined(__alpha__)
static int
aic7xxx_probe(int slot, int base, ahc_flag_type *flags)
{
int i;
unsigned char buf[4];
static struct {
int n;
unsigned char signature[sizeof(buf)];
ahc_chip type;
int bios_disabled;
} AIC7xxx[] = {
{ 4, { 0x04, 0x90, 0x77, 0x70 },
AHC_AIC7770|AHC_EISA, FALSE },
{ 4, { 0x04, 0x90, 0x77, 0x71 },
AHC_AIC7770|AHC_EISA, FALSE },
{ 4, { 0x04, 0x90, 0x77, 0x56 },
AHC_AIC7770|AHC_VL, FALSE },
{ 4, { 0x04, 0x90, 0x77, 0x57 },
AHC_AIC7770|AHC_VL, TRUE }
};
for (i = 0; i < sizeof(buf); i++)
{
outb(0x80 + i, base);
buf[i] = inb(base + i);
}
for (i = 0; i < ARRAY_SIZE(AIC7xxx); i++)
{
if (!memcmp(buf, AIC7xxx[i].signature, AIC7xxx[i].n))
{
if (inb(base + 4) & 1)
{
if (AIC7xxx[i].bios_disabled)
{
*flags |= AHC_USEDEFAULTS;
}
else
{
*flags |= AHC_BIOS_ENABLED;
}
return (i);
}
printk("aic7xxx: <Adaptec 7770 SCSI Host Adapter> "
"disabled at slot %d, ignored.\n", slot);
}
}
return (-1);
}
#endif
static int
read_284x_seeprom(struct aic7xxx_host *p, struct seeprom_config *sc)
{
int i = 0, k = 0;
unsigned char temp;
unsigned short checksum = 0;
unsigned short *seeprom = (unsigned short *) sc;
struct seeprom_cmd {
unsigned char len;
unsigned char bits[3];
};
struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
#define CLOCK_PULSE(p) \
while ((aic_inb(p, STATUS_2840) & EEPROM_TF) == 0) \
{ \
; \
} \
(void) aic_inb(p, SEECTL_2840);
for (k = 0; k < (sizeof(*sc) / 2); k++)
{
aic_outb(p, CK_2840 | CS_2840, SEECTL_2840);
CLOCK_PULSE(p);
for (i = 0; i < seeprom_read.len; i++)
{
temp = CS_2840 | seeprom_read.bits[i];
aic_outb(p, temp, SEECTL_2840);
CLOCK_PULSE(p);
temp = temp ^ CK_2840;
aic_outb(p, temp, SEECTL_2840);
CLOCK_PULSE(p);
}
for (i = 5; i >= 0; i--)
{
temp = k;
temp = (temp >> i) & 1;
temp = CS_2840 | temp;
aic_outb(p, temp, SEECTL_2840);
CLOCK_PULSE(p);
temp = temp ^ CK_2840;
aic_outb(p, temp, SEECTL_2840);
CLOCK_PULSE(p);
}
for (i = 0; i <= 16; i++)
{
temp = CS_2840;
aic_outb(p, temp, SEECTL_2840);
CLOCK_PULSE(p);
temp = temp ^ CK_2840;
seeprom[k] = (seeprom[k] << 1) | (aic_inb(p, STATUS_2840) & DI_2840);
aic_outb(p, temp, SEECTL_2840);
CLOCK_PULSE(p);
}
if (k < (sizeof(*sc) / 2) - 1)
{
checksum = checksum + seeprom[k];
}
aic_outb(p, 0, SEECTL_2840);
CLOCK_PULSE(p);
aic_outb(p, CK_2840, SEECTL_2840);
CLOCK_PULSE(p);
aic_outb(p, 0, SEECTL_2840);
CLOCK_PULSE(p);
}
#if 0
printk("Computed checksum 0x%x, checksum read 0x%x\n", checksum, sc->checksum);
printk("Serial EEPROM:");
for (k = 0; k < (sizeof(*sc) / 2); k++)
{
if (((k % 8) == 0) && (k != 0))
{
printk("\n ");
}
printk(" 0x%x", seeprom[k]);
}
printk("\n");
#endif
if (checksum != sc->checksum)
{
printk("aic7xxx: SEEPROM checksum error, ignoring SEEPROM settings.\n");
return (0);
}
return (1);
#undef CLOCK_PULSE
}
#define CLOCK_PULSE(p) \
do { \
int limit = 0; \
do { \
mb(); \
pause_sequencer(p); \
\
\
\
\
\
udelay(1); \
} while (((aic_inb(p, SEECTL) & SEERDY) == 0) && (++limit < 1000)); \
} while(0)
static int
acquire_seeprom(struct aic7xxx_host *p)
{
aic_outb(p, SEEMS, SEECTL);
CLOCK_PULSE(p);
if ((aic_inb(p, SEECTL) & SEERDY) == 0)
{
aic_outb(p, 0, SEECTL);
return (0);
}
return (1);
}
static void
release_seeprom(struct aic7xxx_host *p)
{
CLOCK_PULSE(p);
aic_outb(p, 0, SEECTL);
}
static int
read_seeprom(struct aic7xxx_host *p, int offset,
unsigned short *scarray, unsigned int len, seeprom_chip_type chip)
{
int i = 0, k;
unsigned char temp;
unsigned short checksum = 0;
struct seeprom_cmd {
unsigned char len;
unsigned char bits[3];
};
struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
if (acquire_seeprom(p) == 0)
{
return (0);
}
for (k = 0; k < len; k++)
{
aic_outb(p, SEEMS | SEECK | SEECS, SEECTL);
CLOCK_PULSE(p);
for (i = 0; i < seeprom_read.len; i++)
{
temp = SEEMS | SEECS | (seeprom_read.bits[i] << 1);
aic_outb(p, temp, SEECTL);
CLOCK_PULSE(p);
temp = temp ^ SEECK;
aic_outb(p, temp, SEECTL);
CLOCK_PULSE(p);
}
for (i = ((int) chip - 1); i >= 0; i--)
{
temp = k + offset;
temp = (temp >> i) & 1;
temp = SEEMS | SEECS | (temp << 1);
aic_outb(p, temp, SEECTL);
CLOCK_PULSE(p);
temp = temp ^ SEECK;
aic_outb(p, temp, SEECTL);
CLOCK_PULSE(p);
}
for (i = 0; i <= 16; i++)
{
temp = SEEMS | SEECS;
aic_outb(p, temp, SEECTL);
CLOCK_PULSE(p);
temp = temp ^ SEECK;
scarray[k] = (scarray[k] << 1) | (aic_inb(p, SEECTL) & SEEDI);
aic_outb(p, temp, SEECTL);
CLOCK_PULSE(p);
}
if (k < (len - 1))
{
checksum = checksum + scarray[k];
}
aic_outb(p, SEEMS, SEECTL);
CLOCK_PULSE(p);
aic_outb(p, SEEMS | SEECK, SEECTL);
CLOCK_PULSE(p);
aic_outb(p, SEEMS, SEECTL);
CLOCK_PULSE(p);
}
release_seeprom(p);
#if 0
printk("Computed checksum 0x%x, checksum read 0x%x\n",
checksum, scarray[len - 1]);
printk("Serial EEPROM:");
for (k = 0; k < len; k++)
{
if (((k % 8) == 0) && (k != 0))
{
printk("\n ");
}
printk(" 0x%x", scarray[k]);
}
printk("\n");
#endif
if ( (checksum != scarray[len - 1]) || (checksum == 0) )
{
return (0);
}
return (1);
}
static unsigned char
read_brdctl(struct aic7xxx_host *p)
{
unsigned char brdctl, value;
CLOCK_PULSE(p);
if (p->features & AHC_ULTRA2)
{
brdctl = BRDRW_ULTRA2;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
value = aic_inb(p, BRDCTL);
CLOCK_PULSE(p);
return(value);
}
brdctl = BRDRW;
if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
(p->flags & AHC_CHNLB) )
{
brdctl |= BRDCS;
}
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
value = aic_inb(p, BRDCTL);
CLOCK_PULSE(p);
aic_outb(p, 0, BRDCTL);
CLOCK_PULSE(p);
return (value);
}
static void
write_brdctl(struct aic7xxx_host *p, unsigned char value)
{
unsigned char brdctl;
CLOCK_PULSE(p);
if (p->features & AHC_ULTRA2)
{
brdctl = value;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
brdctl |= BRDSTB_ULTRA2;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
brdctl &= ~BRDSTB_ULTRA2;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
read_brdctl(p);
CLOCK_PULSE(p);
}
else
{
brdctl = BRDSTB;
if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
(p->flags & AHC_CHNLB) )
{
brdctl |= BRDCS;
}
brdctl = BRDSTB | BRDCS;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
brdctl |= value;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
brdctl &= ~BRDSTB;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
brdctl &= ~BRDCS;
aic_outb(p, brdctl, BRDCTL);
CLOCK_PULSE(p);
}
}
static void
aic785x_cable_detect(struct aic7xxx_host *p, int *int_50,
int *ext_present, int *eeprom)
{
unsigned char brdctl;
aic_outb(p, BRDRW | BRDCS, BRDCTL);
CLOCK_PULSE(p);
aic_outb(p, 0, BRDCTL);
CLOCK_PULSE(p);
brdctl = aic_inb(p, BRDCTL);
CLOCK_PULSE(p);
*int_50 = !(brdctl & BRDDAT5);
*ext_present = !(brdctl & BRDDAT6);
*eeprom = (aic_inb(p, SPIOCAP) & EEPROM);
}
#undef CLOCK_PULSE
static void
aic2940_uwpro_wide_cable_detect(struct aic7xxx_host *p, int *int_68,
int *ext_68, int *eeprom)
{
unsigned char brdctl;
write_brdctl(p, 0);
brdctl = read_brdctl(p);
*int_68 = !(brdctl & BRDDAT7);
write_brdctl(p, BRDDAT5);
brdctl = read_brdctl(p);
*ext_68 = !(brdctl & BRDDAT6);
*eeprom = !(brdctl & BRDDAT7);
}
static void
aic787x_cable_detect(struct aic7xxx_host *p, int *int_50, int *int_68,
int *ext_present, int *eeprom)
{
unsigned char brdctl;
write_brdctl(p, 0);
brdctl = read_brdctl(p);
*int_50 = !(brdctl & BRDDAT6);
*int_68 = !(brdctl & BRDDAT7);
write_brdctl(p, BRDDAT5);
brdctl = read_brdctl(p);
*ext_present = !(brdctl & BRDDAT6);
*eeprom = !(brdctl & BRDDAT7);
}
static void
aic7xxx_ultra2_term_detect(struct aic7xxx_host *p, int *enableSE_low,
int *enableSE_high, int *enableLVD_low,
int *enableLVD_high, int *eprom_present)
{
unsigned char brdctl;
brdctl = read_brdctl(p);
*eprom_present = (brdctl & BRDDAT7);
*enableSE_high = (brdctl & BRDDAT6);
*enableSE_low = (brdctl & BRDDAT5);
*enableLVD_high = (brdctl & BRDDAT4);
*enableLVD_low = (brdctl & BRDDAT3);
}
static void
configure_termination(struct aic7xxx_host *p)
{
int internal50_present = 0;
int internal68_present = 0;
int external_present = 0;
int eprom_present = 0;
int enableSE_low = 0;
int enableSE_high = 0;
int enableLVD_low = 0;
int enableLVD_high = 0;
unsigned char brddat = 0;
unsigned char max_target = 0;
unsigned char sxfrctl1 = aic_inb(p, SXFRCTL1);
if (acquire_seeprom(p))
{
if (p->features & (AHC_WIDE|AHC_TWIN))
max_target = 16;
else
max_target = 8;
aic_outb(p, SEEMS | SEECS, SEECTL);
sxfrctl1 &= ~STPWEN;
if (p->features & AHC_ULTRA2)
{
if (aic7xxx_override_term == -1)
{
aic7xxx_ultra2_term_detect(p, &enableSE_low, &enableSE_high,
&enableLVD_low, &enableLVD_high,
&eprom_present);
}
if (!(p->adapter_control & CFSEAUTOTERM))
{
enableSE_low = (p->adapter_control & CFSTERM);
enableSE_high = (p->adapter_control & CFWSTERM);
}
if (!(p->adapter_control & CFAUTOTERM))
{
enableLVD_low = enableLVD_high = (p->adapter_control & CFLVDSTERM);
}
/*
* Now take those settings that we have and translate them into the
* values that must be written into the registers.
*
* Flash Enable = BRDDAT7
* Secondary High Term Enable = BRDDAT6
* Secondary Low Term Enable = BRDDAT5
* LVD/Primary High Term Enable = BRDDAT4
* LVD/Primary Low Term Enable = STPWEN bit in SXFRCTL1
*/
if (enableLVD_low != 0)
{
sxfrctl1 |= STPWEN;
p->flags |= AHC_TERM_ENB_LVD;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) LVD/Primary Low byte termination "
"Enabled\n", p->host_no);
}
if (enableLVD_high != 0)
{
brddat |= BRDDAT4;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) LVD/Primary High byte termination "
"Enabled\n", p->host_no);
}
if (enableSE_low != 0)
{
brddat |= BRDDAT5;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Secondary Low byte termination "
"Enabled\n", p->host_no);
}
if (enableSE_high != 0)
{
brddat |= BRDDAT6;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Secondary High byte termination "
"Enabled\n", p->host_no);
}
}
else if (p->features & AHC_NEW_AUTOTERM)
{
sxfrctl1 |= STPWEN;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Narrow channel termination Enabled\n",
p->host_no);
if (p->adapter_control & CFAUTOTERM)
{
aic2940_uwpro_wide_cable_detect(p, &internal68_present,
&external_present,
&eprom_present);
printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
"Ext-68 %s)\n", p->host_no,
"Don't Care",
internal68_present ? "YES" : "NO",
external_present ? "YES" : "NO");
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
eprom_present ? "is" : "is not");
if (internal68_present && external_present)
{
brddat = 0;
p->flags &= ~AHC_TERM_ENB_SE_HIGH;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Wide channel termination Disabled\n",
p->host_no);
}
else
{
brddat = BRDDAT6;
p->flags |= AHC_TERM_ENB_SE_HIGH;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
p->host_no);
}
}
else
{
if (p->adapter_control & CFWSTERM)
{
brddat = BRDDAT6;
p->flags |= AHC_TERM_ENB_SE_HIGH;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
p->host_no);
}
else
{
brddat = 0;
}
}
}
else
{
if (p->adapter_control & CFAUTOTERM)
{
if (p->flags & AHC_MOTHERBOARD)
{
printk(KERN_INFO "(scsi%d) Warning - detected auto-termination\n",
p->host_no);
printk(KERN_INFO "(scsi%d) Please verify driver detected settings "
"are correct.\n", p->host_no);
printk(KERN_INFO "(scsi%d) If not, then please properly set the "
"device termination\n", p->host_no);
printk(KERN_INFO "(scsi%d) in the Adaptec SCSI BIOS by hitting "
"CTRL-A when prompted\n", p->host_no);
printk(KERN_INFO "(scsi%d) during machine bootup.\n", p->host_no);
}
if ( (p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870 )
{
aic787x_cable_detect(p, &internal50_present, &internal68_present,
&external_present, &eprom_present);
}
else
{
aic785x_cable_detect(p, &internal50_present, &external_present,
&eprom_present);
}
if (max_target <= 8)
internal68_present = 0;
if (max_target > 8)
{
printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
"Ext-68 %s)\n", p->host_no,
internal50_present ? "YES" : "NO",
internal68_present ? "YES" : "NO",
external_present ? "YES" : "NO");
}
else
{
printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Ext-50 %s)\n",
p->host_no,
internal50_present ? "YES" : "NO",
external_present ? "YES" : "NO");
}
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
eprom_present ? "is" : "is not");
if (internal50_present && internal68_present && external_present)
{
printk(KERN_INFO "(scsi%d) Illegal cable configuration!! Only two\n",
p->host_no);
printk(KERN_INFO "(scsi%d) connectors on the SCSI controller may be "
"in use at a time!\n", p->host_no);
internal50_present = external_present = 0;
enableSE_high = enableSE_low = 1;
}
if ((max_target > 8) &&
((external_present == 0) || (internal68_present == 0)) )
{
brddat |= BRDDAT6;
p->flags |= AHC_TERM_ENB_SE_HIGH;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
p->host_no);
}
if ( ((internal50_present ? 1 : 0) +
(internal68_present ? 1 : 0) +
(external_present ? 1 : 0)) <= 1 )
{
sxfrctl1 |= STPWEN;
p->flags |= AHC_TERM_ENB_SE_LOW;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
p->host_no);
}
}
else
{
if (p->adapter_control & CFSTERM)
{
sxfrctl1 |= STPWEN;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
p->host_no);
}
if (p->adapter_control & CFWSTERM)
{
brddat |= BRDDAT6;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
p->host_no);
}
}
}
aic_outb(p, sxfrctl1, SXFRCTL1);
write_brdctl(p, brddat);
release_seeprom(p);
}
}
static void
detect_maxscb(struct aic7xxx_host *p)
{
int i;
if (p->scb_data->maxhscbs == 0)
{
aic_outb(p, 0, FREE_SCBH);
for (i = 0; i < AIC7XXX_MAXSCB; i++)
{
aic_outb(p, i, SCBPTR);
aic_outb(p, i, SCB_CONTROL);
if (aic_inb(p, SCB_CONTROL) != i)
break;
aic_outb(p, 0, SCBPTR);
if (aic_inb(p, SCB_CONTROL) != 0)
break;
aic_outb(p, i, SCBPTR);
aic_outb(p, 0, SCB_CONTROL);
aic_outb(p, i + 1, SCB_NEXT);
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS);
aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+1);
aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+2);
aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+3);
}
aic_outb(p, i - 1, SCBPTR);
aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
aic_outb(p, 0, SCBPTR);
aic_outb(p, 0, SCB_CONTROL);
p->scb_data->maxhscbs = i;
if ( i == AIC7XXX_MAXSCB )
p->flags &= ~AHC_PAGESCBS;
}
}
static int
aic7xxx_register(struct scsi_host_template *template, struct aic7xxx_host *p,
int reset_delay)
{
int i, result;
int max_targets;
int found = 1;
unsigned char term, scsi_conf;
struct Scsi_Host *host;
host = p->host;
p->scb_data->maxscbs = AIC7XXX_MAXSCB;
host->can_queue = AIC7XXX_MAXSCB;
host->cmd_per_lun = 3;
host->sg_tablesize = AIC7XXX_MAX_SG;
host->this_id = p->scsi_id;
host->io_port = p->base;
host->n_io_port = 0xFF;
host->base = p->mbase;
host->irq = p->irq;
if (p->features & AHC_WIDE)
{
host->max_id = 16;
}
if (p->features & AHC_TWIN)
{
host->max_channel = 1;
}
p->host = host;
p->host_no = host->host_no;
host->unique_id = p->instance;
p->isr_count = 0;
p->next = NULL;
p->completeq.head = NULL;
p->completeq.tail = NULL;
scbq_init(&p->scb_data->free_scbs);
scbq_init(&p->waiting_scbs);
INIT_LIST_HEAD(&p->aic_devs);
p->qinfifonext = 0;
p->qoutfifonext = 0;
printk(KERN_INFO "(scsi%d) <%s> found at ", p->host_no,
board_names[p->board_name_index]);
switch(p->chip)
{
case (AHC_AIC7770|AHC_EISA):
printk("EISA slot %d\n", p->pci_device_fn);
break;
case (AHC_AIC7770|AHC_VL):
printk("VLB slot %d\n", p->pci_device_fn);
break;
default:
printk("PCI %d/%d/%d\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
PCI_FUNC(p->pci_device_fn));
break;
}
if (p->features & AHC_TWIN)
{
printk(KERN_INFO "(scsi%d) Twin Channel, A SCSI ID %d, B SCSI ID %d, ",
p->host_no, p->scsi_id, p->scsi_id_b);
}
else
{
char *channel;
channel = "";
if ((p->flags & AHC_MULTI_CHANNEL) != 0)
{
channel = " A";
if ( (p->flags & (AHC_CHNLB|AHC_CHNLC)) != 0 )
{
channel = (p->flags & AHC_CHNLB) ? " B" : " C";
}
}
if (p->features & AHC_WIDE)
{
printk(KERN_INFO "(scsi%d) Wide ", p->host_no);
}
else
{
printk(KERN_INFO "(scsi%d) Narrow ", p->host_no);
}
printk("Channel%s, SCSI ID=%d, ", channel, p->scsi_id);
}
aic_outb(p, 0, SEQ_FLAGS);
detect_maxscb(p);
printk("%d/%d SCBs\n", p->scb_data->maxhscbs, p->scb_data->maxscbs);
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk(KERN_INFO "(scsi%d) BIOS %sabled, IO Port 0x%lx, IRQ %d\n",
p->host_no, (p->flags & AHC_BIOS_ENABLED) ? "en" : "dis",
p->base, p->irq);
printk(KERN_INFO "(scsi%d) IO Memory at 0x%lx, MMAP Memory at %p\n",
p->host_no, p->mbase, p->maddr);
}
#ifdef CONFIG_PCI
if (aic7xxx_stpwlev != -1)
{
if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
{
unsigned char devconfig;
pci_read_config_byte(p->pdev, DEVCONFIG, &devconfig);
if ( (aic7xxx_stpwlev >> p->instance) & 0x01 )
{
devconfig |= STPWLEVEL;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk("(scsi%d) Force setting STPWLEVEL bit\n", p->host_no);
}
else
{
devconfig &= ~STPWLEVEL;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk("(scsi%d) Force clearing STPWLEVEL bit\n", p->host_no);
}
pci_write_config_byte(p->pdev, DEVCONFIG, devconfig);
}
}
#endif
if (aic7xxx_override_term != -1)
{
if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
{
unsigned char term_override;
term_override = ( (aic7xxx_override_term >> (p->instance * 4)) & 0x0f);
p->adapter_control &=
~(CFSTERM|CFWSTERM|CFLVDSTERM|CFAUTOTERM|CFSEAUTOTERM);
if ( (p->features & AHC_ULTRA2) && (term_override & 0x0c) )
{
p->adapter_control |= CFLVDSTERM;
}
if (term_override & 0x02)
{
p->adapter_control |= CFWSTERM;
}
if (term_override & 0x01)
{
p->adapter_control |= CFSTERM;
}
}
}
if ( (p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1) )
{
if (p->features & AHC_SPIOCAP)
{
if ( aic_inb(p, SPIOCAP) & SSPIOCPS )
configure_termination(p);
}
else if ((p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870)
{
configure_termination(p);
}
}
if (p->features & AHC_TWIN)
{
aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
term = (aic_inb(p, SXFRCTL1) & STPWEN);
else
term = ((p->flags & AHC_TERM_ENB_B) ? STPWEN : 0);
aic_outb(p, p->scsi_id_b, SCSIID);
scsi_conf = aic_inb(p, SCSICONF + 1);
aic_outb(p, DFON | SPIOEN, SXFRCTL0);
aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term |
ENSTIMER | ACTNEGEN, SXFRCTL1);
aic_outb(p, 0, SIMODE0);
aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
aic_outb(p, 0, SCSIRATE);
aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
}
if (p->features & AHC_ULTRA2)
{
aic_outb(p, p->scsi_id, SCSIID_ULTRA2);
}
else
{
aic_outb(p, p->scsi_id, SCSIID);
}
if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
term = (aic_inb(p, SXFRCTL1) & STPWEN);
else
term = ((p->flags & (AHC_TERM_ENB_A|AHC_TERM_ENB_LVD)) ? STPWEN : 0);
scsi_conf = aic_inb(p, SCSICONF);
aic_outb(p, DFON | SPIOEN, SXFRCTL0);
aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term |
ENSTIMER | ACTNEGEN, SXFRCTL1);
aic_outb(p, 0, SIMODE0);
if(p->flags & AHC_NO_STPWEN)
aic_outb(p, ENSELTIMO | ENSCSIPERR, SIMODE1);
else
aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
aic_outb(p, 0, SCSIRATE);
if ( p->features & AHC_ULTRA2)
aic_outb(p, 0, SCSIOFFSET);
if ((p->features & (AHC_TWIN|AHC_WIDE)) == 0)
{
max_targets = 8;
}
else
{
max_targets = 16;
}
if (!(aic7xxx_no_reset))
{
aic_outb(p, 0, ULTRA_ENB);
aic_outb(p, 0, ULTRA_ENB + 1);
p->ultraenb = 0;
}
{
size_t array_size;
unsigned int hscb_physaddr;
array_size = p->scb_data->maxscbs * sizeof(struct aic7xxx_hwscb);
if (p->scb_data->hscbs == NULL)
{
p->scb_data->hscbs = pci_alloc_consistent(p->pdev, array_size,
&p->scb_data->hscbs_dma);
p->scb_data->hscb_kmalloc_ptr = NULL;
p->scb_data->hscbs_dma_len = array_size;
}
if (p->scb_data->hscbs == NULL)
{
printk("(scsi%d) Unable to allocate hardware SCB array; "
"failing detection.\n", p->host_no);
aic_outb(p, 0, SIMODE1);
p->irq = 0;
return(0);
}
hscb_physaddr = p->scb_data->hscbs_dma;
aic_outb(p, hscb_physaddr & 0xFF, HSCB_ADDR);
aic_outb(p, (hscb_physaddr >> 8) & 0xFF, HSCB_ADDR + 1);
aic_outb(p, (hscb_physaddr >> 16) & 0xFF, HSCB_ADDR + 2);
aic_outb(p, (hscb_physaddr >> 24) & 0xFF, HSCB_ADDR + 3);
p->untagged_scbs = pci_alloc_consistent(p->pdev, 3*256, &p->fifo_dma);
if (p->untagged_scbs == NULL)
{
printk("(scsi%d) Unable to allocate hardware FIFO arrays; "
"failing detection.\n", p->host_no);
p->irq = 0;
return(0);
}
p->qoutfifo = p->untagged_scbs + 256;
p->qinfifo = p->qoutfifo + 256;
for (i = 0; i < 256; i++)
{
p->untagged_scbs[i] = SCB_LIST_NULL;
p->qinfifo[i] = SCB_LIST_NULL;
p->qoutfifo[i] = SCB_LIST_NULL;
}
hscb_physaddr = p->fifo_dma;
aic_outb(p, hscb_physaddr & 0xFF, SCBID_ADDR);
aic_outb(p, (hscb_physaddr >> 8) & 0xFF, SCBID_ADDR + 1);
aic_outb(p, (hscb_physaddr >> 16) & 0xFF, SCBID_ADDR + 2);
aic_outb(p, (hscb_physaddr >> 24) & 0xFF, SCBID_ADDR + 3);
}
aic_outb(p, 0, QINPOS);
aic_outb(p, 0, KERNEL_QINPOS);
aic_outb(p, 0, QOUTPOS);
if(p->features & AHC_QUEUE_REGS)
{
aic_outb(p, SCB_QSIZE_256, QOFF_CTLSTA);
aic_outb(p, 0, SDSCB_QOFF);
aic_outb(p, 0, SNSCB_QOFF);
aic_outb(p, 0, HNSCB_QOFF);
}
aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
aic_outb(p, MSG_NOOP, MSG_OUT);
aic_outb(p, MSG_NOOP, LAST_MSG);
aic_outb(p, 0, TMODE_CMDADDR);
aic_outb(p, 0, TMODE_CMDADDR + 1);
aic_outb(p, 0, TMODE_CMDADDR + 2);
aic_outb(p, 0, TMODE_CMDADDR + 3);
aic_outb(p, 0, TMODE_CMDADDR_NEXT);
p->next = first_aic7xxx;
first_aic7xxx = p;
aic7xxx_allocate_scb(p);
aic7xxx_loadseq(p);
aic_outb(p, aic_inb(p, SBLKCTL) & ~AUTOFLUSHDIS, SBLKCTL);
if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
{
aic_outb(p, ENABLE, BCTL);
}
if ( !(aic7xxx_no_reset) )
{
if (p->features & AHC_TWIN)
{
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk(KERN_INFO "(scsi%d) Resetting channel B\n", p->host_no);
aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
aic7xxx_reset_current_bus(p);
aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
}
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
char *channel = "";
if (p->flags & AHC_MULTI_CHANNEL)
{
channel = " A";
if (p->flags & (AHC_CHNLB|AHC_CHNLC))
channel = (p->flags & AHC_CHNLB) ? " B" : " C";
}
printk(KERN_INFO "(scsi%d) Resetting channel%s\n", p->host_no, channel);
}
aic7xxx_reset_current_bus(p);
}
else
{
if (!reset_delay)
{
printk(KERN_INFO "(scsi%d) Not resetting SCSI bus. Note: Don't use "
"the no_reset\n", p->host_no);
printk(KERN_INFO "(scsi%d) option unless you have a verifiable need "
"for it.\n", p->host_no);
}
}
if (!(p->chip & AHC_PCI))
{
result = (request_irq(p->irq, do_aic7xxx_isr, 0, "aic7xxx", p));
}
else
{
result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_SHARED,
"aic7xxx", p));
if (result < 0)
{
result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_DISABLED | IRQF_SHARED,
"aic7xxx", p));
}
}
if (result < 0)
{
printk(KERN_WARNING "(scsi%d) Couldn't register IRQ %d, ignoring "
"controller.\n", p->host_no, p->irq);
aic_outb(p, 0, SIMODE1);
p->irq = 0;
return (0);
}
if(aic_inb(p, INTSTAT) & INT_PEND)
printk(INFO_LEAD "spurious interrupt during configuration, cleared.\n",
p->host_no, -1, -1 , -1);
aic7xxx_clear_intstat(p);
unpause_sequencer(p, TRUE);
return (found);
}
static int
aic7xxx_chip_reset(struct aic7xxx_host *p)
{
unsigned char sblkctl;
int wait;
aic_outb(p, PAUSE | CHIPRST, HCNTRL);
wait = 1000;
while (--wait && !(aic_inb(p, HCNTRL) & CHIPRSTACK))
{
udelay(1);
}
pause_sequencer(p);
sblkctl = aic_inb(p, SBLKCTL) & (SELBUSB|SELWIDE);
if (p->chip & AHC_PCI)
sblkctl &= ~SELBUSB;
switch( sblkctl )
{
case 0:
break;
case 2:
p->features |= AHC_WIDE;
break;
case 8:
p->features |= AHC_TWIN;
p->flags |= AHC_MULTI_CHANNEL;
break;
default:
printk(KERN_WARNING "aic7xxx: Unsupported adapter type %d, ignoring.\n",
aic_inb(p, SBLKCTL) & 0x0a);
return(-1);
}
return(0);
}
static struct aic7xxx_host *
aic7xxx_alloc(struct scsi_host_template *sht, struct aic7xxx_host *temp)
{
struct aic7xxx_host *p = NULL;
struct Scsi_Host *host;
host = scsi_register(sht, sizeof(struct aic7xxx_host));
if (host != NULL)
{
p = (struct aic7xxx_host *) host->hostdata;
memset(p, 0, sizeof(struct aic7xxx_host));
*p = *temp;
p->host = host;
p->scb_data = kzalloc(sizeof(scb_data_type), GFP_ATOMIC);
if (p->scb_data)
{
scbq_init (&p->scb_data->free_scbs);
}
else
{
release_region(p->base, MAXREG - MINREG);
scsi_unregister(host);
return(NULL);
}
p->host_no = host->host_no;
}
return (p);
}
static void
aic7xxx_free(struct aic7xxx_host *p)
{
int i;
if (p->scb_data != NULL)
{
struct aic7xxx_scb_dma *scb_dma = NULL;
if (p->scb_data->hscbs != NULL)
{
pci_free_consistent(p->pdev, p->scb_data->hscbs_dma_len,
p->scb_data->hscbs, p->scb_data->hscbs_dma);
p->scb_data->hscbs = p->scb_data->hscb_kmalloc_ptr = NULL;
}
for (i = 0; i < p->scb_data->numscbs; i++)
{
if (p->scb_data->scb_array[i]->scb_dma != scb_dma)
{
scb_dma = p->scb_data->scb_array[i]->scb_dma;
pci_free_consistent(p->pdev, scb_dma->dma_len,
(void *)((unsigned long)scb_dma->dma_address
- scb_dma->dma_offset),
scb_dma->dma_address);
}
kfree(p->scb_data->scb_array[i]->kmalloc_ptr);
p->scb_data->scb_array[i] = NULL;
}
kfree(p->scb_data);
}
pci_free_consistent(p->pdev, 3*256, (void *)p->untagged_scbs, p->fifo_dma);
}
static void
aic7xxx_load_seeprom(struct aic7xxx_host *p, unsigned char *sxfrctl1)
{
int have_seeprom = 0;
int i, max_targets, mask;
unsigned char scsirate, scsi_conf;
unsigned short scarray[128];
struct seeprom_config *sc = (struct seeprom_config *) scarray;
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk(KERN_INFO "aic7xxx: Loading serial EEPROM...");
}
switch (p->chip)
{
case (AHC_AIC7770|AHC_EISA):
if (aic_inb(p, SCSICONF) & TERM_ENB)
p->flags |= AHC_TERM_ENB_A;
if ( (p->features & AHC_TWIN) && (aic_inb(p, SCSICONF + 1) & TERM_ENB) )
p->flags |= AHC_TERM_ENB_B;
break;
case (AHC_AIC7770|AHC_VL):
have_seeprom = read_284x_seeprom(p, (struct seeprom_config *) scarray);
break;
default:
have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
scarray, p->sc_size, p->sc_type);
if (!have_seeprom)
{
if(p->sc_type == C46)
have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
scarray, p->sc_size, C56_66);
else
have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
scarray, p->sc_size, C46);
}
if (!have_seeprom)
{
p->sc_size = 128;
have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
scarray, p->sc_size, p->sc_type);
if (!have_seeprom)
{
if(p->sc_type == C46)
have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
scarray, p->sc_size, C56_66);
else
have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
scarray, p->sc_size, C46);
}
}
break;
}
if (!have_seeprom)
{
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk("\naic7xxx: No SEEPROM available.\n");
}
p->flags |= AHC_NEWEEPROM_FMT;
if (aic_inb(p, SCSISEQ) == 0)
{
p->flags |= AHC_USEDEFAULTS;
p->flags &= ~AHC_BIOS_ENABLED;
p->scsi_id = p->scsi_id_b = 7;
*sxfrctl1 |= STPWEN;
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk("aic7xxx: Using default values.\n");
}
}
else if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk("aic7xxx: Using leftover BIOS values.\n");
}
if ( ((p->chip & ~AHC_CHIPID_MASK) == AHC_PCI) && (*sxfrctl1 & STPWEN) )
{
p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
sc->adapter_control &= ~CFAUTOTERM;
sc->adapter_control |= CFSTERM | CFWSTERM | CFLVDSTERM;
}
if (aic7xxx_extended)
p->flags |= (AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
else
p->flags &= ~(AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
}
else
{
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk("done\n");
}
p->flags |= AHC_SEEPROM_FOUND;
*sxfrctl1 = 0;
p->scsi_id = (sc->brtime_id & CFSCSIID);
if ((p->chip & AHC_CHIPID_MASK) == AHC_AIC7770)
{
if (sc->bios_control & CF284XEXTEND)
p->flags |= AHC_EXTEND_TRANS_A;
if (sc->adapter_control & CF284XSTERM)
{
*sxfrctl1 |= STPWEN;
p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
}
}
else
{
if (sc->bios_control & CFEXTEND)
p->flags |= AHC_EXTEND_TRANS_A;
if (sc->bios_control & CFBIOSEN)
p->flags |= AHC_BIOS_ENABLED;
else
p->flags &= ~AHC_BIOS_ENABLED;
if (sc->adapter_control & CFSTERM)
{
*sxfrctl1 |= STPWEN;
p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
}
}
memcpy(&p->sc, sc, sizeof(struct seeprom_config));
}
p->discenable = 0;
max_targets = ((p->features & (AHC_TWIN | AHC_WIDE)) ? 16 : 8);
if (have_seeprom)
{
for (i = 0; i < max_targets; i++)
{
if( ((p->features & AHC_ULTRA) &&
!(sc->adapter_control & CFULTRAEN) &&
(sc->device_flags[i] & CFSYNCHISULTRA)) ||
(sc->device_flags[i] & CFNEWULTRAFORMAT) )
{
p->flags |= AHC_NEWEEPROM_FMT;
break;
}
}
}
for (i = 0; i < max_targets; i++)
{
mask = (0x01 << i);
if (!have_seeprom)
{
if (aic_inb(p, SCSISEQ) != 0)
{
p->discenable =
~(aic_inb(p, DISC_DSB) | (aic_inb(p, DISC_DSB + 1) << 8) );
p->ultraenb =
(aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8) );
sc->device_flags[i] = (p->discenable & mask) ? CFDISC : 0;
if (aic_inb(p, TARG_SCSIRATE + i) & WIDEXFER)
sc->device_flags[i] |= CFWIDEB;
if (p->features & AHC_ULTRA2)
{
if (aic_inb(p, TARG_OFFSET + i))
{
sc->device_flags[i] |= CFSYNCH;
sc->device_flags[i] |= (aic_inb(p, TARG_SCSIRATE + i) & 0x07);
if ( (aic_inb(p, TARG_SCSIRATE + i) & 0x18) == 0x18 )
sc->device_flags[i] |= CFSYNCHISULTRA;
}
}
else
{
if (aic_inb(p, TARG_SCSIRATE + i) & ~WIDEXFER)
{
sc->device_flags[i] |= CFSYNCH;
if (p->features & AHC_ULTRA)
sc->device_flags[i] |= ((p->ultraenb & mask) ?
CFSYNCHISULTRA : 0);
}
}
}
else
{
sc->device_flags[i] = CFDISC;
if (p->features & AHC_WIDE)
sc->device_flags[i] |= CFWIDEB;
if (p->features & AHC_ULTRA3)
sc->device_flags[i] |= 2;
else if (p->features & AHC_ULTRA2)
sc->device_flags[i] |= 3;
else if (p->features & AHC_ULTRA)
sc->device_flags[i] |= CFSYNCHISULTRA;
sc->device_flags[i] |= CFSYNCH;
aic_outb(p, 0, TARG_SCSIRATE + i);
if (p->features & AHC_ULTRA2)
aic_outb(p, 0, TARG_OFFSET + i);
}
}
if (sc->device_flags[i] & CFDISC)
{
p->discenable |= mask;
}
if (p->flags & AHC_NEWEEPROM_FMT)
{
if ( !(p->features & AHC_ULTRA2) )
{
if ( (sc->device_flags[i] & CFNEWULTRAFORMAT) &&
((sc->device_flags[i] & CFXFER) == 0x03) )
{
sc->device_flags[i] &= ~CFXFER;
sc->device_flags[i] |= CFSYNCHISULTRA;
}
if (sc->device_flags[i] & CFSYNCHISULTRA)
{
p->ultraenb |= mask;
}
}
else if ( !(sc->device_flags[i] & CFNEWULTRAFORMAT) &&
(p->features & AHC_ULTRA2) &&
(sc->device_flags[i] & CFSYNCHISULTRA) )
{
p->ultraenb |= mask;
}
}
else if (sc->adapter_control & CFULTRAEN)
{
p->ultraenb |= mask;
}
if ( (sc->device_flags[i] & CFSYNCH) == 0)
{
sc->device_flags[i] &= ~CFXFER;
p->ultraenb &= ~mask;
p->user[i].offset = 0;
p->user[i].period = 0;
p->user[i].options = 0;
}
else
{
if (p->features & AHC_ULTRA3)
{
p->user[i].offset = MAX_OFFSET_ULTRA2;
if( (sc->device_flags[i] & CFXFER) < 0x03 )
{
scsirate = (sc->device_flags[i] & CFXFER);
p->user[i].options = MSG_EXT_PPR_OPTION_DT_CRC;
}
else
{
scsirate = (sc->device_flags[i] & CFXFER) |
((p->ultraenb & mask) ? 0x18 : 0x10);
p->user[i].options = 0;
}
p->user[i].period = aic7xxx_find_period(p, scsirate,
AHC_SYNCRATE_ULTRA3);
}
else if (p->features & AHC_ULTRA2)
{
p->user[i].offset = MAX_OFFSET_ULTRA2;
scsirate = (sc->device_flags[i] & CFXFER) |
((p->ultraenb & mask) ? 0x18 : 0x10);
p->user[i].options = 0;
p->user[i].period = aic7xxx_find_period(p, scsirate,
AHC_SYNCRATE_ULTRA2);
}
else
{
scsirate = (sc->device_flags[i] & CFXFER) << 4;
p->user[i].options = 0;
p->user[i].offset = MAX_OFFSET_8BIT;
if (p->features & AHC_ULTRA)
{
short ultraenb;
ultraenb = aic_inb(p, ULTRA_ENB) |
(aic_inb(p, ULTRA_ENB + 1) << 8);
p->user[i].period = aic7xxx_find_period(p, scsirate,
(p->ultraenb & mask) ?
AHC_SYNCRATE_ULTRA :
AHC_SYNCRATE_FAST);
}
else
p->user[i].period = aic7xxx_find_period(p, scsirate,
AHC_SYNCRATE_FAST);
}
}
if ( (sc->device_flags[i] & CFWIDEB) && (p->features & AHC_WIDE) )
{
p->user[i].width = MSG_EXT_WDTR_BUS_16_BIT;
}
else
{
p->user[i].width = MSG_EXT_WDTR_BUS_8_BIT;
}
}
aic_outb(p, ~(p->discenable & 0xFF), DISC_DSB);
aic_outb(p, ~((p->discenable >> 8) & 0xFF), DISC_DSB + 1);
if (p->features & AHC_ULTRA)
p->ultraenb = aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8);
scsi_conf = (p->scsi_id & HSCSIID);
if(have_seeprom)
{
p->adapter_control = sc->adapter_control;
p->bios_control = sc->bios_control;
switch (p->chip & AHC_CHIPID_MASK)
{
case AHC_AIC7895:
case AHC_AIC7896:
case AHC_AIC7899:
if (p->adapter_control & CFBPRIMARY)
p->flags |= AHC_CHANNEL_B_PRIMARY;
default:
break;
}
if (sc->adapter_control & CFSPARITY)
scsi_conf |= ENSPCHK;
}
else
{
scsi_conf |= ENSPCHK | RESET_SCSI;
}
if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
{
aic_outb(p, scsi_conf, SCSICONF);
aic_outb(p, p->scsi_id, SCSICONF + 1);
}
}
static void
aic7xxx_configure_bugs(struct aic7xxx_host *p)
{
unsigned short tmp_word;
switch(p->chip & AHC_CHIPID_MASK)
{
case AHC_AIC7860:
p->bugs |= AHC_BUG_PCI_2_1_RETRY;
case AHC_AIC7850:
case AHC_AIC7870:
p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
break;
case AHC_AIC7880:
p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
break;
case AHC_AIC7890:
p->bugs |= AHC_BUG_AUTOFLUSH | AHC_BUG_CACHETHEN;
break;
case AHC_AIC7892:
p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
break;
case AHC_AIC7895:
p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
break;
case AHC_AIC7896:
p->bugs |= AHC_BUG_CACHETHEN_DIS;
break;
case AHC_AIC7899:
p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
break;
default:
break;
}
pci_read_config_word(p->pdev, PCI_COMMAND, &tmp_word);
if(p->bugs & AHC_BUG_PCI_MWI)
{
tmp_word &= ~PCI_COMMAND_INVALIDATE;
}
else
{
tmp_word |= PCI_COMMAND_INVALIDATE;
}
pci_write_config_word(p->pdev, PCI_COMMAND, tmp_word);
if(p->bugs & AHC_BUG_CACHETHEN)
{
aic_outb(p, aic_inb(p, DSCOMMAND0) & ~CACHETHEN, DSCOMMAND0);
}
else if (p->bugs & AHC_BUG_CACHETHEN_DIS)
{
aic_outb(p, aic_inb(p, DSCOMMAND0) | CACHETHEN, DSCOMMAND0);
}
return;
}
static int
aic7xxx_detect(struct scsi_host_template *template)
{
struct aic7xxx_host *temp_p = NULL;
struct aic7xxx_host *current_p = NULL;
struct aic7xxx_host *list_p = NULL;
int found = 0;
#if defined(__i386__) || defined(__alpha__)
ahc_flag_type flags = 0;
int type;
#endif
unsigned char sxfrctl1;
#if defined(__i386__) || defined(__alpha__)
unsigned char hcntrl, hostconf;
unsigned int slot, base;
#endif
#ifdef MODULE
if(aic7xxx)
aic7xxx_setup(aic7xxx);
#endif
template->proc_name = "aic7xxx";
template->sg_tablesize = AIC7XXX_MAX_SG;
#ifdef CONFIG_PCI
{
static struct
{
unsigned short vendor_id;
unsigned short device_id;
ahc_chip chip;
ahc_flag_type flags;
ahc_feature features;
int board_name_index;
unsigned short seeprom_size;
unsigned short seeprom_type;
} const aic_pdevs[] = {
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7810, AHC_NONE,
AHC_FNONE, AHC_FENONE, 1,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7850, AHC_AIC7850,
AHC_PAGESCBS, AHC_AIC7850_FE, 5,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7855, AHC_AIC7850,
AHC_PAGESCBS, AHC_AIC7850_FE, 6,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7821, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7860_FE, 7,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_3860, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7860_FE, 7,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7860_FE, 7,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7860_FE, 7,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7860, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
AHC_AIC7860_FE, 7,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7861, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7860_FE, 8,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7870, AHC_AIC7870,
AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
AHC_AIC7870_FE, 9,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7871, AHC_AIC7870,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE, 10,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7872, AHC_AIC7870,
AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7870_FE, 11,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7873, AHC_AIC7870,
AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7870_FE, 12,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7874, AHC_AIC7870,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE, 13,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7880, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
AHC_AIC7880_FE, 14,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7881, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE, 15,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7882, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7880_FE, 16,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7883, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7880_FE, 17,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7884, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE, 18,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7885, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE, 18,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7886, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE, 18,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7887, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE | AHC_NEW_AUTOTERM, 19,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7888, AHC_AIC7880,
AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE, 18,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7895, AHC_AIC7895,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7895_FE, 20,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890, AHC_AIC7890,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7890_FE, 21,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890B, AHC_AIC7890,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7890_FE, 21,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2930U2, AHC_AIC7890,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7890_FE, 22,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2940U2, AHC_AIC7890,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7890_FE, 23,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7896, AHC_AIC7896,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7896_FE, 24,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3940U2, AHC_AIC7896,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7896_FE, 25,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3950U2D, AHC_AIC7896,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7896_FE, 26,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_1480A, AHC_AIC7860,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_NO_STPWEN,
AHC_AIC7860_FE, 27,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892A, AHC_AIC7892,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7892_FE, 28,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892B, AHC_AIC7892,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7892_FE, 28,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892D, AHC_AIC7892,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7892_FE, 28,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892P, AHC_AIC7892,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
AHC_AIC7892_FE, 28,
32, C46 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899A, AHC_AIC7899,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7899_FE, 29,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899B, AHC_AIC7899,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7899_FE, 29,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899D, AHC_AIC7899,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7899_FE, 29,
32, C56_66 },
{PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899P, AHC_AIC7899,
AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
AHC_AIC7899_FE, 29,
32, C56_66 },
};
unsigned short command;
unsigned int devconfig, i, oldverbose;
struct pci_dev *pdev = NULL;
for (i = 0; i < ARRAY_SIZE(aic_pdevs); i++)
{
pdev = NULL;
while ((pdev = pci_get_device(aic_pdevs[i].vendor_id,
aic_pdevs[i].device_id,
pdev))) {
if (pci_enable_device(pdev))
continue;
if ( i == 0 )
{
if (aic7xxx_verbose & (VERBOSE_PROBE|VERBOSE_PROBE2))
{
printk(KERN_INFO "aic7xxx: The 7810 RAID controller is not "
"supported by\n");
printk(KERN_INFO " this driver, we are ignoring it.\n");
}
}
else if ( (temp_p = kzalloc(sizeof(struct aic7xxx_host),
GFP_ATOMIC)) != NULL )
{
temp_p->chip = aic_pdevs[i].chip | AHC_PCI;
temp_p->flags = aic_pdevs[i].flags;
temp_p->features = aic_pdevs[i].features;
temp_p->board_name_index = aic_pdevs[i].board_name_index;
temp_p->sc_size = aic_pdevs[i].seeprom_size;
temp_p->sc_type = aic_pdevs[i].seeprom_type;
temp_p->irq = pdev->irq;
temp_p->pdev = pdev;
temp_p->pci_bus = pdev->bus->number;
temp_p->pci_device_fn = pdev->devfn;
temp_p->base = pci_resource_start(pdev, 0);
temp_p->mbase = pci_resource_start(pdev, 1);
current_p = list_p;
while(current_p && temp_p)
{
if ( ((current_p->pci_bus == temp_p->pci_bus) &&
(current_p->pci_device_fn == temp_p->pci_device_fn)) ||
(temp_p->base && (current_p->base == temp_p->base)) ||
(temp_p->mbase && (current_p->mbase == temp_p->mbase)) )
{
kfree(temp_p);
temp_p = NULL;
continue;
}
current_p = current_p->next;
}
if(pci_request_regions(temp_p->pdev, "aic7xxx"))
{
printk("aic7xxx: <%s> at PCI %d/%d/%d\n",
board_names[aic_pdevs[i].board_name_index],
temp_p->pci_bus,
PCI_SLOT(temp_p->pci_device_fn),
PCI_FUNC(temp_p->pci_device_fn));
printk("aic7xxx: I/O ports already in use, ignoring.\n");
kfree(temp_p);
continue;
}
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk("aic7xxx: <%s> at PCI %d/%d\n",
board_names[aic_pdevs[i].board_name_index],
PCI_SLOT(pdev->devfn),
PCI_FUNC(pdev->devfn));
pci_read_config_word(pdev, PCI_COMMAND, &command);
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk("aic7xxx: Initial PCI_COMMAND value was 0x%x\n",
(int)command);
}
#ifdef AIC7XXX_STRICT_PCI_SETUP
command |= PCI_COMMAND_SERR | PCI_COMMAND_PARITY |
PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
#else
command |= PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
#endif
command &= ~PCI_COMMAND_INVALIDATE;
if (aic7xxx_pci_parity == 0)
command &= ~(PCI_COMMAND_SERR | PCI_COMMAND_PARITY);
pci_write_config_word(pdev, PCI_COMMAND, command);
#ifdef AIC7XXX_STRICT_PCI_SETUP
pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk("aic7xxx: Initial DEVCONFIG value was 0x%x\n", devconfig);
}
devconfig |= 0x80000040;
pci_write_config_dword(pdev, DEVCONFIG, devconfig);
#endif
temp_p->unpause = INTEN;
temp_p->pause = temp_p->unpause | PAUSE;
if ( ((temp_p->base == 0) &&
(temp_p->mbase == 0)) ||
(temp_p->irq == 0) )
{
printk("aic7xxx: <%s> at PCI %d/%d/%d\n",
board_names[aic_pdevs[i].board_name_index],
temp_p->pci_bus,
PCI_SLOT(temp_p->pci_device_fn),
PCI_FUNC(temp_p->pci_device_fn));
printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
goto skip_pci_controller;
}
#ifdef MMAPIO
if ( !(temp_p->base) || !(temp_p->flags & AHC_MULTI_CHANNEL) ||
((temp_p->chip != (AHC_AIC7870 | AHC_PCI)) &&
(temp_p->chip != (AHC_AIC7880 | AHC_PCI))) )
{
temp_p->maddr = ioremap_nocache(temp_p->mbase, 256);
if(temp_p->maddr)
{
if(aic_inb(temp_p, HCNTRL) == 0xff)
{
printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n",
board_names[aic_pdevs[i].board_name_index],
temp_p->pci_bus,
PCI_SLOT(temp_p->pci_device_fn),
PCI_FUNC(temp_p->pci_device_fn));
printk(KERN_INFO "aic7xxx: MMAPed I/O failed, reverting to "
"Programmed I/O.\n");
iounmap(temp_p->maddr);
temp_p->maddr = NULL;
if(temp_p->base == 0)
{
printk("aic7xxx: <%s> at PCI %d/%d/%d\n",
board_names[aic_pdevs[i].board_name_index],
temp_p->pci_bus,
PCI_SLOT(temp_p->pci_device_fn),
PCI_FUNC(temp_p->pci_device_fn));
printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
goto skip_pci_controller;
}
}
}
}
#endif
pause_sequencer(temp_p);
oldverbose = aic7xxx_verbose;
aic7xxx_verbose = 0;
aic7xxx_pci_intr(temp_p);
aic7xxx_verbose = oldverbose;
temp_p->bios_address = 0;
if (temp_p->features & AHC_ULTRA2)
temp_p->scsi_id = aic_inb(temp_p, SCSIID_ULTRA2) & OID;
else
temp_p->scsi_id = aic_inb(temp_p, SCSIID) & OID;
sxfrctl1 = aic_inb(temp_p, SXFRCTL1);
if (aic7xxx_chip_reset(temp_p) == -1)
{
goto skip_pci_controller;
}
aic_outb(temp_p, sxfrctl1, SXFRCTL1);
pci_write_config_dword(temp_p->pdev, DEVCONFIG, devconfig);
sxfrctl1 &= STPWEN;
switch (temp_p->chip & AHC_CHIPID_MASK)
{
case AHC_AIC7870:
case AHC_AIC7880:
if(temp_p->flags & AHC_MULTI_CHANNEL)
{
switch(PCI_SLOT(temp_p->pci_device_fn))
{
case 5:
temp_p->flags |= AHC_CHNLB;
break;
case 8:
temp_p->flags |= AHC_CHNLB;
break;
case 12:
temp_p->flags |= AHC_CHNLC;
break;
default:
break;
}
}
break;
case AHC_AIC7895:
case AHC_AIC7896:
case AHC_AIC7899:
if (PCI_FUNC(pdev->devfn) != 0)
{
temp_p->flags |= AHC_CHNLB;
}
if ((temp_p->chip & AHC_CHIPID_MASK) == AHC_AIC7895)
{
pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
devconfig |= SCBSIZE32;
pci_write_config_dword(pdev, DEVCONFIG, devconfig);
}
break;
default:
break;
}
switch (temp_p->chip & AHC_CHIPID_MASK)
{
case AHC_AIC7892:
case AHC_AIC7899:
aic_outb(temp_p, 0, SCAMCTL);
aic_outb(temp_p, aic_inb(temp_p, SFUNCT) | ALT_MODE, SFUNCT);
aic_outb(temp_p, AUTO_MSGOUT_DE | DIS_MSGIN_DUALEDGE, OPTIONMODE);
aic_outb(temp_p, 0x00, 0x0b);
aic_outb(temp_p, 0x10, 0x0a);
aic_outb(temp_p, aic_inb(temp_p, SFUNCT) & ~ALT_MODE, SFUNCT);
aic_outb(temp_p, CRCVALCHKEN | CRCENDCHKEN | CRCREQCHKEN |
TARGCRCENDEN | TARGCRCCNTEN,
CRCCONTROL1);
aic_outb(temp_p, ((aic_inb(temp_p, DSCOMMAND0) | USCBSIZE32 |
MPARCKEN | CIOPARCKEN | CACHETHEN) &
~DPARCKEN), DSCOMMAND0);
aic7xxx_load_seeprom(temp_p, &sxfrctl1);
break;
case AHC_AIC7890:
case AHC_AIC7896:
aic_outb(temp_p, 0, SCAMCTL);
aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
CACHETHEN | MPARCKEN | USCBSIZE32 |
CIOPARCKEN) & ~DPARCKEN, DSCOMMAND0);
aic7xxx_load_seeprom(temp_p, &sxfrctl1);
break;
case AHC_AIC7850:
case AHC_AIC7860:
aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
CACHETHEN | MPARCKEN) & ~DPARCKEN,
DSCOMMAND0);
default:
aic7xxx_load_seeprom(temp_p, &sxfrctl1);
break;
case AHC_AIC7880:
pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
if ((devconfig & 0xff) >= 1)
{
aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
CACHETHEN | MPARCKEN) & ~DPARCKEN,
DSCOMMAND0);
}
aic7xxx_load_seeprom(temp_p, &sxfrctl1);
break;
}
switch(temp_p->chip & AHC_CHIPID_MASK)
{
case AHC_AIC7895:
case AHC_AIC7896:
case AHC_AIC7899:
current_p = list_p;
while(current_p != NULL)
{
if ( (current_p->pci_bus == temp_p->pci_bus) &&
(PCI_SLOT(current_p->pci_device_fn) ==
PCI_SLOT(temp_p->pci_device_fn)) )
{
if ( PCI_FUNC(current_p->pci_device_fn) == 0 )
{
temp_p->flags |=
(current_p->flags & AHC_CHANNEL_B_PRIMARY);
temp_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
temp_p->flags |=
(current_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
}
else
{
current_p->flags |=
(temp_p->flags & AHC_CHANNEL_B_PRIMARY);
current_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
current_p->flags |=
(temp_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
}
}
current_p = current_p->next;
}
break;
default:
break;
}
switch(temp_p->chip & AHC_CHIPID_MASK)
{
default:
break;
case AHC_AIC7895:
case AHC_AIC7896:
case AHC_AIC7899:
pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
if (temp_p->features & AHC_ULTRA2)
{
if ( (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2) &&
(aic7xxx_scbram) )
{
aic_outb(temp_p,
aic_inb(temp_p, DSCOMMAND0) & ~SCBRAMSEL_ULTRA2,
DSCOMMAND0);
temp_p->flags |= AHC_EXTERNAL_SRAM;
devconfig |= EXTSCBPEN;
}
else if (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2)
{
printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n",
board_names[aic_pdevs[i].board_name_index],
temp_p->pci_bus,
PCI_SLOT(temp_p->pci_device_fn),
PCI_FUNC(temp_p->pci_device_fn));
printk("aic7xxx: external SCB RAM detected, "
"but not enabled\n");
}
}
else
{
if ((devconfig & RAMPSM) && (aic7xxx_scbram))
{
devconfig &= ~SCBRAMSEL;
devconfig |= EXTSCBPEN;
temp_p->flags |= AHC_EXTERNAL_SRAM;
}
else if (devconfig & RAMPSM)
{
printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n",
board_names[aic_pdevs[i].board_name_index],
temp_p->pci_bus,
PCI_SLOT(temp_p->pci_device_fn),
PCI_FUNC(temp_p->pci_device_fn));
printk("aic7xxx: external SCB RAM detected, "
"but not enabled\n");
}
}
pci_write_config_dword(pdev, DEVCONFIG, devconfig);
if ( (temp_p->flags & AHC_EXTERNAL_SRAM) &&
(temp_p->flags & AHC_CHNLB) )
aic_outb(temp_p, 1, CCSCBBADDR);
break;
}
aic_outb(temp_p,
(aic_inb(temp_p, SBLKCTL) & ~(DIAGLEDEN | DIAGLEDON)),
SBLKCTL);
if (temp_p->features & AHC_ULTRA2)
{
aic_outb(temp_p, RD_DFTHRSH_MAX | WR_DFTHRSH_MAX, DFF_THRSH);
}
else
{
aic_outb(temp_p, DFTHRSH_100, DSPCISTATUS);
}
aic7xxx_configure_bugs(temp_p);
pci_dev_get(temp_p->pdev);
if ( list_p == NULL )
{
list_p = current_p = temp_p;
}
else
{
current_p = list_p;
while(current_p->next != NULL)
current_p = current_p->next;
current_p->next = temp_p;
}
temp_p->next = NULL;
found++;
continue;
skip_pci_controller:
#ifdef CONFIG_PCI
pci_release_regions(temp_p->pdev);
#endif
kfree(temp_p);
}
else
{
printk("aic7xxx: Found <%s>\n",
board_names[aic_pdevs[i].board_name_index]);
printk(KERN_INFO "aic7xxx: Unable to allocate device memory, "
"skipping.\n");
}
}
}
}
#endif
#if defined(__i386__) || defined(__alpha__)
slot = MINSLOT;
while ( (slot <= MAXSLOT) &&
!(aic7xxx_no_probe) )
{
base = SLOTBASE(slot) + MINREG;
if (!request_region(base, MAXREG - MINREG, "aic7xxx"))
{
slot++;
continue;
}
flags = 0;
type = aic7xxx_probe(slot, base + AHC_HID0, &flags);
if (type == -1)
{
release_region(base, MAXREG - MINREG);
slot++;
continue;
}
temp_p = kmalloc(sizeof(struct aic7xxx_host), GFP_ATOMIC);
if (temp_p == NULL)
{
printk(KERN_WARNING "aic7xxx: Unable to allocate device space.\n");
release_region(base, MAXREG - MINREG);
slot++;
continue;
}
if (aic7xxx_irq_trigger == 1)
hcntrl = IRQMS;
else if (aic7xxx_irq_trigger == 0)
hcntrl = 0;
else
hcntrl = inb(base + HCNTRL) & IRQMS;
memset(temp_p, 0, sizeof(struct aic7xxx_host));
temp_p->unpause = hcntrl | INTEN;
temp_p->pause = hcntrl | PAUSE | INTEN;
temp_p->base = base;
temp_p->mbase = 0;
temp_p->maddr = NULL;
temp_p->pci_bus = 0;
temp_p->pci_device_fn = slot;
aic_outb(temp_p, hcntrl | PAUSE, HCNTRL);
while( (aic_inb(temp_p, HCNTRL) & PAUSE) == 0 ) ;
if (aic7xxx_chip_reset(temp_p) == -1)
temp_p->irq = 0;
else
temp_p->irq = aic_inb(temp_p, INTDEF) & 0x0F;
temp_p->flags |= AHC_PAGESCBS;
switch (temp_p->irq)
{
case 9:
case 10:
case 11:
case 12:
case 14:
case 15:
break;
default:
printk(KERN_WARNING "aic7xxx: Host adapter uses unsupported IRQ "
"level %d, ignoring.\n", temp_p->irq);
kfree(temp_p);
release_region(base, MAXREG - MINREG);
slot++;
continue;
}
if (list_p == NULL)
{
list_p = current_p = temp_p;
}
else
{
current_p = list_p;
while (current_p->next != NULL)
current_p = current_p->next;
current_p->next = temp_p;
}
switch (type)
{
case 0:
temp_p->board_name_index = 2;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk("aic7xxx: <%s> at EISA %d\n",
board_names[2], slot);
case 1:
{
temp_p->chip = AHC_AIC7770 | AHC_EISA;
temp_p->features |= AHC_AIC7770_FE;
temp_p->bios_control = aic_inb(temp_p, HA_274_BIOSCTRL);
if (temp_p->board_name_index == 0)
{
temp_p->board_name_index = 3;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk("aic7xxx: <%s> at EISA %d\n",
board_names[3], slot);
}
if (temp_p->bios_control & CHANNEL_B_PRIMARY)
{
temp_p->flags |= AHC_CHANNEL_B_PRIMARY;
}
if ((temp_p->bios_control & BIOSMODE) == BIOSDISABLED)
{
temp_p->flags &= ~AHC_BIOS_ENABLED;
}
else
{
temp_p->flags &= ~AHC_USEDEFAULTS;
temp_p->flags |= AHC_BIOS_ENABLED;
if ( (temp_p->bios_control & 0x20) == 0 )
{
temp_p->bios_address = 0xcc000;
temp_p->bios_address += (0x4000 * (temp_p->bios_control & 0x07));
}
else
{
temp_p->bios_address = 0xd0000;
temp_p->bios_address += (0x8000 * (temp_p->bios_control & 0x06));
}
}
temp_p->adapter_control = aic_inb(temp_p, SCSICONF) << 8;
temp_p->adapter_control |= aic_inb(temp_p, SCSICONF + 1);
if (temp_p->features & AHC_WIDE)
{
temp_p->scsi_id = temp_p->adapter_control & HWSCSIID;
temp_p->scsi_id_b = temp_p->scsi_id;
}
else
{
temp_p->scsi_id = (temp_p->adapter_control >> 8) & HSCSIID;
temp_p->scsi_id_b = temp_p->adapter_control & HSCSIID;
}
aic7xxx_load_seeprom(temp_p, &sxfrctl1);
break;
}
case 2:
case 3:
temp_p->chip = AHC_AIC7770 | AHC_VL;
temp_p->features |= AHC_AIC7770_FE;
if (type == 2)
temp_p->flags |= AHC_BIOS_ENABLED;
else
temp_p->flags &= ~AHC_BIOS_ENABLED;
if (aic_inb(temp_p, SCSICONF) & TERM_ENB)
sxfrctl1 = STPWEN;
aic7xxx_load_seeprom(temp_p, &sxfrctl1);
temp_p->board_name_index = 4;
if (aic7xxx_verbose & VERBOSE_PROBE2)
printk("aic7xxx: <%s> at VLB %d\n",
board_names[2], slot);
switch( aic_inb(temp_p, STATUS_2840) & BIOS_SEL )
{
case 0x00:
temp_p->bios_address = 0xe0000;
break;
case 0x20:
temp_p->bios_address = 0xc8000;
break;
case 0x40:
temp_p->bios_address = 0xd0000;
break;
case 0x60:
temp_p->bios_address = 0xd8000;
break;
default:
break;
}
break;
default:
break;
}
if (aic7xxx_verbose & VERBOSE_PROBE2)
{
printk(KERN_INFO "aic7xxx: BIOS %sabled, IO Port 0x%lx, IRQ %d (%s)\n",
(temp_p->flags & AHC_USEDEFAULTS) ? "dis" : "en", temp_p->base,
temp_p->irq,
(temp_p->pause & IRQMS) ? "level sensitive" : "edge triggered");
printk(KERN_INFO "aic7xxx: Extended translation %sabled.\n",
(temp_p->flags & AHC_EXTEND_TRANS_A) ? "en" : "dis");
}
temp_p->bugs |= AHC_BUG_TMODE_WIDEODD;
hostconf = aic_inb(temp_p, HOSTCONF);
aic_outb(temp_p, hostconf & DFTHRSH, BUSSPD);
aic_outb(temp_p, (hostconf << 2) & BOFF, BUSTIME);
slot++;
found++;
}
#endif
{
struct aic7xxx_host *sort_list[4] = { NULL, NULL, NULL, NULL };
struct aic7xxx_host *vlb, *pci;
struct aic7xxx_host *prev_p;
struct aic7xxx_host *p;
unsigned char left;
prev_p = vlb = pci = NULL;
temp_p = list_p;
while (temp_p != NULL)
{
switch(temp_p->chip & ~AHC_CHIPID_MASK)
{
case AHC_EISA:
case AHC_VL:
{
p = temp_p;
if (p->flags & AHC_BIOS_ENABLED)
vlb = sort_list[0];
else
vlb = sort_list[2];
if (vlb == NULL)
{
vlb = temp_p;
temp_p = temp_p->next;
vlb->next = NULL;
}
else
{
current_p = vlb;
prev_p = NULL;
while ( (current_p != NULL) &&
(current_p->bios_address < temp_p->bios_address))
{
prev_p = current_p;
current_p = current_p->next;
}
if (prev_p != NULL)
{
prev_p->next = temp_p;
temp_p = temp_p->next;
prev_p->next->next = current_p;
}
else
{
vlb = temp_p;
temp_p = temp_p->next;
vlb->next = current_p;
}
}
if (p->flags & AHC_BIOS_ENABLED)
sort_list[0] = vlb;
else
sort_list[2] = vlb;
break;
}
default:
{
p = temp_p;
if (p->flags & AHC_BIOS_ENABLED)
pci = sort_list[1];
else
pci = sort_list[3];
if (pci == NULL)
{
pci = temp_p;
temp_p = temp_p->next;
pci->next = NULL;
}
else
{
current_p = pci;
prev_p = NULL;
if (!aic7xxx_reverse_scan)
{
while ( (current_p != NULL) &&
( (PCI_SLOT(current_p->pci_device_fn) |
(current_p->pci_bus << 8)) <
(PCI_SLOT(temp_p->pci_device_fn) |
(temp_p->pci_bus << 8)) ) )
{
prev_p = current_p;
current_p = current_p->next;
}
}
else
{
while ( (current_p != NULL) &&
( (PCI_SLOT(current_p->pci_device_fn) |
(current_p->pci_bus << 8)) >
(PCI_SLOT(temp_p->pci_device_fn) |
(temp_p->pci_bus << 8)) ) )
{
prev_p = current_p;
current_p = current_p->next;
}
}
if ( (current_p) && (temp_p->flags & AHC_MULTI_CHANNEL) &&
(temp_p->pci_bus == current_p->pci_bus) &&
(PCI_SLOT(temp_p->pci_device_fn) ==
PCI_SLOT(current_p->pci_device_fn)) )
{
if (temp_p->flags & AHC_CHNLB)
{
if ( !(temp_p->flags & AHC_CHANNEL_B_PRIMARY) )
{
prev_p = current_p;
current_p = current_p->next;
}
}
else
{
if (temp_p->flags & AHC_CHANNEL_B_PRIMARY)
{
prev_p = current_p;
current_p = current_p->next;
}
}
}
if (prev_p != NULL)
{
prev_p->next = temp_p;
temp_p = temp_p->next;
prev_p->next->next = current_p;
}
else
{
pci = temp_p;
temp_p = temp_p->next;
pci->next = current_p;
}
}
if (p->flags & AHC_BIOS_ENABLED)
sort_list[1] = pci;
else
sort_list[3] = pci;
break;
}
}
}
{
int i;
left = found;
for (i=0; i<ARRAY_SIZE(sort_list); i++)
{
temp_p = sort_list[i];
while(temp_p != NULL)
{
template->name = board_names[temp_p->board_name_index];
p = aic7xxx_alloc(template, temp_p);
if (p != NULL)
{
p->instance = found - left;
if (aic7xxx_register(template, p, (--left)) == 0)
{
found--;
aic7xxx_release(p->host);
scsi_unregister(p->host);
}
else if (aic7xxx_dump_card)
{
pause_sequencer(p);
aic7xxx_print_card(p);
aic7xxx_print_scratch_ram(p);
unpause_sequencer(p, TRUE);
}
}
current_p = temp_p;
temp_p = (struct aic7xxx_host *)temp_p->next;
kfree(current_p);
}
}
}
}
return (found);
}
static void aic7xxx_buildscb(struct aic7xxx_host *p, struct scsi_cmnd *cmd,
struct aic7xxx_scb *scb)
{
unsigned short mask;
struct aic7xxx_hwscb *hscb;
struct aic_dev_data *aic_dev = cmd->device->hostdata;
struct scsi_device *sdptr = cmd->device;
unsigned char tindex = TARGET_INDEX(cmd);
int use_sg;
mask = (0x01 << tindex);
hscb = scb->hscb;
hscb->control = 0;
scb->tag_action = 0;
if (p->discenable & mask)
{
hscb->control |= DISCENB;
if (cmd->cmnd[0] != TEST_UNIT_READY && sdptr->simple_tags)
{
hscb->control |= MSG_SIMPLE_Q_TAG;
scb->tag_action = MSG_SIMPLE_Q_TAG;
}
}
if ( !(aic_dev->dtr_pending) &&
(aic_dev->needppr || aic_dev->needwdtr || aic_dev->needsdtr) &&
(aic_dev->flags & DEVICE_DTR_SCANNED) )
{
aic_dev->dtr_pending = 1;
scb->tag_action = 0;
hscb->control &= DISCENB;
hscb->control |= MK_MESSAGE;
if(aic_dev->needppr)
{
scb->flags |= SCB_MSGOUT_PPR;
}
else if(aic_dev->needwdtr)
{
scb->flags |= SCB_MSGOUT_WDTR;
}
else if(aic_dev->needsdtr)
{
scb->flags |= SCB_MSGOUT_SDTR;
}
scb->flags |= SCB_DTR_SCB;
}
hscb->target_channel_lun = ((cmd->device->id << 4) & 0xF0) |
((cmd->device->channel & 0x01) << 3) | (cmd->device->lun & 0x07);
hscb->SCSI_cmd_length = cmd->cmd_len;
memcpy(scb->cmnd, cmd->cmnd, cmd->cmd_len);
hscb->SCSI_cmd_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, scb->cmnd));
use_sg = scsi_dma_map(cmd);
BUG_ON(use_sg < 0);
if (use_sg) {
struct scatterlist *sg;
int i;
scb->sg_length = 0;
scsi_for_each_sg(cmd, sg, use_sg, i) {
unsigned int len = sg_dma_len(sg);
scb->sg_list[i].address = cpu_to_le32(sg_dma_address(sg));
scb->sg_list[i].length = cpu_to_le32(len);
scb->sg_length += len;
}
hscb->data_pointer = scb->sg_list[0].address;
hscb->data_count = scb->sg_list[0].length;
scb->sg_count = i;
hscb->SG_segment_count = i;
hscb->SG_list_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, &scb->sg_list[1]));
} else {
scb->sg_count = 0;
scb->sg_length = 0;
hscb->SG_segment_count = 0;
hscb->SG_list_pointer = 0;
hscb->data_count = 0;
hscb->data_pointer = 0;
}
}
static int aic7xxx_queue_lck(struct scsi_cmnd *cmd, void (*fn)(struct scsi_cmnd *))
{
struct aic7xxx_host *p;
struct aic7xxx_scb *scb;
struct aic_dev_data *aic_dev;
p = (struct aic7xxx_host *) cmd->device->host->hostdata;
aic_dev = cmd->device->hostdata;
#ifdef AIC7XXX_VERBOSE_DEBUGGING
if (aic_dev->active_cmds > aic_dev->max_q_depth)
{
printk(WARN_LEAD "Commands queued exceeds queue "
"depth, active=%d\n",
p->host_no, CTL_OF_CMD(cmd),
aic_dev->active_cmds);
}
#endif
scb = scbq_remove_head(&p->scb_data->free_scbs);
if (scb == NULL)
{
aic7xxx_allocate_scb(p);
scb = scbq_remove_head(&p->scb_data->free_scbs);
if(scb == NULL)
{
printk(WARN_LEAD "Couldn't get a free SCB.\n", p->host_no,
CTL_OF_CMD(cmd));
return 1;
}
}
scb->cmd = cmd;
aic7xxx_position(cmd) = scb->hscb->tag;
cmd->scsi_done = fn;
cmd->result = DID_OK;
aic7xxx_error(cmd) = DID_OK;
aic7xxx_status(cmd) = 0;
cmd->host_scribble = NULL;
aic7xxx_buildscb(p, cmd, scb);
scb->flags |= SCB_ACTIVE | SCB_WAITINGQ;
scbq_insert_tail(&p->waiting_scbs, scb);
aic7xxx_run_waiting_queues(p);
return (0);
}
static DEF_SCSI_QCMD(aic7xxx_queue)
static int __aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
{
struct aic7xxx_host *p;
struct aic7xxx_scb *scb;
struct aic7xxx_hwscb *hscb;
int channel;
unsigned char saved_scbptr, lastphase;
unsigned char hscb_index;
int disconnected;
struct aic_dev_data *aic_dev;
if(cmd == NULL)
{
printk(KERN_ERR "aic7xxx_bus_device_reset: called with NULL cmd!\n");
return FAILED;
}
p = (struct aic7xxx_host *)cmd->device->host->hostdata;
aic_dev = AIC_DEV(cmd);
if(aic7xxx_position(cmd) < p->scb_data->numscbs)
scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
else
return FAILED;
hscb = scb->hscb;
aic7xxx_isr(p);
aic7xxx_done_cmds_complete(p);
if(!(scb->flags & SCB_ACTIVE))
return FAILED;
pause_sequencer(p);
lastphase = aic_inb(p, LASTPHASE);
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
{
printk(INFO_LEAD "Bus Device reset, scb flags 0x%x, ",
p->host_no, CTL_OF_SCB(scb), scb->flags);
switch (lastphase)
{
case P_DATAOUT:
printk("Data-Out phase\n");
break;
case P_DATAIN:
printk("Data-In phase\n");
break;
case P_COMMAND:
printk("Command phase\n");
break;
case P_MESGOUT:
printk("Message-Out phase\n");
break;
case P_STATUS:
printk("Status phase\n");
break;
case P_MESGIN:
printk("Message-In phase\n");
break;
default:
printk("while idle, LASTPHASE = 0x%x\n", lastphase);
break;
}
printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
"0x%x\n", p->host_no, CTL_OF_SCB(scb),
aic_inb(p, SCSISIGI),
aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n", p->host_no,
CTL_OF_SCB(scb),
(p->features & AHC_ULTRA2) ? aic_inb(p, SG_CACHEPTR) : 0,
aic_inb(p, SSTAT2),
aic_inb(p, STCNT + 2) << 16 | aic_inb(p, STCNT + 1) << 8 |
aic_inb(p, STCNT));
}
channel = cmd->device->channel;
saved_scbptr = aic_inb(p, SCBPTR);
disconnected = FALSE;
if (lastphase != P_BUSFREE)
{
if (aic_inb(p, SCB_TAG) >= p->scb_data->numscbs)
{
printk(WARN_LEAD "Invalid SCB ID %d is active, "
"SCB flags = 0x%x.\n", p->host_no,
CTL_OF_CMD(cmd), scb->hscb->tag, scb->flags);
unpause_sequencer(p, FALSE);
return FAILED;
}
if (scb->hscb->tag == aic_inb(p, SCB_TAG))
{
if ( (lastphase == P_MESGOUT) || (lastphase == P_MESGIN) )
{
printk(WARN_LEAD "Device reset, Message buffer "
"in use\n", p->host_no, CTL_OF_SCB(scb));
unpause_sequencer(p, FALSE);
return FAILED;
}
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Device reset message in "
"message buffer\n", p->host_no, CTL_OF_SCB(scb));
scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
aic7xxx_error(cmd) = DID_RESET;
aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
aic_outb(p, HOST_MSG, MSG_OUT);
aic_outb(p, lastphase | ATNO, SCSISIGO);
unpause_sequencer(p, FALSE);
spin_unlock_irq(p->host->host_lock);
ssleep(1);
spin_lock_irq(p->host->host_lock);
if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
return FAILED;
else
return SUCCESS;
}
}
scb->hscb->control |= MK_MESSAGE;
scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
if (aic7xxx_search_qinfifo(p, cmd->device->channel, cmd->device->id, cmd->device->lun, hscb->tag,
0, TRUE, NULL) == 0)
{
disconnected = TRUE;
if ((hscb_index = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
{
unsigned char scb_control;
aic_outb(p, hscb_index, SCBPTR);
scb_control = aic_inb(p, SCB_CONTROL);
disconnected = (scb_control & DISCONNECTED);
aic_outb(p, scb_control | MK_MESSAGE, SCB_CONTROL);
}
if (disconnected)
{
if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
printk(INFO_LEAD "Queueing device reset command.\n", p->host_no,
CTL_OF_SCB(scb));
p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
if (p->features & AHC_QUEUE_REGS)
aic_outb(p, p->qinfifonext, HNSCB_QOFF);
else
aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
scb->flags |= SCB_QUEUED_ABORT;
}
}
aic_outb(p, saved_scbptr, SCBPTR);
unpause_sequencer(p, FALSE);
spin_unlock_irq(p->host->host_lock);
msleep(1000/4);
spin_lock_irq(p->host->host_lock);
if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
return FAILED;
else
return SUCCESS;
}
static int aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
{
int rc;
spin_lock_irq(cmd->device->host->host_lock);
rc = __aic7xxx_bus_device_reset(cmd);
spin_unlock_irq(cmd->device->host->host_lock);
return rc;
}
static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
{
printk("aic7xxx driver version %s\n", AIC7XXX_C_VERSION);
printk("Controller type:\n %s\n", board_names[p->board_name_index]);
printk("p->flags=0x%lx, p->chip=0x%x, p->features=0x%x, "
"sequencer %s paused\n",
p->flags, p->chip, p->features,
(aic_inb(p, HCNTRL) & PAUSE) ? "is" : "isn't" );
pause_sequencer(p);
disable_irq(p->irq);
aic7xxx_print_card(p);
aic7xxx_print_scratch_ram(p);
spin_unlock_irq(p->host->host_lock);
for(;;) barrier();
}
static int __aic7xxx_abort(struct scsi_cmnd *cmd)
{
struct aic7xxx_scb *scb = NULL;
struct aic7xxx_host *p;
int found=0, disconnected;
unsigned char saved_hscbptr, hscbptr, scb_control;
struct aic_dev_data *aic_dev;
if(cmd == NULL)
{
printk(KERN_ERR "aic7xxx_abort: called with NULL cmd!\n");
return FAILED;
}
p = (struct aic7xxx_host *)cmd->device->host->hostdata;
aic_dev = AIC_DEV(cmd);
if(aic7xxx_position(cmd) < p->scb_data->numscbs)
scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
else
return FAILED;
aic7xxx_isr(p);
aic7xxx_done_cmds_complete(p);
if(!(scb->flags & SCB_ACTIVE))
return FAILED;
pause_sequencer(p);
if (aic7xxx_panic_on_abort)
aic7xxx_panic_abort(p, cmd);
if (aic7xxx_verbose & VERBOSE_ABORT)
{
printk(INFO_LEAD "Aborting scb %d, flags 0x%x, SEQADDR 0x%x, LASTPHASE "
"0x%x\n",
p->host_no, CTL_OF_SCB(scb), scb->hscb->tag, scb->flags,
aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
aic_inb(p, LASTPHASE));
printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
p->host_no, CTL_OF_SCB(scb), (p->features & AHC_ULTRA2) ?
aic_inb(p, SG_CACHEPTR) : 0, aic_inb(p, SG_COUNT),
aic_inb(p, SCSISIGI));
printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
p->host_no, CTL_OF_SCB(scb), aic_inb(p, SSTAT0),
aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
}
if (scb->flags & SCB_WAITINGQ)
{
if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
printk(INFO_LEAD "SCB found on waiting list and "
"aborted.\n", p->host_no, CTL_OF_SCB(scb));
scbq_remove(&p->waiting_scbs, scb);
scbq_remove(&aic_dev->delayed_scbs, scb);
aic_dev->active_cmds++;
p->activescbs++;
scb->flags &= ~(SCB_WAITINGQ | SCB_ACTIVE);
scb->flags |= SCB_ABORT | SCB_QUEUED_FOR_DONE;
goto success;
}
if ( ((found = aic7xxx_search_qinfifo(p, cmd->device->id, cmd->device->channel,
cmd->device->lun, scb->hscb->tag, SCB_ABORT | SCB_QUEUED_FOR_DONE,
FALSE, NULL)) != 0) &&
(aic7xxx_verbose & VERBOSE_ABORT_PROCESS))
{
printk(INFO_LEAD "SCB found in QINFIFO and aborted.\n", p->host_no,
CTL_OF_SCB(scb));
goto success;
}
saved_hscbptr = aic_inb(p, SCBPTR);
if ((hscbptr = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
{
aic_outb(p, hscbptr, SCBPTR);
scb_control = aic_inb(p, SCB_CONTROL);
disconnected = scb_control & DISCONNECTED;
if(!disconnected && aic_inb(p, LASTPHASE) == P_BUSFREE) {
if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
printk(INFO_LEAD "SCB found on hardware waiting"
" list and aborted.\n", p->host_no, CTL_OF_SCB(scb));
if (aic_inb(p, WAITING_SCBH) == hscbptr && aic_inb(p, SCB_NEXT) ==
SCB_LIST_NULL)
{
aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
aic_outb(p, CLRSELTIMEO, CLRSINT1);
aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
}
else
{
unsigned char prev, next;
prev = SCB_LIST_NULL;
next = aic_inb(p, WAITING_SCBH);
while(next != SCB_LIST_NULL)
{
aic_outb(p, next, SCBPTR);
if (next == hscbptr)
{
next = aic_inb(p, SCB_NEXT);
if (prev != SCB_LIST_NULL)
{
aic_outb(p, prev, SCBPTR);
aic_outb(p, next, SCB_NEXT);
}
else
aic_outb(p, next, WAITING_SCBH);
aic_outb(p, hscbptr, SCBPTR);
next = SCB_LIST_NULL;
}
else
{
prev = next;
next = aic_inb(p, SCB_NEXT);
}
}
}
aic_outb(p, SCB_LIST_NULL, SCB_TAG);
aic_outb(p, 0, SCB_CONTROL);
aic7xxx_add_curscb_to_free_list(p);
scb->flags = SCB_ABORT | SCB_QUEUED_FOR_DONE;
goto success;
}
else if (!disconnected)
{
if((aic_inb(p, LASTPHASE) == P_MESGIN) ||
(aic_inb(p, LASTPHASE) == P_MESGOUT))
{
printk(INFO_LEAD "message buffer busy, unable to abort.\n",
p->host_no, CTL_OF_SCB(scb));
unpause_sequencer(p, FALSE);
return FAILED;
}
}
aic_outb(p, scb_control | MK_MESSAGE, SCB_CONTROL);
if(!disconnected)
{
aic_outb(p, HOST_MSG, MSG_OUT);
aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
}
aic_outb(p, saved_hscbptr, SCBPTR);
}
else
{
disconnected = 1;
}
p->flags |= AHC_ABORT_PENDING;
scb->flags |= SCB_QUEUED_ABORT | SCB_ABORT | SCB_RECOVERY_SCB;
scb->hscb->control |= MK_MESSAGE;
if(disconnected)
{
if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
printk(INFO_LEAD "SCB disconnected. Queueing Abort"
" SCB.\n", p->host_no, CTL_OF_SCB(scb));
p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
if (p->features & AHC_QUEUE_REGS)
aic_outb(p, p->qinfifonext, HNSCB_QOFF);
else
aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
}
unpause_sequencer(p, FALSE);
spin_unlock_irq(p->host->host_lock);
msleep(1000/4);
spin_lock_irq(p->host->host_lock);
if (p->flags & AHC_ABORT_PENDING)
{
if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
printk(INFO_LEAD "Abort never delivered, returning FAILED\n", p->host_no,
CTL_OF_CMD(cmd));
p->flags &= ~AHC_ABORT_PENDING;
return FAILED;
}
if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
return SUCCESS;
success:
if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
aic7xxx_run_done_queue(p, TRUE);
unpause_sequencer(p, FALSE);
return SUCCESS;
}
static int aic7xxx_abort(struct scsi_cmnd *cmd)
{
int rc;
spin_lock_irq(cmd->device->host->host_lock);
rc = __aic7xxx_abort(cmd);
spin_unlock_irq(cmd->device->host->host_lock);
return rc;
}
static int aic7xxx_reset(struct scsi_cmnd *cmd)
{
struct aic7xxx_scb *scb;
struct aic7xxx_host *p;
struct aic_dev_data *aic_dev;
p = (struct aic7xxx_host *) cmd->device->host->hostdata;
spin_lock_irq(p->host->host_lock);
aic_dev = AIC_DEV(cmd);
if(aic7xxx_position(cmd) < p->scb_data->numscbs)
{
scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
if (scb->cmd != cmd)
scb = NULL;
}
else
{
scb = NULL;
}
if (aic7xxx_panic_on_abort)
aic7xxx_panic_abort(p, cmd);
pause_sequencer(p);
while((aic_inb(p, INTSTAT) & INT_PEND) && !(p->flags & AHC_IN_ISR))
{
aic7xxx_isr(p);
pause_sequencer(p);
}
aic7xxx_done_cmds_complete(p);
if(scb && (scb->cmd == NULL))
{
unpause_sequencer(p, FALSE);
spin_unlock_irq(p->host->host_lock);
return SUCCESS;
}
aic7xxx_reset_channel(p, cmd->device->channel, TRUE);
if (p->features & AHC_TWIN)
{
aic7xxx_reset_channel(p, cmd->device->channel ^ 0x01, TRUE);
restart_sequencer(p);
}
aic_outb(p, aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
aic7xxx_clear_intstat(p);
p->flags &= ~AHC_HANDLING_REQINITS;
p->msg_type = MSG_TYPE_NONE;
p->msg_index = 0;
p->msg_len = 0;
aic7xxx_run_done_queue(p, TRUE);
unpause_sequencer(p, FALSE);
spin_unlock_irq(p->host->host_lock);
ssleep(2);
return SUCCESS;
}
static int
aic7xxx_biosparam(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int geom[])
{
sector_t heads, sectors, cylinders;
int ret;
struct aic7xxx_host *p;
unsigned char *buf;
p = (struct aic7xxx_host *) sdev->host->hostdata;
buf = scsi_bios_ptable(bdev);
if ( buf )
{
ret = scsi_partsize(buf, capacity, &geom[2], &geom[0], &geom[1]);
kfree(buf);
if ( ret != -1 )
return(ret);
}
heads = 64;
sectors = 32;
cylinders = capacity >> 11;
if ((p->flags & AHC_EXTEND_TRANS_A) && (cylinders > 1024))
{
heads = 255;
sectors = 63;
cylinders = capacity >> 14;
if(capacity > (65535 * heads * sectors))
cylinders = 65535;
else
cylinders = ((unsigned int)capacity) / (unsigned int)(heads * sectors);
}
geom[0] = (int)heads;
geom[1] = (int)sectors;
geom[2] = (int)cylinders;
return (0);
}
static int
aic7xxx_release(struct Scsi_Host *host)
{
struct aic7xxx_host *p = (struct aic7xxx_host *) host->hostdata;
struct aic7xxx_host *next, *prev;
if(p->irq)
free_irq(p->irq, p);
#ifdef MMAPIO
if(p->maddr)
{
iounmap(p->maddr);
}
#endif
if(!p->pdev)
release_region(p->base, MAXREG - MINREG);
#ifdef CONFIG_PCI
else {
pci_release_regions(p->pdev);
pci_dev_put(p->pdev);
}
#endif
prev = NULL;
next = first_aic7xxx;
while(next != NULL)
{
if(next == p)
{
if(prev == NULL)
first_aic7xxx = next->next;
else
prev->next = next->next;
}
else
{
prev = next;
}
next = next->next;
}
aic7xxx_free(p);
return(0);
}
static void
aic7xxx_print_card(struct aic7xxx_host *p)
{
int i, j, k, chip;
static struct register_ranges {
int num_ranges;
int range_val[32];
} cards_ds[] = {
{ 0, {0,} },
{10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1f, 0x1f, 0x60, 0x60,
0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9b, 0x9f} },
{ 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66,
0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
{ 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66,
0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
{10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1c, 0x1f, 0x60, 0x60,
0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
{10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1a, 0x1c, 0x1f, 0x60, 0x60,
0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
{16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66,
0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
0xfe, 0xff} },
{12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1b, 0x1f, 0x60, 0x60,
0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a,
0x9f, 0x9f, 0xe0, 0xf1} },
{16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66,
0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
0xfe, 0xff} },
{12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66,
0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
0xe0, 0xf1, 0xf4, 0xfc} },
{12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66,
0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
0xe0, 0xf1, 0xf4, 0xfc} },
};
chip = p->chip & AHC_CHIPID_MASK;
printk("%s at ",
board_names[p->board_name_index]);
switch(p->chip & ~AHC_CHIPID_MASK)
{
case AHC_VL:
printk("VLB Slot %d.\n", p->pci_device_fn);
break;
case AHC_EISA:
printk("EISA Slot %d.\n", p->pci_device_fn);
break;
case AHC_PCI:
default:
printk("PCI %d/%d/%d.\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
PCI_FUNC(p->pci_device_fn));
break;
}
printk("Card Dump:\n");
k = 0;
for(i=0; i<cards_ds[chip].num_ranges; i++)
{
for(j = cards_ds[chip].range_val[ i * 2 ];
j <= cards_ds[chip].range_val[ i * 2 + 1 ] ;
j++)
{
printk("%02x:%02x ", j, aic_inb(p, j));
if(++k == 13)
{
printk("\n");
k=0;
}
}
}
if(k != 0)
printk("\n");
if(p->features & AHC_QUEUE_REGS)
{
aic_outb(p, 0, SDSCB_QOFF);
aic_outb(p, 0, SNSCB_QOFF);
aic_outb(p, 0, HNSCB_QOFF);
}
}
static void
aic7xxx_print_scratch_ram(struct aic7xxx_host *p)
{
int i, k;
k = 0;
printk("Scratch RAM:\n");
for(i = SRAM_BASE; i < SEQCTL; i++)
{
printk("%02x:%02x ", i, aic_inb(p, i));
if(++k == 13)
{
printk("\n");
k=0;
}
}
if (p->features & AHC_MORE_SRAM)
{
for(i = TARG_OFFSET; i < 0x80; i++)
{
printk("%02x:%02x ", i, aic_inb(p, i));
if(++k == 13)
{
printk("\n");
k=0;
}
}
}
printk("\n");
}
#include "aic7xxx_old/aic7xxx_proc.c"
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(AIC7XXX_H_VERSION);
static struct scsi_host_template driver_template = {
.proc_info = aic7xxx_proc_info,
.detect = aic7xxx_detect,
.release = aic7xxx_release,
.info = aic7xxx_info,
.queuecommand = aic7xxx_queue,
.slave_alloc = aic7xxx_slave_alloc,
.slave_configure = aic7xxx_slave_configure,
.slave_destroy = aic7xxx_slave_destroy,
.bios_param = aic7xxx_biosparam,
.eh_abort_handler = aic7xxx_abort,
.eh_device_reset_handler = aic7xxx_bus_device_reset,
.eh_host_reset_handler = aic7xxx_reset,
.can_queue = 255,
.this_id = -1,
.max_sectors = 2048,
.cmd_per_lun = 3,
.use_clustering = ENABLE_CLUSTERING,
};
#include "scsi_module.c"
| gpl-2.0 |
standak3/ElementalX_4.4.2 | drivers/regulator/tps6105x-regulator.c | 34 | 4760 | /*
* Driver for TPS61050/61052 boost converters, typically used for white LEDs
* or audio amplifiers.
*
* Copyright (C) 2011 ST-Ericsson SA
* Written on behalf of Linaro for ST-Ericsson
*
* Author: Linus Walleij <linus.walleij@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/mfd/core.h>
#include <linux/mfd/tps6105x.h>
static const int tps6105x_voltages[] = {
4500000,
5000000,
5250000,
5000000,
};
static int tps6105x_regulator_enable(struct regulator_dev *rdev)
{
struct tps6105x *tps6105x = rdev_get_drvdata(rdev);
int ret;
ret = tps6105x_mask_and_set(tps6105x, TPS6105X_REG_0,
TPS6105X_REG0_MODE_MASK,
TPS6105X_REG0_MODE_VOLTAGE << TPS6105X_REG0_MODE_SHIFT);
if (ret)
return ret;
return 0;
}
static int tps6105x_regulator_disable(struct regulator_dev *rdev)
{
struct tps6105x *tps6105x = rdev_get_drvdata(rdev);
int ret;
ret = tps6105x_mask_and_set(tps6105x, TPS6105X_REG_0,
TPS6105X_REG0_MODE_MASK,
TPS6105X_REG0_MODE_SHUTDOWN << TPS6105X_REG0_MODE_SHIFT);
if (ret)
return ret;
return 0;
}
static int tps6105x_regulator_is_enabled(struct regulator_dev *rdev)
{
struct tps6105x *tps6105x = rdev_get_drvdata(rdev);
u8 regval;
int ret;
ret = tps6105x_get(tps6105x, TPS6105X_REG_0, ®val);
if (ret)
return ret;
regval &= TPS6105X_REG0_MODE_MASK;
regval >>= TPS6105X_REG0_MODE_SHIFT;
if (regval == TPS6105X_REG0_MODE_VOLTAGE)
return 1;
return 0;
}
static int tps6105x_regulator_get_voltage_sel(struct regulator_dev *rdev)
{
struct tps6105x *tps6105x = rdev_get_drvdata(rdev);
u8 regval;
int ret;
ret = tps6105x_get(tps6105x, TPS6105X_REG_0, ®val);
if (ret)
return ret;
regval &= TPS6105X_REG0_VOLTAGE_MASK;
regval >>= TPS6105X_REG0_VOLTAGE_SHIFT;
return (int) regval;
}
static int tps6105x_regulator_set_voltage_sel(struct regulator_dev *rdev,
unsigned selector)
{
struct tps6105x *tps6105x = rdev_get_drvdata(rdev);
int ret;
ret = tps6105x_mask_and_set(tps6105x, TPS6105X_REG_0,
TPS6105X_REG0_VOLTAGE_MASK,
selector << TPS6105X_REG0_VOLTAGE_SHIFT);
if (ret)
return ret;
return 0;
}
static int tps6105x_regulator_list_voltage(struct regulator_dev *rdev,
unsigned selector)
{
if (selector >= ARRAY_SIZE(tps6105x_voltages))
return -EINVAL;
return tps6105x_voltages[selector];
}
static struct regulator_ops tps6105x_regulator_ops = {
.enable = tps6105x_regulator_enable,
.disable = tps6105x_regulator_disable,
.is_enabled = tps6105x_regulator_is_enabled,
.get_voltage_sel = tps6105x_regulator_get_voltage_sel,
.set_voltage_sel = tps6105x_regulator_set_voltage_sel,
.list_voltage = tps6105x_regulator_list_voltage,
};
static struct regulator_desc tps6105x_regulator_desc = {
.name = "tps6105x-boost",
.ops = &tps6105x_regulator_ops,
.type = REGULATOR_VOLTAGE,
.id = 0,
.owner = THIS_MODULE,
.n_voltages = ARRAY_SIZE(tps6105x_voltages),
};
static int __devinit tps6105x_regulator_probe(struct platform_device *pdev)
{
struct tps6105x *tps6105x = dev_get_platdata(&pdev->dev);
struct tps6105x_platform_data *pdata = tps6105x->pdata;
int ret;
if (pdata->mode != TPS6105X_MODE_VOLTAGE) {
dev_info(&pdev->dev,
"chip not in voltage mode mode, exit probe \n");
return 0;
}
tps6105x->regulator = regulator_register(&tps6105x_regulator_desc,
&tps6105x->client->dev,
pdata->regulator_data, tps6105x,
NULL);
if (IS_ERR(tps6105x->regulator)) {
ret = PTR_ERR(tps6105x->regulator);
dev_err(&tps6105x->client->dev,
"failed to register regulator\n");
return ret;
}
platform_set_drvdata(pdev, tps6105x);
return 0;
}
static int __devexit tps6105x_regulator_remove(struct platform_device *pdev)
{
struct tps6105x *tps6105x = dev_get_platdata(&pdev->dev);
regulator_unregister(tps6105x->regulator);
return 0;
}
static struct platform_driver tps6105x_regulator_driver = {
.driver = {
.name = "tps6105x-regulator",
.owner = THIS_MODULE,
},
.probe = tps6105x_regulator_probe,
.remove = __devexit_p(tps6105x_regulator_remove),
};
static __init int tps6105x_regulator_init(void)
{
return platform_driver_register(&tps6105x_regulator_driver);
}
subsys_initcall(tps6105x_regulator_init);
static __exit void tps6105x_regulator_exit(void)
{
platform_driver_unregister(&tps6105x_regulator_driver);
}
module_exit(tps6105x_regulator_exit);
MODULE_AUTHOR("Linus Walleij <linus.walleij@linaro.org>");
MODULE_DESCRIPTION("TPS6105x regulator driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:tps6105x-regulator");
| gpl-2.0 |
jenswi-linaro/linux | drivers/acpi/acpica/exoparg2.c | 290 | 15940 | /******************************************************************************
*
* Module Name: exoparg2 - AML execution - opcodes with 2 arguments
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2016, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#include "acinterp.h"
#include "acevents.h"
#include "amlcode.h"
#define _COMPONENT ACPI_EXECUTER
ACPI_MODULE_NAME("exoparg2")
/*!
* Naming convention for AML interpreter execution routines.
*
* The routines that begin execution of AML opcodes are named with a common
* convention based upon the number of arguments, the number of target operands,
* and whether or not a value is returned:
*
* AcpiExOpcode_xA_yT_zR
*
* Where:
*
* xA - ARGUMENTS: The number of arguments (input operands) that are
* required for this opcode type (1 through 6 args).
* yT - TARGETS: The number of targets (output operands) that are required
* for this opcode type (0, 1, or 2 targets).
* zR - RETURN VALUE: Indicates whether this opcode type returns a value
* as the function return (0 or 1).
*
* The AcpiExOpcode* functions are called via the Dispatcher component with
* fully resolved operands.
!*/
/*******************************************************************************
*
* FUNCTION: acpi_ex_opcode_2A_0T_0R
*
* PARAMETERS: walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Execute opcode with two arguments, no target, and no return
* value.
*
* ALLOCATION: Deletes both operands
*
******************************************************************************/
acpi_status acpi_ex_opcode_2A_0T_0R(struct acpi_walk_state *walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
struct acpi_namespace_node *node;
u32 value;
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_0T_0R,
acpi_ps_get_opcode_name(walk_state->opcode));
/* Examine the opcode */
switch (walk_state->opcode) {
case AML_NOTIFY_OP: /* Notify (notify_object, notify_value) */
/* The first operand is a namespace node */
node = (struct acpi_namespace_node *)operand[0];
/* Second value is the notify value */
value = (u32) operand[1]->integer.value;
/* Are notifies allowed on this object? */
if (!acpi_ev_is_notify_object(node)) {
ACPI_ERROR((AE_INFO,
"Unexpected notify object type [%s]",
acpi_ut_get_type_name(node->type)));
status = AE_AML_OPERAND_TYPE;
break;
}
/*
* Dispatch the notify to the appropriate handler
* NOTE: the request is queued for execution after this method
* completes. The notify handlers are NOT invoked synchronously
* from this thread -- because handlers may in turn run other
* control methods.
*/
status = acpi_ev_queue_notify_request(node, value);
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_opcode_2A_2T_1R
*
* PARAMETERS: walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Execute a dyadic operator (2 operands) with 2 output targets
* and one implicit return value.
*
******************************************************************************/
acpi_status acpi_ex_opcode_2A_2T_1R(struct acpi_walk_state *walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *return_desc1 = NULL;
union acpi_operand_object *return_desc2 = NULL;
acpi_status status;
ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_2T_1R,
acpi_ps_get_opcode_name(walk_state->opcode));
/* Execute the opcode */
switch (walk_state->opcode) {
case AML_DIVIDE_OP:
/* Divide (Dividend, Divisor, remainder_result quotient_result) */
return_desc1 =
acpi_ut_create_internal_object(ACPI_TYPE_INTEGER);
if (!return_desc1) {
status = AE_NO_MEMORY;
goto cleanup;
}
return_desc2 =
acpi_ut_create_internal_object(ACPI_TYPE_INTEGER);
if (!return_desc2) {
status = AE_NO_MEMORY;
goto cleanup;
}
/* Quotient to return_desc1, remainder to return_desc2 */
status = acpi_ut_divide(operand[0]->integer.value,
operand[1]->integer.value,
&return_desc1->integer.value,
&return_desc2->integer.value);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
goto cleanup;
}
/* Store the results to the target reference operands */
status = acpi_ex_store(return_desc2, operand[2], walk_state);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
status = acpi_ex_store(return_desc1, operand[3], walk_state);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
cleanup:
/*
* Since the remainder is not returned indirectly, remove a reference to
* it. Only the quotient is returned indirectly.
*/
acpi_ut_remove_reference(return_desc2);
if (ACPI_FAILURE(status)) {
/* Delete the return object */
acpi_ut_remove_reference(return_desc1);
}
/* Save return object (the remainder) on success */
else {
walk_state->result_obj = return_desc1;
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_opcode_2A_1T_1R
*
* PARAMETERS: walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Execute opcode with two arguments, one target, and a return
* value.
*
******************************************************************************/
acpi_status acpi_ex_opcode_2A_1T_1R(struct acpi_walk_state *walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *return_desc = NULL;
u64 index;
acpi_status status = AE_OK;
acpi_size length = 0;
ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_1T_1R,
acpi_ps_get_opcode_name(walk_state->opcode));
/* Execute the opcode */
if (walk_state->op_info->flags & AML_MATH) {
/* All simple math opcodes (add, etc.) */
return_desc = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
return_desc->integer.value =
acpi_ex_do_math_op(walk_state->opcode,
operand[0]->integer.value,
operand[1]->integer.value);
goto store_result_to_target;
}
switch (walk_state->opcode) {
case AML_MOD_OP: /* Mod (Dividend, Divisor, remainder_result (ACPI 2.0) */
return_desc = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
/* return_desc will contain the remainder */
status = acpi_ut_divide(operand[0]->integer.value,
operand[1]->integer.value,
NULL, &return_desc->integer.value);
break;
case AML_CONCAT_OP: /* Concatenate (Data1, Data2, Result) */
status =
acpi_ex_do_concatenate(operand[0], operand[1], &return_desc,
walk_state);
break;
case AML_TO_STRING_OP: /* to_string (Buffer, Length, Result) (ACPI 2.0) */
/*
* Input object is guaranteed to be a buffer at this point (it may have
* been converted.) Copy the raw buffer data to a new object of
* type String.
*/
/*
* Get the length of the new string. It is the smallest of:
* 1) Length of the input buffer
* 2) Max length as specified in the to_string operator
* 3) Length of input buffer up to a zero byte (null terminator)
*
* NOTE: A length of zero is ok, and will create a zero-length, null
* terminated string.
*/
while ((length < operand[0]->buffer.length) &&
(length < operand[1]->integer.value) &&
(operand[0]->buffer.pointer[length])) {
length++;
}
/* Allocate a new string object */
return_desc = acpi_ut_create_string_object(length);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
/*
* Copy the raw buffer data with no transform.
* (NULL terminated already)
*/
memcpy(return_desc->string.pointer,
operand[0]->buffer.pointer, length);
break;
case AML_CONCAT_RES_OP:
/* concatenate_res_template (Buffer, Buffer, Result) (ACPI 2.0) */
status =
acpi_ex_concat_template(operand[0], operand[1],
&return_desc, walk_state);
break;
case AML_INDEX_OP: /* Index (Source Index Result) */
/* Create the internal return object */
return_desc =
acpi_ut_create_internal_object(ACPI_TYPE_LOCAL_REFERENCE);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
/* Initialize the Index reference object */
index = operand[1]->integer.value;
return_desc->reference.value = (u32) index;
return_desc->reference.class = ACPI_REFCLASS_INDEX;
/*
* At this point, the Source operand is a String, Buffer, or Package.
* Verify that the index is within range.
*/
switch ((operand[0])->common.type) {
case ACPI_TYPE_STRING:
if (index >= operand[0]->string.length) {
length = operand[0]->string.length;
status = AE_AML_STRING_LIMIT;
}
return_desc->reference.target_type =
ACPI_TYPE_BUFFER_FIELD;
return_desc->reference.index_pointer =
&(operand[0]->buffer.pointer[index]);
break;
case ACPI_TYPE_BUFFER:
if (index >= operand[0]->buffer.length) {
length = operand[0]->buffer.length;
status = AE_AML_BUFFER_LIMIT;
}
return_desc->reference.target_type =
ACPI_TYPE_BUFFER_FIELD;
return_desc->reference.index_pointer =
&(operand[0]->buffer.pointer[index]);
break;
case ACPI_TYPE_PACKAGE:
if (index >= operand[0]->package.count) {
length = operand[0]->package.count;
status = AE_AML_PACKAGE_LIMIT;
}
return_desc->reference.target_type = ACPI_TYPE_PACKAGE;
return_desc->reference.where =
&operand[0]->package.elements[index];
break;
default:
status = AE_AML_INTERNAL;
goto cleanup;
}
/* Failure means that the Index was beyond the end of the object */
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Index (0x%X%8.8X) is beyond end of object (length 0x%X)",
ACPI_FORMAT_UINT64(index),
(u32)length));
goto cleanup;
}
/*
* Save the target object and add a reference to it for the life
* of the index
*/
return_desc->reference.object = operand[0];
acpi_ut_add_reference(operand[0]);
/* Store the reference to the Target */
status = acpi_ex_store(return_desc, operand[2], walk_state);
/* Return the reference */
walk_state->result_obj = return_desc;
goto cleanup;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
break;
}
store_result_to_target:
if (ACPI_SUCCESS(status)) {
/*
* Store the result of the operation (which is now in return_desc) into
* the Target descriptor.
*/
status = acpi_ex_store(return_desc, operand[2], walk_state);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
if (!walk_state->result_obj) {
walk_state->result_obj = return_desc;
}
}
cleanup:
/* Delete return object on error */
if (ACPI_FAILURE(status)) {
acpi_ut_remove_reference(return_desc);
walk_state->result_obj = NULL;
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_opcode_2A_0T_1R
*
* PARAMETERS: walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Execute opcode with 2 arguments, no target, and a return value
*
******************************************************************************/
acpi_status acpi_ex_opcode_2A_0T_1R(struct acpi_walk_state *walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *return_desc = NULL;
acpi_status status = AE_OK;
u8 logical_result = FALSE;
ACPI_FUNCTION_TRACE_STR(ex_opcode_2A_0T_1R,
acpi_ps_get_opcode_name(walk_state->opcode));
/* Create the internal return object */
return_desc = acpi_ut_create_internal_object(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
/* Execute the Opcode */
if (walk_state->op_info->flags & AML_LOGICAL_NUMERIC) {
/* logical_op (Operand0, Operand1) */
status = acpi_ex_do_logical_numeric_op(walk_state->opcode,
operand[0]->integer.
value,
operand[1]->integer.
value, &logical_result);
goto store_logical_result;
} else if (walk_state->op_info->flags & AML_LOGICAL) {
/* logical_op (Operand0, Operand1) */
status = acpi_ex_do_logical_op(walk_state->opcode, operand[0],
operand[1], &logical_result);
goto store_logical_result;
}
switch (walk_state->opcode) {
case AML_ACQUIRE_OP: /* Acquire (mutex_object, Timeout) */
status =
acpi_ex_acquire_mutex(operand[1], operand[0], walk_state);
if (status == AE_TIME) {
logical_result = TRUE; /* TRUE = Acquire timed out */
status = AE_OK;
}
break;
case AML_WAIT_OP: /* Wait (event_object, Timeout) */
status = acpi_ex_system_wait_event(operand[1], operand[0]);
if (status == AE_TIME) {
logical_result = TRUE; /* TRUE, Wait timed out */
status = AE_OK;
}
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
goto cleanup;
}
store_logical_result:
/*
* Set return value to according to logical_result. logical TRUE (all ones)
* Default is FALSE (zero)
*/
if (logical_result) {
return_desc->integer.value = ACPI_UINT64_MAX;
}
cleanup:
/* Delete return object on error */
if (ACPI_FAILURE(status)) {
acpi_ut_remove_reference(return_desc);
}
/* Save return object on success */
else {
walk_state->result_obj = return_desc;
}
return_ACPI_STATUS(status);
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.